Source file registerer.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
module Source = struct
let hash =
Some (Tezos_crypto.Hashed.Protocol_hash.of_b58check_exn "PtEdo2ZkT9oKpimTah6x2embF25oss54njMuPzkJTEi5RqfdZFA")
let sources = Tezos_base.Protocol.
{ expected_env = V1 ;
components = [{ name = "Misc" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** {2 Helper functions} *)\n\ntype 'a lazyt = unit -> 'a\n\ntype 'a lazy_list_t = LCons of 'a * 'a lazy_list_t tzresult Lwt.t lazyt\n\ntype 'a lazy_list = 'a lazy_list_t tzresult Lwt.t\n\n(** Include bounds *)\nval ( --> ) : int -> int -> int list\n\nval ( ---> ) : Int32.t -> Int32.t -> Int32.t list\n\nval pp_print_paragraph : Format.formatter -> string -> unit\n\nval take : int -> 'a list -> ('a list * 'a list) option\n\n(** Some (input with [prefix] removed), if string has [prefix], else [None] *)\nval remove_prefix : prefix:string -> string -> string option\n\n(** [remove nb list] remove the first [nb] elements from the list [list]. *)\nval remove_elem_from_list : int -> 'a list -> 'a list\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype 'a lazyt = unit -> 'a\n\ntype 'a lazy_list_t = LCons of 'a * 'a lazy_list_t tzresult Lwt.t lazyt\n\ntype 'a lazy_list = 'a lazy_list_t tzresult Lwt.t\n\nlet rec ( --> ) i j =\n (* [i; i+1; ...; j] *)\n if Compare.Int.(i > j) then [] else i :: (succ i --> j)\n\nlet rec ( ---> ) i j =\n (* [i; i+1; ...; j] *)\n if Compare.Int32.(i > j) then [] else i :: (Int32.succ i ---> j)\n\nlet split delim ?(limit = max_int) path =\n let l = String.length path in\n let rec do_slashes acc limit i =\n if Compare.Int.(i >= l) then List.rev acc\n else if Compare.Char.(path.[i] = delim) then do_slashes acc limit (i + 1)\n else do_split acc limit i\n and do_split acc limit i =\n if Compare.Int.(limit <= 0) then\n if Compare.Int.(i = l) then List.rev acc\n else List.rev (String.sub path i (l - i) :: acc)\n else do_component acc (pred limit) i i\n and do_component acc limit i j =\n if Compare.Int.(j >= l) then\n if Compare.Int.(i = j) then List.rev acc\n else List.rev (String.sub path i (j - i) :: acc)\n else if Compare.Char.(path.[j] = delim) then\n do_slashes (String.sub path i (j - i) :: acc) limit j\n else do_component acc limit i (j + 1)\n in\n if Compare.Int.(limit > 0) then do_slashes [] limit 0 else [path]\n [@@coq_axiom \"non-top-level mutual recursion\"]\n\nlet pp_print_paragraph ppf description =\n Format.fprintf\n ppf\n \"@[%a@]\"\n Format.(pp_print_list ~pp_sep:pp_print_space pp_print_string)\n (split ' ' description)\n\nlet take n l =\n let rec loop acc n xs =\n if Compare.Int.(n <= 0) then Some (List.rev acc, xs)\n else match xs with [] -> None | x :: xs -> loop (x :: acc) (n - 1) xs\n in\n loop [] n l\n\nlet remove_prefix ~prefix s =\n let x = String.length prefix in\n let n = String.length s in\n if Compare.Int.(n >= x) && Compare.String.(String.sub s 0 x = prefix) then\n Some (String.sub s x (n - x))\n else None\n\nlet rec remove_elem_from_list nb = function\n | [] ->\n []\n | _ :: _ as l when Compare.Int.(nb <= 0) ->\n l\n | _ :: tl ->\n remove_elem_from_list (nb - 1) tl\n" ;
} ;
{ name = "Storage_description" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Typed description of the key-value context. *)\ntype 'key t\n\n(** Trivial display of the key-value context layout. *)\nval pp : Format.formatter -> 'key t -> unit\n\n(** Export an RPC hierarchy for querying the context. There is one service\n by possible path in the context. Services for \"directory\" are able to\n aggregate in one JSON object the whole subtree. *)\nval build_directory : 'key t -> 'key RPC_directory.t\n\n(** Create a empty context description,\n keys will be registered by side effects. *)\nval create : unit -> 'key t\n\n(** Register a single key accessor at a given path. *)\nval register_value :\n 'key t ->\n get:('key -> 'a option tzresult Lwt.t) ->\n 'a Data_encoding.t ->\n unit\n\n(** Return a description for a prefixed fragment of the given context.\n All keys registered in the subcontext will be shared by the external\n context *)\nval register_named_subcontext : 'key t -> string list -> 'key t\n\n(** Description of an index as a sequence of `RPC_arg.t`. *)\ntype (_, _, _) args =\n | One : {\n rpc_arg : 'a RPC_arg.t;\n encoding : 'a Data_encoding.t;\n compare : 'a -> 'a -> int;\n }\n -> ('key, 'a, 'key * 'a) args\n | Pair :\n ('key, 'a, 'inter_key) args * ('inter_key, 'b, 'sub_key) args\n -> ('key, 'a * 'b, 'sub_key) args\n\n(** Return a description for a indexed sub-context.\n All keys registered in the subcontext will be shared by the external\n context. One should provide a function to list all the registered\n index in the context. *)\nval register_indexed_subcontext :\n 'key t ->\n list:('key -> 'arg list tzresult Lwt.t) ->\n ('key, 'arg, 'sub_key) args ->\n 'sub_key t\n\n(** Helpers for manipulating and defining indexes. *)\n\nval pack : ('key, 'a, 'sub_key) args -> 'key -> 'a -> 'sub_key\n\nval unpack : ('key, 'a, 'sub_key) args -> 'sub_key -> 'key * 'a\n\nmodule type INDEX = sig\n type t\n\n val path_length : int\n\n val to_path : t -> string list -> string list\n\n val of_path : string list -> t option\n\n val rpc_arg : t RPC_arg.t\n\n val encoding : t Data_encoding.t\n\n val compare : t -> t -> int\nend\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule StringMap = Map.Make (String)\n\ntype 'key t = 'key description ref\n\nand 'key description =\n | Empty : 'key description\n | Value : {\n get : 'key -> 'a option tzresult Lwt.t;\n encoding : 'a Data_encoding.t;\n }\n -> 'key description\n | NamedDir : 'key t StringMap.t -> 'key description\n | IndexedDir : {\n arg : 'a RPC_arg.t;\n arg_encoding : 'a Data_encoding.t;\n list : 'key -> 'a list tzresult Lwt.t;\n subdir : ('key * 'a) t;\n }\n -> 'key description\n\nlet rec register_named_subcontext : type r. r t -> string list -> r t =\n fun dir names ->\n match (!dir, names) with\n | (_, []) ->\n dir\n | (Value _, _) ->\n invalid_arg \"\"\n | (IndexedDir _, _) ->\n invalid_arg \"\"\n | (Empty, name :: names) ->\n let subdir = ref Empty in\n dir := NamedDir (StringMap.singleton name subdir) ;\n register_named_subcontext subdir names\n | (NamedDir map, name :: names) ->\n let subdir =\n match StringMap.find_opt name map with\n | Some subdir ->\n subdir\n | None ->\n let subdir = ref Empty in\n dir := NamedDir (StringMap.add name subdir map) ;\n subdir\n in\n register_named_subcontext subdir names\n\ntype (_, _, _) args =\n | One : {\n rpc_arg : 'a RPC_arg.t;\n encoding : 'a Data_encoding.t;\n compare : 'a -> 'a -> int;\n }\n -> ('key, 'a, 'key * 'a) args\n | Pair :\n ('key, 'a, 'inter_key) args * ('inter_key, 'b, 'sub_key) args\n -> ('key, 'a * 'b, 'sub_key) args\n\nlet rec unpack : type a b c. (a, b, c) args -> c -> a * b = function\n | One _ ->\n fun x -> x\n | Pair (l, r) ->\n let unpack_l = unpack l in\n let unpack_r = unpack r in\n fun x ->\n let (c, d) = unpack_r x in\n let (b, a) = unpack_l c in\n (b, (a, d))\n\nlet rec pack : type a b c. (a, b, c) args -> a -> b -> c = function\n | One _ ->\n fun b a -> (b, a)\n | Pair (l, r) ->\n let pack_l = pack l in\n let pack_r = pack r in\n fun b (a, d) ->\n let c = pack_l b a in\n pack_r c d\n\nlet rec compare : type a b c. (a, b, c) args -> b -> b -> int = function\n | One {compare; _} ->\n compare\n | Pair (l, r) -> (\n let compare_l = compare l in\n let compare_r = compare r in\n fun (a1, b1) (a2, b2) ->\n match compare_l a1 a2 with 0 -> compare_r b1 b2 | x -> x )\n\nlet destutter equal l =\n match l with\n | [] ->\n []\n | (i, _) :: l ->\n let rec loop acc i = function\n | [] ->\n acc\n | (j, _) :: l ->\n if equal i j then loop acc i l else loop (j :: acc) j l\n in\n loop [i] i l\n\nlet rec register_indexed_subcontext :\n type r a b.\n r t -> list:(r -> a list tzresult Lwt.t) -> (r, a, b) args -> b t =\n fun dir ~list path ->\n match path with\n | Pair (left, right) ->\n let compare_left = compare left in\n let equal_left x y = Compare.Int.(compare_left x y = 0) in\n let list_left r = list r >|=? fun l -> destutter equal_left l in\n let list_right r =\n let (a, k) = unpack left r in\n list a\n >|=? fun l ->\n List.map snd (List.filter (fun (x, _) -> equal_left x k) l)\n in\n register_indexed_subcontext\n (register_indexed_subcontext dir ~list:list_left left)\n ~list:list_right\n right\n | One {rpc_arg = arg; encoding = arg_encoding; _} -> (\n match !dir with\n | Value _ ->\n invalid_arg \"\"\n | NamedDir _ ->\n invalid_arg \"\"\n | Empty ->\n let subdir = ref Empty in\n dir := IndexedDir {arg; arg_encoding; list; subdir} ;\n subdir\n | IndexedDir {arg = inner_arg; subdir; _} -> (\n match RPC_arg.eq arg inner_arg with\n | None ->\n invalid_arg \"\"\n | Some RPC_arg.Eq ->\n subdir ) )\n\nlet register_value :\n type a b.\n a t -> get:(a -> b option tzresult Lwt.t) -> b Data_encoding.t -> unit =\n fun dir ~get encoding ->\n match !dir with Empty -> dir := Value {get; encoding} | _ -> invalid_arg \"\"\n\nlet create () = ref Empty\n\nlet rec pp : type a. Format.formatter -> a t -> unit =\n fun ppf dir ->\n match !dir with\n | Empty ->\n Format.fprintf ppf \"EMPTY\"\n | Value _e ->\n Format.fprintf ppf \"Value\"\n | NamedDir map ->\n Format.fprintf\n ppf\n \"@[<v>%a@]\"\n (Format.pp_print_list pp_item)\n (StringMap.bindings map)\n | IndexedDir {arg; subdir; _} ->\n let name = Format.asprintf \"<%s>\" (RPC_arg.descr arg).name in\n pp_item ppf (name, subdir)\n\nand pp_item : type a. Format.formatter -> string * a t -> unit =\n fun ppf (name, dir) -> Format.fprintf ppf \"@[<v 2>%s@ %a@]\" name pp dir\n\nmodule type INDEX = sig\n type t\n\n val path_length : int\n\n val to_path : t -> string list -> string list\n\n val of_path : string list -> t option\n\n val rpc_arg : t RPC_arg.t\n\n val encoding : t Data_encoding.t\n\n val compare : t -> t -> int\nend\n\ntype _ handler =\n | Handler : {\n encoding : 'a Data_encoding.t;\n get : 'key -> int -> 'a tzresult Lwt.t;\n }\n -> 'key handler\n\ntype _ opt_handler =\n | Opt_handler : {\n encoding : 'a Data_encoding.t;\n get : 'key -> int -> 'a option tzresult Lwt.t;\n }\n -> 'key opt_handler\n\nlet rec combine_object = function\n | [] ->\n Handler {encoding = Data_encoding.unit; get = (fun _ _ -> return_unit)}\n | (name, Opt_handler handler) :: fields ->\n let (Handler handlers) = combine_object fields in\n Handler\n {\n encoding =\n Data_encoding.merge_objs\n Data_encoding.(obj1 (opt name (dynamic_size handler.encoding)))\n handlers.encoding;\n get =\n (fun k i ->\n handler.get k i\n >>=? fun v1 -> handlers.get k i >|=? fun v2 -> (v1, v2));\n }\n\ntype query = {depth : int}\n\nlet depth_query =\n let open RPC_query in\n query (fun depth -> {depth})\n |+ field \"depth\" RPC_arg.int 0 (fun t -> t.depth)\n |> seal\n\nlet build_directory : type key. key t -> key RPC_directory.t =\n fun dir ->\n let rpc_dir = ref (RPC_directory.empty : key RPC_directory.t) in\n let register : type ikey. (key, ikey) RPC_path.t -> ikey opt_handler -> unit\n =\n fun path (Opt_handler {encoding; get}) ->\n let service =\n RPC_service.get_service ~query:depth_query ~output:encoding path\n in\n rpc_dir :=\n RPC_directory.register !rpc_dir service (fun k q () ->\n get k (q.depth + 1)\n >|=? function None -> raise Not_found | Some x -> x)\n in\n let rec build_handler :\n type ikey. ikey t -> (key, ikey) RPC_path.t -> ikey opt_handler =\n fun dir path ->\n match !dir with\n | Empty ->\n Opt_handler\n {encoding = Data_encoding.unit; get = (fun _ _ -> return_none)}\n | Value {get; encoding} ->\n let handler =\n Opt_handler\n {\n encoding;\n get =\n (fun k i -> if Compare.Int.(i < 0) then return_none else get k);\n }\n in\n register path handler ; handler\n | NamedDir map ->\n let fields = StringMap.bindings map in\n let fields =\n List.map\n (fun (name, dir) ->\n (name, build_handler dir RPC_path.(path / name)))\n fields\n in\n let (Handler handler) = combine_object fields in\n let handler =\n Opt_handler\n {\n encoding = handler.encoding;\n get =\n (fun k i ->\n if Compare.Int.(i < 0) then return_none\n else handler.get k (i - 1) >>=? fun v -> return_some v);\n }\n in\n register path handler ; handler\n | IndexedDir {arg; arg_encoding; list; subdir} ->\n let (Opt_handler handler) =\n build_handler subdir RPC_path.(path /: arg)\n in\n let encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"Leaf\"\n (dynamic_size arg_encoding)\n (function (key, None) -> Some key | _ -> None)\n (fun key -> (key, None));\n case\n (Tag 1)\n ~title:\"Dir\"\n (tup2\n (dynamic_size arg_encoding)\n (dynamic_size handler.encoding))\n (function (key, Some value) -> Some (key, value) | _ -> None)\n (fun (key, value) -> (key, Some value)) ]\n in\n let get k i =\n if Compare.Int.(i < 0) then return_none\n else if Compare.Int.(i = 0) then return_some []\n else\n list k\n >>=? fun keys ->\n map_s\n (fun key ->\n if Compare.Int.(i = 1) then return (key, None)\n else handler.get (k, key) (i - 1) >|=? fun value -> (key, value))\n keys\n >>=? fun values -> return_some values\n in\n let handler =\n Opt_handler\n {encoding = Data_encoding.(list (dynamic_size encoding)); get}\n in\n register path handler ; handler\n in\n ignore (build_handler dir RPC_path.open_root : key opt_handler) ;\n !rpc_dir\n" ;
} ;
{ name = "State_hash" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet random_state_hash = \"\\076\\064\\204\" (* rng(53): never used... *)\n\ninclude Blake2B.Make\n (Base58)\n (struct\n let name = \"random\"\n\n let title = \"A random generation state\"\n\n let b58check_prefix = random_state_hash\n\n let size = None\n end)\n\nlet () = Base58.check_encoded_prefix b58check_encoding \"rng\" 53\n" ;
} ;
{ name = "Nonce_hash" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* 32 *)\nlet nonce_hash = \"\\069\\220\\169\" (* nce(53) *)\n\ninclude Blake2B.Make\n (Base58)\n (struct\n let name = \"cycle_nonce\"\n\n let title = \"A nonce hash\"\n\n let b58check_prefix = nonce_hash\n\n let size = None\n end)\n\nlet () = Base58.check_encoded_prefix b58check_encoding \"nce\" 53\n" ;
} ;
{ name = "Script_expr_hash" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet script_expr_hash = \"\\013\\044\\064\\027\" (* expr(54) *)\n\ninclude Blake2B.Make\n (Base58)\n (struct\n let name = \"script_expr\"\n\n let title = \"A script expression ID\"\n\n let b58check_prefix = script_expr_hash\n\n let size = None\n end)\n\nlet () = Base58.check_encoded_prefix b58check_encoding \"expr\" 54\n" ;
} ;
{ name = "Contract_hash" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* 20 *)\nlet contract_hash = \"\\002\\090\\121\" (* KT1(36) *)\n\ninclude Blake2B.Make\n (Base58)\n (struct\n let name = \"Contract_hash\"\n\n let title = \"A contract ID\"\n\n let b58check_prefix = contract_hash\n\n let size = Some 20\n end)\n\nlet () = Base58.check_encoded_prefix b58check_encoding \"KT1\" 36\n" ;
} ;
{ name = "Blinded_public_key_hash" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ninclude S.HASH\n\ntype activation_code\n\nval activation_code_encoding : activation_code Data_encoding.t\n\nval of_ed25519_pkh : activation_code -> Ed25519.Public_key_hash.t -> t\n\nval activation_code_of_hex : string -> activation_code\n\nmodule Index : Storage_description.INDEX with type t = t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule H =\n Blake2B.Make\n (Base58)\n (struct\n let name = \"Blinded public key hash\"\n\n let title = \"A blinded public key hash\"\n\n let b58check_prefix = \"\\001\\002\\049\\223\"\n\n let size = Some Ed25519.Public_key_hash.size\n end)\n\ninclude H\n\nlet () = Base58.check_encoded_prefix b58check_encoding \"btz1\" 37\n\nlet of_ed25519_pkh activation_code pkh =\n hash_bytes ~key:activation_code [Ed25519.Public_key_hash.to_bytes pkh]\n\ntype activation_code = bytes\n\nlet activation_code_size = Ed25519.Public_key_hash.size\n\nlet activation_code_encoding = Data_encoding.Fixed.bytes activation_code_size\n\nlet activation_code_of_hex h =\n if Compare.Int.(String.length h <> activation_code_size * 2) then\n invalid_arg \"Blinded_public_key_hash.activation_code_of_hex\" ;\n Hex.to_bytes (`Hex h)\n\nmodule Index = H\n" ;
} ;
{ name = "Tez_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t\n\ntype tez = t\n\nval zero : t\n\nval one_mutez : t\n\nval one_cent : t\n\nval fifty_cents : t\n\nval one : t\n\nval ( -? ) : t -> t -> t tzresult\n\nval ( +? ) : t -> t -> t tzresult\n\nval ( *? ) : t -> int64 -> t tzresult\n\nval ( /? ) : t -> int64 -> t tzresult\n\nval to_mutez : t -> int64\n\n(** [of_mutez n] (micro tez) is None if n is negative *)\nval of_mutez : int64 -> t option\n\n(** [of_mutez_exn n] fails if n is negative.\n It should only be used at toplevel for constants. *)\nval of_mutez_exn : int64 -> t\n\n(** It should only be used at toplevel for constants. *)\nval mul_exn : t -> int -> t\n\nval encoding : t Data_encoding.t\n\nval to_int64 : t -> int64\n\ninclude Compare.S with type t := t\n\nval pp : Format.formatter -> t -> unit\n\nval of_string : string -> t option\n\nval to_string : t -> string\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet id = \"tez\"\n\nlet name = \"mutez\"\n\ninclude Compare.Int64 (* invariant: positive *)\n\ntype error +=\n | Addition_overflow of t * t (* `Temporary *)\n | Subtraction_underflow of t * t (* `Temporary *)\n | Multiplication_overflow of t * int64 (* `Temporary *)\n | Negative_multiplicator of t * int64 (* `Temporary *)\n | Invalid_divisor of t * int64\n\n(* `Temporary *)\n\nlet zero = 0L\n\n(* all other constant are defined from the value of one micro tez *)\nlet one_mutez = 1L\n\nlet one_cent = Int64.mul one_mutez 10_000L\n\nlet fifty_cents = Int64.mul one_cent 50L\n\n(* 1 tez = 100 cents = 1_000_000 mutez *)\nlet one = Int64.mul one_cent 100L\n\nlet of_string s =\n let triplets = function\n | hd :: tl ->\n let len = String.length hd in\n Compare.Int.(\n len <= 3 && len > 0 && List.for_all (fun s -> String.length s = 3) tl)\n | [] ->\n false\n in\n let integers s = triplets (String.split_on_char ',' s) in\n let decimals s =\n let l = String.split_on_char ',' s in\n if Compare.Int.(List.length l > 2) then false else triplets (List.rev l)\n in\n let parse left right =\n let remove_commas s = String.concat \"\" (String.split_on_char ',' s) in\n let pad_to_six s =\n let len = String.length s in\n String.init 6 (fun i -> if Compare.Int.(i < len) then s.[i] else '0')\n in\n Int64.of_string_opt (remove_commas left ^ pad_to_six (remove_commas right))\n in\n match String.split_on_char '.' s with\n | [left; right] ->\n if String.contains s ',' then\n if integers left && decimals right then parse left right else None\n else if\n Compare.Int.(String.length right > 0)\n && Compare.Int.(String.length right <= 6)\n then parse left right\n else None\n | [left] ->\n if (not (String.contains s ',')) || integers left then parse left \"\"\n else None\n | _ ->\n None\n\nlet pp ppf amount =\n let mult_int = 1_000_000L in\n let rec left ppf amount =\n let (d, r) = (Int64.(div amount 1000L), Int64.(rem amount 1000L)) in\n if d > 0L then Format.fprintf ppf \"%a%03Ld\" left d r\n else Format.fprintf ppf \"%Ld\" r\n in\n let right ppf amount =\n let triplet ppf v =\n if Compare.Int.(v mod 10 > 0) then Format.fprintf ppf \"%03d\" v\n else if Compare.Int.(v mod 100 > 0) then\n Format.fprintf ppf \"%02d\" (v / 10)\n else Format.fprintf ppf \"%d\" (v / 100)\n in\n let (hi, lo) = (amount / 1000, amount mod 1000) in\n if Compare.Int.(lo = 0) then Format.fprintf ppf \"%a\" triplet hi\n else Format.fprintf ppf \"%03d%a\" hi triplet lo\n in\n let (ints, decs) =\n (Int64.(div amount mult_int), Int64.(to_int (rem amount mult_int)))\n in\n left ppf ints ;\n if Compare.Int.(decs > 0) then Format.fprintf ppf \".%a\" right decs\n\nlet to_string t = Format.asprintf \"%a\" pp t\n\nlet ( -? ) t1 t2 =\n if t2 <= t1 then ok (Int64.sub t1 t2)\n else error (Subtraction_underflow (t1, t2))\n\nlet ( +? ) t1 t2 =\n let t = Int64.add t1 t2 in\n if t < t1 then error (Addition_overflow (t1, t2)) else ok t\n\nlet ( *? ) t m =\n let open Compare.Int64 in\n let open Int64 in\n let rec step cur pow acc =\n if cur = 0L then ok acc\n else\n pow +? pow\n >>? fun npow ->\n if logand cur 1L = 1L then\n acc +? pow >>? fun nacc -> step (shift_right_logical cur 1) npow nacc\n else step (shift_right_logical cur 1) npow acc\n in\n if m < 0L then error (Negative_multiplicator (t, m))\n else\n match step m t 0L with\n | Ok res ->\n Ok res\n | Error ([Addition_overflow _] as errs) ->\n Error (Multiplication_overflow (t, m) :: errs)\n | Error errs ->\n Error errs\n\nlet ( /? ) t d =\n if d <= 0L then error (Invalid_divisor (t, d)) else ok (Int64.div t d)\n\nlet mul_exn t m =\n match t *? Int64.(of_int m) with\n | Ok v ->\n v\n | Error _ ->\n invalid_arg \"mul_exn\"\n\nlet of_mutez t = if t < 0L then None else Some t\n\nlet of_mutez_exn x =\n match of_mutez x with None -> invalid_arg \"Tez.of_mutez\" | Some v -> v\n\nlet to_int64 t = t\n\nlet to_mutez t = t\n\nlet encoding =\n let open Data_encoding in\n Data_encoding.def\n name\n (check_size 10 (conv Z.of_int64 (Json.wrap_error Z.to_int64) n))\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Temporary\n ~id:(id ^ \".addition_overflow\")\n ~title:(\"Overflowing \" ^ id ^ \" addition\")\n ~pp:(fun ppf (opa, opb) ->\n Format.fprintf\n ppf\n \"Overflowing addition of %a %s and %a %s\"\n pp\n opa\n id\n pp\n opb\n id)\n ~description:(\"An addition of two \" ^ id ^ \" amounts overflowed\")\n (obj1 (req \"amounts\" (tup2 encoding encoding)))\n (function Addition_overflow (a, b) -> Some (a, b) | _ -> None)\n (fun (a, b) -> Addition_overflow (a, b)) ;\n register_error_kind\n `Temporary\n ~id:(id ^ \".subtraction_underflow\")\n ~title:(\"Underflowing \" ^ id ^ \" subtraction\")\n ~pp:(fun ppf (opa, opb) ->\n Format.fprintf\n ppf\n \"Underflowing subtraction of %a %s and %a %s\"\n pp\n opa\n id\n pp\n opb\n id)\n ~description:(\"An subtraction of two \" ^ id ^ \" amounts underflowed\")\n (obj1 (req \"amounts\" (tup2 encoding encoding)))\n (function Subtraction_underflow (a, b) -> Some (a, b) | _ -> None)\n (fun (a, b) -> Subtraction_underflow (a, b)) ;\n register_error_kind\n `Temporary\n ~id:(id ^ \".multiplication_overflow\")\n ~title:(\"Overflowing \" ^ id ^ \" multiplication\")\n ~pp:(fun ppf (opa, opb) ->\n Format.fprintf\n ppf\n \"Overflowing multiplication of %a %s and %Ld\"\n pp\n opa\n id\n opb)\n ~description:\n (\"A multiplication of a \" ^ id ^ \" amount by an integer overflowed\")\n (obj2 (req \"amount\" encoding) (req \"multiplicator\" int64))\n (function Multiplication_overflow (a, b) -> Some (a, b) | _ -> None)\n (fun (a, b) -> Multiplication_overflow (a, b)) ;\n register_error_kind\n `Temporary\n ~id:(id ^ \".negative_multiplicator\")\n ~title:(\"Negative \" ^ id ^ \" multiplicator\")\n ~pp:(fun ppf (opa, opb) ->\n Format.fprintf\n ppf\n \"Multiplication of %a %s by negative integer %Ld\"\n pp\n opa\n id\n opb)\n ~description:(\"Multiplication of a \" ^ id ^ \" amount by a negative integer\")\n (obj2 (req \"amount\" encoding) (req \"multiplicator\" int64))\n (function Negative_multiplicator (a, b) -> Some (a, b) | _ -> None)\n (fun (a, b) -> Negative_multiplicator (a, b)) ;\n register_error_kind\n `Temporary\n ~id:(id ^ \".invalid_divisor\")\n ~title:(\"Invalid \" ^ id ^ \" divisor\")\n ~pp:(fun ppf (opa, opb) ->\n Format.fprintf\n ppf\n \"Division of %a %s by non positive integer %Ld\"\n pp\n opa\n id\n opb)\n ~description:\n (\"Multiplication of a \" ^ id ^ \" amount by a non positive integer\")\n (obj2 (req \"amount\" encoding) (req \"divisor\" int64))\n (function Invalid_divisor (a, b) -> Some (a, b) | _ -> None)\n (fun (a, b) -> Invalid_divisor (a, b))\n\ntype tez = t\n" ;
} ;
{ name = "Period_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t\n\ntype period = t\n\ninclude Compare.S with type t := t\n\nval encoding : period Data_encoding.t\n\nval rpc_arg : period RPC_arg.t\n\nval pp : Format.formatter -> period -> unit\n\nval to_seconds : period -> int64\n\n(** [of_second period] fails if period is not positive *)\nval of_seconds : int64 -> period tzresult\n\n(** [of_second period] fails if period is not positive.\n It should only be used at toplevel for constants. *)\nval of_seconds_exn : int64 -> period\n\nval mult : int32 -> period -> period tzresult\n\nval zero : period\n\nval one_second : period\n\nval one_minute : period\n\nval one_hour : period\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = Int64.t\n\ntype period = t\n\ninclude (Compare.Int64 : Compare.S with type t := t)\n\nlet encoding = Data_encoding.int64\n\nlet rpc_arg = RPC_arg.int64\n\nlet pp ppf v = Format.fprintf ppf \"%Ld\" v\n\ntype error += (* `Permanent *)\n Malformed_period | Invalid_arg\n\nlet () =\n let open Data_encoding in\n (* Malformed period *)\n register_error_kind\n `Permanent\n ~id:\"malformed_period\"\n ~title:\"Malformed period\"\n ~description:\"Period is negative.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Malformed period\")\n empty\n (function Malformed_period -> Some () | _ -> None)\n (fun () -> Malformed_period) ;\n (* Invalid arg *)\n register_error_kind\n `Permanent\n ~id:\"invalid_arg\"\n ~title:\"Invalid arg\"\n ~description:\"Negative multiple of periods are not allowed.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Invalid arg\")\n empty\n (function Invalid_arg -> Some () | _ -> None)\n (fun () -> Invalid_arg)\n\nlet of_seconds t =\n if Compare.Int64.(t >= 0L) then ok t else error Malformed_period\n\nlet to_seconds t = t\n\nlet of_seconds_exn t =\n match of_seconds t with\n | Ok t ->\n t\n | _ ->\n invalid_arg \"Period.of_seconds_exn\"\n\nlet mult i p =\n (* TODO check overflow *)\n if Compare.Int32.(i < 0l) then error Invalid_arg\n else ok (Int64.mul (Int64.of_int32 i) p)\n\nlet zero = of_seconds_exn 0L\n\nlet one_second = of_seconds_exn 1L\n\nlet one_minute = of_seconds_exn 60L\n\nlet one_hour = of_seconds_exn 3600L\n" ;
} ;
{ name = "Time_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ninclude module type of struct\n include Time\nend\n\ntype time = t\n\nval pp : Format.formatter -> t -> unit\n\nval of_seconds_string : string -> time option\n\nval to_seconds_string : time -> string\n\nval ( +? ) : time -> Period_repr.t -> time tzresult\n\nval ( -? ) : time -> time -> Period_repr.t tzresult\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ninclude Time\n\ntype time = t\n\ntype error += Timestamp_add (* `Permanent *)\n\ntype error += Timestamp_sub (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"timestamp_add\"\n ~title:\"Timestamp add\"\n ~description:\"Overflow when adding timestamps.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Overflow when adding timestamps.\")\n Data_encoding.empty\n (function Timestamp_add -> Some () | _ -> None)\n (fun () -> Timestamp_add) ;\n register_error_kind\n `Permanent\n ~id:\"timestamp_sub\"\n ~title:\"Timestamp sub\"\n ~description:\"Subtracting timestamps resulted in negative period.\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"Subtracting timestamps resulted in negative period.\")\n Data_encoding.empty\n (function Timestamp_sub -> Some () | _ -> None)\n (fun () -> Timestamp_sub)\n\nlet of_seconds_string s = Option.map of_seconds (Int64.of_string_opt s)\n\nlet to_seconds_string s = Int64.to_string (to_seconds s)\n\nlet pp = pp_hum\n\nlet ( +? ) x y =\n try ok (add x (Period_repr.to_seconds y)) with _exn -> error Timestamp_add\n\nlet ( -? ) x y = record_trace Timestamp_sub (Period_repr.of_seconds (diff x y))\n" ;
} ;
{ name = "Fixed_point_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype fp_tag (* Tag for fixed point computations *)\n\ntype integral_tag (* Tag for integral computations *)\n\nmodule type Safe = sig\n type 'a t\n\n type fp = fp_tag t\n\n type integral = integral_tag t\n\n val integral : Z.t -> integral\n\n val integral_of_int : int -> integral\n\n val integral_to_z : integral -> Z.t\n\n val zero : 'a t\n\n val add : 'a t -> 'a t -> 'a t\n\n val sub : 'a t -> 'a t -> 'a t\n\n val ceil : fp -> integral\n\n val floor : fp -> integral\n\n val fp : 'a t -> fp\n\n val ( = ) : 'a t -> 'b t -> bool\n\n val ( <> ) : 'a t -> 'b t -> bool\n\n val ( < ) : 'a t -> 'b t -> bool\n\n val ( <= ) : 'a t -> 'b t -> bool\n\n val ( >= ) : 'a t -> 'b t -> bool\n\n val ( > ) : 'a t -> 'b t -> bool\n\n val compare : 'a t -> 'b t -> int\n\n val equal : 'a t -> 'b t -> bool\n\n val max : 'a t -> 'a t -> 'a t\n\n val min : 'a t -> 'a t -> 'a t\n\n val pp : Format.formatter -> 'a t -> unit\n\n val pp_integral : Format.formatter -> integral -> unit\n\n val n_fp_encoding : fp Data_encoding.t\n\n val n_integral_encoding : integral Data_encoding.t\n\n val z_fp_encoding : fp Data_encoding.t\n\n val z_integral_encoding : integral Data_encoding.t\nend\n\nmodule type Full = sig\n include Safe\n\n val unsafe_fp : Z.t -> fp\nend\n\nmodule type Decimals = sig\n val decimals : int\nend\n\nmodule Make (Arg : Decimals) : Full\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype fp_tag (* Tag for fixed point computations *)\n\ntype integral_tag (* Tag for integral computations *)\n\nmodule type Safe = sig\n type 'a t\n\n type fp = fp_tag t\n\n type integral = integral_tag t\n\n val integral : Z.t -> integral\n\n val integral_of_int : int -> integral\n\n val integral_to_z : integral -> Z.t\n\n val zero : 'a t\n\n val add : 'a t -> 'a t -> 'a t\n\n val sub : 'a t -> 'a t -> 'a t\n\n val ceil : fp -> integral\n\n val floor : fp -> integral\n\n val fp : 'a t -> fp\n\n val ( = ) : 'a t -> 'b t -> bool\n\n val ( <> ) : 'a t -> 'b t -> bool\n\n val ( < ) : 'a t -> 'b t -> bool\n\n val ( <= ) : 'a t -> 'b t -> bool\n\n val ( >= ) : 'a t -> 'b t -> bool\n\n val ( > ) : 'a t -> 'b t -> bool\n\n val compare : 'a t -> 'b t -> int\n\n val equal : 'a t -> 'b t -> bool\n\n val max : 'a t -> 'a t -> 'a t\n\n val min : 'a t -> 'a t -> 'a t\n\n val pp : Format.formatter -> 'a t -> unit\n\n val pp_integral : Format.formatter -> integral -> unit\n\n val n_fp_encoding : fp Data_encoding.t\n\n val n_integral_encoding : integral Data_encoding.t\n\n val z_fp_encoding : fp Data_encoding.t\n\n val z_integral_encoding : integral Data_encoding.t\nend\n\nmodule type Full = sig\n include Safe\n\n val unsafe_fp : Z.t -> fp\nend\n\nmodule type Decimals = sig\n val decimals : int\nend\n\nmodule Make (Arg : Decimals) : Full = struct\n let () = assert (Compare.Int.(Arg.decimals >= 0))\n\n type 'a t = Z.t\n\n let scaling_factor = Z.pow (Z.of_int 10) Arg.decimals\n\n type fp = fp_tag t\n\n type integral = integral_tag t\n\n let integral z = Z.mul z scaling_factor\n\n let integral_of_int int = integral @@ Z.of_int int\n\n let integral_to_z x = Z.ediv x scaling_factor\n\n let unsafe_fp x = x\n\n let zero = Z.zero\n\n let add = Z.add\n\n let sub = Z.sub\n\n let ceil x =\n let r = Z.erem x scaling_factor in\n if Z.equal r Z.zero then x else Z.add x (Z.sub scaling_factor r)\n\n let floor x =\n let r = Z.ediv_rem x scaling_factor |> snd in\n if Z.equal r Z.zero then x else Z.sub x r\n\n let fp x = x\n\n let ( = ) = Compare.Z.( = )\n\n let ( <> ) = Compare.Z.( <> )\n\n let ( < ) = Compare.Z.( < )\n\n let ( <= ) = Compare.Z.( <= )\n\n let ( >= ) = Compare.Z.( >= )\n\n let ( > ) = Compare.Z.( > )\n\n let compare = Z.compare\n\n let equal = Z.equal\n\n let max = Compare.Z.max\n\n let min = Compare.Z.min\n\n let pp_positive_fp fmtr milligas =\n if Compare.Int.(Arg.decimals <> 3) then\n Format.fprintf fmtr \"pp_positive_fp: cannot print (decimals <> 3)\"\n else\n let (q, r) = Z.ediv_rem milligas scaling_factor in\n if Z.equal r Z.zero then Z.pp_print fmtr q\n else Format.fprintf fmtr \"%a.%03d\" Z.pp_print q (Z.to_int r)\n\n let pp fmtr fp =\n if Compare.Z.(fp >= Z.zero) then pp_positive_fp fmtr fp\n else Format.fprintf fmtr \"-%a\" pp_positive_fp (Z.neg fp)\n\n let pp_integral = pp\n\n let n_fp_encoding : fp Data_encoding.t = Data_encoding.n\n\n let z_fp_encoding : fp Data_encoding.t = Data_encoding.z\n\n let n_integral_encoding : integral Data_encoding.t =\n Data_encoding.conv integral_to_z integral Data_encoding.n\n\n let z_integral_encoding : integral Data_encoding.t =\n Data_encoding.conv integral_to_z integral Data_encoding.z\nend\n" ;
} ;
{ name = "Gas_limit_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule Arith : Fixed_point_repr.Full\n\ntype t = Unaccounted | Limited of {remaining : Arith.fp}\n\nval encoding : t Data_encoding.encoding\n\nval pp : Format.formatter -> t -> unit\n\ntype cost = Z.t\n\nval cost_encoding : cost Data_encoding.encoding\n\nval pp_cost : Format.formatter -> cost -> unit\n\ntype error += Block_quota_exceeded (* `Temporary *)\n\ntype error += Operation_quota_exceeded (* `Temporary *)\n\nval raw_consume : Arith.fp -> t -> cost -> (Arith.fp * t) tzresult\n\nval raw_check_enough : Arith.fp -> t -> cost -> unit tzresult\n\nval free : cost\n\nval atomic_step_cost : Z.t -> cost\n\nval step_cost : Z.t -> cost\n\nval alloc_cost : Z.t -> cost\n\nval alloc_bytes_cost : int -> cost\n\nval alloc_mbytes_cost : int -> cost\n\nval read_bytes_cost : Z.t -> cost\n\nval write_bytes_cost : Z.t -> cost\n\nval ( *@ ) : Z.t -> cost -> cost\n\nval ( +@ ) : cost -> cost -> cost\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet scaling_factor = 1000\n\nlet decimals = 3\n\nmodule Arith = Fixed_point_repr.Make (struct\n let decimals = decimals\nend)\n\ntype t = Unaccounted | Limited of {remaining : Arith.fp}\n\ntype cost = Z.t\n\nlet encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"Limited\"\n Arith.z_fp_encoding\n (function Limited {remaining} -> Some remaining | _ -> None)\n (fun remaining -> Limited {remaining});\n case\n (Tag 1)\n ~title:\"Unaccounted\"\n (constant \"unaccounted\")\n (function Unaccounted -> Some () | _ -> None)\n (fun () -> Unaccounted) ]\n\nlet pp ppf = function\n | Unaccounted ->\n Format.fprintf ppf \"unaccounted\"\n | Limited {remaining} ->\n Format.fprintf ppf \"%a units remaining\" Arith.pp remaining\n\nlet cost_encoding = Data_encoding.z\n\nlet pp_cost fmt z = Z.pp_print fmt z\n\ntype error += Block_quota_exceeded (* `Temporary *)\n\ntype error += Operation_quota_exceeded (* `Temporary *)\n\nlet allocation_weight = Z.of_int (scaling_factor * 2)\n\nlet step_weight = Z.of_int scaling_factor\n\nlet read_base_weight = Z.of_int (scaling_factor * 100)\n\nlet write_base_weight = Z.of_int (scaling_factor * 160)\n\nlet byte_read_weight = Z.of_int (scaling_factor * 10)\n\nlet byte_written_weight = Z.of_int (scaling_factor * 15)\n\nlet cost_to_milligas (cost : cost) : Arith.fp = Arith.unsafe_fp cost\n\nlet raw_consume block_gas operation_gas cost =\n match operation_gas with\n | Unaccounted ->\n ok (block_gas, Unaccounted)\n | Limited {remaining} ->\n let gas = cost_to_milligas cost in\n if Arith.(gas > zero) then\n let remaining = Arith.sub remaining gas in\n let block_remaining = Arith.sub block_gas gas in\n if Arith.(remaining < zero) then error Operation_quota_exceeded\n else if Arith.(block_remaining < zero) then error Block_quota_exceeded\n else ok (block_remaining, Limited {remaining})\n else ok (block_gas, operation_gas)\n\nlet raw_check_enough block_gas operation_gas cost =\n raw_consume block_gas operation_gas cost\n >|? fun (_block_remaining, _remaining) -> ()\n\nlet alloc_cost n = Z.mul allocation_weight (Z.succ n)\n\nlet alloc_bytes_cost n = alloc_cost (Z.of_int ((n + 7) / 8))\n\nlet atomic_step_cost n = n\n\nlet step_cost n = Z.mul step_weight n\n\nlet free = Z.zero\n\nlet read_bytes_cost n = Z.add read_base_weight (Z.mul byte_read_weight n)\n\nlet write_bytes_cost n = Z.add write_base_weight (Z.mul byte_written_weight n)\n\nlet ( +@ ) x y = Z.add x y\n\nlet ( *@ ) x y = Z.mul x y\n\nlet alloc_mbytes_cost n = alloc_cost (Z.of_int 12) +@ alloc_bytes_cost n\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Temporary\n ~id:\"gas_exhausted.operation\"\n ~title:\"Gas quota exceeded for the operation\"\n ~description:\n \"A script or one of its callee took more time than the operation said \\\n it would\"\n empty\n (function Operation_quota_exceeded -> Some () | _ -> None)\n (fun () -> Operation_quota_exceeded) ;\n register_error_kind\n `Temporary\n ~id:\"gas_exhausted.block\"\n ~title:\"Gas quota exceeded for the block\"\n ~description:\n \"The sum of gas consumed by all the operations in the block exceeds the \\\n hard gas limit per block\"\n empty\n (function Block_quota_exceeded -> Some () | _ -> None)\n (fun () -> Block_quota_exceeded)\n" ;
} ;
{ name = "Constants_repr" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet version_number_004 = \"\\000\"\n\nlet version_number = \"\\001\"\n\nlet proof_of_work_nonce_size = 8\n\nlet nonce_length = 32\n\nlet max_anon_ops_per_block = 132\n\nlet max_proposals_per_delegate = 20\n\nlet max_operation_data_length = 16 * 1024 (* 16kB *)\n\ntype fixed = {\n proof_of_work_nonce_size : int;\n nonce_length : int;\n max_anon_ops_per_block : int;\n max_operation_data_length : int;\n max_proposals_per_delegate : int;\n}\n\nlet fixed_encoding =\n let open Data_encoding in\n conv\n (fun c ->\n ( c.proof_of_work_nonce_size,\n c.nonce_length,\n c.max_anon_ops_per_block,\n c.max_operation_data_length,\n c.max_proposals_per_delegate ))\n (fun ( proof_of_work_nonce_size,\n nonce_length,\n max_anon_ops_per_block,\n max_operation_data_length,\n max_proposals_per_delegate ) ->\n {\n proof_of_work_nonce_size;\n nonce_length;\n max_anon_ops_per_block;\n max_operation_data_length;\n max_proposals_per_delegate;\n })\n (obj5\n (req \"proof_of_work_nonce_size\" uint8)\n (req \"nonce_length\" uint8)\n (req \"max_anon_ops_per_block\" uint8)\n (req \"max_operation_data_length\" int31)\n (req \"max_proposals_per_delegate\" uint8))\n\nlet fixed =\n {\n proof_of_work_nonce_size;\n nonce_length;\n max_anon_ops_per_block;\n max_operation_data_length;\n max_proposals_per_delegate;\n }\n\ntype parametric = {\n preserved_cycles : int;\n blocks_per_cycle : int32;\n blocks_per_commitment : int32;\n blocks_per_roll_snapshot : int32;\n blocks_per_voting_period : int32;\n time_between_blocks : Period_repr.t list;\n endorsers_per_block : int;\n hard_gas_limit_per_operation : Gas_limit_repr.Arith.integral;\n hard_gas_limit_per_block : Gas_limit_repr.Arith.integral;\n proof_of_work_threshold : int64;\n tokens_per_roll : Tez_repr.t;\n michelson_maximum_type_size : int;\n seed_nonce_revelation_tip : Tez_repr.t;\n origination_size : int;\n block_security_deposit : Tez_repr.t;\n endorsement_security_deposit : Tez_repr.t;\n baking_reward_per_endorsement : Tez_repr.t list;\n endorsement_reward : Tez_repr.t list;\n cost_per_byte : Tez_repr.t;\n hard_storage_limit_per_operation : Z.t;\n test_chain_duration : int64;\n (* in seconds *)\n quorum_min : int32;\n quorum_max : int32;\n min_proposal_quorum : int32;\n initial_endorsers : int;\n delay_per_missing_endorsement : Period_repr.t;\n}\n\nlet parametric_encoding =\n let open Data_encoding in\n conv\n (fun c ->\n ( ( c.preserved_cycles,\n c.blocks_per_cycle,\n c.blocks_per_commitment,\n c.blocks_per_roll_snapshot,\n c.blocks_per_voting_period,\n c.time_between_blocks,\n c.endorsers_per_block,\n c.hard_gas_limit_per_operation,\n c.hard_gas_limit_per_block ),\n ( ( c.proof_of_work_threshold,\n c.tokens_per_roll,\n c.michelson_maximum_type_size,\n c.seed_nonce_revelation_tip,\n c.origination_size,\n c.block_security_deposit,\n c.endorsement_security_deposit,\n c.baking_reward_per_endorsement ),\n ( c.endorsement_reward,\n c.cost_per_byte,\n c.hard_storage_limit_per_operation,\n c.test_chain_duration,\n c.quorum_min,\n c.quorum_max,\n c.min_proposal_quorum,\n c.initial_endorsers,\n c.delay_per_missing_endorsement ) ) ))\n (fun ( ( preserved_cycles,\n blocks_per_cycle,\n blocks_per_commitment,\n blocks_per_roll_snapshot,\n blocks_per_voting_period,\n time_between_blocks,\n endorsers_per_block,\n hard_gas_limit_per_operation,\n hard_gas_limit_per_block ),\n ( ( proof_of_work_threshold,\n tokens_per_roll,\n michelson_maximum_type_size,\n seed_nonce_revelation_tip,\n origination_size,\n block_security_deposit,\n endorsement_security_deposit,\n baking_reward_per_endorsement ),\n ( endorsement_reward,\n cost_per_byte,\n hard_storage_limit_per_operation,\n test_chain_duration,\n quorum_min,\n quorum_max,\n min_proposal_quorum,\n initial_endorsers,\n delay_per_missing_endorsement ) ) ) ->\n {\n preserved_cycles;\n blocks_per_cycle;\n blocks_per_commitment;\n blocks_per_roll_snapshot;\n blocks_per_voting_period;\n time_between_blocks;\n endorsers_per_block;\n hard_gas_limit_per_operation;\n hard_gas_limit_per_block;\n proof_of_work_threshold;\n tokens_per_roll;\n michelson_maximum_type_size;\n seed_nonce_revelation_tip;\n origination_size;\n block_security_deposit;\n endorsement_security_deposit;\n baking_reward_per_endorsement;\n endorsement_reward;\n cost_per_byte;\n hard_storage_limit_per_operation;\n test_chain_duration;\n quorum_min;\n quorum_max;\n min_proposal_quorum;\n initial_endorsers;\n delay_per_missing_endorsement;\n })\n (merge_objs\n (obj9\n (req \"preserved_cycles\" uint8)\n (req \"blocks_per_cycle\" int32)\n (req \"blocks_per_commitment\" int32)\n (req \"blocks_per_roll_snapshot\" int32)\n (req \"blocks_per_voting_period\" int32)\n (req \"time_between_blocks\" (list Period_repr.encoding))\n (req \"endorsers_per_block\" uint16)\n (req\n \"hard_gas_limit_per_operation\"\n Gas_limit_repr.Arith.z_integral_encoding)\n (req\n \"hard_gas_limit_per_block\"\n Gas_limit_repr.Arith.z_integral_encoding))\n (merge_objs\n (obj8\n (req \"proof_of_work_threshold\" int64)\n (req \"tokens_per_roll\" Tez_repr.encoding)\n (req \"michelson_maximum_type_size\" uint16)\n (req \"seed_nonce_revelation_tip\" Tez_repr.encoding)\n (req \"origination_size\" int31)\n (req \"block_security_deposit\" Tez_repr.encoding)\n (req \"endorsement_security_deposit\" Tez_repr.encoding)\n (req \"baking_reward_per_endorsement\" (list Tez_repr.encoding)))\n (obj9\n (req \"endorsement_reward\" (list Tez_repr.encoding))\n (req \"cost_per_byte\" Tez_repr.encoding)\n (req \"hard_storage_limit_per_operation\" z)\n (req \"test_chain_duration\" int64)\n (req \"quorum_min\" int32)\n (req \"quorum_max\" int32)\n (req \"min_proposal_quorum\" int32)\n (req \"initial_endorsers\" uint16)\n (req \"delay_per_missing_endorsement\" Period_repr.encoding))))\n\ntype t = {fixed : fixed; parametric : parametric}\n\nlet encoding =\n let open Data_encoding in\n conv\n (fun {fixed; parametric} -> (fixed, parametric))\n (fun (fixed, parametric) -> {fixed; parametric})\n (merge_objs fixed_encoding parametric_encoding)\n" ;
} ;
{ name = "Fitness_repr" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error += Invalid_fitness (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"invalid_fitness\"\n ~title:\"Invalid fitness\"\n ~description:\"Fitness representation should be exactly 8 bytes long.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Invalid fitness\")\n Data_encoding.empty\n (function Invalid_fitness -> Some () | _ -> None)\n (fun () -> Invalid_fitness)\n\nlet int64_to_bytes i =\n let b = Bytes.make 8 '0' in\n TzEndian.set_int64 b 0 i ; b\n\nlet int64_of_bytes b =\n if Compare.Int.(Bytes.length b <> 8) then error Invalid_fitness\n else ok (TzEndian.get_int64 b 0)\n\nlet from_int64 fitness =\n [Bytes.of_string Constants_repr.version_number; int64_to_bytes fitness]\n\nlet to_int64 = function\n | [version; fitness]\n when Compare.String.(\n Bytes.to_string version = Constants_repr.version_number) ->\n int64_of_bytes fitness\n | [version; _fitness (* ignored since higher version takes priority *)]\n when Compare.String.(\n Bytes.to_string version = Constants_repr.version_number_004) ->\n ok 0L\n | [] ->\n ok 0L\n | _ ->\n error Invalid_fitness\n" ;
} ;
{ name = "Raw_level_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** The shell's notion of a level: an integer indicating the number of blocks\n since genesis: genesis is 0, all other blocks have increasing levels from\n there. *)\ntype t\n\ntype raw_level = t\n\nval encoding : raw_level Data_encoding.t\n\nval rpc_arg : raw_level RPC_arg.arg\n\nval pp : Format.formatter -> raw_level -> unit\n\ninclude Compare.S with type t := raw_level\n\nval to_int32 : raw_level -> int32\n\nval of_int32_exn : int32 -> raw_level\n\nval of_int32 : int32 -> raw_level tzresult\n\nval diff : raw_level -> raw_level -> int32\n\nval root : raw_level\n\nval succ : raw_level -> raw_level\n\nval pred : raw_level -> raw_level option\n\nmodule Index : Storage_description.INDEX with type t = raw_level\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = int32\n\ntype raw_level = t\n\ninclude (Compare.Int32 : Compare.S with type t := t)\n\nlet encoding = Data_encoding.int32\n\nlet pp ppf level = Format.fprintf ppf \"%ld\" level\n\nlet rpc_arg =\n let construct raw_level = Int32.to_string raw_level in\n let destruct str =\n Int32.of_string_opt str |> Option.to_result ~none:\"Cannot parse level\"\n in\n RPC_arg.make\n ~descr:\"A level integer\"\n ~name:\"block_level\"\n ~construct\n ~destruct\n ()\n\nlet root = 0l\n\nlet succ = Int32.succ\n\nlet pred l = if l = 0l then None else Some (Int32.pred l)\n\nlet diff = Int32.sub\n\nlet to_int32 l = l\n\nlet of_int32_exn l =\n if Compare.Int32.(l >= 0l) then l else invalid_arg \"Level_repr.of_int32\"\n\ntype error += Unexpected_level of Int32.t (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"unexpected_level\"\n ~title:\"Unexpected level\"\n ~description:\"Level must be non-negative.\"\n ~pp:(fun ppf l ->\n Format.fprintf\n ppf\n \"The level is %s but should be non-negative.\"\n (Int32.to_string l))\n Data_encoding.(obj1 (req \"level\" int32))\n (function Unexpected_level l -> Some l | _ -> None)\n (fun l -> Unexpected_level l)\n\nlet of_int32 l = try Ok (of_int32_exn l) with _ -> error (Unexpected_level l)\n\nmodule Index = struct\n type t = raw_level\n\n let path_length = 1\n\n let to_path level l = Int32.to_string level :: l\n\n let of_path = function [s] -> Int32.of_string_opt s | _ -> None\n\n let rpc_arg = rpc_arg\n\n let encoding = encoding\n\n let compare = compare\nend\n" ;
} ;
{ name = "Cycle_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t\n\ntype cycle = t\n\ninclude Compare.S with type t := t\n\nval encoding : cycle Data_encoding.t\n\nval rpc_arg : cycle RPC_arg.arg\n\nval pp : Format.formatter -> cycle -> unit\n\nval root : cycle\n\nval pred : cycle -> cycle option\n\nval add : cycle -> int -> cycle\n\nval sub : cycle -> int -> cycle option\n\nval succ : cycle -> cycle\n\nval to_int32 : cycle -> int32\n\nval of_int32_exn : int32 -> cycle\n\nmodule Map : S.MAP with type key = cycle\n\nmodule Index : Storage_description.INDEX with type t = cycle\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = int32\n\ntype cycle = t\n\nlet encoding = Data_encoding.int32\n\nlet rpc_arg =\n let construct = Int32.to_string in\n let destruct str =\n Int32.of_string_opt str |> Option.to_result ~none:\"Cannot parse cycle\"\n in\n RPC_arg.make\n ~descr:\"A cycle integer\"\n ~name:\"block_cycle\"\n ~construct\n ~destruct\n ()\n\nlet pp ppf cycle = Format.fprintf ppf \"%ld\" cycle\n\ninclude (Compare.Int32 : Compare.S with type t := t)\n\nmodule Map = Map.Make (Compare.Int32)\n\nlet root = 0l\n\nlet succ = Int32.succ\n\nlet pred = function 0l -> None | i -> Some (Int32.pred i)\n\nlet add c i =\n assert (Compare.Int.(i >= 0)) ;\n Int32.add c (Int32.of_int i)\n\nlet sub c i =\n assert (Compare.Int.(i >= 0)) ;\n let r = Int32.sub c (Int32.of_int i) in\n if Compare.Int32.(r < 0l) then None else Some r\n\nlet to_int32 i = i\n\nlet of_int32_exn l =\n if Compare.Int32.(l >= 0l) then l\n else invalid_arg \"Level_repr.Cycle.of_int32\"\n\nmodule Index = struct\n type t = cycle\n\n let path_length = 1\n\n let to_path c l = Int32.to_string (to_int32 c) :: l\n\n let of_path = function [s] -> Int32.of_string_opt s | _ -> None\n\n let rpc_arg = rpc_arg\n\n let encoding = encoding\n\n let compare = compare\nend\n" ;
} ;
{ name = "Level_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = private {\n level : Raw_level_repr.t;\n (** The level of the block relative to genesis. This\n is also the Shell's notion of level. *)\n level_position : int32;\n (** The level of the block relative to the block that started the first\n version of protocol alpha. *)\n cycle : Cycle_repr.t;\n (** The current cycle's number. Note that cycles are a protocol-specific\n notion. As a result, the cycle number starts at 0 with the first block of\n the first version of protocol alpha. *)\n cycle_position : int32;\n (** The current level of the block relative to the first block of the current\n cycle. *)\n expected_commitment : bool;\n}\n\n(* Note that, the type `t` above must respect some invariants (hence the\n `private` annotation). Notably:\n\n level_position = cycle * blocks_per_cycle + cycle_position\n*)\n\ntype level = t\n\ninclude Compare.S with type t := level\n\nval encoding : level Data_encoding.t\n\nval pp : Format.formatter -> level -> unit\n\nval pp_full : Format.formatter -> level -> unit\n\nval root_level : Raw_level_repr.t -> level\n\nval level_from_raw :\n first_level:Raw_level_repr.t ->\n blocks_per_cycle:int32 ->\n blocks_per_commitment:int32 ->\n Raw_level_repr.t ->\n level\n\nval diff : level -> level -> int32\n\n(** Compatibility module with Level_repr.t from protocol 007.\n In this version, the [voting_period] and [voting_period_position] fields are\n deprecated and replaced by a new RPC endpoint at\n [Voting_services.voting_period] *)\ntype compat_t = {\n level : Raw_level_repr.t;\n level_position : int32;\n cycle : Cycle_repr.t;\n cycle_position : int32;\n voting_period : int32;\n voting_period_position : int32;\n expected_commitment : bool;\n}\n\nval compat_encoding : compat_t Data_encoding.t\n\nval to_deprecated_type :\n t -> voting_period_index:int32 -> voting_period_position:int32 -> compat_t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = {\n level : Raw_level_repr.t;\n level_position : int32;\n cycle : Cycle_repr.t;\n cycle_position : int32;\n expected_commitment : bool;\n}\n\ninclude Compare.Make (struct\n type nonrec t = t\n\n let compare {level = l1} {level = l2} = Raw_level_repr.compare l1 l2\nend)\n\ntype level = t\n\nlet pp ppf {level} = Raw_level_repr.pp ppf level\n\nlet pp_full ppf l =\n Format.fprintf\n ppf\n \"%a.%ld (cycle %a.%ld)\"\n Raw_level_repr.pp\n l.level\n l.level_position\n Cycle_repr.pp\n l.cycle\n l.cycle_position\n\nlet encoding =\n let open Data_encoding in\n conv\n (fun {level; level_position; cycle; cycle_position; expected_commitment} ->\n (level, level_position, cycle, cycle_position, expected_commitment))\n (fun (level, level_position, cycle, cycle_position, expected_commitment) ->\n {level; level_position; cycle; cycle_position; expected_commitment})\n (obj5\n (req\n \"level\"\n ~description:\n \"The level of the block relative to genesis. This is also the \\\n Shell's notion of level\"\n Raw_level_repr.encoding)\n (req\n \"level_position\"\n ~description:\n \"The level of the block relative to the block that starts \\\n protocol alpha. This is specific to the protocol alpha. Other \\\n protocols might or might not include a similar notion.\"\n int32)\n (req\n \"cycle\"\n ~description:\n \"The current cycle's number. Note that cycles are a \\\n protocol-specific notion. As a result, the cycle number starts \\\n at 0 with the first block of protocol alpha.\"\n Cycle_repr.encoding)\n (req\n \"cycle_position\"\n ~description:\n \"The current level of the block relative to the first block of \\\n the current cycle.\"\n int32)\n (req\n \"expected_commitment\"\n ~description:\n \"Tells wether the baker of this block has to commit a seed nonce \\\n hash.\"\n bool))\n\nlet root_level first_level =\n {\n level = first_level;\n level_position = 0l;\n cycle = Cycle_repr.root;\n cycle_position = 0l;\n expected_commitment = false;\n }\n\nlet level_from_raw ~first_level ~blocks_per_cycle ~blocks_per_commitment level\n =\n let raw_level = Raw_level_repr.to_int32 level in\n let first_level = Raw_level_repr.to_int32 first_level in\n let level_position =\n Compare.Int32.max 0l (Int32.sub raw_level first_level)\n in\n let cycle =\n Cycle_repr.of_int32_exn (Int32.div level_position blocks_per_cycle)\n in\n let cycle_position = Int32.rem level_position blocks_per_cycle in\n let expected_commitment =\n Compare.Int32.(\n Int32.rem cycle_position blocks_per_commitment\n = Int32.pred blocks_per_commitment)\n in\n {level; level_position; cycle; cycle_position; expected_commitment}\n\nlet diff {level = l1; _} {level = l2; _} =\n Int32.sub (Raw_level_repr.to_int32 l1) (Raw_level_repr.to_int32 l2)\n\ntype compat_t = {\n level : Raw_level_repr.t;\n level_position : int32;\n cycle : Cycle_repr.t;\n cycle_position : int32;\n voting_period : int32;\n voting_period_position : int32;\n expected_commitment : bool;\n}\n\nlet compat_encoding =\n let open Data_encoding in\n conv\n (fun { level;\n level_position;\n cycle;\n cycle_position;\n voting_period;\n voting_period_position;\n expected_commitment } ->\n ( level,\n level_position,\n cycle,\n cycle_position,\n voting_period,\n voting_period_position,\n expected_commitment ))\n (fun ( level,\n level_position,\n cycle,\n cycle_position,\n voting_period,\n voting_period_position,\n expected_commitment ) ->\n {\n level;\n level_position;\n cycle;\n cycle_position;\n voting_period;\n voting_period_position;\n expected_commitment;\n })\n (obj7\n (req\n \"level\"\n ~description:\n \"The level of the block relative to genesis. This is also the \\\n Shell's notion of level\"\n Raw_level_repr.encoding)\n (req\n \"level_position\"\n ~description:\n \"The level of the block relative to the block that starts \\\n protocol alpha. This is specific to the protocol alpha. Other \\\n protocols might or might not include a similar notion.\"\n int32)\n (req\n \"cycle\"\n ~description:\n \"The current cycle's number. Note that cycles are a \\\n protocol-specific notion. As a result, the cycle number starts \\\n at 0 with the first block of protocol alpha.\"\n Cycle_repr.encoding)\n (req\n \"cycle_position\"\n ~description:\n \"The current level of the block relative to the first block of \\\n the current cycle.\"\n int32)\n (req\n \"voting_period\"\n ~description:\n \"The current voting period's index. Note that cycles are a \\\n protocol-specific notion. As a result, the voting period index \\\n starts at 0 with the first block of protocol alpha. This field \\\n is DEPRECATED: use `..<block_id>/votes/voting_period` RPC \\\n instead.\"\n int32)\n (req\n \"voting_period_position\"\n ~description:\n \"The current level of the block relative to the first block of \\\n the current voting period. This field is DEPRECATED: use \\\n `..<block_id>/votes/voting_period` RPC instead.\"\n int32)\n (req\n \"expected_commitment\"\n ~description:\n \"Tells wether the baker of this block has to commit a seed nonce \\\n hash.\"\n bool))\n\nlet to_deprecated_type\n ({level; level_position; cycle; cycle_position; expected_commitment} : t)\n ~voting_period_index ~voting_period_position =\n {\n level;\n level_position;\n cycle;\n cycle_position;\n voting_period = voting_period_index;\n voting_period_position;\n expected_commitment;\n }\n" ;
} ;
{ name = "Seed_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Tezos Protocol Implementation - Random number generation\n\n This is not expected to be a good cryptographic random number\n generator. In particular this is supposed to be used in situations\n where the seed is a globally known information.\n\n The only expected property is: It should be difficult to find a\n seed such that the generated sequence is a given one. *)\n\n(** {2 Random Generation} *)\n\n(** The state of the random number generator *)\ntype t\n\n(** A random seed, to derive random sequences from *)\ntype seed\n\n(** A random sequence, to derive random values from *)\ntype sequence\n\n(** [initialize_new state ident] returns a new generator *)\nval initialize_new : seed -> bytes list -> t\n\n(** [sequence state n] prepares the n-th sequence of a state *)\nval sequence : t -> int32 -> sequence\n\n(** Generates the next random value in the sequence *)\nval take : sequence -> bytes * sequence\n\n(** Generates the next random value as a bounded [int32] *)\nval take_int32 : sequence -> int32 -> int32 * sequence\n\n(** {2 Predefined seeds} *)\n\nval empty : seed\n\n(** Returns a new seed by hashing the one passed with a constant. *)\nval deterministic_seed : seed -> seed\n\n(** [initial_seeds n] generates the first [n] seeds for which there are no nonces.\n The first seed is a constant value. The kth seed is the hash of seed (k-1)\n concatenated with a constant. *)\nval initial_seeds : int -> seed list\n\n(** {2 Entropy} *)\n\n(** A nonce for adding entropy to the generator *)\ntype nonce\n\n(** Add entropy to the seed generator *)\nval nonce : seed -> nonce -> seed\n\n(** Use a byte sequence as a nonce *)\nval make_nonce : bytes -> nonce tzresult\n\n(** Compute the has of a nonce *)\nval hash : nonce -> Nonce_hash.t\n\n(** [check_hash nonce hash] is true if the nonce correspond to the hash *)\nval check_hash : nonce -> Nonce_hash.t -> bool\n\n(** For using nonce hashes as keys in the hierarchical database *)\nval nonce_hash_key_part : Nonce_hash.t -> string list -> string list\n\n(** {2 Predefined nonce} *)\n\nval initial_nonce_0 : nonce\n\nval initial_nonce_hash_0 : Nonce_hash.t\n\n(** {2 Serializers} *)\n\nval nonce_encoding : nonce Data_encoding.t\n\nval seed_encoding : seed Data_encoding.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* Tezos Protocol Implementation - Random number generation *)\n\ntype seed = B of State_hash.t\n\ntype t = T of State_hash.t\n\ntype sequence = S of State_hash.t\n\ntype nonce = bytes\n\nlet nonce_encoding = Data_encoding.Fixed.bytes Constants_repr.nonce_length\n\nlet initial_seed = \"Laissez-faire les proprietaires.\"\n\nlet zero_bytes = Bytes.make Nonce_hash.size '\\000'\n\nlet state_hash_encoding =\n let open Data_encoding in\n conv\n State_hash.to_bytes\n State_hash.of_bytes_exn\n (Fixed.bytes Nonce_hash.size)\n\nlet seed_encoding =\n let open Data_encoding in\n conv (fun (B b) -> b) (fun b -> B b) state_hash_encoding\n\nlet empty = B (State_hash.hash_bytes [Bytes.of_string initial_seed])\n\nlet nonce (B state) nonce =\n B (State_hash.hash_bytes [State_hash.to_bytes state; nonce])\n\nlet initialize_new (B state) append =\n T (State_hash.hash_bytes (State_hash.to_bytes state :: zero_bytes :: append))\n\nlet xor_higher_bits i b =\n let higher = TzEndian.get_int32 b 0 in\n let r = Int32.logxor higher i in\n let res = Bytes.copy b in\n TzEndian.set_int32 res 0 r ; res\n\nlet sequence (T state) n =\n State_hash.to_bytes state |> xor_higher_bits n\n |> fun b -> S (State_hash.hash_bytes [b])\n\nlet take (S state) =\n let b = State_hash.to_bytes state in\n let h = State_hash.hash_bytes [b] in\n (State_hash.to_bytes h, S h)\n\nlet take_int32 s bound =\n if Compare.Int32.(bound <= 0l) then invalid_arg \"Seed_repr.take_int32\"\n (* FIXME *)\n else\n let rec loop s =\n let (bytes, s) = take s in\n let r = Int32.abs (TzEndian.get_int32 bytes 0) in\n let drop_if_over =\n Int32.sub Int32.max_int (Int32.rem Int32.max_int bound)\n in\n if Compare.Int32.(r >= drop_if_over) then loop s\n else\n let v = Int32.rem r bound in\n (v, s)\n in\n loop s\n\ntype error += Unexpected_nonce_length (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"unexpected_nonce_length\"\n ~title:\"Unexpected nonce length\"\n ~description:\"Nonce length is incorrect.\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"Nonce length is not %i bytes long as it should.\"\n Constants_repr.nonce_length)\n Data_encoding.empty\n (function Unexpected_nonce_length -> Some () | _ -> None)\n (fun () -> Unexpected_nonce_length)\n\nlet make_nonce nonce =\n if Compare.Int.(Bytes.length nonce <> Constants_repr.nonce_length) then\n error Unexpected_nonce_length\n else ok nonce\n\nlet hash nonce = Nonce_hash.hash_bytes [nonce]\n\nlet check_hash nonce hash =\n Compare.Int.(Bytes.length nonce = Constants_repr.nonce_length)\n && Nonce_hash.equal (Nonce_hash.hash_bytes [nonce]) hash\n\nlet nonce_hash_key_part = Nonce_hash.to_path\n\nlet initial_nonce_0 = zero_bytes\n\nlet initial_nonce_hash_0 = hash initial_nonce_0\n\nlet deterministic_seed seed = nonce seed zero_bytes\n\nlet initial_seeds n =\n let rec loop acc elt i =\n if Compare.Int.(i = 1) then List.rev (elt :: acc)\n else loop (elt :: acc) (deterministic_seed elt) (i - 1)\n in\n loop [] (B (State_hash.hash_bytes [])) n\n" ;
} ;
{ name = "Voting_period_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** The voting period kinds are ordered as follows:\n Proposal -> Testing_vote -> Testing -> Promotion_vote -> Adoption.\n This order is the one used be the function [succ] below.\n *)\ntype kind =\n | Proposal (** protocols can be proposed *)\n | Testing_vote (** a proposal can be voted *)\n | Testing (** winning proposal is forked on a testnet *)\n | Promotion_vote (** activation can be voted *)\n | Adoption (** a delay before activation *)\n\nval kind_encoding : kind Data_encoding.t\n\n(** A voting period can be of 5 kinds and is uniquely identified by a counter\n since the root. *)\ntype voting_period = {index : Int32.t; kind : kind; start_position : Int32.t}\n\ntype t = voting_period\n\ntype info = {voting_period : t; position : Int32.t; remaining : Int32.t}\n\nval root : start_position:Int32.t -> t\n\ninclude Compare.S with type t := voting_period\n\nval encoding : t Data_encoding.t\n\nval info_encoding : info Data_encoding.t\n\nval pp : Format.formatter -> t -> unit\n\nval pp_info : Format.formatter -> info -> unit\n\nval pp_kind : Format.formatter -> kind -> unit\n\n(** [reset period ~start_position] increment the index by one and set the kind\n to Proposal which is the period kind that start the voting\n process. [start_position] is the level at wich this voting_period started.\n*)\nval reset : t -> start_position:Int32.t -> t\n\n(** [succ period ~start_position] increment the index by one and set the kind to\n its successor. [start_position] is the level at which this voting_period\n started. *)\nval succ : t -> start_position:Int32.t -> t\n\nval position_since : Level_repr.t -> t -> Int32.t\n\nval remaining_blocks :\n Level_repr.t -> t -> blocks_per_voting_period:Int32.t -> Int32.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype kind = Proposal | Testing_vote | Testing | Promotion_vote | Adoption\n\nlet string_of_kind = function\n | Proposal ->\n \"proposal\"\n | Testing_vote ->\n \"testing_vote\"\n | Testing ->\n \"testing\"\n | Promotion_vote ->\n \"promotion_vote\"\n | Adoption ->\n \"adoption\"\n\nlet pp_kind ppf kind = Format.fprintf ppf \"%s\" @@ string_of_kind kind\n\nlet kind_encoding =\n let open Data_encoding in\n union\n ~tag_size:`Uint8\n [ case\n (Tag 0)\n ~title:\"Proposal\"\n (constant \"proposal\")\n (function Proposal -> Some () | _ -> None)\n (fun () -> Proposal);\n case\n (Tag 1)\n ~title:\"Testing_vote\"\n (constant \"testing_vote\")\n (function Testing_vote -> Some () | _ -> None)\n (fun () -> Testing_vote);\n case\n (Tag 2)\n ~title:\"Testing\"\n (constant \"testing\")\n (function Testing -> Some () | _ -> None)\n (fun () -> Testing);\n case\n (Tag 3)\n ~title:\"Promotion_vote\"\n (constant \"promotion_vote\")\n (function Promotion_vote -> Some () | _ -> None)\n (fun () -> Promotion_vote);\n case\n (Tag 4)\n ~title:\"Adoption\"\n (constant \"adoption\")\n (function Adoption -> Some () | _ -> None)\n (fun () -> Adoption) ]\n\nlet succ_kind = function\n | Proposal ->\n Testing_vote\n | Testing_vote ->\n Testing\n | Testing ->\n Promotion_vote\n | Promotion_vote ->\n Adoption\n | Adoption ->\n Proposal\n\ntype voting_period = {index : int32; kind : kind; start_position : int32}\n\ntype t = voting_period\n\ntype info = {voting_period : t; position : int32; remaining : int32}\n\nlet root ~start_position = {index = 0l; kind = Proposal; start_position}\n\nlet pp ppf {index; kind; start_position} =\n Format.fprintf\n ppf\n \"@[<hv 2>index: %ld@ ,kind:%a@, start_position: %ld@]\"\n index\n pp_kind\n kind\n start_position\n\nlet pp_info ppf {voting_period; position; remaining} =\n Format.fprintf\n ppf\n \"@[<hv 2>voting_period: %a@ ,position:%ld@, remaining: %ld@]\"\n pp\n voting_period\n position\n remaining\n\nlet encoding =\n let open Data_encoding in\n conv\n (fun {index; kind; start_position} -> (index, kind, start_position))\n (fun (index, kind, start_position) -> {index; kind; start_position})\n (obj3\n (req\n \"index\"\n ~description:\n \"The voting period's index. Starts at 0 with the first block of \\\n protocol alpha.\"\n int32)\n (req \"kind\" kind_encoding)\n (req \"start_position\" int32))\n\nlet info_encoding =\n let open Data_encoding in\n conv\n (fun {voting_period; position; remaining} ->\n (voting_period, position, remaining))\n (fun (voting_period, position, remaining) ->\n {voting_period; position; remaining})\n (obj3\n (req \"voting_period\" encoding)\n (req \"position\" int32)\n (req \"remaining\" int32))\n\ninclude Compare.Make (struct\n type nonrec t = t\n\n let compare p p' = Compare.Int32.compare p.index p'.index\nend)\n\nlet reset period ~start_position =\n let index = Int32.succ period.index in\n let kind = Proposal in\n {index; kind; start_position}\n\nlet succ period ~start_position =\n let index = Int32.succ period.index in\n let kind = succ_kind period.kind in\n {index; kind; start_position}\n\nlet position_since (level : Level_repr.t) (voting_period : t) =\n Int32.(sub level.level_position voting_period.start_position)\n\nlet remaining_blocks (level : Level_repr.t) (voting_period : t)\n ~blocks_per_voting_period =\n let position = position_since level voting_period in\n Int32.(sub blocks_per_voting_period (succ position))\n" ;
} ;
{ name = "Script_int_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** The types for arbitrary precision integers in Michelson.\n The type variable ['t] is always [n] or [z],\n [n num] and [z num] are incompatible.\n\n This is internally a [Z.t].\n This module mostly adds signedness preservation guarantees. *)\ntype 't num\n\n(** Flag for natural numbers. *)\ntype n = Natural_tag\n\n(** Flag for relative numbers. *)\ntype z = Integer_tag\n\n(** Natural zero. *)\nval zero_n : n num\n\n(** Relative zero. *)\nval zero : z num\n\n(** Compare two numbers as if they were *)\nval compare : 'a num -> 'a num -> int\n\n(** Conversion to an OCaml [string] in decimal notation. *)\nval to_string : _ num -> string\n\n(** Conversion from an OCaml [string].\n Returns [None] in case of an invalid notation.\n Supports [+] and [-] sign modifiers, and [0x], [0o] and [0b] base modifiers. *)\nval of_string : string -> z num option\n\n(** Conversion from an OCaml [int32]. *)\nval of_int32 : int32 -> z num\n\n(** Conversion to an OCaml [int64], returns [None] on overflow. *)\nval to_int64 : _ num -> int64 option\n\n(** Conversion from an OCaml [int64]. *)\nval of_int64 : int64 -> z num\n\n(** Conversion to an OCaml [int], returns [None] on overflow. *)\nval to_int : _ num -> int option\n\n(** Conversion from an OCaml [int]. *)\nval of_int : int -> z num\n\n(** Conversion from a Zarith integer ([Z.t]). *)\nval of_zint : Z.t -> z num\n\n(** Conversion to a Zarith integer ([Z.t]). *)\nval to_zint : 'a num -> Z.t\n\n(** Addition between naturals. *)\nval add_n : n num -> n num -> n num\n\n(** Multiplication between naturals. *)\nval mul_n : n num -> n num -> n num\n\n(** Euclidean division between naturals.\n [ediv_n n d] returns [None] if divisor is zero,\n or [Some (q, r)] where [n = d * q + r] and [[0 <= r < d]] otherwise. *)\nval ediv_n : n num -> n num -> (n num * n num) option\n\n(** Sign agnostic addition.\n Use {!add_n} when working with naturals to preserve the sign. *)\nval add : _ num -> _ num -> z num\n\n(** Sign agnostic subtraction.\n Use {!sub_n} when working with naturals to preserve the sign. *)\nval sub : _ num -> _ num -> z num\n\n(** Sign agnostic multiplication.\n Use {!mul_n} when working with naturals to preserve the sign. *)\nval mul : _ num -> _ num -> z num\n\n(** Sign agnostic euclidean division.\n [ediv n d] returns [None] if divisor is zero,\n or [Some (q, r)] where [n = d * q + r] and [[0 <= r < |d|]] otherwise.\n Use {!ediv_n} when working with naturals to preserve the sign. *)\nval ediv : _ num -> _ num -> (z num * n num) option\n\n(** Compute the absolute value of a relative, turning it into a natural. *)\nval abs : z num -> n num\n\n(** Partial identity over [N]. *)\nval is_nat : z num -> n num option\n\n(** Negates a number. *)\nval neg : _ num -> z num\n\n(** Turns a natural into a relative, not changing its value. *)\nval int : n num -> z num\n\n(** Reverses each bit in the representation of the number.\n Also applies to the sign. *)\nval lognot : _ num -> z num\n\n(** Shifts the natural to the left of a number of bits between 0 and 256.\n Returns [None] if the amount is too high. *)\nval shift_left_n : n num -> n num -> n num option\n\n(** Shifts the natural to the right of a number of bits between 0 and 256.\n Returns [None] if the amount is too high. *)\nval shift_right_n : n num -> n num -> n num option\n\n(** Shifts the number to the left of a number of bits between 0 and 256.\n Returns [None] if the amount is too high. *)\nval shift_left : 'a num -> n num -> 'a num option\n\n(** Shifts the number to the right of a number of bits between 0 and 256.\n Returns [None] if the amount is too high. *)\nval shift_right : 'a num -> n num -> 'a num option\n\n(** Applies a boolean or operation to each bit. *)\nval logor : 'a num -> 'a num -> 'a num\n\n(** Applies a boolean and operation to each bit. *)\nval logand : _ num -> n num -> n num\n\n(** Applies a boolean xor operation to each bit. *)\nval logxor : n num -> n num -> n num\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype n = Natural_tag\n\ntype z = Integer_tag\n\ntype 't num = Z.t\n\nlet compare x y = Z.compare x y\n\nlet zero = Z.zero\n\nlet zero_n = Z.zero\n\nlet to_string x = Z.to_string x\n\nlet of_string s = try Some (Z.of_string s) with _ -> None\n\nlet of_int32 n = Z.of_int64 @@ Int64.of_int32 n\n\nlet to_int64 x = try Some (Z.to_int64 x) with _ -> None\n\nlet of_int64 n = Z.of_int64 n\n\nlet to_int x = try Some (Z.to_int x) with _ -> None\n\nlet of_int n = Z.of_int n\n\nlet of_zint x = x\n\nlet to_zint x = x\n\nlet add x y = Z.add x y\n\nlet sub x y = Z.sub x y\n\nlet mul x y = Z.mul x y\n\nlet ediv x y =\n try\n let (q, r) = Z.ediv_rem x y in\n Some (q, r)\n with _ -> None\n\nlet add_n = add\n\nlet mul_n = mul\n\nlet ediv_n = ediv\n\nlet abs x = Z.abs x\n\nlet is_nat x = if Compare.Z.(x < Z.zero) then None else Some x\n\nlet neg x = Z.neg x\n\nlet int x = x\n\nlet shift_left x y =\n if Compare.Int.(Z.compare y (Z.of_int 256) > 0) then None\n else\n let y = Z.to_int y in\n Some (Z.shift_left x y)\n\nlet shift_right x y =\n if Compare.Int.(Z.compare y (Z.of_int 256) > 0) then None\n else\n let y = Z.to_int y in\n Some (Z.shift_right x y)\n\nlet shift_left_n = shift_left\n\nlet shift_right_n = shift_right\n\nlet logor x y = Z.logor x y\n\nlet logxor x y = Z.logxor x y\n\nlet logand x y = Z.logand x y\n\nlet lognot x = Z.lognot x\n" ;
} ;
{ name = "Script_timestamp_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Script_int_repr\n\ntype t\n\nval of_int64 : int64 -> t\n\nval compare : t -> t -> int\n\n(* Convert a timestamp to a notation if possible *)\nval to_notation : t -> string option\n\n(* Convert a timestamp to a string representation of the seconds *)\nval to_num_str : t -> string\n\n(* Convert to a notation if possible, or num if not *)\nval to_string : t -> string\n\nval of_string : string -> t option\n\nval diff : t -> t -> z num\n\nval add_delta : t -> z num -> t\n\nval sub_delta : t -> z num -> t\n\nval to_zint : t -> Z.t\n\nval of_zint : Z.t -> t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = Z.t\n\nlet compare = Z.compare\n\nlet of_int64 = Z.of_int64\n\nlet of_string x =\n match Time_repr.of_notation x with\n | None -> (\n try Some (Z.of_string x) with _ -> None )\n | Some time ->\n Some (of_int64 (Time_repr.to_seconds time))\n\nlet to_notation x =\n try\n let notation = Time_repr.to_notation (Time.of_seconds (Z.to_int64 x)) in\n if String.equal notation \"out_of_range\" then None else Some notation\n with _ -> None\n\nlet to_num_str = Z.to_string\n\nlet to_string x = match to_notation x with None -> to_num_str x | Some s -> s\n\nlet diff x y = Script_int_repr.of_zint @@ Z.sub x y\n\nlet sub_delta t delta = Z.sub t (Script_int_repr.to_zint delta)\n\nlet add_delta t delta = Z.add t (Script_int_repr.to_zint delta)\n\nlet to_zint x = x\n\nlet of_zint x = x\n" ;
} ;
{ name = "Michelson_v1_primitives" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error += (* `Permanent *) Unknown_primitive_name of string\n\ntype error += (* `Permanent *) Invalid_case of string\n\ntype error +=\n | (* `Permanent *)\n Invalid_primitive_name of\n string Micheline.canonical * Micheline.canonical_location\n\ntype prim =\n | K_parameter\n | K_storage\n | K_code\n | D_False\n | D_Elt\n | D_Left\n | D_None\n | D_Pair\n | D_Right\n | D_Some\n | D_True\n | D_Unit\n | I_PACK\n | I_UNPACK\n | I_BLAKE2B\n | I_SHA256\n | I_SHA512\n | I_ABS\n | I_ADD\n | I_AMOUNT\n | I_AND\n | I_BALANCE\n | I_CAR\n | I_CDR\n | I_CHAIN_ID\n | I_CHECK_SIGNATURE\n | I_COMPARE\n | I_CONCAT\n | I_CONS\n | I_CREATE_ACCOUNT\n | I_CREATE_CONTRACT\n | I_IMPLICIT_ACCOUNT\n | I_DIP\n | I_DROP\n | I_DUP\n | I_EDIV\n | I_EMPTY_BIG_MAP\n | I_EMPTY_MAP\n | I_EMPTY_SET\n | I_EQ\n | I_EXEC\n | I_APPLY\n | I_FAILWITH\n | I_GE\n | I_GET\n | I_GET_AND_UPDATE\n | I_GT\n | I_HASH_KEY\n | I_IF\n | I_IF_CONS\n | I_IF_LEFT\n | I_IF_NONE\n | I_INT\n | I_LAMBDA\n | I_LE\n | I_LEFT\n | I_LEVEL\n | I_LOOP\n | I_LSL\n | I_LSR\n | I_LT\n | I_MAP\n | I_MEM\n | I_MUL\n | I_NEG\n | I_NEQ\n | I_NIL\n | I_NONE\n | I_NOT\n | I_NOW\n | I_OR\n | I_PAIR\n | I_UNPAIR\n | I_PUSH\n | I_RIGHT\n | I_SIZE\n | I_SOME\n | I_SOURCE\n | I_SENDER\n | I_SELF\n | I_SELF_ADDRESS\n | I_SLICE\n | I_STEPS_TO_QUOTA\n | I_SUB\n | I_SWAP\n | I_TRANSFER_TOKENS\n | I_SET_DELEGATE\n | I_UNIT\n | I_UPDATE\n | I_XOR\n | I_ITER\n | I_LOOP_LEFT\n | I_ADDRESS\n | I_CONTRACT\n | I_ISNAT\n | I_CAST\n | I_RENAME\n | I_SAPLING_EMPTY_STATE\n | I_SAPLING_VERIFY_UPDATE\n | I_DIG\n | I_DUG\n | I_NEVER\n | I_VOTING_POWER\n | I_TOTAL_VOTING_POWER\n | I_KECCAK\n | I_SHA3\n | I_PAIRING_CHECK\n | I_TICKET\n | I_READ_TICKET\n | I_SPLIT_TICKET\n | I_JOIN_TICKETS\n | T_bool\n | T_contract\n | T_int\n | T_key\n | T_key_hash\n | T_lambda\n | T_list\n | T_map\n | T_big_map\n | T_nat\n | T_option\n | T_or\n | T_pair\n | T_set\n | T_signature\n | T_string\n | T_bytes\n | T_mutez\n | T_timestamp\n | T_unit\n | T_operation\n | T_address\n | T_sapling_transaction\n | T_sapling_state\n | T_chain_id\n | T_never\n | T_bls12_381_g1\n | T_bls12_381_g2\n | T_bls12_381_fr\n | T_ticket\n\n(** Auxiliary types for error documentation.\n All the prim constructor prefixes must match their namespace. *)\ntype namespace =\n | (* prefix \"T\" *) Type_namespace\n | (* prefix \"D\" *) Constant_namespace\n | (* prefix \"I\" *) Instr_namespace\n | (* prefix \"K\" *) Keyword_namespace\n\nval namespace : prim -> namespace\n\nval prim_encoding : prim Data_encoding.encoding\n\nval string_of_prim : prim -> string\n\nval prim_of_string : string -> prim tzresult\n\nval prims_of_strings :\n string Micheline.canonical -> prim Micheline.canonical tzresult\n\nval strings_of_prims : prim Micheline.canonical -> string Micheline.canonical\n\n(** The string corresponds to the constructor prefix from the given namespace\n (i.e. \"T\", \"D\", \"I\" or \"K\") *)\nval string_of_namespace : namespace -> string\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Micheline\n\ntype error += Unknown_primitive_name of string\n\ntype error += Invalid_case of string\n\ntype error +=\n | Invalid_primitive_name of\n string Micheline.canonical * Micheline.canonical_location\n\ntype prim =\n | K_parameter\n | K_storage\n | K_code\n | D_False\n | D_Elt\n | D_Left\n | D_None\n | D_Pair\n | D_Right\n | D_Some\n | D_True\n | D_Unit\n | I_PACK\n | I_UNPACK\n | I_BLAKE2B\n | I_SHA256\n | I_SHA512\n | I_ABS\n | I_ADD\n | I_AMOUNT\n | I_AND\n | I_BALANCE\n | I_CAR\n | I_CDR\n | I_CHAIN_ID\n | I_CHECK_SIGNATURE\n | I_COMPARE\n | I_CONCAT\n | I_CONS\n | I_CREATE_ACCOUNT\n | I_CREATE_CONTRACT\n | I_IMPLICIT_ACCOUNT\n | I_DIP\n | I_DROP\n | I_DUP\n | I_EDIV\n | I_EMPTY_BIG_MAP\n | I_EMPTY_MAP\n | I_EMPTY_SET\n | I_EQ\n | I_EXEC\n | I_APPLY\n | I_FAILWITH\n | I_GE\n | I_GET\n | I_GET_AND_UPDATE\n | I_GT\n | I_HASH_KEY\n | I_IF\n | I_IF_CONS\n | I_IF_LEFT\n | I_IF_NONE\n | I_INT\n | I_LAMBDA\n | I_LE\n | I_LEFT\n | I_LEVEL\n | I_LOOP\n | I_LSL\n | I_LSR\n | I_LT\n | I_MAP\n | I_MEM\n | I_MUL\n | I_NEG\n | I_NEQ\n | I_NIL\n | I_NONE\n | I_NOT\n | I_NOW\n | I_OR\n | I_PAIR\n | I_UNPAIR\n | I_PUSH\n | I_RIGHT\n | I_SIZE\n | I_SOME\n | I_SOURCE\n | I_SENDER\n | I_SELF\n | I_SELF_ADDRESS\n | I_SLICE\n | I_STEPS_TO_QUOTA\n | I_SUB\n | I_SWAP\n | I_TRANSFER_TOKENS\n | I_SET_DELEGATE\n | I_UNIT\n | I_UPDATE\n | I_XOR\n | I_ITER\n | I_LOOP_LEFT\n | I_ADDRESS\n | I_CONTRACT\n | I_ISNAT\n | I_CAST\n | I_RENAME\n | I_SAPLING_EMPTY_STATE\n | I_SAPLING_VERIFY_UPDATE\n | I_DIG\n | I_DUG\n | I_NEVER\n | I_VOTING_POWER\n | I_TOTAL_VOTING_POWER\n | I_KECCAK\n | I_SHA3\n | I_PAIRING_CHECK\n | I_TICKET\n | I_READ_TICKET\n | I_SPLIT_TICKET\n | I_JOIN_TICKETS\n | T_bool\n | T_contract\n | T_int\n | T_key\n | T_key_hash\n | T_lambda\n | T_list\n | T_map\n | T_big_map\n | T_nat\n | T_option\n | T_or\n | T_pair\n | T_set\n | T_signature\n | T_string\n | T_bytes\n | T_mutez\n | T_timestamp\n | T_unit\n | T_operation\n | T_address\n | T_sapling_transaction\n | T_sapling_state\n | T_chain_id\n | T_never\n | T_bls12_381_g1\n | T_bls12_381_g2\n | T_bls12_381_fr\n | T_ticket\n\n(* Auxiliary types for error documentation.\n All the prim constructor prefixes must match their namespace. *)\ntype namespace =\n | (* prefix \"T\" *) Type_namespace\n | (* prefix \"D\" *) Constant_namespace\n | (* prefix \"I\" *) Instr_namespace\n | (* prefix \"K\" *) Keyword_namespace\n\nlet namespace = function\n | K_code | K_parameter | K_storage ->\n Keyword_namespace\n | D_Elt\n | D_False\n | D_Left\n | D_None\n | D_Pair\n | D_Right\n | D_Some\n | D_True\n | D_Unit ->\n Constant_namespace\n | I_ABS\n | I_ADD\n | I_ADDRESS\n | I_AMOUNT\n | I_AND\n | I_APPLY\n | I_BALANCE\n | I_BLAKE2B\n | I_CAR\n | I_CAST\n | I_CDR\n | I_CHAIN_ID\n | I_CHECK_SIGNATURE\n | I_COMPARE\n | I_CONCAT\n | I_CONS\n | I_CONTRACT\n | I_CREATE_ACCOUNT\n | I_CREATE_CONTRACT\n | I_DIG\n | I_DIP\n | I_DROP\n | I_DUG\n | I_DUP\n | I_EDIV\n | I_EMPTY_BIG_MAP\n | I_EMPTY_MAP\n | I_EMPTY_SET\n | I_EQ\n | I_EXEC\n | I_FAILWITH\n | I_GE\n | I_GET\n | I_GET_AND_UPDATE\n | I_GT\n | I_HASH_KEY\n | I_IF\n | I_IF_CONS\n | I_IF_LEFT\n | I_IF_NONE\n | I_IMPLICIT_ACCOUNT\n | I_INT\n | I_ISNAT\n | I_ITER\n | I_JOIN_TICKETS\n | I_KECCAK\n | I_LAMBDA\n | I_LE\n | I_LEFT\n | I_LEVEL\n | I_LOOP\n | I_LOOP_LEFT\n | I_LSL\n | I_LSR\n | I_LT\n | I_MAP\n | I_MEM\n | I_MUL\n | I_NEG\n | I_NEQ\n | I_NEVER\n | I_NIL\n | I_NONE\n | I_NOT\n | I_NOW\n | I_OR\n | I_PACK\n | I_PAIR\n | I_PAIRING_CHECK\n | I_PUSH\n | I_READ_TICKET\n | I_RENAME\n | I_RIGHT\n | I_SAPLING_EMPTY_STATE\n | I_SAPLING_VERIFY_UPDATE\n | I_SELF\n | I_SELF_ADDRESS\n | I_SENDER\n | I_SET_DELEGATE\n | I_SHA256\n | I_SHA512\n | I_SHA3\n | I_SIZE\n | I_SLICE\n | I_SOME\n | I_SOURCE\n | I_SPLIT_TICKET\n | I_STEPS_TO_QUOTA\n | I_SUB\n | I_SWAP\n | I_TICKET\n | I_TOTAL_VOTING_POWER\n | I_TRANSFER_TOKENS\n | I_UNIT\n | I_UNPACK\n | I_UNPAIR\n | I_UPDATE\n | I_VOTING_POWER\n | I_XOR ->\n Instr_namespace\n | T_address\n | T_big_map\n | T_bool\n | T_bytes\n | T_chain_id\n | T_contract\n | T_int\n | T_key\n | T_key_hash\n | T_lambda\n | T_list\n | T_map\n | T_mutez\n | T_nat\n | T_never\n | T_operation\n | T_option\n | T_or\n | T_pair\n | T_sapling_state\n | T_sapling_transaction\n | T_set\n | T_signature\n | T_string\n | T_timestamp\n | T_unit\n | T_bls12_381_fr\n | T_bls12_381_g1\n | T_bls12_381_g2\n | T_ticket ->\n Type_namespace\n\nlet valid_case name =\n let is_lower = function '_' | 'a' .. 'z' -> true | _ -> false in\n let is_upper = function '_' | 'A' .. 'Z' -> true | _ -> false in\n let rec for_all a b f =\n Compare.Int.(a > b) || (f a && for_all (a + 1) b f)\n in\n let len = String.length name in\n Compare.Int.(len <> 0)\n && Compare.Char.(name.[0] <> '_')\n && ( (is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_upper name.[i]))\n || (is_upper name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i]))\n || (is_lower name.[0] && for_all 1 (len - 1) (fun i -> is_lower name.[i]))\n )\n\nlet string_of_prim = function\n | K_parameter ->\n \"parameter\"\n | K_storage ->\n \"storage\"\n | K_code ->\n \"code\"\n | D_False ->\n \"False\"\n | D_Elt ->\n \"Elt\"\n | D_Left ->\n \"Left\"\n | D_None ->\n \"None\"\n | D_Pair ->\n \"Pair\"\n | D_Right ->\n \"Right\"\n | D_Some ->\n \"Some\"\n | D_True ->\n \"True\"\n | D_Unit ->\n \"Unit\"\n | I_PACK ->\n \"PACK\"\n | I_UNPACK ->\n \"UNPACK\"\n | I_BLAKE2B ->\n \"BLAKE2B\"\n | I_SHA256 ->\n \"SHA256\"\n | I_SHA512 ->\n \"SHA512\"\n | I_ABS ->\n \"ABS\"\n | I_ADD ->\n \"ADD\"\n | I_AMOUNT ->\n \"AMOUNT\"\n | I_AND ->\n \"AND\"\n | I_BALANCE ->\n \"BALANCE\"\n | I_CAR ->\n \"CAR\"\n | I_CDR ->\n \"CDR\"\n | I_CHAIN_ID ->\n \"CHAIN_ID\"\n | I_CHECK_SIGNATURE ->\n \"CHECK_SIGNATURE\"\n | I_COMPARE ->\n \"COMPARE\"\n | I_CONCAT ->\n \"CONCAT\"\n | I_CONS ->\n \"CONS\"\n | I_CREATE_ACCOUNT ->\n \"CREATE_ACCOUNT\"\n | I_CREATE_CONTRACT ->\n \"CREATE_CONTRACT\"\n | I_IMPLICIT_ACCOUNT ->\n \"IMPLICIT_ACCOUNT\"\n | I_DIP ->\n \"DIP\"\n | I_DROP ->\n \"DROP\"\n | I_DUP ->\n \"DUP\"\n | I_EDIV ->\n \"EDIV\"\n | I_EMPTY_BIG_MAP ->\n \"EMPTY_BIG_MAP\"\n | I_EMPTY_MAP ->\n \"EMPTY_MAP\"\n | I_EMPTY_SET ->\n \"EMPTY_SET\"\n | I_EQ ->\n \"EQ\"\n | I_EXEC ->\n \"EXEC\"\n | I_APPLY ->\n \"APPLY\"\n | I_FAILWITH ->\n \"FAILWITH\"\n | I_GE ->\n \"GE\"\n | I_GET ->\n \"GET\"\n | I_GET_AND_UPDATE ->\n \"GET_AND_UPDATE\"\n | I_GT ->\n \"GT\"\n | I_HASH_KEY ->\n \"HASH_KEY\"\n | I_IF ->\n \"IF\"\n | I_IF_CONS ->\n \"IF_CONS\"\n | I_IF_LEFT ->\n \"IF_LEFT\"\n | I_IF_NONE ->\n \"IF_NONE\"\n | I_INT ->\n \"INT\"\n | I_LAMBDA ->\n \"LAMBDA\"\n | I_LE ->\n \"LE\"\n | I_LEFT ->\n \"LEFT\"\n | I_LEVEL ->\n \"LEVEL\"\n | I_LOOP ->\n \"LOOP\"\n | I_LSL ->\n \"LSL\"\n | I_LSR ->\n \"LSR\"\n | I_LT ->\n \"LT\"\n | I_MAP ->\n \"MAP\"\n | I_MEM ->\n \"MEM\"\n | I_MUL ->\n \"MUL\"\n | I_NEG ->\n \"NEG\"\n | I_NEQ ->\n \"NEQ\"\n | I_NIL ->\n \"NIL\"\n | I_NONE ->\n \"NONE\"\n | I_NOT ->\n \"NOT\"\n | I_NOW ->\n \"NOW\"\n | I_OR ->\n \"OR\"\n | I_PAIR ->\n \"PAIR\"\n | I_PUSH ->\n \"PUSH\"\n | I_RIGHT ->\n \"RIGHT\"\n | I_SIZE ->\n \"SIZE\"\n | I_SOME ->\n \"SOME\"\n | I_SOURCE ->\n \"SOURCE\"\n | I_SENDER ->\n \"SENDER\"\n | I_SELF ->\n \"SELF\"\n | I_SELF_ADDRESS ->\n \"SELF_ADDRESS\"\n | I_SLICE ->\n \"SLICE\"\n | I_STEPS_TO_QUOTA ->\n \"STEPS_TO_QUOTA\"\n | I_SUB ->\n \"SUB\"\n | I_SWAP ->\n \"SWAP\"\n | I_TRANSFER_TOKENS ->\n \"TRANSFER_TOKENS\"\n | I_SET_DELEGATE ->\n \"SET_DELEGATE\"\n | I_UNIT ->\n \"UNIT\"\n | I_UNPAIR ->\n \"UNPAIR\"\n | I_UPDATE ->\n \"UPDATE\"\n | I_XOR ->\n \"XOR\"\n | I_ITER ->\n \"ITER\"\n | I_LOOP_LEFT ->\n \"LOOP_LEFT\"\n | I_ADDRESS ->\n \"ADDRESS\"\n | I_CONTRACT ->\n \"CONTRACT\"\n | I_ISNAT ->\n \"ISNAT\"\n | I_CAST ->\n \"CAST\"\n | I_RENAME ->\n \"RENAME\"\n | I_SAPLING_EMPTY_STATE ->\n \"SAPLING_EMPTY_STATE\"\n | I_SAPLING_VERIFY_UPDATE ->\n \"SAPLING_VERIFY_UPDATE\"\n | I_DIG ->\n \"DIG\"\n | I_DUG ->\n \"DUG\"\n | I_NEVER ->\n \"NEVER\"\n | I_VOTING_POWER ->\n \"VOTING_POWER\"\n | I_TOTAL_VOTING_POWER ->\n \"TOTAL_VOTING_POWER\"\n | I_KECCAK ->\n \"KECCAK\"\n | I_SHA3 ->\n \"SHA3\"\n | I_PAIRING_CHECK ->\n \"PAIRING_CHECK\"\n | I_TICKET ->\n \"TICKET\"\n | I_READ_TICKET ->\n \"READ_TICKET\"\n | I_SPLIT_TICKET ->\n \"SPLIT_TICKET\"\n | I_JOIN_TICKETS ->\n \"JOIN_TICKETS\"\n | T_bool ->\n \"bool\"\n | T_contract ->\n \"contract\"\n | T_int ->\n \"int\"\n | T_key ->\n \"key\"\n | T_key_hash ->\n \"key_hash\"\n | T_lambda ->\n \"lambda\"\n | T_list ->\n \"list\"\n | T_map ->\n \"map\"\n | T_big_map ->\n \"big_map\"\n | T_nat ->\n \"nat\"\n | T_option ->\n \"option\"\n | T_or ->\n \"or\"\n | T_pair ->\n \"pair\"\n | T_set ->\n \"set\"\n | T_signature ->\n \"signature\"\n | T_string ->\n \"string\"\n | T_bytes ->\n \"bytes\"\n | T_mutez ->\n \"mutez\"\n | T_timestamp ->\n \"timestamp\"\n | T_unit ->\n \"unit\"\n | T_operation ->\n \"operation\"\n | T_address ->\n \"address\"\n | T_sapling_state ->\n \"sapling_state\"\n | T_sapling_transaction ->\n \"sapling_transaction\"\n | T_chain_id ->\n \"chain_id\"\n | T_never ->\n \"never\"\n | T_bls12_381_g1 ->\n \"bls12_381_g1\"\n | T_bls12_381_g2 ->\n \"bls12_381_g2\"\n | T_bls12_381_fr ->\n \"bls12_381_fr\"\n | T_ticket ->\n \"ticket\"\n\nlet prim_of_string = function\n | \"parameter\" ->\n ok K_parameter\n | \"storage\" ->\n ok K_storage\n | \"code\" ->\n ok K_code\n | \"False\" ->\n ok D_False\n | \"Elt\" ->\n ok D_Elt\n | \"Left\" ->\n ok D_Left\n | \"None\" ->\n ok D_None\n | \"Pair\" ->\n ok D_Pair\n | \"Right\" ->\n ok D_Right\n | \"Some\" ->\n ok D_Some\n | \"True\" ->\n ok D_True\n | \"Unit\" ->\n ok D_Unit\n | \"PACK\" ->\n ok I_PACK\n | \"UNPACK\" ->\n ok I_UNPACK\n | \"BLAKE2B\" ->\n ok I_BLAKE2B\n | \"SHA256\" ->\n ok I_SHA256\n | \"SHA512\" ->\n ok I_SHA512\n | \"ABS\" ->\n ok I_ABS\n | \"ADD\" ->\n ok I_ADD\n | \"AMOUNT\" ->\n ok I_AMOUNT\n | \"AND\" ->\n ok I_AND\n | \"BALANCE\" ->\n ok I_BALANCE\n | \"CAR\" ->\n ok I_CAR\n | \"CDR\" ->\n ok I_CDR\n | \"CHAIN_ID\" ->\n ok I_CHAIN_ID\n | \"CHECK_SIGNATURE\" ->\n ok I_CHECK_SIGNATURE\n | \"COMPARE\" ->\n ok I_COMPARE\n | \"CONCAT\" ->\n ok I_CONCAT\n | \"CONS\" ->\n ok I_CONS\n | \"CREATE_ACCOUNT\" ->\n ok I_CREATE_ACCOUNT\n | \"CREATE_CONTRACT\" ->\n ok I_CREATE_CONTRACT\n | \"IMPLICIT_ACCOUNT\" ->\n ok I_IMPLICIT_ACCOUNT\n | \"DIP\" ->\n ok I_DIP\n | \"DROP\" ->\n ok I_DROP\n | \"DUP\" ->\n ok I_DUP\n | \"EDIV\" ->\n ok I_EDIV\n | \"EMPTY_BIG_MAP\" ->\n ok I_EMPTY_BIG_MAP\n | \"EMPTY_MAP\" ->\n ok I_EMPTY_MAP\n | \"EMPTY_SET\" ->\n ok I_EMPTY_SET\n | \"EQ\" ->\n ok I_EQ\n | \"EXEC\" ->\n ok I_EXEC\n | \"APPLY\" ->\n ok I_APPLY\n | \"FAILWITH\" ->\n ok I_FAILWITH\n | \"GE\" ->\n ok I_GE\n | \"GET\" ->\n ok I_GET\n | \"GET_AND_UPDATE\" ->\n ok I_GET_AND_UPDATE\n | \"GT\" ->\n ok I_GT\n | \"HASH_KEY\" ->\n ok I_HASH_KEY\n | \"IF\" ->\n ok I_IF\n | \"IF_CONS\" ->\n ok I_IF_CONS\n | \"IF_LEFT\" ->\n ok I_IF_LEFT\n | \"IF_NONE\" ->\n ok I_IF_NONE\n | \"INT\" ->\n ok I_INT\n | \"KECCAK\" ->\n ok I_KECCAK\n | \"LAMBDA\" ->\n ok I_LAMBDA\n | \"LE\" ->\n ok I_LE\n | \"LEFT\" ->\n ok I_LEFT\n | \"LEVEL\" ->\n ok I_LEVEL\n | \"LOOP\" ->\n ok I_LOOP\n | \"LSL\" ->\n ok I_LSL\n | \"LSR\" ->\n ok I_LSR\n | \"LT\" ->\n ok I_LT\n | \"MAP\" ->\n ok I_MAP\n | \"MEM\" ->\n ok I_MEM\n | \"MUL\" ->\n ok I_MUL\n | \"NEG\" ->\n ok I_NEG\n | \"NEQ\" ->\n ok I_NEQ\n | \"NIL\" ->\n ok I_NIL\n | \"NONE\" ->\n ok I_NONE\n | \"NOT\" ->\n ok I_NOT\n | \"NOW\" ->\n ok I_NOW\n | \"OR\" ->\n ok I_OR\n | \"PAIR\" ->\n ok I_PAIR\n | \"UNPAIR\" ->\n ok I_UNPAIR\n | \"PAIRING_CHECK\" ->\n ok I_PAIRING_CHECK\n | \"PUSH\" ->\n ok I_PUSH\n | \"RIGHT\" ->\n ok I_RIGHT\n | \"SHA3\" ->\n ok I_SHA3\n | \"SIZE\" ->\n ok I_SIZE\n | \"SOME\" ->\n ok I_SOME\n | \"SOURCE\" ->\n ok I_SOURCE\n | \"SENDER\" ->\n ok I_SENDER\n | \"SELF\" ->\n ok I_SELF\n | \"SELF_ADDRESS\" ->\n ok I_SELF_ADDRESS\n | \"SLICE\" ->\n ok I_SLICE\n | \"STEPS_TO_QUOTA\" ->\n ok I_STEPS_TO_QUOTA\n | \"SUB\" ->\n ok I_SUB\n | \"SWAP\" ->\n ok I_SWAP\n | \"TRANSFER_TOKENS\" ->\n ok I_TRANSFER_TOKENS\n | \"SET_DELEGATE\" ->\n ok I_SET_DELEGATE\n | \"UNIT\" ->\n ok I_UNIT\n | \"UPDATE\" ->\n ok I_UPDATE\n | \"XOR\" ->\n ok I_XOR\n | \"ITER\" ->\n ok I_ITER\n | \"LOOP_LEFT\" ->\n ok I_LOOP_LEFT\n | \"ADDRESS\" ->\n ok I_ADDRESS\n | \"CONTRACT\" ->\n ok I_CONTRACT\n | \"ISNAT\" ->\n ok I_ISNAT\n | \"CAST\" ->\n ok I_CAST\n | \"RENAME\" ->\n ok I_RENAME\n | \"SAPLING_EMPTY_STATE\" ->\n ok I_SAPLING_EMPTY_STATE\n | \"SAPLING_VERIFY_UPDATE\" ->\n ok I_SAPLING_VERIFY_UPDATE\n | \"DIG\" ->\n ok I_DIG\n | \"DUG\" ->\n ok I_DUG\n | \"NEVER\" ->\n ok I_NEVER\n | \"VOTING_POWER\" ->\n ok I_VOTING_POWER\n | \"TOTAL_VOTING_POWER\" ->\n ok I_TOTAL_VOTING_POWER\n | \"TICKET\" ->\n ok I_TICKET\n | \"READ_TICKET\" ->\n ok I_READ_TICKET\n | \"SPLIT_TICKET\" ->\n ok I_SPLIT_TICKET\n | \"JOIN_TICKETS\" ->\n ok I_JOIN_TICKETS\n | \"bool\" ->\n ok T_bool\n | \"contract\" ->\n ok T_contract\n | \"int\" ->\n ok T_int\n | \"key\" ->\n ok T_key\n | \"key_hash\" ->\n ok T_key_hash\n | \"lambda\" ->\n ok T_lambda\n | \"list\" ->\n ok T_list\n | \"map\" ->\n ok T_map\n | \"big_map\" ->\n ok T_big_map\n | \"nat\" ->\n ok T_nat\n | \"option\" ->\n ok T_option\n | \"or\" ->\n ok T_or\n | \"pair\" ->\n ok T_pair\n | \"set\" ->\n ok T_set\n | \"signature\" ->\n ok T_signature\n | \"string\" ->\n ok T_string\n | \"bytes\" ->\n ok T_bytes\n | \"mutez\" ->\n ok T_mutez\n | \"timestamp\" ->\n ok T_timestamp\n | \"unit\" ->\n ok T_unit\n | \"operation\" ->\n ok T_operation\n | \"address\" ->\n ok T_address\n | \"sapling_state\" ->\n ok T_sapling_state\n | \"sapling_transaction\" ->\n ok T_sapling_transaction\n | \"chain_id\" ->\n ok T_chain_id\n | \"never\" ->\n ok T_never\n | \"bls12_381_g1\" ->\n ok T_bls12_381_g1\n | \"bls12_381_g2\" ->\n ok T_bls12_381_g2\n | \"bls12_381_fr\" ->\n ok T_bls12_381_fr\n | \"ticket\" ->\n ok T_ticket\n | n ->\n if valid_case n then error (Unknown_primitive_name n)\n else error (Invalid_case n)\n\nlet prims_of_strings expr =\n let rec convert = function\n | (Int _ | String _ | Bytes _) as expr ->\n ok expr\n | Prim (loc, prim, args, annot) ->\n Error_monad.record_trace\n (Invalid_primitive_name (expr, loc))\n (prim_of_string prim)\n >>? fun prim ->\n map convert args >|? fun args -> Prim (0, prim, args, annot)\n | Seq (_, args) ->\n map convert args >|? fun args -> Seq (0, args)\n in\n convert (root expr) >|? fun expr -> strip_locations expr\n [@@coq_axiom \"implicit type conversion for expr in the constant cases\"]\n\nlet strings_of_prims expr =\n let rec convert = function\n | (Int _ | String _ | Bytes _) as expr ->\n expr\n | Prim (_, prim, args, annot) ->\n let prim = string_of_prim prim in\n let args = List.map convert args in\n Prim (0, prim, args, annot)\n | Seq (_, args) ->\n let args = List.map convert args in\n Seq (0, args)\n in\n strip_locations (convert (root expr))\n [@@coq_axiom \"implicit type conversion for expr in the constant cases\"]\n\nlet prim_encoding =\n let open Data_encoding in\n def \"michelson.v1.primitives\"\n @@ string_enum\n (* Add the comment below every 10 lines *)\n [ (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"parameter\", K_parameter);\n (\"storage\", K_storage);\n (\"code\", K_code);\n (\"False\", D_False);\n (\"Elt\", D_Elt);\n (\"Left\", D_Left);\n (\"None\", D_None);\n (\"Pair\", D_Pair);\n (\"Right\", D_Right);\n (\"Some\", D_Some);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"True\", D_True);\n (\"Unit\", D_Unit);\n (\"PACK\", I_PACK);\n (\"UNPACK\", I_UNPACK);\n (\"BLAKE2B\", I_BLAKE2B);\n (\"SHA256\", I_SHA256);\n (\"SHA512\", I_SHA512);\n (\"ABS\", I_ABS);\n (\"ADD\", I_ADD);\n (\"AMOUNT\", I_AMOUNT);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"AND\", I_AND);\n (\"BALANCE\", I_BALANCE);\n (\"CAR\", I_CAR);\n (\"CDR\", I_CDR);\n (\"CHECK_SIGNATURE\", I_CHECK_SIGNATURE);\n (\"COMPARE\", I_COMPARE);\n (\"CONCAT\", I_CONCAT);\n (\"CONS\", I_CONS);\n (\"CREATE_ACCOUNT\", I_CREATE_ACCOUNT);\n (\"CREATE_CONTRACT\", I_CREATE_CONTRACT);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"IMPLICIT_ACCOUNT\", I_IMPLICIT_ACCOUNT);\n (\"DIP\", I_DIP);\n (\"DROP\", I_DROP);\n (\"DUP\", I_DUP);\n (\"EDIV\", I_EDIV);\n (\"EMPTY_MAP\", I_EMPTY_MAP);\n (\"EMPTY_SET\", I_EMPTY_SET);\n (\"EQ\", I_EQ);\n (\"EXEC\", I_EXEC);\n (\"FAILWITH\", I_FAILWITH);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"GE\", I_GE);\n (\"GET\", I_GET);\n (\"GT\", I_GT);\n (\"HASH_KEY\", I_HASH_KEY);\n (\"IF\", I_IF);\n (\"IF_CONS\", I_IF_CONS);\n (\"IF_LEFT\", I_IF_LEFT);\n (\"IF_NONE\", I_IF_NONE);\n (\"INT\", I_INT);\n (\"LAMBDA\", I_LAMBDA);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"LE\", I_LE);\n (\"LEFT\", I_LEFT);\n (\"LOOP\", I_LOOP);\n (\"LSL\", I_LSL);\n (\"LSR\", I_LSR);\n (\"LT\", I_LT);\n (\"MAP\", I_MAP);\n (\"MEM\", I_MEM);\n (\"MUL\", I_MUL);\n (\"NEG\", I_NEG);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"NEQ\", I_NEQ);\n (\"NIL\", I_NIL);\n (\"NONE\", I_NONE);\n (\"NOT\", I_NOT);\n (\"NOW\", I_NOW);\n (\"OR\", I_OR);\n (\"PAIR\", I_PAIR);\n (\"PUSH\", I_PUSH);\n (\"RIGHT\", I_RIGHT);\n (\"SIZE\", I_SIZE);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"SOME\", I_SOME);\n (\"SOURCE\", I_SOURCE);\n (\"SENDER\", I_SENDER);\n (\"SELF\", I_SELF);\n (\"STEPS_TO_QUOTA\", I_STEPS_TO_QUOTA);\n (\"SUB\", I_SUB);\n (\"SWAP\", I_SWAP);\n (\"TRANSFER_TOKENS\", I_TRANSFER_TOKENS);\n (\"SET_DELEGATE\", I_SET_DELEGATE);\n (\"UNIT\", I_UNIT);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"UPDATE\", I_UPDATE);\n (\"XOR\", I_XOR);\n (\"ITER\", I_ITER);\n (\"LOOP_LEFT\", I_LOOP_LEFT);\n (\"ADDRESS\", I_ADDRESS);\n (\"CONTRACT\", I_CONTRACT);\n (\"ISNAT\", I_ISNAT);\n (\"CAST\", I_CAST);\n (\"RENAME\", I_RENAME);\n (\"bool\", T_bool);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"contract\", T_contract);\n (\"int\", T_int);\n (\"key\", T_key);\n (\"key_hash\", T_key_hash);\n (\"lambda\", T_lambda);\n (\"list\", T_list);\n (\"map\", T_map);\n (\"big_map\", T_big_map);\n (\"nat\", T_nat);\n (\"option\", T_option);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"or\", T_or);\n (\"pair\", T_pair);\n (\"set\", T_set);\n (\"signature\", T_signature);\n (\"string\", T_string);\n (\"bytes\", T_bytes);\n (\"mutez\", T_mutez);\n (\"timestamp\", T_timestamp);\n (\"unit\", T_unit);\n (\"operation\", T_operation);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (\"address\", T_address);\n (* Alpha_002 addition *)\n (\"SLICE\", I_SLICE);\n (* Alpha_005 addition *)\n (\"DIG\", I_DIG);\n (\"DUG\", I_DUG);\n (\"EMPTY_BIG_MAP\", I_EMPTY_BIG_MAP);\n (\"APPLY\", I_APPLY);\n (\"chain_id\", T_chain_id);\n (\"CHAIN_ID\", I_CHAIN_ID);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (* Alpha_008 addition *)\n (\"LEVEL\", I_LEVEL);\n (\"SELF_ADDRESS\", I_SELF_ADDRESS);\n (\"never\", T_never);\n (\"NEVER\", I_NEVER);\n (\"UNPAIR\", I_UNPAIR);\n (\"VOTING_POWER\", I_VOTING_POWER);\n (\"TOTAL_VOTING_POWER\", I_TOTAL_VOTING_POWER);\n (\"KECCAK\", I_KECCAK);\n (\"SHA3\", I_SHA3);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (* Alpha_008 addition *)\n (\"PAIRING_CHECK\", I_PAIRING_CHECK);\n (\"bls12_381_g1\", T_bls12_381_g1);\n (\"bls12_381_g2\", T_bls12_381_g2);\n (\"bls12_381_fr\", T_bls12_381_fr);\n (\"sapling_state\", T_sapling_state);\n (\"sapling_transaction\", T_sapling_transaction);\n (\"SAPLING_EMPTY_STATE\", I_SAPLING_EMPTY_STATE);\n (\"SAPLING_VERIFY_UPDATE\", I_SAPLING_VERIFY_UPDATE);\n (\"ticket\", T_ticket);\n (* /!\\ NEW INSTRUCTIONS MUST BE ADDED AT THE END OF THE STRING_ENUM, FOR BACKWARD COMPATIBILITY OF THE ENCODING. *)\n (* Alpha_008 addition *)\n (\"TICKET\", I_TICKET);\n (\"READ_TICKET\", I_READ_TICKET);\n (\"SPLIT_TICKET\", I_SPLIT_TICKET);\n (\"JOIN_TICKETS\", I_JOIN_TICKETS);\n (\"GET_AND_UPDATE\", I_GET_AND_UPDATE)\n (* New instructions must be added here, for backward compatibility of the encoding. *)\n (* Keep the comment above at the end of the list *)\n ]\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unknown_primitive_name\"\n ~title:\"Unknown primitive name\"\n ~description:\"In a script or data expression, a primitive was unknown.\"\n ~pp:(fun ppf n -> Format.fprintf ppf \"Unknown primitive %s.\" n)\n Data_encoding.(obj1 (req \"wrong_primitive_name\" string))\n (function Unknown_primitive_name got -> Some got | _ -> None)\n (fun got -> Unknown_primitive_name got) ;\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_primitive_name_case\"\n ~title:\"Invalid primitive name case\"\n ~description:\n \"In a script or data expression, a primitive name is neither uppercase, \\\n lowercase or capitalized.\"\n ~pp:(fun ppf n -> Format.fprintf ppf \"Primitive %s has invalid case.\" n)\n Data_encoding.(obj1 (req \"wrong_primitive_name\" string))\n (function Invalid_case name -> Some name | _ -> None)\n (fun name -> Invalid_case name) ;\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_primitive_name\"\n ~title:\"Invalid primitive name\"\n ~description:\n \"In a script or data expression, a primitive name is unknown or has a \\\n wrong case.\"\n ~pp:(fun ppf _ -> Format.fprintf ppf \"Invalid primitive.\")\n Data_encoding.(\n obj2\n (req\n \"expression\"\n (Micheline.canonical_encoding ~variant:\"generic\" string))\n (req \"location\" Micheline.canonical_location_encoding))\n (function\n | Invalid_primitive_name (expr, loc) -> Some (expr, loc) | _ -> None)\n (fun (expr, loc) -> Invalid_primitive_name (expr, loc))\n\nlet string_of_namespace = function\n | Type_namespace ->\n \"T\"\n | Constant_namespace ->\n \"D\"\n | Instr_namespace ->\n \"I\"\n | Keyword_namespace ->\n \"K\"\n" ;
} ;
{ name = "Script_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype location = Micheline.canonical_location\n\ntype annot = Micheline.annot\n\ntype expr = Michelson_v1_primitives.prim Micheline.canonical\n\ntype error += Lazy_script_decode (* `Permanent *)\n\ntype lazy_expr = expr Data_encoding.lazy_t\n\ntype node = (location, Michelson_v1_primitives.prim) Micheline.node\n\nval location_encoding : location Data_encoding.t\n\nval expr_encoding : expr Data_encoding.t\n\nval lazy_expr_encoding : lazy_expr Data_encoding.t\n\nval lazy_expr : expr -> lazy_expr\n\ntype t = {code : lazy_expr; storage : lazy_expr}\n\nval encoding : t Data_encoding.encoding\n\nval deserialized_cost : expr -> Gas_limit_repr.cost\n\nval serialized_cost : bytes -> Gas_limit_repr.cost\n\nval traversal_cost : node -> Gas_limit_repr.cost\n\nval int_node_cost : Z.t -> Gas_limit_repr.cost\n\nval int_node_cost_of_numbits : int -> Gas_limit_repr.cost\n\nval string_node_cost : string -> Gas_limit_repr.cost\n\nval string_node_cost_of_length : int -> Gas_limit_repr.cost\n\nval bytes_node_cost : bytes -> Gas_limit_repr.cost\n\nval bytes_node_cost_of_length : int -> Gas_limit_repr.cost\n\nval prim_node_cost_nonrec : expr list -> annot -> Gas_limit_repr.cost\n\nval seq_node_cost_nonrec : expr list -> Gas_limit_repr.cost\n\nval seq_node_cost_nonrec_of_length : int -> Gas_limit_repr.cost\n\nval force_decode : lazy_expr -> (expr * Gas_limit_repr.cost) tzresult\n\nval force_bytes : lazy_expr -> (bytes * Gas_limit_repr.cost) tzresult\n\nval minimal_deserialize_cost : lazy_expr -> Gas_limit_repr.cost\n\nval unit_parameter : lazy_expr\n\nval is_unit_parameter : lazy_expr -> bool\n\nval strip_annotations : node -> node\n\nval micheline_nodes : node -> int\n\nval strip_locations_cost : node -> Gas_limit_repr.cost\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype location = Micheline.canonical_location\n\nlet location_encoding = Micheline.canonical_location_encoding\n\ntype annot = Micheline.annot\n\ntype expr = Michelson_v1_primitives.prim Micheline.canonical\n\ntype lazy_expr = expr Data_encoding.lazy_t\n\ntype node = (location, Michelson_v1_primitives.prim) Micheline.node\n\nlet expr_encoding =\n Micheline.canonical_encoding_v1\n ~variant:\"michelson_v1\"\n Michelson_v1_primitives.prim_encoding\n\ntype error += Lazy_script_decode (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"invalid_binary_format\"\n ~title:\"Invalid binary format\"\n ~description:\n \"Could not deserialize some piece of data from its binary representation\"\n Data_encoding.empty\n (function Lazy_script_decode -> Some () | _ -> None)\n (fun () -> Lazy_script_decode)\n\nlet lazy_expr_encoding = Data_encoding.lazy_encoding expr_encoding\n\nlet lazy_expr expr = Data_encoding.make_lazy expr_encoding expr\n\ntype t = {code : lazy_expr; storage : lazy_expr}\n\nlet encoding =\n let open Data_encoding in\n def \"scripted.contracts\"\n @@ conv\n (fun {code; storage} -> (code, storage))\n (fun (code, storage) -> {code; storage})\n (obj2 (req \"code\" lazy_expr_encoding) (req \"storage\" lazy_expr_encoding))\n\nlet int_node_size_of_numbits n = (1, 1 + ((n + 63) / 64))\n\nlet int_node_size n = int_node_size_of_numbits (Z.numbits n)\n\nlet string_node_size_of_length s = (1, 1 + ((s + 7) / 8))\n\nlet string_node_size s = string_node_size_of_length (String.length s)\n\nlet bytes_node_size_of_length s =\n (* approx cost of indirection to the C heap *)\n (2, 1 + ((s + 7) / 8) + 12)\n\nlet bytes_node_size s = bytes_node_size_of_length (Bytes.length s)\n\nlet prim_node_size_nonrec_of_lengths n_args annots =\n let annots_length =\n List.fold_left (fun acc s -> acc + String.length s) 0 annots\n in\n if Compare.Int.(annots_length = 0) then (1 + n_args, 2 + (2 * n_args))\n else (2 + n_args, 4 + (2 * n_args) + ((annots_length + 7) / 8))\n\nlet prim_node_size_nonrec args annots =\n let n_args = List.length args in\n prim_node_size_nonrec_of_lengths n_args annots\n\nlet seq_node_size_nonrec_of_length n_args = (1 + n_args, 2 + (2 * n_args))\n\nlet seq_node_size_nonrec args =\n let n_args = List.length args in\n seq_node_size_nonrec_of_length n_args\n\nlet convert_pair (i1, i2) = (Z.of_int i1, Z.of_int i2)\n\nlet rec node_size node =\n let open Micheline in\n match node with\n | Int (_, n) ->\n convert_pair (int_node_size n)\n | String (_, s) ->\n convert_pair (string_node_size s)\n | Bytes (_, s) ->\n convert_pair (bytes_node_size s)\n | Prim (_, _, args, annot) ->\n List.fold_left\n (fun (blocks, words) node ->\n let (nblocks, nwords) = node_size node in\n (Z.add blocks nblocks, Z.add words nwords))\n (convert_pair (prim_node_size_nonrec args annot))\n args\n | Seq (_, args) ->\n List.fold_left\n (fun (blocks, words) node ->\n let (nblocks, nwords) = node_size node in\n (Z.add blocks nblocks, Z.add words nwords))\n (convert_pair (seq_node_size_nonrec args))\n args\n\nlet expr_size expr = node_size (Micheline.root expr)\n\nlet traversal_cost node =\n let (blocks, _words) = node_size node in\n Gas_limit_repr.step_cost blocks\n\nlet cost_of_size (blocks, words) =\n let open Gas_limit_repr in\n (Compare.Z.max Z.zero (Z.sub blocks Z.one) *@ alloc_cost Z.zero)\n +@ alloc_cost words +@ step_cost blocks\n\nlet cost_of_size_int pair = cost_of_size (convert_pair pair)\n\nlet int_node_cost n = cost_of_size_int (int_node_size n)\n\nlet int_node_cost_of_numbits n = cost_of_size_int (int_node_size_of_numbits n)\n\nlet string_node_cost s = cost_of_size_int (string_node_size s)\n\nlet string_node_cost_of_length s =\n cost_of_size_int (string_node_size_of_length s)\n\nlet bytes_node_cost s = cost_of_size_int (bytes_node_size s)\n\nlet bytes_node_cost_of_length s =\n cost_of_size_int (bytes_node_size_of_length s)\n\nlet prim_node_cost_nonrec args annot =\n cost_of_size_int (prim_node_size_nonrec args annot)\n\nlet seq_node_cost_nonrec args = cost_of_size_int (seq_node_size_nonrec args)\n\nlet seq_node_cost_nonrec_of_length n_args =\n cost_of_size_int (seq_node_size_nonrec_of_length n_args)\n\nlet deserialized_cost expr = cost_of_size (expr_size expr)\n\nlet serialized_cost bytes =\n let open Gas_limit_repr in\n alloc_bytes_cost (Bytes.length bytes)\n\nlet force_decode lexpr =\n let account_deserialization_cost =\n Data_encoding.apply_lazy\n ~fun_value:(fun _ -> false)\n ~fun_bytes:(fun _ -> true)\n ~fun_combine:(fun _ _ -> false)\n lexpr\n in\n match Data_encoding.force_decode lexpr with\n | Some v ->\n if account_deserialization_cost then ok (v, deserialized_cost v)\n else ok (v, Gas_limit_repr.free)\n | None ->\n error Lazy_script_decode\n\nlet force_bytes expr =\n let open Gas_limit_repr in\n let account_serialization_cost =\n Data_encoding.apply_lazy\n ~fun_value:(fun v -> Some v)\n ~fun_bytes:(fun _ -> None)\n ~fun_combine:(fun _ _ -> None)\n expr\n in\n match Data_encoding.force_bytes expr with\n | bytes -> (\n match account_serialization_cost with\n | Some v ->\n ok (bytes, traversal_cost (Micheline.root v) +@ serialized_cost bytes)\n | None ->\n ok (bytes, Gas_limit_repr.free) )\n | exception _ ->\n error Lazy_script_decode\n\nlet minimal_deserialize_cost lexpr =\n Data_encoding.apply_lazy\n ~fun_value:(fun _ -> Gas_limit_repr.free)\n ~fun_bytes:(fun b -> serialized_cost b)\n ~fun_combine:(fun c_free _ -> c_free)\n lexpr\n\nlet unit =\n Micheline.strip_locations (Prim (0, Michelson_v1_primitives.D_Unit, [], []))\n\nlet unit_parameter = lazy_expr unit\n\nlet is_unit_parameter =\n let unit_bytes = Data_encoding.force_bytes unit_parameter in\n Data_encoding.apply_lazy\n ~fun_value:(fun v ->\n match Micheline.root v with\n | Prim (_, Michelson_v1_primitives.D_Unit, [], []) ->\n true\n | _ ->\n false)\n ~fun_bytes:(fun b -> Compare.Bytes.equal b unit_bytes)\n ~fun_combine:(fun res _ -> res)\n\nlet rec strip_annotations node =\n let open Micheline in\n match node with\n | (Int (_, _) | String (_, _) | Bytes (_, _)) as leaf ->\n leaf\n | Prim (loc, name, args, _) ->\n Prim (loc, name, List.map strip_annotations args, [])\n | Seq (loc, args) ->\n Seq (loc, List.map strip_annotations args)\n\nlet rec micheline_nodes node acc k =\n match node with\n | Micheline.Int (_, _) ->\n k (acc + 1)\n | Micheline.String (_, _) ->\n k (acc + 1)\n | Micheline.Bytes (_, _) ->\n k (acc + 1)\n | Micheline.Prim (_, _, subterms, _) ->\n micheline_nodes_list subterms (acc + 1) k\n | Micheline.Seq (_, subterms) ->\n micheline_nodes_list subterms (acc + 1) k\n\nand micheline_nodes_list subterms acc k =\n match subterms with\n | [] ->\n k acc\n | n :: nodes ->\n micheline_nodes_list nodes acc (fun acc -> micheline_nodes n acc k)\n\nlet micheline_nodes node = micheline_nodes node 0 (fun x -> x)\n\nlet cost_MICHELINE_STRIP_LOCATIONS size = Z.mul (Z.of_int size) (Z.of_int 100)\n\nlet strip_locations_cost node =\n let nodes = micheline_nodes node in\n Gas_limit_repr.atomic_step_cost (cost_MICHELINE_STRIP_LOCATIONS nodes)\n" ;
} ;
{ name = "Contract_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = private\n | Implicit of Signature.Public_key_hash.t\n | Originated of Contract_hash.t\n\ntype contract = t\n\ninclude Compare.S with type t := contract\n\n(** {2 Implicit contracts} *)\n\nval implicit_contract : Signature.Public_key_hash.t -> contract\n\nval is_implicit : contract -> Signature.Public_key_hash.t option\n\n(** {2 Originated contracts} *)\n\n(** Originated contracts handles are crafted from the hash of the\n operation that triggered their origination (and nothing else).\n As a single operation can trigger several originations, the\n corresponding handles are forged from a deterministic sequence of\n nonces, initialized with the hash of the operation. *)\ntype origination_nonce\n\nval originated_contract : origination_nonce -> contract\n\nval originated_contracts :\n since:origination_nonce -> until:origination_nonce -> contract list\n\nval initial_origination_nonce : Operation_hash.t -> origination_nonce\n\nval incr_origination_nonce : origination_nonce -> origination_nonce\n\nval is_originated : contract -> Contract_hash.t option\n\n(** {2 Human readable notation} *)\n\ntype error += Invalid_contract_notation of string (* `Permanent *)\n\nval to_b58check : contract -> string\n\nval of_b58check : string -> contract tzresult\n\nval pp : Format.formatter -> contract -> unit\n\nval pp_short : Format.formatter -> contract -> unit\n\n(** {2 Serializers} *)\n\nval encoding : contract Data_encoding.t\n\nval origination_nonce_encoding : origination_nonce Data_encoding.t\n\nval rpc_arg : contract RPC_arg.arg\n\nmodule Index : Storage_description.INDEX with type t = t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t =\n | Implicit of Signature.Public_key_hash.t\n | Originated of Contract_hash.t\n\ninclude Compare.Make (struct\n type nonrec t = t\n\n let compare l1 l2 =\n match (l1, l2) with\n | (Implicit pkh1, Implicit pkh2) ->\n Signature.Public_key_hash.compare pkh1 pkh2\n | (Originated h1, Originated h2) ->\n Contract_hash.compare h1 h2\n | (Implicit _, Originated _) ->\n -1\n | (Originated _, Implicit _) ->\n 1\nend)\n\ntype contract = t\n\ntype error += Invalid_contract_notation of string (* `Permanent *)\n\nlet to_b58check = function\n | Implicit pbk ->\n Signature.Public_key_hash.to_b58check pbk\n | Originated h ->\n Contract_hash.to_b58check h\n\nlet of_b58check s =\n match Base58.decode s with\n | Some (Ed25519.Public_key_hash.Data h) ->\n ok (Implicit (Signature.Ed25519 h))\n | Some (Secp256k1.Public_key_hash.Data h) ->\n ok (Implicit (Signature.Secp256k1 h))\n | Some (P256.Public_key_hash.Data h) ->\n ok (Implicit (Signature.P256 h))\n | Some (Contract_hash.Data h) ->\n ok (Originated h)\n | _ ->\n error (Invalid_contract_notation s)\n\nlet pp ppf = function\n | Implicit pbk ->\n Signature.Public_key_hash.pp ppf pbk\n | Originated h ->\n Contract_hash.pp ppf h\n\nlet pp_short ppf = function\n | Implicit pbk ->\n Signature.Public_key_hash.pp_short ppf pbk\n | Originated h ->\n Contract_hash.pp_short ppf h\n\nlet encoding =\n let open Data_encoding in\n def\n \"contract_id\"\n ~title:\"A contract handle\"\n ~description:\n \"A contract notation as given to an RPC or inside scripts. Can be a \\\n base58 implicit contract hash or a base58 originated contract hash.\"\n @@ splitted\n ~binary:\n (union\n ~tag_size:`Uint8\n [ case\n (Tag 0)\n ~title:\"Implicit\"\n Signature.Public_key_hash.encoding\n (function Implicit k -> Some k | _ -> None)\n (fun k -> Implicit k);\n case\n (Tag 1)\n (Fixed.add_padding Contract_hash.encoding 1)\n ~title:\"Originated\"\n (function Originated k -> Some k | _ -> None)\n (fun k -> Originated k) ])\n ~json:\n (conv\n to_b58check\n (fun s ->\n match of_b58check s with\n | Ok s ->\n s\n | Error _ ->\n Json.cannot_destruct \"Invalid contract notation.\")\n string)\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Permanent\n ~id:\"contract.invalid_contract_notation\"\n ~title:\"Invalid contract notation\"\n ~pp:(fun ppf x -> Format.fprintf ppf \"Invalid contract notation %S\" x)\n ~description:\n \"A malformed contract notation was given to an RPC or in a script.\"\n (obj1 (req \"notation\" string))\n (function Invalid_contract_notation loc -> Some loc | _ -> None)\n (fun loc -> Invalid_contract_notation loc)\n\nlet implicit_contract id = Implicit id\n\nlet is_implicit = function Implicit m -> Some m | Originated _ -> None\n\nlet is_originated = function Implicit _ -> None | Originated h -> Some h\n\ntype origination_nonce = {\n operation_hash : Operation_hash.t;\n origination_index : int32;\n}\n\nlet origination_nonce_encoding =\n let open Data_encoding in\n conv\n (fun {operation_hash; origination_index} ->\n (operation_hash, origination_index))\n (fun (operation_hash, origination_index) ->\n {operation_hash; origination_index})\n @@ obj2 (req \"operation\" Operation_hash.encoding) (dft \"index\" int32 0l)\n\nlet originated_contract nonce =\n let data =\n Data_encoding.Binary.to_bytes_exn origination_nonce_encoding nonce\n in\n Originated (Contract_hash.hash_bytes [data])\n\nlet originated_contracts\n ~since:{origination_index = first; operation_hash = first_hash}\n ~until:( {origination_index = last; operation_hash = last_hash} as\n origination_nonce ) =\n assert (Operation_hash.equal first_hash last_hash) ;\n let rec contracts acc origination_index =\n if Compare.Int32.(origination_index < first) then acc\n else\n let origination_nonce = {origination_nonce with origination_index} in\n let acc = originated_contract origination_nonce :: acc in\n contracts acc (Int32.pred origination_index)\n in\n contracts [] (Int32.pred last)\n\nlet initial_origination_nonce operation_hash =\n {operation_hash; origination_index = 0l}\n\nlet incr_origination_nonce nonce =\n let origination_index = Int32.succ nonce.origination_index in\n {nonce with origination_index}\n\nlet rpc_arg =\n let construct = to_b58check in\n let destruct hash =\n match of_b58check hash with\n | Error _ ->\n Error \"Cannot parse contract id\"\n | Ok contract ->\n Ok contract\n in\n RPC_arg.make\n ~descr:\"A contract identifier encoded in b58check.\"\n ~name:\"contract_id\"\n ~construct\n ~destruct\n ()\n\nmodule Index = struct\n type t = contract\n\n let path_length = 7\n\n let to_path c l =\n let raw_key = Data_encoding.Binary.to_bytes_exn encoding c in\n let (`Hex key) = Hex.of_bytes raw_key in\n let (`Hex index_key) = Hex.of_bytes (Raw_hashes.blake2b raw_key) in\n String.sub index_key 0 2 :: String.sub index_key 2 2\n :: String.sub index_key 4 2 :: String.sub index_key 6 2\n :: String.sub index_key 8 2 :: String.sub index_key 10 2 :: key :: l\n\n let of_path = function\n | []\n | [_]\n | [_; _]\n | [_; _; _]\n | [_; _; _; _]\n | [_; _; _; _; _]\n | [_; _; _; _; _; _]\n | _ :: _ :: _ :: _ :: _ :: _ :: _ :: _ :: _ ->\n None\n | [index1; index2; index3; index4; index5; index6; key] ->\n let raw_key = Hex.to_bytes (`Hex key) in\n let (`Hex index_key) = Hex.of_bytes (Raw_hashes.blake2b raw_key) in\n assert (Compare.String.(String.sub index_key 0 2 = index1)) ;\n assert (Compare.String.(String.sub index_key 2 2 = index2)) ;\n assert (Compare.String.(String.sub index_key 4 2 = index3)) ;\n assert (Compare.String.(String.sub index_key 6 2 = index4)) ;\n assert (Compare.String.(String.sub index_key 8 2 = index5)) ;\n assert (Compare.String.(String.sub index_key 10 2 = index6)) ;\n Data_encoding.Binary.of_bytes encoding raw_key\n\n let rpc_arg = rpc_arg\n\n let encoding = encoding\n\n let compare = compare\nend\n" ;
} ;
{ name = "Roll_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = private int32\n\ntype roll = t\n\nval encoding : roll Data_encoding.t\n\nval rpc_arg : roll RPC_arg.t\n\nval random : Seed_repr.sequence -> bound:roll -> roll * Seed_repr.sequence\n\nval first : roll\n\nval succ : roll -> roll\n\nval to_int32 : roll -> Int32.t\n\nval ( = ) : roll -> roll -> bool\n\nmodule Index : Storage_description.INDEX with type t = roll\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ninclude Compare.Int32\n\ntype roll = t\n\nlet encoding = Data_encoding.int32\n\nlet first = 0l\n\nlet succ i = Int32.succ i\n\nlet random sequence ~bound = Seed_repr.take_int32 sequence bound\n\nlet rpc_arg = RPC_arg.like RPC_arg.int32 \"roll\"\n\nlet to_int32 v = v\n\nmodule Index = struct\n type t = roll\n\n let path_length = 3\n\n let to_path roll l =\n (Int32.to_string @@ Int32.logand roll (Int32.of_int 0xff))\n :: ( Int32.to_string\n @@ Int32.logand (Int32.shift_right_logical roll 8) (Int32.of_int 0xff)\n )\n :: Int32.to_string roll :: l\n\n let of_path = function\n | _ :: _ :: s :: _ ->\n Int32.of_string_opt s\n | _ ->\n None\n\n let rpc_arg = rpc_arg\n\n let encoding = encoding\n\n let compare = compare\nend\n" ;
} ;
{ name = "Vote_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** a protocol change proposal *)\ntype proposal = Protocol_hash.t\n\n(** votes can be for, against or neutral.\n Neutral serves to count towards a quorum *)\ntype ballot = Yay | Nay | Pass\n\nval ballot_encoding : ballot Data_encoding.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype proposal = Protocol_hash.t\n\ntype ballot = Yay | Nay | Pass\n\nlet ballot_encoding =\n let of_int8 = function\n | 0 ->\n Yay\n | 1 ->\n Nay\n | 2 ->\n Pass\n | _ ->\n invalid_arg \"ballot_of_int8\"\n in\n let to_int8 = function Yay -> 0 | Nay -> 1 | Pass -> 2 in\n let open Data_encoding in\n (* union *)\n splitted\n ~binary:(conv to_int8 of_int8 int8)\n ~json:(string_enum [(\"yay\", Yay); (\"nay\", Nay); (\"pass\", Pass)])\n" ;
} ;
{ name = "Block_header_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = {shell : Block_header.shell_header; protocol_data : protocol_data}\n\nand protocol_data = {contents : contents; signature : Signature.t}\n\nand contents = {\n priority : int;\n seed_nonce_hash : Nonce_hash.t option;\n proof_of_work_nonce : bytes;\n}\n\ntype block_header = t\n\ntype raw = Block_header.t\n\ntype shell_header = Block_header.shell_header\n\nval raw : block_header -> raw\n\nval encoding : block_header Data_encoding.encoding\n\nval raw_encoding : raw Data_encoding.t\n\nval contents_encoding : contents Data_encoding.t\n\nval unsigned_encoding : (Block_header.shell_header * contents) Data_encoding.t\n\nval protocol_data_encoding : protocol_data Data_encoding.encoding\n\nval shell_header_encoding : shell_header Data_encoding.encoding\n\n(** The maximum size of block headers in bytes *)\nval max_header_length : int\n\nval hash : block_header -> Block_hash.t\n\nval hash_raw : raw -> Block_hash.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Block header *)\n\ntype t = {shell : Block_header.shell_header; protocol_data : protocol_data}\n\nand protocol_data = {contents : contents; signature : Signature.t}\n\nand contents = {\n priority : int;\n seed_nonce_hash : Nonce_hash.t option;\n proof_of_work_nonce : bytes;\n}\n\ntype block_header = t\n\ntype raw = Block_header.t\n\ntype shell_header = Block_header.shell_header\n\nlet raw_encoding = Block_header.encoding\n\nlet shell_header_encoding = Block_header.shell_header_encoding\n\nlet contents_encoding =\n let open Data_encoding in\n def \"block_header.alpha.unsigned_contents\"\n @@ conv\n (fun {priority; seed_nonce_hash; proof_of_work_nonce} ->\n (priority, proof_of_work_nonce, seed_nonce_hash))\n (fun (priority, proof_of_work_nonce, seed_nonce_hash) ->\n {priority; seed_nonce_hash; proof_of_work_nonce})\n (obj3\n (req \"priority\" uint16)\n (req\n \"proof_of_work_nonce\"\n (Fixed.bytes Constants_repr.proof_of_work_nonce_size))\n (opt \"seed_nonce_hash\" Nonce_hash.encoding))\n\nlet protocol_data_encoding =\n let open Data_encoding in\n def \"block_header.alpha.signed_contents\"\n @@ conv\n (fun {contents; signature} -> (contents, signature))\n (fun (contents, signature) -> {contents; signature})\n (merge_objs\n contents_encoding\n (obj1 (req \"signature\" Signature.encoding)))\n\nlet raw {shell; protocol_data} =\n let protocol_data =\n Data_encoding.Binary.to_bytes_exn protocol_data_encoding protocol_data\n in\n {Block_header.shell; protocol_data}\n\nlet unsigned_encoding =\n let open Data_encoding in\n merge_objs Block_header.shell_header_encoding contents_encoding\n\nlet encoding =\n let open Data_encoding in\n def \"block_header.alpha.full_header\"\n @@ conv\n (fun {shell; protocol_data} -> (shell, protocol_data))\n (fun (shell, protocol_data) -> {shell; protocol_data})\n (merge_objs Block_header.shell_header_encoding protocol_data_encoding)\n\n(** Constants *)\n\nlet max_header_length =\n let fake_shell =\n {\n Block_header.level = 0l;\n proto_level = 0;\n predecessor = Block_hash.zero;\n timestamp = Time.of_seconds 0L;\n validation_passes = 0;\n operations_hash = Operation_list_list_hash.zero;\n fitness = Fitness_repr.from_int64 0L;\n context = Context_hash.zero;\n }\n and fake_contents =\n {\n priority = 0;\n proof_of_work_nonce =\n Bytes.make Constants_repr.proof_of_work_nonce_size '0';\n seed_nonce_hash = Some Nonce_hash.zero;\n }\n in\n Data_encoding.Binary.length\n encoding\n {\n shell = fake_shell;\n protocol_data = {contents = fake_contents; signature = Signature.zero};\n }\n\n(** Header parsing entry point *)\n\nlet hash_raw = Block_header.hash\n\nlet hash {shell; protocol_data} =\n Block_header.hash\n {\n shell;\n protocol_data =\n Data_encoding.Binary.to_bytes_exn protocol_data_encoding protocol_data;\n }\n" ;
} ;
{ name = "Operation_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* Tezos Protocol Implementation - Low level Repr. of Operations *)\n\nmodule Kind : sig\n type seed_nonce_revelation = Seed_nonce_revelation_kind\n\n type double_endorsement_evidence = Double_endorsement_evidence_kind\n\n type double_baking_evidence = Double_baking_evidence_kind\n\n type activate_account = Activate_account_kind\n\n type endorsement = Endorsement_kind\n\n type proposals = Proposals_kind\n\n type ballot = Ballot_kind\n\n type reveal = Reveal_kind\n\n type transaction = Transaction_kind\n\n type origination = Origination_kind\n\n type delegation = Delegation_kind\n\n type 'a manager =\n | Reveal_manager_kind : reveal manager\n | Transaction_manager_kind : transaction manager\n | Origination_manager_kind : origination manager\n | Delegation_manager_kind : delegation manager\nend\n\ntype raw = Operation.t = {shell : Operation.shell_header; proto : bytes}\n\nval raw_encoding : raw Data_encoding.t\n\ntype 'kind operation = {\n shell : Operation.shell_header;\n protocol_data : 'kind protocol_data;\n}\n\nand 'kind protocol_data = {\n contents : 'kind contents_list;\n signature : Signature.t option;\n}\n\nand _ contents_list =\n | Single : 'kind contents -> 'kind contents_list\n | Cons :\n 'kind Kind.manager contents * 'rest Kind.manager contents_list\n -> ('kind * 'rest) Kind.manager contents_list\n\nand _ contents =\n | Endorsement : {level : Raw_level_repr.t} -> Kind.endorsement contents\n | Seed_nonce_revelation : {\n level : Raw_level_repr.t;\n nonce : Seed_repr.nonce;\n }\n -> Kind.seed_nonce_revelation contents\n | Double_endorsement_evidence : {\n op1 : Kind.endorsement operation;\n op2 : Kind.endorsement operation;\n }\n -> Kind.double_endorsement_evidence contents\n | Double_baking_evidence : {\n bh1 : Block_header_repr.t;\n bh2 : Block_header_repr.t;\n }\n -> Kind.double_baking_evidence contents\n | Activate_account : {\n id : Ed25519.Public_key_hash.t;\n activation_code : Blinded_public_key_hash.activation_code;\n }\n -> Kind.activate_account contents\n | Proposals : {\n source : Signature.Public_key_hash.t;\n period : int32;\n proposals : Protocol_hash.t list;\n }\n -> Kind.proposals contents\n | Ballot : {\n source : Signature.Public_key_hash.t;\n period : int32;\n proposal : Protocol_hash.t;\n ballot : Vote_repr.ballot;\n }\n -> Kind.ballot contents\n | Manager_operation : {\n source : Signature.Public_key_hash.t;\n fee : Tez_repr.tez;\n counter : counter;\n operation : 'kind manager_operation;\n gas_limit : Gas_limit_repr.Arith.integral;\n storage_limit : Z.t;\n }\n -> 'kind Kind.manager contents\n\nand _ manager_operation =\n | Reveal : Signature.Public_key.t -> Kind.reveal manager_operation\n | Transaction : {\n amount : Tez_repr.tez;\n parameters : Script_repr.lazy_expr;\n entrypoint : string;\n destination : Contract_repr.contract;\n }\n -> Kind.transaction manager_operation\n | Origination : {\n delegate : Signature.Public_key_hash.t option;\n script : Script_repr.t;\n credit : Tez_repr.tez;\n preorigination : Contract_repr.t option;\n }\n -> Kind.origination manager_operation\n | Delegation :\n Signature.Public_key_hash.t option\n -> Kind.delegation manager_operation\n\nand counter = Z.t\n\ntype 'kind internal_operation = {\n source : Contract_repr.contract;\n operation : 'kind manager_operation;\n nonce : int;\n}\n\ntype packed_manager_operation =\n | Manager : 'kind manager_operation -> packed_manager_operation\n\ntype packed_contents = Contents : 'kind contents -> packed_contents\n\ntype packed_contents_list =\n | Contents_list : 'kind contents_list -> packed_contents_list\n\nval of_list : packed_contents list -> packed_contents_list\n\nval to_list : packed_contents_list -> packed_contents list\n\ntype packed_protocol_data =\n | Operation_data : 'kind protocol_data -> packed_protocol_data\n\ntype packed_operation = {\n shell : Operation.shell_header;\n protocol_data : packed_protocol_data;\n}\n\nval pack : 'kind operation -> packed_operation\n\ntype packed_internal_operation =\n | Internal_operation : 'kind internal_operation -> packed_internal_operation\n\nval manager_kind : 'kind manager_operation -> 'kind Kind.manager\n\nval encoding : packed_operation Data_encoding.t\n\nval contents_encoding : packed_contents Data_encoding.t\n\nval contents_list_encoding : packed_contents_list Data_encoding.t\n\nval protocol_data_encoding : packed_protocol_data Data_encoding.t\n\nval unsigned_operation_encoding :\n (Operation.shell_header * packed_contents_list) Data_encoding.t\n\nval raw : _ operation -> raw\n\nval hash_raw : raw -> Operation_hash.t\n\nval hash : _ operation -> Operation_hash.t\n\nval hash_packed : packed_operation -> Operation_hash.t\n\nval acceptable_passes : packed_operation -> int list\n\ntype error += Missing_signature (* `Permanent *)\n\ntype error += Invalid_signature (* `Permanent *)\n\nval check_signature :\n Signature.Public_key.t -> Chain_id.t -> _ operation -> unit tzresult\n\nval internal_operation_encoding : packed_internal_operation Data_encoding.t\n\ntype ('a, 'b) eq = Eq : ('a, 'a) eq\n\nval equal : 'a operation -> 'b operation -> ('a, 'b) eq option\n\nmodule Encoding : sig\n type 'b case =\n | Case : {\n tag : int;\n name : string;\n encoding : 'a Data_encoding.t;\n select : packed_contents -> 'b contents option;\n proj : 'b contents -> 'a;\n inj : 'a -> 'b contents;\n }\n -> 'b case\n\n val endorsement_case : Kind.endorsement case\n\n val seed_nonce_revelation_case : Kind.seed_nonce_revelation case\n\n val double_endorsement_evidence_case : Kind.double_endorsement_evidence case\n\n val double_baking_evidence_case : Kind.double_baking_evidence case\n\n val activate_account_case : Kind.activate_account case\n\n val proposals_case : Kind.proposals case\n\n val ballot_case : Kind.ballot case\n\n val reveal_case : Kind.reveal Kind.manager case\n\n val transaction_case : Kind.transaction Kind.manager case\n\n val origination_case : Kind.origination Kind.manager case\n\n val delegation_case : Kind.delegation Kind.manager case\n\n module Manager_operations : sig\n type 'b case =\n | MCase : {\n tag : int;\n name : string;\n encoding : 'a Data_encoding.t;\n select : packed_manager_operation -> 'kind manager_operation option;\n proj : 'kind manager_operation -> 'a;\n inj : 'a -> 'kind manager_operation;\n }\n -> 'kind case\n\n val reveal_case : Kind.reveal case\n\n val transaction_case : Kind.transaction case\n\n val origination_case : Kind.origination case\n\n val delegation_case : Kind.delegation case\n end\nend\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* Tezos Protocol Implementation - Low level Repr. of Operations *)\n\nmodule Kind = struct\n type seed_nonce_revelation = Seed_nonce_revelation_kind\n\n type double_endorsement_evidence = Double_endorsement_evidence_kind\n\n type double_baking_evidence = Double_baking_evidence_kind\n\n type activate_account = Activate_account_kind\n\n type endorsement = Endorsement_kind\n\n type proposals = Proposals_kind\n\n type ballot = Ballot_kind\n\n type reveal = Reveal_kind\n\n type transaction = Transaction_kind\n\n type origination = Origination_kind\n\n type delegation = Delegation_kind\n\n type 'a manager =\n | Reveal_manager_kind : reveal manager\n | Transaction_manager_kind : transaction manager\n | Origination_manager_kind : origination manager\n | Delegation_manager_kind : delegation manager\nend\n\ntype raw = Operation.t = {shell : Operation.shell_header; proto : bytes}\n\nlet raw_encoding = Operation.encoding\n\ntype 'kind operation = {\n shell : Operation.shell_header;\n protocol_data : 'kind protocol_data;\n}\n\nand 'kind protocol_data = {\n contents : 'kind contents_list;\n signature : Signature.t option;\n}\n\nand _ contents_list =\n | Single : 'kind contents -> 'kind contents_list\n | Cons :\n 'kind Kind.manager contents * 'rest Kind.manager contents_list\n -> ('kind * 'rest) Kind.manager contents_list\n\nand _ contents =\n | Endorsement : {level : Raw_level_repr.t} -> Kind.endorsement contents\n | Seed_nonce_revelation : {\n level : Raw_level_repr.t;\n nonce : Seed_repr.nonce;\n }\n -> Kind.seed_nonce_revelation contents\n | Double_endorsement_evidence : {\n op1 : Kind.endorsement operation;\n op2 : Kind.endorsement operation;\n }\n -> Kind.double_endorsement_evidence contents\n | Double_baking_evidence : {\n bh1 : Block_header_repr.t;\n bh2 : Block_header_repr.t;\n }\n -> Kind.double_baking_evidence contents\n | Activate_account : {\n id : Ed25519.Public_key_hash.t;\n activation_code : Blinded_public_key_hash.activation_code;\n }\n -> Kind.activate_account contents\n | Proposals : {\n source : Signature.Public_key_hash.t;\n period : int32;\n proposals : Protocol_hash.t list;\n }\n -> Kind.proposals contents\n | Ballot : {\n source : Signature.Public_key_hash.t;\n period : int32;\n proposal : Protocol_hash.t;\n ballot : Vote_repr.ballot;\n }\n -> Kind.ballot contents\n | Manager_operation : {\n source : Signature.public_key_hash;\n fee : Tez_repr.tez;\n counter : counter;\n operation : 'kind manager_operation;\n gas_limit : Gas_limit_repr.Arith.integral;\n storage_limit : Z.t;\n }\n -> 'kind Kind.manager contents\n\nand _ manager_operation =\n | Reveal : Signature.Public_key.t -> Kind.reveal manager_operation\n | Transaction : {\n amount : Tez_repr.tez;\n parameters : Script_repr.lazy_expr;\n entrypoint : string;\n destination : Contract_repr.contract;\n }\n -> Kind.transaction manager_operation\n | Origination : {\n delegate : Signature.Public_key_hash.t option;\n script : Script_repr.t;\n credit : Tez_repr.tez;\n preorigination : Contract_repr.t option;\n }\n -> Kind.origination manager_operation\n | Delegation :\n Signature.Public_key_hash.t option\n -> Kind.delegation manager_operation\n\nand counter = Z.t\n\nlet manager_kind : type kind. kind manager_operation -> kind Kind.manager =\n function\n | Reveal _ ->\n Kind.Reveal_manager_kind\n | Transaction _ ->\n Kind.Transaction_manager_kind\n | Origination _ ->\n Kind.Origination_manager_kind\n | Delegation _ ->\n Kind.Delegation_manager_kind\n\ntype 'kind internal_operation = {\n source : Contract_repr.contract;\n operation : 'kind manager_operation;\n nonce : int;\n}\n\ntype packed_manager_operation =\n | Manager : 'kind manager_operation -> packed_manager_operation\n\ntype packed_contents = Contents : 'kind contents -> packed_contents\n\ntype packed_contents_list =\n | Contents_list : 'kind contents_list -> packed_contents_list\n\ntype packed_protocol_data =\n | Operation_data : 'kind protocol_data -> packed_protocol_data\n\ntype packed_operation = {\n shell : Operation.shell_header;\n protocol_data : packed_protocol_data;\n}\n\nlet pack ({shell; protocol_data} : _ operation) : packed_operation =\n {shell; protocol_data = Operation_data protocol_data}\n\ntype packed_internal_operation =\n | Internal_operation : 'kind internal_operation -> packed_internal_operation\n\nlet rec to_list = function\n | Contents_list (Single o) ->\n [Contents o]\n | Contents_list (Cons (o, os)) ->\n Contents o :: to_list (Contents_list os)\n\nlet rec of_list = function\n | [] ->\n assert false\n | [Contents o] ->\n Contents_list (Single o)\n | Contents o :: os -> (\n let (Contents_list os) = of_list os in\n match (o, os) with\n | (Manager_operation _, Single (Manager_operation _)) ->\n Contents_list (Cons (o, os))\n | (Manager_operation _, Cons _) ->\n Contents_list (Cons (o, os))\n | _ ->\n Pervasives.failwith\n \"Operation list of length > 1 should only contains manager \\\n operations.\" )\n\nmodule Encoding = struct\n open Data_encoding\n\n let case tag name args proj inj =\n let open Data_encoding in\n case\n tag\n ~title:(String.capitalize_ascii name)\n (merge_objs (obj1 (req \"kind\" (constant name))) args)\n (fun x -> match proj x with None -> None | Some x -> Some ((), x))\n (fun ((), x) -> inj x)\n\n module Manager_operations = struct\n type 'kind case =\n | MCase : {\n tag : int;\n name : string;\n encoding : 'a Data_encoding.t;\n select : packed_manager_operation -> 'kind manager_operation option;\n proj : 'kind manager_operation -> 'a;\n inj : 'a -> 'kind manager_operation;\n }\n -> 'kind case\n\n let reveal_case =\n MCase\n {\n tag = 0;\n name = \"reveal\";\n encoding = obj1 (req \"public_key\" Signature.Public_key.encoding);\n select = (function Manager (Reveal _ as op) -> Some op | _ -> None);\n proj = (function Reveal pkh -> pkh);\n inj = (fun pkh -> Reveal pkh);\n }\n\n let entrypoint_encoding =\n def\n ~title:\"entrypoint\"\n ~description:\"Named entrypoint to a Michelson smart contract\"\n \"entrypoint\"\n @@\n let builtin_case tag name =\n Data_encoding.case\n (Tag tag)\n ~title:name\n (constant name)\n (fun n -> if Compare.String.(n = name) then Some () else None)\n (fun () -> name)\n in\n union\n [ builtin_case 0 \"default\";\n builtin_case 1 \"root\";\n builtin_case 2 \"do\";\n builtin_case 3 \"set_delegate\";\n builtin_case 4 \"remove_delegate\";\n Data_encoding.case\n (Tag 255)\n ~title:\"named\"\n (Bounded.string 31)\n (fun s -> Some s)\n (fun s -> s) ]\n\n let transaction_case =\n MCase\n {\n tag = 1;\n name = \"transaction\";\n encoding =\n obj3\n (req \"amount\" Tez_repr.encoding)\n (req \"destination\" Contract_repr.encoding)\n (opt\n \"parameters\"\n (obj2\n (req \"entrypoint\" entrypoint_encoding)\n (req \"value\" Script_repr.lazy_expr_encoding)));\n select =\n (function Manager (Transaction _ as op) -> Some op | _ -> None);\n proj =\n (function\n | Transaction {amount; destination; parameters; entrypoint} ->\n let parameters =\n if\n Script_repr.is_unit_parameter parameters\n && Compare.String.(entrypoint = \"default\")\n then None\n else Some (entrypoint, parameters)\n in\n (amount, destination, parameters));\n inj =\n (fun (amount, destination, parameters) ->\n let (entrypoint, parameters) =\n match parameters with\n | None ->\n (\"default\", Script_repr.unit_parameter)\n | Some (entrypoint, value) ->\n (entrypoint, value)\n in\n Transaction {amount; destination; parameters; entrypoint});\n }\n\n let origination_case =\n MCase\n {\n tag = 2;\n name = \"origination\";\n encoding =\n obj3\n (req \"balance\" Tez_repr.encoding)\n (opt \"delegate\" Signature.Public_key_hash.encoding)\n (req \"script\" Script_repr.encoding);\n select =\n (function Manager (Origination _ as op) -> Some op | _ -> None);\n proj =\n (function\n | Origination\n { credit;\n delegate;\n script;\n preorigination =\n _\n (* the hash is only used internally\n when originating from smart\n contracts, don't serialize it *)\n } ->\n (credit, delegate, script));\n inj =\n (fun (credit, delegate, script) ->\n Origination {credit; delegate; script; preorigination = None});\n }\n\n let delegation_case =\n MCase\n {\n tag = 3;\n name = \"delegation\";\n encoding = obj1 (opt \"delegate\" Signature.Public_key_hash.encoding);\n select =\n (function Manager (Delegation _ as op) -> Some op | _ -> None);\n proj = (function Delegation key -> key);\n inj = (fun key -> Delegation key);\n }\n\n let encoding =\n let make (MCase {tag; name; encoding; select; proj; inj}) =\n case\n (Tag tag)\n name\n encoding\n (fun o ->\n match select o with None -> None | Some o -> Some (proj o))\n (fun x -> Manager (inj x))\n in\n union\n ~tag_size:`Uint8\n [ make reveal_case;\n make transaction_case;\n make origination_case;\n make delegation_case ]\n end\n\n type 'b case =\n | Case : {\n tag : int;\n name : string;\n encoding : 'a Data_encoding.t;\n select : packed_contents -> 'b contents option;\n proj : 'b contents -> 'a;\n inj : 'a -> 'b contents;\n }\n -> 'b case\n\n let endorsement_encoding = obj1 (req \"level\" Raw_level_repr.encoding)\n\n let endorsement_case =\n Case\n {\n tag = 0;\n name = \"endorsement\";\n encoding = endorsement_encoding;\n select =\n (function Contents (Endorsement _ as op) -> Some op | _ -> None);\n proj = (fun (Endorsement {level}) -> level);\n inj = (fun level -> Endorsement {level});\n }\n\n let endorsement_encoding =\n let make (Case {tag; name; encoding; select = _; proj; inj}) =\n case (Tag tag) name encoding (fun o -> Some (proj o)) (fun x -> inj x)\n in\n let to_list : Kind.endorsement contents_list -> _ = function\n | Single o ->\n o\n in\n let of_list : Kind.endorsement contents -> _ = function o -> Single o in\n def \"inlined.endorsement\"\n @@ conv\n (fun ({shell; protocol_data = {contents; signature}} : _ operation) ->\n (shell, (contents, signature)))\n (fun (shell, (contents, signature)) ->\n ({shell; protocol_data = {contents; signature}} : _ operation))\n (merge_objs\n Operation.shell_header_encoding\n (obj2\n (req\n \"operations\"\n ( conv to_list of_list\n @@ def \"inlined.endorsement.contents\"\n @@ union [make endorsement_case] ))\n (varopt \"signature\" Signature.encoding)))\n\n let seed_nonce_revelation_case =\n Case\n {\n tag = 1;\n name = \"seed_nonce_revelation\";\n encoding =\n obj2\n (req \"level\" Raw_level_repr.encoding)\n (req \"nonce\" Seed_repr.nonce_encoding);\n select =\n (function\n | Contents (Seed_nonce_revelation _ as op) -> Some op | _ -> None);\n proj = (fun (Seed_nonce_revelation {level; nonce}) -> (level, nonce));\n inj = (fun (level, nonce) -> Seed_nonce_revelation {level; nonce});\n }\n\n let double_endorsement_evidence_case : Kind.double_endorsement_evidence case\n =\n Case\n {\n tag = 2;\n name = \"double_endorsement_evidence\";\n encoding =\n obj2\n (req \"op1\" (dynamic_size endorsement_encoding))\n (req \"op2\" (dynamic_size endorsement_encoding));\n select =\n (function\n | Contents (Double_endorsement_evidence _ as op) ->\n Some op\n | _ ->\n None);\n proj = (fun (Double_endorsement_evidence {op1; op2}) -> (op1, op2));\n inj = (fun (op1, op2) -> Double_endorsement_evidence {op1; op2});\n }\n\n let double_baking_evidence_case =\n Case\n {\n tag = 3;\n name = \"double_baking_evidence\";\n encoding =\n obj2\n (req \"bh1\" (dynamic_size Block_header_repr.encoding))\n (req \"bh2\" (dynamic_size Block_header_repr.encoding));\n select =\n (function\n | Contents (Double_baking_evidence _ as op) -> Some op | _ -> None);\n proj = (fun (Double_baking_evidence {bh1; bh2}) -> (bh1, bh2));\n inj = (fun (bh1, bh2) -> Double_baking_evidence {bh1; bh2});\n }\n\n let activate_account_case =\n Case\n {\n tag = 4;\n name = \"activate_account\";\n encoding =\n obj2\n (req \"pkh\" Ed25519.Public_key_hash.encoding)\n (req \"secret\" Blinded_public_key_hash.activation_code_encoding);\n select =\n (function\n | Contents (Activate_account _ as op) -> Some op | _ -> None);\n proj =\n (fun (Activate_account {id; activation_code}) ->\n (id, activation_code));\n inj =\n (fun (id, activation_code) -> Activate_account {id; activation_code});\n }\n\n let proposals_case =\n Case\n {\n tag = 5;\n name = \"proposals\";\n encoding =\n obj3\n (req \"source\" Signature.Public_key_hash.encoding)\n (req \"period\" int32)\n (req \"proposals\" (list Protocol_hash.encoding));\n select =\n (function Contents (Proposals _ as op) -> Some op | _ -> None);\n proj =\n (fun (Proposals {source; period; proposals}) ->\n (source, period, proposals));\n inj =\n (fun (source, period, proposals) ->\n Proposals {source; period; proposals});\n }\n\n let ballot_case =\n Case\n {\n tag = 6;\n name = \"ballot\";\n encoding =\n obj4\n (req \"source\" Signature.Public_key_hash.encoding)\n (req \"period\" int32)\n (req \"proposal\" Protocol_hash.encoding)\n (req \"ballot\" Vote_repr.ballot_encoding);\n select = (function Contents (Ballot _ as op) -> Some op | _ -> None);\n proj =\n (function\n | Ballot {source; period; proposal; ballot} ->\n (source, period, proposal, ballot));\n inj =\n (fun (source, period, proposal, ballot) ->\n Ballot {source; period; proposal; ballot});\n }\n\n let manager_encoding =\n obj5\n (req \"source\" Signature.Public_key_hash.encoding)\n (req \"fee\" Tez_repr.encoding)\n (req \"counter\" (check_size 10 n))\n (req \"gas_limit\" (check_size 10 Gas_limit_repr.Arith.n_integral_encoding))\n (req \"storage_limit\" (check_size 10 n))\n\n let extract (type kind)\n (Manager_operation\n {source; fee; counter; gas_limit; storage_limit; operation = _} :\n kind Kind.manager contents) =\n (source, fee, counter, gas_limit, storage_limit)\n\n let rebuild (source, fee, counter, gas_limit, storage_limit) operation =\n Manager_operation\n {source; fee; counter; gas_limit; storage_limit; operation}\n\n let make_manager_case tag (type kind)\n (Manager_operations.MCase mcase : kind Manager_operations.case) =\n Case\n {\n tag;\n name = mcase.name;\n encoding = merge_objs manager_encoding mcase.encoding;\n select =\n (function\n | Contents (Manager_operation ({operation; _} as op)) -> (\n match mcase.select (Manager operation) with\n | None ->\n None\n | Some operation ->\n Some (Manager_operation {op with operation}) )\n | _ ->\n None);\n proj =\n (function\n | Manager_operation {operation; _} as op ->\n (extract op, mcase.proj operation));\n inj = (fun (op, contents) -> rebuild op (mcase.inj contents));\n }\n\n let reveal_case = make_manager_case 107 Manager_operations.reveal_case\n\n let transaction_case =\n make_manager_case 108 Manager_operations.transaction_case\n\n let origination_case =\n make_manager_case 109 Manager_operations.origination_case\n\n let delegation_case =\n make_manager_case 110 Manager_operations.delegation_case\n\n let contents_encoding =\n let make (Case {tag; name; encoding; select; proj; inj}) =\n case\n (Tag tag)\n name\n encoding\n (fun o -> match select o with None -> None | Some o -> Some (proj o))\n (fun x -> Contents (inj x))\n in\n def \"operation.alpha.contents\"\n @@ union\n [ make endorsement_case;\n make seed_nonce_revelation_case;\n make double_endorsement_evidence_case;\n make double_baking_evidence_case;\n make activate_account_case;\n make proposals_case;\n make ballot_case;\n make reveal_case;\n make transaction_case;\n make origination_case;\n make delegation_case ]\n\n let contents_list_encoding =\n conv to_list of_list (Variable.list contents_encoding)\n\n let optional_signature_encoding =\n conv\n (function Some s -> s | None -> Signature.zero)\n (fun s -> if Signature.equal s Signature.zero then None else Some s)\n Signature.encoding\n\n let protocol_data_encoding =\n def \"operation.alpha.contents_and_signature\"\n @@ conv\n (fun (Operation_data {contents; signature}) ->\n (Contents_list contents, signature))\n (fun (Contents_list contents, signature) ->\n Operation_data {contents; signature})\n (obj2\n (req \"contents\" contents_list_encoding)\n (req \"signature\" optional_signature_encoding))\n\n let operation_encoding =\n conv\n (fun {shell; protocol_data} -> (shell, protocol_data))\n (fun (shell, protocol_data) -> {shell; protocol_data})\n (merge_objs Operation.shell_header_encoding protocol_data_encoding)\n\n let unsigned_operation_encoding =\n def \"operation.alpha.unsigned_operation\"\n @@ merge_objs\n Operation.shell_header_encoding\n (obj1 (req \"contents\" contents_list_encoding))\n\n let internal_operation_encoding =\n def \"operation.alpha.internal_operation\"\n @@ conv\n (fun (Internal_operation {source; operation; nonce}) ->\n ((source, nonce), Manager operation))\n (fun ((source, nonce), Manager operation) ->\n Internal_operation {source; operation; nonce})\n (merge_objs\n (obj2 (req \"source\" Contract_repr.encoding) (req \"nonce\" uint16))\n Manager_operations.encoding)\nend\n\nlet encoding = Encoding.operation_encoding\n\nlet contents_encoding = Encoding.contents_encoding\n\nlet contents_list_encoding = Encoding.contents_list_encoding\n\nlet protocol_data_encoding = Encoding.protocol_data_encoding\n\nlet unsigned_operation_encoding = Encoding.unsigned_operation_encoding\n\nlet internal_operation_encoding = Encoding.internal_operation_encoding\n\nlet raw ({shell; protocol_data} : _ operation) =\n let proto =\n Data_encoding.Binary.to_bytes_exn\n protocol_data_encoding\n (Operation_data protocol_data)\n in\n {Operation.shell; proto}\n\nlet acceptable_passes (op : packed_operation) =\n let (Operation_data protocol_data) = op.protocol_data in\n match protocol_data.contents with\n | Single (Endorsement _) ->\n [0]\n | Single (Proposals _) ->\n [1]\n | Single (Ballot _) ->\n [1]\n | Single (Seed_nonce_revelation _) ->\n [2]\n | Single (Double_endorsement_evidence _) ->\n [2]\n | Single (Double_baking_evidence _) ->\n [2]\n | Single (Activate_account _) ->\n [2]\n | Single (Manager_operation _) ->\n [3]\n | Cons _ ->\n [3]\n\ntype error += Invalid_signature (* `Permanent *)\n\ntype error += Missing_signature (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"operation.invalid_signature\"\n ~title:\"Invalid operation signature\"\n ~description:\n \"The operation signature is ill-formed or has been made with the wrong \\\n public key\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"The operation signature is invalid\")\n Data_encoding.unit\n (function Invalid_signature -> Some () | _ -> None)\n (fun () -> Invalid_signature) ;\n register_error_kind\n `Permanent\n ~id:\"operation.missing_signature\"\n ~title:\"Missing operation signature\"\n ~description:\n \"The operation is of a kind that must be signed, but the signature is \\\n missing\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"The operation requires a signature\")\n Data_encoding.unit\n (function Missing_signature -> Some () | _ -> None)\n (fun () -> Missing_signature)\n\nlet check_signature (type kind) key chain_id\n ({shell; protocol_data} : kind operation) =\n let check ~watermark contents signature =\n let unsigned_operation =\n Data_encoding.Binary.to_bytes_exn\n unsigned_operation_encoding\n (shell, contents)\n in\n if Signature.check ~watermark key signature unsigned_operation then Ok ()\n else error Invalid_signature\n in\n match (protocol_data.contents, protocol_data.signature) with\n | (Single _, None) ->\n error Missing_signature\n | (Cons _, None) ->\n error Missing_signature\n | ((Single (Endorsement _) as contents), Some signature) ->\n check\n ~watermark:(Endorsement chain_id)\n (Contents_list contents)\n signature\n | ((Single _ as contents), Some signature) ->\n check ~watermark:Generic_operation (Contents_list contents) signature\n | ((Cons _ as contents), Some signature) ->\n check ~watermark:Generic_operation (Contents_list contents) signature\n\nlet hash_raw = Operation.hash\n\nlet hash (o : _ operation) =\n let proto =\n Data_encoding.Binary.to_bytes_exn\n protocol_data_encoding\n (Operation_data o.protocol_data)\n in\n Operation.hash {shell = o.shell; proto}\n\nlet hash_packed (o : packed_operation) =\n let proto =\n Data_encoding.Binary.to_bytes_exn protocol_data_encoding o.protocol_data\n in\n Operation.hash {shell = o.shell; proto}\n\ntype ('a, 'b) eq = Eq : ('a, 'a) eq\n\nlet equal_manager_operation_kind :\n type a b. a manager_operation -> b manager_operation -> (a, b) eq option =\n fun op1 op2 ->\n match (op1, op2) with\n | (Reveal _, Reveal _) ->\n Some Eq\n | (Reveal _, _) ->\n None\n | (Transaction _, Transaction _) ->\n Some Eq\n | (Transaction _, _) ->\n None\n | (Origination _, Origination _) ->\n Some Eq\n | (Origination _, _) ->\n None\n | (Delegation _, Delegation _) ->\n Some Eq\n | (Delegation _, _) ->\n None\n\nlet equal_contents_kind :\n type a b. a contents -> b contents -> (a, b) eq option =\n fun op1 op2 ->\n match (op1, op2) with\n | (Endorsement _, Endorsement _) ->\n Some Eq\n | (Endorsement _, _) ->\n None\n | (Seed_nonce_revelation _, Seed_nonce_revelation _) ->\n Some Eq\n | (Seed_nonce_revelation _, _) ->\n None\n | (Double_endorsement_evidence _, Double_endorsement_evidence _) ->\n Some Eq\n | (Double_endorsement_evidence _, _) ->\n None\n | (Double_baking_evidence _, Double_baking_evidence _) ->\n Some Eq\n | (Double_baking_evidence _, _) ->\n None\n | (Activate_account _, Activate_account _) ->\n Some Eq\n | (Activate_account _, _) ->\n None\n | (Proposals _, Proposals _) ->\n Some Eq\n | (Proposals _, _) ->\n None\n | (Ballot _, Ballot _) ->\n Some Eq\n | (Ballot _, _) ->\n None\n | (Manager_operation op1, Manager_operation op2) -> (\n match equal_manager_operation_kind op1.operation op2.operation with\n | None ->\n None\n | Some Eq ->\n Some Eq )\n | (Manager_operation _, _) ->\n None\n\nlet rec equal_contents_kind_list :\n type a b. a contents_list -> b contents_list -> (a, b) eq option =\n fun op1 op2 ->\n match (op1, op2) with\n | (Single op1, Single op2) ->\n equal_contents_kind op1 op2\n | (Single _, Cons _) ->\n None\n | (Cons _, Single _) ->\n None\n | (Cons (op1, ops1), Cons (op2, ops2)) -> (\n match equal_contents_kind op1 op2 with\n | None ->\n None\n | Some Eq -> (\n match equal_contents_kind_list ops1 ops2 with\n | None ->\n None\n | Some Eq ->\n Some Eq ) )\n\nlet equal : type a b. a operation -> b operation -> (a, b) eq option =\n fun op1 op2 ->\n if not (Operation_hash.equal (hash op1) (hash op2)) then None\n else\n equal_contents_kind_list\n op1.protocol_data.contents\n op2.protocol_data.contents\n" ;
} ;
{ name = "Manager_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* Tezos Protocol Implementation - Low level Repr. of Managers' keys *)\n\n(** The public key of the manager of a contract is reveled only after the\n first operation. At Origination time, the manager provides only the hash\n of its public key that is stored in the contract. When the public key\n is actually revealed, the public key instead of the hash of the key *)\ntype manager_key =\n | Hash of Signature.Public_key_hash.t\n | Public_key of Signature.Public_key.t\n\ntype t = manager_key\n\nval encoding : t Data_encoding.encoding\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* Tezos Protocol Implementation - Low level Repr. of Managers' keys *)\n\ntype manager_key =\n | Hash of Signature.Public_key_hash.t\n | Public_key of Signature.Public_key.t\n\ntype t = manager_key\n\nopen Data_encoding\n\nlet hash_case tag =\n case\n tag\n ~title:\"Public_key_hash\"\n Signature.Public_key_hash.encoding\n (function Hash hash -> Some hash | _ -> None)\n (fun hash -> Hash hash)\n\nlet pubkey_case tag =\n case\n tag\n ~title:\"Public_key\"\n Signature.Public_key.encoding\n (function Public_key hash -> Some hash | _ -> None)\n (fun hash -> Public_key hash)\n\nlet encoding = union [hash_case (Tag 0); pubkey_case (Tag 1)]\n" ;
} ;
{ name = "Commitment_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = {\n blinded_public_key_hash : Blinded_public_key_hash.t;\n amount : Tez_repr.t;\n}\n\nval encoding : t Data_encoding.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = {\n blinded_public_key_hash : Blinded_public_key_hash.t;\n amount : Tez_repr.t;\n}\n\nlet encoding =\n let open Data_encoding in\n conv\n (fun {blinded_public_key_hash; amount} ->\n (blinded_public_key_hash, amount))\n (fun (blinded_public_key_hash, amount) ->\n {blinded_public_key_hash; amount})\n (tup2 Blinded_public_key_hash.encoding Tez_repr.encoding)\n" ;
} ;
{ name = "Parameters_repr" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype bootstrap_account = {\n public_key_hash : Signature.Public_key_hash.t;\n public_key : Signature.Public_key.t option;\n amount : Tez_repr.t;\n}\n\ntype bootstrap_contract = {\n delegate : Signature.Public_key_hash.t;\n amount : Tez_repr.t;\n script : Script_repr.t;\n}\n\ntype t = {\n bootstrap_accounts : bootstrap_account list;\n bootstrap_contracts : bootstrap_contract list;\n commitments : Commitment_repr.t list;\n constants : Constants_repr.parametric;\n security_deposit_ramp_up_cycles : int option;\n no_reward_cycles : int option;\n}\n\nval encoding : t Data_encoding.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype bootstrap_account = {\n public_key_hash : Signature.Public_key_hash.t;\n public_key : Signature.Public_key.t option;\n amount : Tez_repr.t;\n}\n\ntype bootstrap_contract = {\n delegate : Signature.Public_key_hash.t;\n amount : Tez_repr.t;\n script : Script_repr.t;\n}\n\ntype t = {\n bootstrap_accounts : bootstrap_account list;\n bootstrap_contracts : bootstrap_contract list;\n commitments : Commitment_repr.t list;\n constants : Constants_repr.parametric;\n security_deposit_ramp_up_cycles : int option;\n no_reward_cycles : int option;\n}\n\nlet bootstrap_account_encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"Public_key_known\"\n (tup2 Signature.Public_key.encoding Tez_repr.encoding)\n (function\n | {public_key_hash; public_key = Some public_key; amount} ->\n assert (\n Signature.Public_key_hash.equal\n (Signature.Public_key.hash public_key)\n public_key_hash ) ;\n Some (public_key, amount)\n | {public_key = None} ->\n None)\n (fun (public_key, amount) ->\n {\n public_key = Some public_key;\n public_key_hash = Signature.Public_key.hash public_key;\n amount;\n });\n case\n (Tag 1)\n ~title:\"Public_key_unknown\"\n (tup2 Signature.Public_key_hash.encoding Tez_repr.encoding)\n (function\n | {public_key_hash; public_key = None; amount} ->\n Some (public_key_hash, amount)\n | {public_key = Some _} ->\n None)\n (fun (public_key_hash, amount) ->\n {public_key = None; public_key_hash; amount}) ]\n\nlet bootstrap_contract_encoding =\n let open Data_encoding in\n conv\n (fun {delegate; amount; script} -> (delegate, amount, script))\n (fun (delegate, amount, script) -> {delegate; amount; script})\n (obj3\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"amount\" Tez_repr.encoding)\n (req \"script\" Script_repr.encoding))\n\nlet encoding =\n let open Data_encoding in\n conv\n (fun { bootstrap_accounts;\n bootstrap_contracts;\n commitments;\n constants;\n security_deposit_ramp_up_cycles;\n no_reward_cycles } ->\n ( ( bootstrap_accounts,\n bootstrap_contracts,\n commitments,\n security_deposit_ramp_up_cycles,\n no_reward_cycles ),\n constants ))\n (fun ( ( bootstrap_accounts,\n bootstrap_contracts,\n commitments,\n security_deposit_ramp_up_cycles,\n no_reward_cycles ),\n constants ) ->\n {\n bootstrap_accounts;\n bootstrap_contracts;\n commitments;\n constants;\n security_deposit_ramp_up_cycles;\n no_reward_cycles;\n })\n (merge_objs\n (obj5\n (req \"bootstrap_accounts\" (list bootstrap_account_encoding))\n (dft \"bootstrap_contracts\" (list bootstrap_contract_encoding) [])\n (dft \"commitments\" (list Commitment_repr.encoding) [])\n (opt \"security_deposit_ramp_up_cycles\" int31)\n (opt \"no_reward_cycles\" int31))\n Constants_repr.parametric_encoding)\n" ;
} ;
{ name = "Sapling_repr" ;
interface = None ;
implementation = "(* The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE. *)\n\ntype transaction = Sapling.UTXO.transaction\n\nlet transaction_encoding = Sapling.UTXO.transaction_encoding\n\n(* The two data structures in the state are all ordered by position, a diff\n contains the elements starting from an offset position up to the most recent\n position. A diff can be applied to a state stored in a context to obtain a\n new state.\n Diffs are used by the Michelson interpreter during the evaluation of smart\n contracts to keep a temporary state that may be discarded.\n Diffs are also returned by an RPC to allow a client to synchronize its own\n state with the chain.\n *)\ntype diff = {\n commitments_and_ciphertexts :\n (Sapling.Commitment.t * Sapling.Ciphertext.t) list;\n nullifiers : Sapling.Nullifier.t list;\n}\n\nlet diff_encoding =\n let open Data_encoding in\n conv\n (fun d -> (d.commitments_and_ciphertexts, d.nullifiers))\n (fun (commitments_and_ciphertexts, nullifiers) ->\n ( match commitments_and_ciphertexts with\n | [] ->\n ()\n | (_cm_hd, ct_hd) :: rest ->\n let memo_size = Sapling.Ciphertext.get_memo_size ct_hd in\n List.iter\n (fun (_cm, ct) ->\n assert (\n Compare.Int.(Sapling.Ciphertext.get_memo_size ct = memo_size)\n ))\n rest ) ;\n {commitments_and_ciphertexts; nullifiers})\n (obj2\n (req\n \"commitments_and_ciphertexts\"\n (list (tup2 Sapling.Commitment.encoding Sapling.Ciphertext.encoding)))\n (req \"nullifiers\" (list Sapling.Nullifier.encoding)))\n\nmodule Memo_size = struct\n type t = int\n\n let encoding = Data_encoding.uint16\n\n let equal = Compare.Int.( = )\n\n let max_uint16 = 0xffff\n\n let max_uint16_z = Z.of_int max_uint16\n\n let err =\n Error\n ( \"a positive 16-bit integer (between 0 and \" ^ string_of_int max_uint16\n ^ \")\" )\n\n let parse_z z =\n if Compare.Z.(Z.zero <= z) && Compare.Z.(z <= max_uint16_z) then\n Ok (Z.to_int z)\n else err\n\n let unparse_to_z = Z.of_int\nend\n\nlet transaction_get_memo_size (transaction : Sapling.UTXO.transaction) =\n match transaction.outputs with\n | [] ->\n None\n | {ciphertext; _} :: _ ->\n (* Encoding ensures all ciphertexts have the same memo size. *)\n Some (Sapling.Ciphertext.get_memo_size ciphertext)\n" ;
} ;
{ name = "Lazy_storage_kind" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(**\n Lazy_storage offers a unified interface for specific Michelson datatype that\n behave somewhat lazily, because they are intended to be quite big.\n Instead of serializing/deserializing the whole value to/from the storage,\n only an identifier is used. The identifier acts like a pointer.\n When using the value in a Michelson script, some part of it may be read from\n the storage, and a lightweight diff is computed.\n The diff is effectively applied to the storage at the end of the execution.\n\n This module defines the different kinds of lazy storages and their basic\n properties. See also [Lazy_storage_diff].\n\n Lazy storage types are:\n - Big_map\n*)\n\n(**\n Lazy storage ids are kept as abstract as possible to avoid mixing them up.\n\n Behind the scene they are [Z.t]s but, within the protocol, only [parse_data]/\n [unparse_data] are allowed convert from/to it.\n\n Temporary ids may be used to pass values between contracts that won't be kept\n longer than the lifetime of the operation.\n Behind the scene, temporary ids are negative [Z.t]s.\n*)\nmodule type ID = sig\n type t\n\n val compare : t -> t -> int\n\n val encoding : t Data_encoding.t\n\n val rpc_arg : t RPC_arg.arg\n\n (** Initial value for ids: zero. *)\n val init : t\n\n (** In the protocol, to be used in parse_data only *)\n val parse_z : Z.t -> t\n\n (** In the protocol, to be used in unparse_data only *)\n val unparse_to_z : t -> Z.t\n\n val next : t -> t\n\n val is_temp : t -> bool\n\n (* To be used in storage: *)\n\n val path_length : int\n\n val to_path : t -> string list -> string list\n\n val of_path : string list -> t option\n\n (* To be removed once legacy big map diff is removed: *)\n\n val of_legacy_USE_ONLY_IN_Legacy_big_map_diff : Z.t -> t\n\n val to_legacy_USE_ONLY_IN_Legacy_big_map_diff : t -> Z.t\nend\n\nmodule Big_map : sig\n val title : string\n\n module Id : ID\n\n type alloc = {key_type : Script_repr.expr; value_type : Script_repr.expr}\n\n type update = {\n key : Script_repr.expr;\n (** The key is ignored by [apply_update] but is shown in the receipt,\n as specified in [print_big_map_diff]. *)\n key_hash : Script_expr_hash.t;\n value : Script_repr.expr option;\n }\n\n type updates = update list\n\n val alloc_encoding : alloc Data_encoding.t\n\n val updates_encoding : updates Data_encoding.t\nend\n\nmodule Sapling_state : sig\n val title : string\n\n module Id : ID\n\n type alloc = {memo_size : Sapling_repr.Memo_size.t}\n\n type updates = Sapling_repr.diff\n\n val alloc_encoding : alloc Data_encoding.t\n\n val updates_encoding : updates Data_encoding.t\nend\n\n(**\n Kinds of lazy storage.\n The GADT ensures operations are properly applied to the correct kind.\n\n ['id] the abstract type for the identifier of the kind.\n ['alloc] is the type used to construct a new value.\n ['updates] is the type used to update a value.\n*)\ntype ('id, 'alloc, 'updates) t =\n | Big_map : (Big_map.Id.t, Big_map.alloc, Big_map.updates) t\n | Sapling_state\n : (Sapling_state.Id.t, Sapling_state.alloc, Sapling_state.updates) t\n\ntype ex = Ex_Kind : (_, _, _) t -> ex\n\nval all : (int * ex) list\n\ntype (_, _) cmp = Eq : ('a, 'a) cmp | Neq\n\nval equal :\n ('i1, 'a1, 'u1) t ->\n ('i2, 'a2, 'u2) t ->\n ('i1 * 'a1 * 'u1, 'i2 * 'a2 * 'u2) cmp\n\ntype ('i, 'a, 'u) kind = ('i, 'a, 'u) t\n\n(**\n Type to manage temporary ids.\n Used only in the context.\n*)\nmodule Temp_ids : sig\n type t\n\n val init : t\n\n val fresh : ('i, 'a, 'u) kind -> t -> t * 'i\n\n val fold_s :\n ('i, 'a, 'u) kind -> ('acc -> 'i -> 'acc Lwt.t) -> t -> 'acc -> 'acc Lwt.t\nend\n\nmodule IdSet : sig\n type t\n\n type 'acc fold_f = {f : 'i 'a 'u. ('i, 'a, 'u) kind -> 'i -> 'acc -> 'acc}\n\n val empty : t\n\n val mem : ('i, 'a, 'u) kind -> 'i -> t -> bool\n\n val add : ('i, 'a, 'u) kind -> 'i -> t -> t\n\n val diff : t -> t -> t\n\n val fold : ('i, 'a, 'u) kind -> ('i -> 'acc -> 'acc) -> t -> 'acc -> 'acc\n\n val fold_all : 'acc fold_f -> t -> 'acc -> 'acc\nend\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule type Temp_id = sig\n type t\n\n val equal : t -> t -> bool\n\n val init : t\n\n val next : t -> t\nend\n\nmodule type ID = sig\n type t\n\n val compare : t -> t -> int\n\n val encoding : t Data_encoding.t\n\n val rpc_arg : t RPC_arg.arg\n\n val init : t\n\n (** In the protocol, to be used in parse_data only *)\n val parse_z : Z.t -> t\n\n (** In the protocol, to be used in unparse_data only *)\n val unparse_to_z : t -> Z.t\n\n val next : t -> t\n\n val is_temp : t -> bool\n\n val path_length : int\n\n val to_path : t -> string list -> string list\n\n val of_path : string list -> t option\n\n val of_legacy_USE_ONLY_IN_Legacy_big_map_diff : Z.t -> t\n\n val to_legacy_USE_ONLY_IN_Legacy_big_map_diff : t -> Z.t\nend\n\nmodule type Title = sig\n val title : string\nend\n\nmodule type TitleWithId = sig\n val title : string\n\n module Id : sig\n include ID\n\n module Temp : Temp_id with type t = private t\n end\n\n module IdSet : S.SET with type elt = Id.t\nend\n\nmodule MakeId (Title : Title) : TitleWithId = struct\n let title = Title.title\n\n let title_words = String.map (function '_' -> ' ' | c -> c) title\n\n let rpc_arg_error = Format.sprintf \"Cannot parse %s id\" title_words\n\n let description = Format.sprintf \"A %s identifier\" title_words\n\n let name = title ^ \"_id\"\n\n let encoding_title = String.capitalize_ascii title_words ^ \" identifier\"\n\n module Id = struct\n type t = Z.t\n\n let compare = Z.compare\n\n let encoding =\n Data_encoding.def name ~title:encoding_title ~description Data_encoding.z\n\n let rpc_arg =\n let construct = Z.to_string in\n let destruct hash =\n match Z.of_string hash with\n | exception _ ->\n Error rpc_arg_error\n | id ->\n Ok id\n in\n RPC_arg.make ~descr:description ~name ~construct ~destruct ()\n\n let init = Z.zero\n\n let parse_z (z : Z.t) : t = z\n\n let unparse_to_z (z : t) : Z.t = z\n\n let next = Z.succ\n\n let of_legacy_USE_ONLY_IN_Legacy_big_map_diff (z : Z.t) : t = z\n\n let to_legacy_USE_ONLY_IN_Legacy_big_map_diff (z : t) : Z.t = z\n\n module Temp = struct\n type nonrec t = t\n\n let equal = Z.equal\n\n let init = Z.of_int ~-1\n\n let next z = Z.sub z Z.one\n end\n\n let is_temp z = Compare.Z.(z < Z.zero)\n\n let path_length = 1\n\n let to_path z l = Z.to_string z :: l\n\n let of_path = function\n | [] | _ :: _ :: _ ->\n None\n | [z] ->\n Some (Z.of_string z)\n end\n\n module IdSet = Set.Make (Id)\nend\n\nmodule Big_map = struct\n include MakeId (struct\n let title = \"big_map\"\n end)\n\n type alloc = {key_type : Script_repr.expr; value_type : Script_repr.expr}\n\n type update = {\n key : Script_repr.expr;\n (** The key is ignored by [apply_update] but is shown in the receipt,\n as specified in [print_big_map_diff]. *)\n key_hash : Script_expr_hash.t;\n value : Script_repr.expr option;\n }\n\n type updates = update list\n\n let alloc_encoding =\n let open Data_encoding in\n conv\n (fun {key_type; value_type} -> (key_type, value_type))\n (fun (key_type, value_type) -> {key_type; value_type})\n (obj2\n (req \"key_type\" Script_repr.expr_encoding)\n (req \"value_type\" Script_repr.expr_encoding))\n\n let update_encoding =\n let open Data_encoding in\n conv\n (fun {key_hash; key; value} -> (key_hash, key, value))\n (fun (key_hash, key, value) -> {key_hash; key; value})\n (obj3\n (req \"key_hash\" Script_expr_hash.encoding)\n (req \"key\" Script_repr.expr_encoding)\n (opt \"value\" Script_repr.expr_encoding))\n\n let updates_encoding = Data_encoding.list update_encoding\nend\n\nmodule Sapling_state = struct\n include MakeId (struct\n let title = \"sapling_state\"\n end)\n\n type alloc = {memo_size : Sapling_repr.Memo_size.t}\n\n type updates = Sapling_repr.diff\n\n let alloc_encoding =\n let open Data_encoding in\n conv\n (fun {memo_size} -> memo_size)\n (fun memo_size -> {memo_size})\n (obj1 (req \"memo_size\" Sapling_repr.Memo_size.encoding))\n\n let updates_encoding = Sapling_repr.diff_encoding\nend\n\n(*\n When adding cases to this type, grep for [new lazy storage kind] in the code\n for locations to update.\n It must be:\n - the value [all] right below,\n - modules [Temp_ids], [IdSet] below,\n - the rest should be guided by type errors.\n*)\ntype ('id, 'alloc, 'updates) t =\n | Big_map : (Big_map.Id.t, Big_map.alloc, Big_map.updates) t\n | Sapling_state\n : (Sapling_state.Id.t, Sapling_state.alloc, Sapling_state.updates) t\n\ntype ex = Ex_Kind : (_, _, _) t -> ex\n\n(* /!\\ Don't forget to add new lazy storage kinds here. /!\\ *)\nlet all = [(0, Ex_Kind Big_map); (1, Ex_Kind Sapling_state)]\n\ntype (_, _) cmp = Eq : ('a, 'a) cmp | Neq\n\nlet equal :\n type i1 a1 u1 i2 a2 u2.\n (i1, a1, u1) t -> (i2, a2, u2) t -> (i1 * a1 * u1, i2 * a2 * u2) cmp =\n fun k1 k2 ->\n match (k1, k2) with\n | (Big_map, Big_map) ->\n Eq\n | (Sapling_state, Sapling_state) ->\n Eq\n | (Big_map, _) ->\n Neq\n | (_, Big_map) ->\n Neq\n\ntype ('i, 'a, 'u) kind = ('i, 'a, 'u) t\n\nmodule Temp_ids = struct\n type t = {\n big_map : Big_map.Id.Temp.t;\n sapling_state : Sapling_state.Id.Temp.t;\n }\n\n let init =\n {\n big_map = Big_map.Id.Temp.init;\n sapling_state = Sapling_state.Id.Temp.init;\n }\n\n let fresh : type i a u. (i, a, u) kind -> t -> t * i =\n fun kind temp_ids ->\n match kind with\n | Big_map ->\n let big_map = Big_map.Id.Temp.next temp_ids.big_map in\n ({temp_ids with big_map}, (big_map :> Big_map.Id.t))\n | Sapling_state ->\n let sapling_state =\n Sapling_state.Id.Temp.next temp_ids.sapling_state\n in\n ({temp_ids with sapling_state}, (sapling_state :> Sapling_state.Id.t))\n [@@coq_axiom \"gadt\"]\n\n let fold_s :\n type i a u.\n (i, a, u) kind -> ('acc -> i -> 'acc Lwt.t) -> t -> 'acc -> 'acc Lwt.t =\n fun kind f temp_ids acc ->\n let helper (type j) (module Temp_id : Temp_id with type t = j) ~last f =\n let rec aux acc id =\n if Temp_id.equal id last then Lwt.return acc\n else f acc id >>= fun acc -> aux acc (Temp_id.next id)\n in\n aux acc Temp_id.init\n in\n match kind with\n | Big_map ->\n helper\n (module Big_map.Id.Temp)\n ~last:temp_ids.big_map\n (fun acc temp_id -> f acc (temp_id :> i))\n | Sapling_state ->\n helper\n (module Sapling_state.Id.Temp)\n ~last:temp_ids.sapling_state\n (fun acc temp_id -> f acc (temp_id :> i))\n [@@coq_axiom \"gadt\"]\nend\n\nmodule IdSet = struct\n type t = {big_map : Big_map.IdSet.t; sapling_state : Sapling_state.IdSet.t}\n\n type 'acc fold_f = {f : 'i 'a 'u. ('i, 'a, 'u) kind -> 'i -> 'acc -> 'acc}\n\n let empty =\n {big_map = Big_map.IdSet.empty; sapling_state = Sapling_state.IdSet.empty}\n\n let mem (type i a u) (kind : (i, a, u) kind) (id : i) set =\n match (kind, set) with\n | (Big_map, {big_map}) ->\n Big_map.IdSet.mem id big_map\n | (Sapling_state, {sapling_state}) ->\n Sapling_state.IdSet.mem id sapling_state\n\n let add (type i a u) (kind : (i, a, u) kind) (id : i) set =\n match (kind, set) with\n | (Big_map, {big_map}) ->\n let big_map = Big_map.IdSet.add id big_map in\n {set with big_map}\n | (Sapling_state, {sapling_state}) ->\n let sapling_state = Sapling_state.IdSet.add id sapling_state in\n {set with sapling_state}\n\n let diff set1 set2 =\n let big_map = Big_map.IdSet.diff set1.big_map set2.big_map in\n let sapling_state =\n Sapling_state.IdSet.diff set1.sapling_state set2.sapling_state\n in\n {big_map; sapling_state}\n\n let fold (type i a u) (kind : (i, a, u) kind) (f : i -> 'acc -> 'acc) set\n (acc : 'acc) =\n match (kind, set) with\n | (Big_map, {big_map}) ->\n Big_map.IdSet.fold f big_map acc\n | (Sapling_state, {sapling_state}) ->\n Sapling_state.IdSet.fold f sapling_state acc\n\n let fold_all f set acc =\n List.fold_left\n (fun acc (_, Ex_Kind kind) -> fold kind (f.f kind) set acc)\n acc\n all\nend\n" ;
} ;
{ name = "Raw_context" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** {1 Errors} *)\n\ntype error += Too_many_internal_operations (* `Permanent *)\n\ntype missing_key_kind = Get | Set | Del | Copy\n\n(** An internal storage error that should not happen *)\ntype storage_error =\n | Incompatible_protocol_version of string\n | Missing_key of string list * missing_key_kind\n | Existing_key of string list\n | Corrupted_data of string list\n\ntype error += Storage_error of storage_error\n\ntype error += Failed_to_parse_parameter of bytes\n\ntype error += Failed_to_decode_parameter of Data_encoding.json * string\n\nval storage_error : storage_error -> 'a tzresult\n\n(** {1 Abstract Context} *)\n\n(** Abstract view of the context.\n Includes a handle to the functional key-value database\n ({!Context.t}) along with some in-memory values (gas, etc.). *)\ntype t\n\ntype context = t\n\ntype root_context = t\n\n(** Retrieves the state of the database and gives its abstract view.\n It also returns wether this is the first block validated\n with this version of the protocol. *)\nval prepare :\n level:Int32.t ->\n predecessor_timestamp:Time.t ->\n timestamp:Time.t ->\n fitness:Fitness.t ->\n Context.t ->\n context tzresult Lwt.t\n\ntype previous_protocol = Genesis of Parameters_repr.t | Delphi_007\n\nval prepare_first_block :\n level:int32 ->\n timestamp:Time.t ->\n fitness:Fitness.t ->\n Context.t ->\n (previous_protocol * context * Int32.t) tzresult Lwt.t\n\nval activate : context -> Protocol_hash.t -> t Lwt.t\n\nval fork_test_chain : context -> Protocol_hash.t -> Time.t -> t Lwt.t\n\n(** Returns the state of the database resulting of operations on its\n abstract view *)\nval recover : context -> Context.t\n\nval current_level : context -> Level_repr.t\n\nval predecessor_timestamp : context -> Time.t\n\nval current_timestamp : context -> Time.t\n\nval current_fitness : context -> Int64.t\n\nval set_current_fitness : context -> Int64.t -> t\n\nval constants : context -> Constants_repr.parametric\n\nval patch_constants :\n context ->\n (Constants_repr.parametric -> Constants_repr.parametric) ->\n context Lwt.t\n\nval first_level : context -> Raw_level_repr.t\n\n(** Increment the current block fee stash that will be credited to baker's\n frozen_fees account at finalize_application *)\nval add_fees : context -> Tez_repr.t -> context tzresult\n\n(** Increment the current block reward stash that will be credited to baker's\n frozen_fees account at finalize_application *)\nval add_rewards : context -> Tez_repr.t -> context tzresult\n\n(** Increment the current block deposit stash for a specific delegate. All the\n delegates' frozen_deposit accounts are credited at finalize_application *)\nval add_deposit :\n context -> Signature.Public_key_hash.t -> Tez_repr.t -> context tzresult\n\nval get_fees : context -> Tez_repr.t\n\nval get_rewards : context -> Tez_repr.t\n\nval get_deposits : context -> Tez_repr.t Signature.Public_key_hash.Map.t\n\ntype error += Gas_limit_too_high (* `Permanent *)\n\nval check_gas_limit : t -> 'a Gas_limit_repr.Arith.t -> unit tzresult\n\nval set_gas_limit : t -> 'a Gas_limit_repr.Arith.t -> t\n\nval set_gas_unlimited : t -> t\n\nval gas_level : t -> Gas_limit_repr.t\n\nval gas_consumed : since:t -> until:t -> Gas_limit_repr.Arith.fp\n\nval block_gas_level : t -> Gas_limit_repr.Arith.fp\n\nval init_storage_space_to_pay : t -> t\n\nval update_storage_space_to_pay : t -> Z.t -> t\n\nval update_allocated_contracts_count : t -> t\n\nval clear_storage_space_to_pay : t -> t * Z.t * int\n\ntype error += Undefined_operation_nonce (* `Permanent *)\n\nval init_origination_nonce : t -> Operation_hash.t -> t\n\nval origination_nonce : t -> Contract_repr.origination_nonce tzresult\n\nval increment_origination_nonce :\n t -> (t * Contract_repr.origination_nonce) tzresult\n\nval unset_origination_nonce : t -> t\n\n(** {1 Generic accessors} *)\n\ntype key = string list\n\ntype value = bytes\n\n(** All context manipulation functions. This signature is included\n as-is for direct context accesses, and used in {!Storage_functors}\n to provide restricted views to the context. *)\nmodule type T = sig\n type t\n\n type context = t\n\n (** Tells if the key is already defined as a value. *)\n val mem : context -> key -> bool Lwt.t\n\n (** Tells if the key is already defined as a directory. *)\n val dir_mem : context -> key -> bool Lwt.t\n\n (** Retrieve the value from the storage bucket ; returns a\n {!Storage_error Missing_key} if the key is not set. *)\n val get : context -> key -> value tzresult Lwt.t\n\n (** Retrieves the value from the storage bucket ; returns [None] if\n the data is not initialized. *)\n val get_option : context -> key -> value option Lwt.t\n\n (** Allocates the storage bucket and initializes it ; returns a\n {!Storage_error Existing_key} if the bucket exists. *)\n val init : context -> key -> value -> context tzresult Lwt.t\n\n (** Updates the content of the bucket ; returns a {!Storage_error\n Missing_key} if the value does not exists. *)\n val set : context -> key -> value -> context tzresult Lwt.t\n\n (** Allocates the data and initializes it with a value ; just\n updates it if the bucket exists. *)\n val init_set : context -> key -> value -> context Lwt.t\n\n (** When the value is [Some v], allocates the data and initializes\n it with [v] ; just updates it if the bucket exists. When the\n value is [None], delete the storage bucket when the value ; does\n nothing if the bucket does not exists. *)\n val set_option : context -> key -> value option -> context Lwt.t\n\n (** Delete the storage bucket ; returns a {!Storage_error\n Missing_key} if the bucket does not exists. *)\n val delete : context -> key -> context tzresult Lwt.t\n\n (** Removes the storage bucket and its contents ; does nothing if the\n bucket does not exists. *)\n val remove : context -> key -> context Lwt.t\n\n (** Recursively removes all the storage buckets and contents ; does\n nothing if no bucket exists. *)\n val remove_rec : context -> key -> context Lwt.t\n\n val copy : context -> from:key -> to_:key -> context tzresult Lwt.t\n\n (** Iterator on all the items of a given directory. *)\n val fold :\n context ->\n key ->\n init:'a ->\n f:(Context.key_or_dir -> 'a -> 'a Lwt.t) ->\n 'a Lwt.t\n\n (** Recursively list all subkeys of a given key. *)\n val keys : context -> key -> key list Lwt.t\n\n (** Recursive iterator on all the subkeys of a given key. *)\n val fold_keys :\n context -> key -> init:'a -> f:(key -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n (** Internally used in {!Storage_functors} to escape from a view. *)\n val project : context -> root_context\n\n (** Internally used in {!Storage_functors} to retrieve a full key\n from partial key relative a view. *)\n val absolute_key : context -> key -> key\n\n (** Internally used in {!Storage_functors} to consume gas from\n within a view. *)\n val consume_gas : context -> Gas_limit_repr.cost -> context tzresult\n\n (** Check if consume_gas will fail *)\n val check_enough_gas : context -> Gas_limit_repr.cost -> unit tzresult\n\n val description : context Storage_description.t\nend\n\ninclude T with type t := t and type context := context\n\n(** Initialize the local nonce used for preventing a script to\n duplicate an internal operation to replay it. *)\nval reset_internal_nonce : context -> context\n\n(** Increments the internal operation nonce. *)\nval fresh_internal_nonce : context -> (context * int) tzresult\n\n(** Mark an internal operation nonce as taken. *)\nval record_internal_nonce : context -> int -> context\n\n(** Check is the internal operation nonce has been taken. *)\nval internal_nonce_already_recorded : context -> int -> bool\n\n(** Returns a map where to each endorser's pkh is associated the list of its\n endorsing slots (in decreasing order) for a given level. *)\nval allowed_endorsements :\n context ->\n (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t\n\n(** Keep track of the number of endorsements that are included in a block *)\nval included_endorsements : context -> int\n\n(** Initializes the map of allowed endorsements, this function must only be\n called once. *)\nval init_endorsements :\n context ->\n (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t ->\n context\n\n(** Marks an endorsement in the map as used. *)\nval record_endorsement : context -> Signature.Public_key_hash.t -> context\n\nval fold_map_temporary_lazy_storage_ids :\n context ->\n (Lazy_storage_kind.Temp_ids.t -> Lazy_storage_kind.Temp_ids.t * 'res) ->\n context * 'res\n\nval map_temporary_lazy_storage_ids_s :\n context ->\n (Lazy_storage_kind.Temp_ids.t ->\n (context * Lazy_storage_kind.Temp_ids.t) Lwt.t) ->\n context Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule Int_set = Set.Make (Compare.Int)\n\ntype t = {\n context : Context.t;\n constants : Constants_repr.parametric;\n first_level : Raw_level_repr.t;\n level : Level_repr.t;\n predecessor_timestamp : Time.t;\n timestamp : Time.t;\n fitness : Int64.t;\n deposits : Tez_repr.t Signature.Public_key_hash.Map.t;\n included_endorsements : int;\n allowed_endorsements :\n (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t;\n fees : Tez_repr.t;\n rewards : Tez_repr.t;\n block_gas : Gas_limit_repr.Arith.fp;\n operation_gas : Gas_limit_repr.t;\n storage_space_to_pay : Z.t option;\n allocated_contracts : int option;\n origination_nonce : Contract_repr.origination_nonce option;\n temporary_lazy_storage_ids : Lazy_storage_kind.Temp_ids.t;\n internal_nonce : int;\n internal_nonces_used : Int_set.t;\n}\n\ntype context = t\n\ntype root_context = t\n\nlet current_level ctxt = ctxt.level\n\nlet predecessor_timestamp ctxt = ctxt.predecessor_timestamp\n\nlet current_timestamp ctxt = ctxt.timestamp\n\nlet current_fitness ctxt = ctxt.fitness\n\nlet first_level ctxt = ctxt.first_level\n\nlet constants ctxt = ctxt.constants\n\nlet recover ctxt = ctxt.context\n\nlet record_endorsement ctxt k =\n match Signature.Public_key_hash.Map.find_opt k ctxt.allowed_endorsements with\n | None ->\n assert false\n | Some (_, _, true) ->\n assert false (* right already used *)\n | Some (d, s, false) ->\n {\n ctxt with\n included_endorsements = ctxt.included_endorsements + List.length s;\n allowed_endorsements =\n Signature.Public_key_hash.Map.add\n k\n (d, s, true)\n ctxt.allowed_endorsements;\n }\n\nlet init_endorsements ctxt allowed_endorsements =\n if Signature.Public_key_hash.Map.is_empty allowed_endorsements then\n assert false (* can't initialize to empty *)\n else if Signature.Public_key_hash.Map.is_empty ctxt.allowed_endorsements then\n {ctxt with allowed_endorsements}\n else assert false\n\n(* can't initialize twice *)\n\nlet allowed_endorsements ctxt = ctxt.allowed_endorsements\n\nlet included_endorsements ctxt = ctxt.included_endorsements\n\ntype error += Too_many_internal_operations (* `Permanent *)\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Permanent\n ~id:\"too_many_internal_operations\"\n ~title:\"Too many internal operations\"\n ~description:\n \"A transaction exceeded the hard limit of internal operations it can emit\"\n empty\n (function Too_many_internal_operations -> Some () | _ -> None)\n (fun () -> Too_many_internal_operations)\n\nlet fresh_internal_nonce ctxt =\n if Compare.Int.(ctxt.internal_nonce >= 65_535) then\n error Too_many_internal_operations\n else\n ok\n ( {ctxt with internal_nonce = ctxt.internal_nonce + 1},\n ctxt.internal_nonce )\n\nlet reset_internal_nonce ctxt =\n {ctxt with internal_nonces_used = Int_set.empty; internal_nonce = 0}\n\nlet record_internal_nonce ctxt k =\n {ctxt with internal_nonces_used = Int_set.add k ctxt.internal_nonces_used}\n\nlet internal_nonce_already_recorded ctxt k =\n Int_set.mem k ctxt.internal_nonces_used\n\nlet set_current_fitness ctxt fitness = {ctxt with fitness}\n\nlet add_fees ctxt fees =\n Tez_repr.(ctxt.fees +? fees) >|? fun fees -> {ctxt with fees}\n\nlet add_rewards ctxt rewards =\n Tez_repr.(ctxt.rewards +? rewards) >|? fun rewards -> {ctxt with rewards}\n\nlet add_deposit ctxt delegate deposit =\n let previous =\n match Signature.Public_key_hash.Map.find_opt delegate ctxt.deposits with\n | Some tz ->\n tz\n | None ->\n Tez_repr.zero\n in\n Tez_repr.(previous +? deposit)\n >|? fun deposit ->\n let deposits =\n Signature.Public_key_hash.Map.add delegate deposit ctxt.deposits\n in\n {ctxt with deposits}\n\nlet get_deposits ctxt = ctxt.deposits\n\nlet get_rewards ctxt = ctxt.rewards\n\nlet get_fees ctxt = ctxt.fees\n\ntype error += Undefined_operation_nonce (* `Permanent *)\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Permanent\n ~id:\"undefined_operation_nonce\"\n ~title:\"Ill timed access to the origination nonce\"\n ~description:\n \"An origination was attempted out of the scope of a manager operation\"\n empty\n (function Undefined_operation_nonce -> Some () | _ -> None)\n (fun () -> Undefined_operation_nonce)\n\nlet init_origination_nonce ctxt operation_hash =\n let origination_nonce =\n Some (Contract_repr.initial_origination_nonce operation_hash)\n in\n {ctxt with origination_nonce}\n\nlet origination_nonce ctxt =\n match ctxt.origination_nonce with\n | None ->\n error Undefined_operation_nonce\n | Some origination_nonce ->\n ok origination_nonce\n\nlet increment_origination_nonce ctxt =\n match ctxt.origination_nonce with\n | None ->\n error Undefined_operation_nonce\n | Some cur_origination_nonce ->\n let origination_nonce =\n Some (Contract_repr.incr_origination_nonce cur_origination_nonce)\n in\n ok ({ctxt with origination_nonce}, cur_origination_nonce)\n\nlet unset_origination_nonce ctxt = {ctxt with origination_nonce = None}\n\ntype error += Gas_limit_too_high (* `Permanent *)\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Permanent\n ~id:\"gas_limit_too_high\"\n ~title:\"Gas limit out of protocol hard bounds\"\n ~description:\"A transaction tried to exceed the hard limit on gas\"\n empty\n (function Gas_limit_too_high -> Some () | _ -> None)\n (fun () -> Gas_limit_too_high)\n\nlet check_gas_limit ctxt (remaining : 'a Gas_limit_repr.Arith.t) =\n if\n Gas_limit_repr.Arith.(\n remaining > ctxt.constants.hard_gas_limit_per_operation\n || remaining < zero)\n then error Gas_limit_too_high\n else ok_unit\n\nlet set_gas_limit ctxt (remaining : 'a Gas_limit_repr.Arith.t) =\n let remaining = Gas_limit_repr.Arith.fp remaining in\n {ctxt with operation_gas = Limited {remaining}}\n\nlet set_gas_unlimited ctxt = {ctxt with operation_gas = Unaccounted}\n\nlet consume_gas ctxt cost =\n Gas_limit_repr.raw_consume ctxt.block_gas ctxt.operation_gas cost\n >>? fun (block_gas, operation_gas) -> ok {ctxt with block_gas; operation_gas}\n\nlet check_enough_gas ctxt cost =\n Gas_limit_repr.raw_check_enough ctxt.block_gas ctxt.operation_gas cost\n\nlet gas_level ctxt = ctxt.operation_gas\n\nlet block_gas_level ctxt = ctxt.block_gas\n\nlet gas_consumed ~since ~until =\n match (gas_level since, gas_level until) with\n | (Limited {remaining = before}, Limited {remaining = after}) ->\n Gas_limit_repr.Arith.sub before after\n | (_, _) ->\n Gas_limit_repr.Arith.zero\n\nlet init_storage_space_to_pay ctxt =\n match ctxt.storage_space_to_pay with\n | Some _ ->\n assert false\n | None ->\n {\n ctxt with\n storage_space_to_pay = Some Z.zero;\n allocated_contracts = Some 0;\n }\n\nlet update_storage_space_to_pay ctxt n =\n match ctxt.storage_space_to_pay with\n | None ->\n assert false\n | Some storage_space_to_pay ->\n {ctxt with storage_space_to_pay = Some (Z.add n storage_space_to_pay)}\n\nlet update_allocated_contracts_count ctxt =\n match ctxt.allocated_contracts with\n | None ->\n assert false\n | Some allocated_contracts ->\n {ctxt with allocated_contracts = Some (succ allocated_contracts)}\n\nlet clear_storage_space_to_pay ctxt =\n match (ctxt.storage_space_to_pay, ctxt.allocated_contracts) with\n | (None, _) | (_, None) ->\n assert false\n | (Some storage_space_to_pay, Some allocated_contracts) ->\n ( {ctxt with storage_space_to_pay = None; allocated_contracts = None},\n storage_space_to_pay,\n allocated_contracts )\n\ntype missing_key_kind = Get | Set | Del | Copy\n\ntype storage_error =\n | Incompatible_protocol_version of string\n | Missing_key of string list * missing_key_kind\n | Existing_key of string list\n | Corrupted_data of string list\n\nlet storage_error_encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"Incompatible_protocol_version\"\n (obj1 (req \"incompatible_protocol_version\" string))\n (function Incompatible_protocol_version arg -> Some arg | _ -> None)\n (fun arg -> Incompatible_protocol_version arg);\n case\n (Tag 1)\n ~title:\"Missing_key\"\n (obj2\n (req \"missing_key\" (list string))\n (req\n \"function\"\n (string_enum\n [(\"get\", Get); (\"set\", Set); (\"del\", Del); (\"copy\", Copy)])))\n (function Missing_key (key, f) -> Some (key, f) | _ -> None)\n (fun (key, f) -> Missing_key (key, f));\n case\n (Tag 2)\n ~title:\"Existing_key\"\n (obj1 (req \"existing_key\" (list string)))\n (function Existing_key key -> Some key | _ -> None)\n (fun key -> Existing_key key);\n case\n (Tag 3)\n ~title:\"Corrupted_data\"\n (obj1 (req \"corrupted_data\" (list string)))\n (function Corrupted_data key -> Some key | _ -> None)\n (fun key -> Corrupted_data key) ]\n\nlet pp_storage_error ppf = function\n | Incompatible_protocol_version version ->\n Format.fprintf\n ppf\n \"Found a context with an unexpected version '%s'.\"\n version\n | Missing_key (key, Get) ->\n Format.fprintf ppf \"Missing key '%s'.\" (String.concat \"/\" key)\n | Missing_key (key, Set) ->\n Format.fprintf\n ppf\n \"Cannot set undefined key '%s'.\"\n (String.concat \"/\" key)\n | Missing_key (key, Del) ->\n Format.fprintf\n ppf\n \"Cannot delete undefined key '%s'.\"\n (String.concat \"/\" key)\n | Missing_key (key, Copy) ->\n Format.fprintf\n ppf\n \"Cannot copy undefined key '%s'.\"\n (String.concat \"/\" key)\n | Existing_key key ->\n Format.fprintf\n ppf\n \"Cannot initialize defined key '%s'.\"\n (String.concat \"/\" key)\n | Corrupted_data key ->\n Format.fprintf\n ppf\n \"Failed to parse the data at '%s'.\"\n (String.concat \"/\" key)\n\ntype error += Storage_error of storage_error\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"context.storage_error\"\n ~title:\"Storage error (fatal internal error)\"\n ~description:\n \"An error that should never happen unless something has been deleted or \\\n corrupted in the database.\"\n ~pp:(fun ppf err ->\n Format.fprintf ppf \"@[<v 2>Storage error:@ %a@]\" pp_storage_error err)\n storage_error_encoding\n (function Storage_error err -> Some err | _ -> None)\n (fun err -> Storage_error err)\n\nlet storage_error err = error (Storage_error err)\n\n(* Initialization *********************************************************)\n\n(* This key should always be populated for every version of the\n protocol. It's absence meaning that the context is empty. *)\nlet version_key = [\"version\"]\n\nlet version_value = \"edo_008\"\n\nlet version = \"v1\"\n\nlet first_level_key = [version; \"first_level\"]\n\nlet constants_key = [version; \"constants\"]\n\nlet protocol_param_key = [\"protocol_parameters\"]\n\nlet get_first_level ctxt =\n Context.get ctxt first_level_key\n >|= function\n | None ->\n storage_error (Missing_key (first_level_key, Get))\n | Some bytes -> (\n match Data_encoding.Binary.of_bytes Raw_level_repr.encoding bytes with\n | None ->\n storage_error (Corrupted_data first_level_key)\n | Some level ->\n ok level )\n\nlet set_first_level ctxt level =\n let bytes =\n Data_encoding.Binary.to_bytes_exn Raw_level_repr.encoding level\n in\n Context.set ctxt first_level_key bytes >|= ok\n\ntype error += Failed_to_parse_parameter of bytes\n\ntype error += Failed_to_decode_parameter of Data_encoding.json * string\n\nlet () =\n register_error_kind\n `Temporary\n ~id:\"context.failed_to_parse_parameter\"\n ~title:\"Failed to parse parameter\"\n ~description:\"The protocol parameters are not valid JSON.\"\n ~pp:(fun ppf bytes ->\n Format.fprintf\n ppf\n \"@[<v 2>Cannot parse the protocol parameter:@ %s@]\"\n (Bytes.to_string bytes))\n Data_encoding.(obj1 (req \"contents\" bytes))\n (function Failed_to_parse_parameter data -> Some data | _ -> None)\n (fun data -> Failed_to_parse_parameter data) ;\n register_error_kind\n `Temporary\n ~id:\"context.failed_to_decode_parameter\"\n ~title:\"Failed to decode parameter\"\n ~description:\"Unexpected JSON object.\"\n ~pp:(fun ppf (json, msg) ->\n Format.fprintf\n ppf\n \"@[<v 2>Cannot decode the protocol parameter:@ %s@ %a@]\"\n msg\n Data_encoding.Json.pp\n json)\n Data_encoding.(obj2 (req \"contents\" json) (req \"error\" string))\n (function\n | Failed_to_decode_parameter (json, msg) -> Some (json, msg) | _ -> None)\n (fun (json, msg) -> Failed_to_decode_parameter (json, msg))\n\nlet get_proto_param ctxt =\n Context.get ctxt protocol_param_key\n >>= function\n | None ->\n failwith \"Missing protocol parameters.\"\n | Some bytes -> (\n match Data_encoding.Binary.of_bytes Data_encoding.json bytes with\n | None ->\n fail (Failed_to_parse_parameter bytes)\n | Some json -> (\n Context.remove_rec ctxt protocol_param_key\n >|= fun ctxt ->\n match Data_encoding.Json.destruct Parameters_repr.encoding json with\n | exception (Data_encoding.Json.Cannot_destruct _ as exn) ->\n Format.kasprintf\n failwith\n \"Invalid protocol_parameters: %a %a\"\n (fun ppf -> Data_encoding.Json.print_error ppf)\n exn\n Data_encoding.Json.pp\n json\n | param ->\n ok (param, ctxt) ) )\n\nlet set_constants ctxt constants =\n let bytes =\n Data_encoding.Binary.to_bytes_exn\n Constants_repr.parametric_encoding\n constants\n in\n Context.set ctxt constants_key bytes\n\nlet get_constants ctxt =\n Context.get ctxt constants_key\n >|= function\n | None ->\n failwith \"Internal error: cannot read constants in context.\"\n | Some bytes -> (\n match\n Data_encoding.Binary.of_bytes Constants_repr.parametric_encoding bytes\n with\n | None ->\n failwith \"Internal error: cannot parse constants in context.\"\n | Some constants ->\n ok constants )\n\nlet patch_constants ctxt f =\n let constants = f ctxt.constants in\n set_constants ctxt.context constants\n >|= fun context -> {ctxt with context; constants}\n\nlet check_inited ctxt =\n Context.get ctxt version_key\n >|= function\n | None ->\n failwith \"Internal error: un-initialized context.\"\n | Some bytes ->\n let s = Bytes.to_string bytes in\n if Compare.String.(s = version_value) then ok_unit\n else storage_error (Incompatible_protocol_version s)\n\nlet prepare ~level ~predecessor_timestamp ~timestamp ~fitness ctxt =\n Raw_level_repr.of_int32 level\n >>?= fun level ->\n Fitness_repr.to_int64 fitness\n >>?= fun fitness ->\n check_inited ctxt\n >>=? fun () ->\n get_constants ctxt\n >>=? fun constants ->\n get_first_level ctxt\n >|=? fun first_level ->\n let level =\n Level_repr.level_from_raw\n ~first_level\n ~blocks_per_cycle:constants.Constants_repr.blocks_per_cycle\n ~blocks_per_commitment:constants.Constants_repr.blocks_per_commitment\n level\n in\n {\n context = ctxt;\n constants;\n level;\n predecessor_timestamp;\n timestamp;\n fitness;\n first_level;\n allowed_endorsements = Signature.Public_key_hash.Map.empty;\n included_endorsements = 0;\n fees = Tez_repr.zero;\n rewards = Tez_repr.zero;\n deposits = Signature.Public_key_hash.Map.empty;\n operation_gas = Unaccounted;\n storage_space_to_pay = None;\n allocated_contracts = None;\n block_gas =\n Gas_limit_repr.Arith.fp constants.Constants_repr.hard_gas_limit_per_block;\n origination_nonce = None;\n temporary_lazy_storage_ids = Lazy_storage_kind.Temp_ids.init;\n internal_nonce = 0;\n internal_nonces_used = Int_set.empty;\n }\n\ntype previous_protocol = Genesis of Parameters_repr.t | Delphi_007\n\nlet check_and_update_protocol_version ctxt =\n Context.get ctxt version_key\n >>= (function\n | None ->\n failwith\n \"Internal error: un-initialized context in check_first_block.\"\n | Some bytes ->\n let s = Bytes.to_string bytes in\n if Compare.String.(s = version_value) then\n failwith \"Internal error: previously initialized context.\"\n else if Compare.String.(s = \"genesis\") then\n get_proto_param ctxt\n >|=? fun (param, ctxt) -> (Genesis param, ctxt)\n else if Compare.String.(s = \"delphi_007\") then\n return (Delphi_007, ctxt)\n else Lwt.return @@ storage_error (Incompatible_protocol_version s))\n >>=? fun (previous_proto, ctxt) ->\n Context.set ctxt version_key (Bytes.of_string version_value)\n >|= fun ctxt -> ok (previous_proto, ctxt)\n\nlet prepare_first_block ~level ~timestamp ~fitness ctxt =\n check_and_update_protocol_version ctxt\n >>=? fun (previous_proto, ctxt) ->\n ( match previous_proto with\n | Genesis param ->\n Raw_level_repr.of_int32 level\n >>?= fun first_level ->\n set_first_level ctxt first_level\n >>=? fun ctxt ->\n set_constants ctxt param.constants\n >|= fun ctxt -> ok (ctxt, param.constants.blocks_per_voting_period)\n | Delphi_007 ->\n get_constants ctxt\n >>=? fun c ->\n let prev_blocks_per_voting_period = c.blocks_per_voting_period in\n let constants =\n Constants_repr.\n {\n c with\n blocks_per_voting_period = 20480l;\n test_chain_duration = 1_228_800L;\n }\n in\n set_constants ctxt constants\n >>= fun ctxt -> return (ctxt, prev_blocks_per_voting_period) )\n >>=? fun (ctxt, prev_blocks_per_voting_period) ->\n prepare ctxt ~level ~predecessor_timestamp:timestamp ~timestamp ~fitness\n >|=? fun ctxt -> (previous_proto, ctxt, prev_blocks_per_voting_period)\n\nlet activate ({context = c; _} as s) h =\n Updater.activate c h >|= fun c -> {s with context = c}\n\nlet fork_test_chain ({context = c; _} as s) protocol expiration =\n Updater.fork_test_chain c ~protocol ~expiration\n >|= fun c -> {s with context = c}\n\n(* Generic context ********************************************************)\n\ntype key = string list\n\ntype value = bytes\n\nmodule type T = sig\n type t\n\n type context = t\n\n val mem : context -> key -> bool Lwt.t\n\n val dir_mem : context -> key -> bool Lwt.t\n\n val get : context -> key -> value tzresult Lwt.t\n\n val get_option : context -> key -> value option Lwt.t\n\n val init : context -> key -> value -> context tzresult Lwt.t\n\n val set : context -> key -> value -> context tzresult Lwt.t\n\n val init_set : context -> key -> value -> context Lwt.t\n\n val set_option : context -> key -> value option -> context Lwt.t\n\n val delete : context -> key -> context tzresult Lwt.t\n\n val remove : context -> key -> context Lwt.t\n\n val remove_rec : context -> key -> context Lwt.t\n\n val copy : context -> from:key -> to_:key -> context tzresult Lwt.t\n\n val fold :\n context ->\n key ->\n init:'a ->\n f:(Context.key_or_dir -> 'a -> 'a Lwt.t) ->\n 'a Lwt.t\n\n val keys : context -> key -> key list Lwt.t\n\n val fold_keys :\n context -> key -> init:'a -> f:(key -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n val project : context -> root_context\n\n val absolute_key : context -> key -> key\n\n val consume_gas : context -> Gas_limit_repr.cost -> context tzresult\n\n val check_enough_gas : context -> Gas_limit_repr.cost -> unit tzresult\n\n val description : context Storage_description.t\nend\n\nlet mem ctxt k = Context.mem ctxt.context k\n\nlet dir_mem ctxt k = Context.dir_mem ctxt.context k\n\nlet get ctxt k =\n Context.get ctxt.context k\n >|= function None -> storage_error (Missing_key (k, Get)) | Some v -> ok v\n\nlet get_option ctxt k = Context.get ctxt.context k\n\n(* Verify that the k is present before modifying *)\nlet set ctxt k v =\n Context.mem ctxt.context k\n >>= function\n | false ->\n Lwt.return @@ storage_error (Missing_key (k, Set))\n | true ->\n Context.set ctxt.context k v >|= fun context -> ok {ctxt with context}\n\n(* Verify that the k is not present before inserting *)\nlet init ctxt k v =\n Context.mem ctxt.context k\n >>= function\n | true ->\n Lwt.return @@ storage_error (Existing_key k)\n | false ->\n Context.set ctxt.context k v >|= fun context -> ok {ctxt with context}\n\n(* Does not verify that the key is present or not *)\nlet init_set ctxt k v =\n Context.set ctxt.context k v >|= fun context -> {ctxt with context}\n\n(* Verify that the key is present before deleting *)\nlet delete ctxt k =\n Context.mem ctxt.context k\n >>= function\n | false ->\n Lwt.return @@ storage_error (Missing_key (k, Del))\n | true ->\n Context.remove_rec ctxt.context k\n >|= fun context -> ok {ctxt with context}\n\n(* Do not verify before deleting *)\nlet remove ctxt k =\n Context.remove_rec ctxt.context k >|= fun context -> {ctxt with context}\n\nlet set_option ctxt k = function\n | None ->\n remove ctxt k\n | Some v ->\n init_set ctxt k v\n\nlet remove_rec ctxt k =\n Context.remove_rec ctxt.context k >|= fun context -> {ctxt with context}\n\nlet copy ctxt ~from ~to_ =\n Context.copy ctxt.context ~from ~to_\n >|= function\n | None ->\n storage_error (Missing_key (from, Copy))\n | Some context ->\n ok {ctxt with context}\n\nlet fold ctxt k ~init ~f = Context.fold ctxt.context k ~init ~f\n\nlet keys ctxt k = Context.keys ctxt.context k\n\nlet fold_keys ctxt k ~init ~f = Context.fold_keys ctxt.context k ~init ~f\n\nlet project x = x\n\nlet absolute_key _ k = k\n\nlet description = Storage_description.create ()\n\nlet fold_map_temporary_lazy_storage_ids ctxt f =\n f ctxt.temporary_lazy_storage_ids\n |> fun (temporary_lazy_storage_ids, x) ->\n ({ctxt with temporary_lazy_storage_ids}, x)\n\nlet map_temporary_lazy_storage_ids_s ctxt f =\n f ctxt.temporary_lazy_storage_ids\n >|= fun (ctxt, temporary_lazy_storage_ids) ->\n {ctxt with temporary_lazy_storage_ids}\n" ;
} ;
{ name = "Storage_costs" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Cost of reading [read_bytes] at a key of length [path_length]. *)\nval read_access : path_length:int -> read_bytes:int -> Gas_limit_repr.cost\n\n(** Cost of performing a single write access, writing [written_bytes] bytes. *)\nval write_access : written_bytes:int -> Gas_limit_repr.cost\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* The model for read accesses is the following:\n\n cost(path_length, read_bytes) = 200_000 + 5000 * path_length + 2 * read_bytes\n*)\nlet read_access ~path_length ~read_bytes =\n let base_cost = Z.of_int (200_000 + (5000 * path_length)) in\n Gas_limit_repr.atomic_step_cost\n (Z.add base_cost (Z.mul (Z.of_int 2) (Z.of_int read_bytes)))\n\n(* The model for write accesses is the following:\n\n cost(written_bytes) = 200_000 + 4 * written_bytes\n*)\nlet write_access ~written_bytes =\n Gas_limit_repr.atomic_step_cost\n (Z.add (Z.of_int 200_000) (Z.mul (Z.of_int 4) (Z.of_int written_bytes)))\n" ;
} ;
{ name = "Storage_sigs" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** {1 Entity Accessor Signatures} *)\n\n(** The generic signature of a single data accessor (a single value\n bound to a specific key in the hierarchical (key x value)\n database). *)\nmodule type Single_data_storage = sig\n type t\n\n type context = t\n\n (** The type of the value *)\n type value\n\n (** Tells if the data is already defined *)\n val mem : context -> bool Lwt.t\n\n (** Retrieve the value from the storage bucket ; returns a\n {!Storage_error} if the key is not set or if the deserialisation\n fails *)\n val get : context -> value tzresult Lwt.t\n\n (** Retrieves the value from the storage bucket ; returns [None] if\n the data is not initialized, or {!Storage_helpers.Storage_error}\n if the deserialisation fails *)\n val get_option : context -> value option tzresult Lwt.t\n\n (** Allocates the storage bucket and initializes it ; returns a\n {!Storage_error Existing_key} if the bucket exists *)\n val init : context -> value -> Raw_context.t tzresult Lwt.t\n\n (** Updates the content of the bucket ; returns a {!Storage_Error\n Missing_key} if the value does not exists *)\n val set : context -> value -> Raw_context.t tzresult Lwt.t\n\n (** Allocates the data and initializes it with a value ; just\n updates it if the bucket exists *)\n val init_set : context -> value -> Raw_context.t Lwt.t\n\n (** When the value is [Some v], allocates the data and initializes\n it with [v] ; just updates it if the bucket exists. When the\n value is [None], delete the storage bucket when the value ; does\n nothing if the bucket does not exists. *)\n val set_option : context -> value option -> Raw_context.t Lwt.t\n\n (** Delete the storage bucket ; returns a {!Storage_error\n Missing_key} if the bucket does not exists *)\n val delete : context -> Raw_context.t tzresult Lwt.t\n\n (** Removes the storage bucket and its contents ; does nothing if\n the bucket does not exists *)\n val remove : context -> Raw_context.t Lwt.t\nend\n\n(** Variant of {!Single_data_storage} with gas accounting. *)\nmodule type Single_carbonated_data_storage = sig\n type t\n\n type context = t\n\n (** The type of the value *)\n type value\n\n (** Tells if the data is already defined.\n Consumes [Gas_repr.read_bytes_cost Z.zero]. *)\n val mem : context -> (Raw_context.t * bool) tzresult Lwt.t\n\n (** Retrieve the value from the storage bucket ; returns a\n {!Storage_error} if the key is not set or if the deserialisation\n fails.\n Consumes [Gas_repr.read_bytes_cost <size of the value>]. *)\n val get : context -> (Raw_context.t * value) tzresult Lwt.t\n\n (** Retrieves the value from the storage bucket ; returns [None] if\n the data is not initialized, or {!Storage_helpers.Storage_error}\n if the deserialisation fails.\n Consumes [Gas_repr.read_bytes_cost <size of the value>] if present\n or [Gas_repr.read_bytes_cost Z.zero]. *)\n val get_option : context -> (Raw_context.t * value option) tzresult Lwt.t\n\n (** Allocates the storage bucket and initializes it ; returns a\n {!Storage_error Missing_key} if the bucket exists.\n Consumes [Gas_repr.write_bytes_cost <size of the value>].\n Returns the size. *)\n val init : context -> value -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Updates the content of the bucket ; returns a {!Storage_Error\n Existing_key} if the value does not exists.\n Consumes [Gas_repr.write_bytes_cost <size of the new value>].\n Returns the difference from the old to the new size. *)\n val set : context -> value -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Allocates the data and initializes it with a value ; just\n updates it if the bucket exists.\n Consumes [Gas_repr.write_bytes_cost <size of the new value>].\n Returns the difference from the old (maybe 0) to the new size, and a boolean\n indicating if a value was already associated to this key. *)\n val init_set :\n context -> value -> (Raw_context.t * int * bool) tzresult Lwt.t\n\n (** When the value is [Some v], allocates the data and initializes\n it with [v] ; just updates it if the bucket exists. When the\n value is [None], delete the storage bucket when the value ; does\n nothing if the bucket does not exists.\n Consumes the same gas cost as either {!remove} or {!init_set}.\n Returns the difference from the old (maybe 0) to the new size, and a boolean\n indicating if a value was already associated to this key. *)\n val set_option :\n context -> value option -> (Raw_context.t * int * bool) tzresult Lwt.t\n\n (** Delete the storage bucket ; returns a {!Storage_error\n Missing_key} if the bucket does not exists.\n Consumes [Gas_repr.write_bytes_cost Z.zero].\n Returns the freed size. *)\n val delete : context -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Removes the storage bucket and its contents ; does nothing if\n the bucket does not exists.\n Consumes [Gas_repr.write_bytes_cost Z.zero].\n Returns the freed size, and a boolean\n indicating if a value was already associated to this key. *)\n val remove : context -> (Raw_context.t * int * bool) tzresult Lwt.t\nend\n\n(** Restricted version of {!Indexed_data_storage} w/o iterators. *)\nmodule type Non_iterable_indexed_data_storage = sig\n type t\n\n type context = t\n\n (** An abstract type for keys *)\n type key\n\n (** The type of values *)\n type value\n\n (** Tells if a given key is already bound to a storage bucket *)\n val mem : context -> key -> bool Lwt.t\n\n (** Retrieve a value from the storage bucket at a given key ;\n returns {!Storage_error Missing_key} if the key is not set ;\n returns {!Storage_error Corrupted_data} if the deserialisation\n fails. *)\n val get : context -> key -> value tzresult Lwt.t\n\n (** Retrieve a value from the storage bucket at a given key ;\n returns [None] if the value is not set ; returns {!Storage_error\n Corrupted_data} if the deserialisation fails. *)\n val get_option : context -> key -> value option tzresult Lwt.t\n\n (** Updates the content of a bucket ; returns A {!Storage_Error\n Missing_key} if the value does not exists. *)\n val set : context -> key -> value -> Raw_context.t tzresult Lwt.t\n\n (** Allocates a storage bucket at the given key and initializes it ;\n returns a {!Storage_error Existing_key} if the bucket exists. *)\n val init : context -> key -> value -> Raw_context.t tzresult Lwt.t\n\n (** Allocates a storage bucket at the given key and initializes it\n with a value ; just updates it if the bucket exists. *)\n val init_set : context -> key -> value -> Raw_context.t Lwt.t\n\n (** When the value is [Some v], allocates the data and initializes\n it with [v] ; just updates it if the bucket exists. When the\n value is [None], delete the storage bucket when the value ; does\n nothing if the bucket does not exists. *)\n val set_option : context -> key -> value option -> Raw_context.t Lwt.t\n\n (** Delete a storage bucket and its contents ; returns a\n {!Storage_error Missing_key} if the bucket does not exists. *)\n val delete : context -> key -> Raw_context.t tzresult Lwt.t\n\n (** Removes a storage bucket and its contents ; does nothing if the\n bucket does not exists. *)\n val remove : context -> key -> Raw_context.t Lwt.t\nend\n\n(** Variant of {!Non_iterable_indexed_data_storage} with gas accounting. *)\nmodule type Non_iterable_indexed_carbonated_data_storage = sig\n type t\n\n type context = t\n\n (** An abstract type for keys *)\n type key\n\n (** The type of values *)\n type value\n\n (** Tells if a given key is already bound to a storage bucket.\n Consumes [Gas_repr.read_bytes_cost Z.zero]. *)\n val mem : context -> key -> (Raw_context.t * bool) tzresult Lwt.t\n\n (** Retrieve a value from the storage bucket at a given key ;\n returns {!Storage_error Missing_key} if the key is not set ;\n returns {!Storage_error Corrupted_data} if the deserialisation\n fails.\n Consumes [Gas_repr.read_bytes_cost <size of the value>]. *)\n val get : context -> key -> (Raw_context.t * value) tzresult Lwt.t\n\n (** Retrieve a value from the storage bucket at a given key ;\n returns [None] if the value is not set ; returns {!Storage_error\n Corrupted_data} if the deserialisation fails.\n Consumes [Gas_repr.read_bytes_cost <size of the value>] if present\n or [Gas_repr.read_bytes_cost Z.zero]. *)\n val get_option :\n context -> key -> (Raw_context.t * value option) tzresult Lwt.t\n\n (** Updates the content of a bucket ; returns A {!Storage_Error\n Missing_key} if the value does not exists.\n Consumes serialization cost.\n Consumes [Gas_repr.write_bytes_cost <size of the new value>].\n Returns the difference from the old to the new size. *)\n val set : context -> key -> value -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Allocates a storage bucket at the given key and initializes it ;\n returns a {!Storage_error Existing_key} if the bucket exists.\n Consumes serialization cost.\n Consumes [Gas_repr.write_bytes_cost <size of the value>].\n Returns the size. *)\n val init : context -> key -> value -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Allocates a storage bucket at the given key and initializes it\n with a value ; just updates it if the bucket exists.\n Consumes serialization cost.\n Consumes [Gas_repr.write_bytes_cost <size of the new value>].\n Returns the difference from the old (maybe 0) to the new size, and a boolean\n indicating if a value was already associated to this key. *)\n val init_set :\n context -> key -> value -> (Raw_context.t * int * bool) tzresult Lwt.t\n\n (** When the value is [Some v], allocates the data and initializes\n it with [v] ; just updates it if the bucket exists. When the\n value is [None], delete the storage bucket when the value ; does\n nothing if the bucket does not exists.\n Consumes serialization cost.\n Consumes the same gas cost as either {!remove} or {!init_set}.\n Returns the difference from the old (maybe 0) to the new size, and a boolean\n indicating if a value was already associated to this key. *)\n val set_option :\n context ->\n key ->\n value option ->\n (Raw_context.t * int * bool) tzresult Lwt.t\n\n (** Delete a storage bucket and its contents ; returns a\n {!Storage_error Missing_key} if the bucket does not exists.\n Consumes [Gas_repr.write_bytes_cost Z.zero].\n Returns the freed size. *)\n val delete : context -> key -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Removes a storage bucket and its contents ; does nothing if the\n bucket does not exists.\n Consumes [Gas_repr.write_bytes_cost Z.zero].\n Returns the freed size, and a boolean\n indicating if a value was already associated to this key. *)\n val remove : context -> key -> (Raw_context.t * int * bool) tzresult Lwt.t\nend\n\n(** The generic signature of indexed data accessors (a set of values\n of the same type indexed by keys of the same form in the\n hierarchical (key x value) database). *)\nmodule type Indexed_data_storage = sig\n include Non_iterable_indexed_data_storage\n\n (** Empties all the keys and associated data. *)\n val clear : context -> Raw_context.t Lwt.t\n\n (** Lists all the keys. *)\n val keys : context -> key list Lwt.t\n\n (** Lists all the keys and associated data. *)\n val bindings : context -> (key * value) list Lwt.t\n\n (** Iterates over all the keys and associated data. *)\n val fold :\n context -> init:'a -> f:(key -> value -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n (** Iterate over all the keys. *)\n val fold_keys : context -> init:'a -> f:(key -> 'a -> 'a Lwt.t) -> 'a Lwt.t\nend\n\nmodule type Indexed_data_snapshotable_storage = sig\n type snapshot\n\n type key\n\n include Indexed_data_storage with type key := key\n\n module Snapshot :\n Indexed_data_storage\n with type key = snapshot * key\n and type value = value\n and type t = t\n\n val snapshot_exists : context -> snapshot -> bool Lwt.t\n\n val snapshot : context -> snapshot -> Raw_context.t tzresult Lwt.t\n\n val delete_snapshot : context -> snapshot -> Raw_context.t Lwt.t\nend\n\n(** The generic signature of a data set accessor (a set of values\n bound to a specific key prefix in the hierarchical (key x value)\n database). *)\nmodule type Data_set_storage = sig\n type t\n\n type context = t\n\n (** The type of elements. *)\n type elt\n\n (** Tells if a elt is a member of the set *)\n val mem : context -> elt -> bool Lwt.t\n\n (** Adds a elt is a member of the set *)\n val add : context -> elt -> Raw_context.t Lwt.t\n\n (** Removes a elt of the set ; does nothing if not a member *)\n val del : context -> elt -> Raw_context.t Lwt.t\n\n (** Adds/Removes a elt of the set *)\n val set : context -> elt -> bool -> Raw_context.t Lwt.t\n\n (** Returns the elements of the set, deserialized in a list in no\n particular order. *)\n val elements : context -> elt list Lwt.t\n\n (** Iterates over the elements of the set. *)\n val fold : context -> init:'a -> f:(elt -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n (** Removes all elements in the set *)\n val clear : context -> Raw_context.t Lwt.t\nend\n\n(** Variant of {!Data_set_storage} with gas accounting. *)\nmodule type Carbonated_data_set_storage = sig\n type t\n\n type context = t\n\n (** The type of elements. *)\n type elt\n\n (** Tells whether an elt is a member of the set.\n Consumes [Gas_repr.read_bytes_cost Z.zero] *)\n val mem : context -> elt -> (Raw_context.t * bool) tzresult Lwt.t\n\n (** Adds an elt as a member of the set.\n Consumes [Gas_repr.write_bytes_cost <size of the new value>].\n Returns the difference from the old (maybe 0) to the new size. *)\n val init : context -> elt -> (Raw_context.t * int) tzresult Lwt.t\n\n (** Removes an elt from the set ; does nothing if not a member.\n Consumes [Gas_repr.write_bytes_cost Z.zero].\n Returns the freed size, and a boolean\n indicating if a value was already associated to this key. *)\n val del : context -> elt -> (Raw_context.t * int * bool) tzresult Lwt.t\n\n val fold_keys_unaccounted :\n context -> init:'acc -> f:(elt -> 'acc -> 'acc Lwt.t) -> 'acc Lwt.t\nend\n\nmodule type NAME = sig\n val name : Raw_context.key\nend\n\nmodule type VALUE = sig\n type t\n\n val encoding : t Data_encoding.t\nend\n\nmodule type REGISTER = sig\n val ghost : bool\nend\n\nmodule type Indexed_raw_context = sig\n type t\n\n type context = t\n\n type key\n\n type 'a ipath\n\n val clear : context -> Raw_context.t Lwt.t\n\n val fold_keys : context -> init:'a -> f:(key -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n val keys : context -> key list Lwt.t\n\n val resolve : context -> string list -> key list Lwt.t\n\n val remove_rec : context -> key -> context Lwt.t\n\n val copy : context -> from:key -> to_:key -> context tzresult Lwt.t\n\n module Make_set (R : REGISTER) (N : NAME) :\n Data_set_storage with type t = t and type elt = key\n\n module Make_map (N : NAME) (V : VALUE) :\n Indexed_data_storage\n with type t = t\n and type key = key\n and type value = V.t\n\n module Make_carbonated_map (N : NAME) (V : VALUE) :\n Non_iterable_indexed_carbonated_data_storage\n with type t = t\n and type key = key\n and type value = V.t\n\n module Raw_context : Raw_context.T with type t = t ipath\nend\n" ;
} ;
{ name = "Storage_functors" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Tezos Protocol Implementation - Typed storage builders. *)\n\nopen Storage_sigs\n\nmodule Registered : REGISTER\n\nmodule Ghost : REGISTER\n\nmodule Make_subcontext (R : REGISTER) (C : Raw_context.T) (N : NAME) :\n Raw_context.T with type t = C.t\n\nmodule Make_single_data_storage\n (R : REGISTER)\n (C : Raw_context.T)\n (N : NAME)\n (V : VALUE) : Single_data_storage with type t = C.t and type value = V.t\n\nmodule type INDEX = sig\n type t\n\n val path_length : int\n\n val to_path : t -> string list -> string list\n\n val of_path : string list -> t option\n\n type 'a ipath\n\n val args : ('a, t, 'a ipath) Storage_description.args\nend\n\nmodule Pair (I1 : INDEX) (I2 : INDEX) : INDEX with type t = I1.t * I2.t\n\nmodule Make_data_set_storage (C : Raw_context.T) (I : INDEX) :\n Data_set_storage with type t = C.t and type elt = I.t\n\nmodule Make_carbonated_data_set_storage (C : Raw_context.T) (I : INDEX) :\n Carbonated_data_set_storage with type t = C.t and type elt = I.t\n\nmodule Make_indexed_data_storage (C : Raw_context.T) (I : INDEX) (V : VALUE) :\n Indexed_data_storage\n with type t = C.t\n and type key = I.t\n and type value = V.t\n\nmodule Make_indexed_carbonated_data_storage\n (C : Raw_context.T)\n (I : INDEX)\n (V : VALUE) :\n Non_iterable_indexed_carbonated_data_storage\n with type t = C.t\n and type key = I.t\n and type value = V.t\n\nmodule Make_indexed_data_snapshotable_storage\n (C : Raw_context.T)\n (Snapshot : INDEX)\n (I : INDEX)\n (V : VALUE) :\n Indexed_data_snapshotable_storage\n with type t = C.t\n and type snapshot = Snapshot.t\n and type key = I.t\n and type value = V.t\n\nmodule Make_indexed_subcontext (C : Raw_context.T) (I : INDEX) :\n Indexed_raw_context\n with type t = C.t\n and type key = I.t\n and type 'a ipath = 'a I.ipath\n\nmodule type WRAPPER = sig\n type t\n\n type key\n\n val wrap : t -> key\n\n val unwrap : key -> t option\nend\n\nmodule Wrap_indexed_data_storage\n (C : Indexed_data_storage)\n (K : WRAPPER with type key := C.key) :\n Indexed_data_storage\n with type t = C.t\n and type key = K.t\n and type value = C.value\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Storage_sigs\n\nmodule Registered = struct\n let ghost = false\nend\n\nmodule Ghost = struct\n let ghost = true\nend\n\nmodule Make_encoder (V : VALUE) = struct\n let of_bytes ~key b =\n match Data_encoding.Binary.of_bytes V.encoding b with\n | None ->\n error (Raw_context.Storage_error (Corrupted_data key))\n | Some v ->\n Ok v\n\n let to_bytes v =\n match Data_encoding.Binary.to_bytes V.encoding v with\n | Some b ->\n b\n | None ->\n Bytes.empty\nend\n\nlet len_name = \"len\"\n\nlet data_name = \"data\"\n\nlet encode_len_value bytes =\n let length = Bytes.length bytes in\n Data_encoding.(Binary.to_bytes_exn int31) length\n\nlet decode_len_value key len =\n match Data_encoding.(Binary.of_bytes int31) len with\n | None ->\n error (Raw_context.Storage_error (Corrupted_data key))\n | Some len ->\n ok len\n\nlet map_key f = function `Key k -> `Key (f k) | `Dir k -> `Dir (f k)\n\nmodule Make_subcontext (R : REGISTER) (C : Raw_context.T) (N : NAME) :\n Raw_context.T with type t = C.t = struct\n type t = C.t\n\n type context = t\n\n let name_length = List.length N.name\n\n let to_key k = N.name @ k\n\n let of_key k = Misc.remove_elem_from_list name_length k\n\n let mem t k = C.mem t (to_key k)\n\n let dir_mem t k = C.dir_mem t (to_key k)\n\n let get t k = C.get t (to_key k)\n\n let get_option t k = C.get_option t (to_key k)\n\n let init t k v = C.init t (to_key k) v\n\n let set t k v = C.set t (to_key k) v\n\n let init_set t k v = C.init_set t (to_key k) v\n\n let set_option t k v = C.set_option t (to_key k) v\n\n let delete t k = C.delete t (to_key k)\n\n let remove t k = C.remove t (to_key k)\n\n let remove_rec t k = C.remove_rec t (to_key k)\n\n let copy t ~from ~to_ = C.copy t ~from:(to_key from) ~to_:(to_key to_)\n\n let fold t k ~init ~f =\n C.fold t (to_key k) ~init ~f:(fun k acc -> f (map_key of_key k) acc)\n\n let keys t k = C.keys t (to_key k) >|= fun keys -> List.map of_key keys\n\n let fold_keys t k ~init ~f =\n C.fold_keys t (to_key k) ~init ~f:(fun k acc -> f (of_key k) acc)\n\n let project = C.project\n\n let absolute_key c k = C.absolute_key c (to_key k)\n\n let consume_gas = C.consume_gas\n\n let check_enough_gas = C.check_enough_gas\n\n let description =\n let description =\n if R.ghost then Storage_description.create () else C.description\n in\n Storage_description.register_named_subcontext description N.name\nend\n\nmodule Make_single_data_storage\n (R : REGISTER)\n (C : Raw_context.T)\n (N : NAME)\n (V : VALUE) : Single_data_storage with type t = C.t and type value = V.t =\nstruct\n type t = C.t\n\n type context = t\n\n type value = V.t\n\n let mem t = C.mem t N.name\n\n include Make_encoder (V)\n\n let get t =\n C.get t N.name\n >>=? fun b ->\n let key = C.absolute_key t N.name in\n Lwt.return (of_bytes ~key b)\n\n let get_option t =\n C.get_option t N.name\n >|= function\n | None ->\n ok_none\n | Some b ->\n let key = C.absolute_key t N.name in\n of_bytes ~key b >|? fun v -> Some v\n\n let init t v = C.init t N.name (to_bytes v) >|=? fun t -> C.project t\n\n let set t v = C.set t N.name (to_bytes v) >|=? fun t -> C.project t\n\n let init_set t v = C.init_set t N.name (to_bytes v) >|= fun t -> C.project t\n\n let set_option t v =\n C.set_option t N.name (Option.map to_bytes v) >|= fun t -> C.project t\n\n let remove t = C.remove t N.name >|= fun t -> C.project t\n\n let delete t = C.delete t N.name >|=? fun t -> C.project t\n\n let () =\n let open Storage_description in\n let description =\n if R.ghost then Storage_description.create () else C.description\n in\n register_value\n ~get:get_option\n (register_named_subcontext description N.name)\n V.encoding\nend\n\nmodule type INDEX = sig\n type t\n\n val path_length : int\n\n val to_path : t -> string list -> string list\n\n val of_path : string list -> t option\n\n type 'a ipath\n\n val args : ('a, t, 'a ipath) Storage_description.args\nend\n\nmodule Pair (I1 : INDEX) (I2 : INDEX) : INDEX with type t = I1.t * I2.t =\nstruct\n type t = I1.t * I2.t\n\n let path_length = I1.path_length + I2.path_length\n\n let to_path (x, y) l = I1.to_path x (I2.to_path y l)\n\n let of_path l =\n match Misc.take I1.path_length l with\n | None ->\n None\n | Some (l1, l2) -> (\n match (I1.of_path l1, I2.of_path l2) with\n | (Some x, Some y) ->\n Some (x, y)\n | _ ->\n None )\n\n type 'a ipath = 'a I1.ipath I2.ipath\n\n let args = Storage_description.Pair (I1.args, I2.args)\nend\n\nmodule Make_data_set_storage (C : Raw_context.T) (I : INDEX) :\n Data_set_storage with type t = C.t and type elt = I.t = struct\n type t = C.t\n\n type context = t\n\n type elt = I.t\n\n let inited = Bytes.of_string \"inited\"\n\n let mem s i = C.mem s (I.to_path i [])\n\n let add s i = C.init_set s (I.to_path i []) inited >|= fun t -> C.project t\n\n let del s i = C.remove s (I.to_path i []) >|= fun t -> C.project t\n\n let set s i = function true -> add s i | false -> del s i\n\n let clear s = C.remove_rec s [] >|= fun t -> C.project t\n\n let fold s ~init ~f =\n let rec dig i path acc =\n if Compare.Int.(i <= 1) then\n C.fold s path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir _ ->\n Lwt.return acc\n | `Key file -> (\n match I.of_path file with\n | None ->\n assert false\n | Some p ->\n f p acc ))\n else\n C.fold s path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir k ->\n dig (i - 1) k acc\n | `Key _ ->\n Lwt.return acc)\n in\n dig I.path_length [] init\n\n let elements s = fold s ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc))\n\n let () =\n let open Storage_description in\n let unpack = unpack I.args in\n register_value (* TODO fixme 'elements...' *)\n ~get:(fun c ->\n let (c, k) = unpack c in\n mem c k >>= function true -> return_some true | false -> return_none)\n (register_indexed_subcontext\n ~list:(fun c -> elements c >|= ok)\n C.description\n I.args)\n Data_encoding.bool\nend\n\nmodule Make_indexed_data_storage (C : Raw_context.T) (I : INDEX) (V : VALUE) :\n Indexed_data_storage\n with type t = C.t\n and type key = I.t\n and type value = V.t = struct\n type t = C.t\n\n type context = t\n\n type key = I.t\n\n type value = V.t\n\n include Make_encoder (V)\n\n let mem s i = C.mem s (I.to_path i [])\n\n let get s i =\n C.get s (I.to_path i [])\n >>=? fun b ->\n let key = C.absolute_key s (I.to_path i []) in\n Lwt.return (of_bytes ~key b)\n\n let get_option s i =\n C.get_option s (I.to_path i [])\n >|= function\n | None ->\n ok_none\n | Some b ->\n let key = C.absolute_key s (I.to_path i []) in\n of_bytes ~key b >|? fun v -> Some v\n\n let set s i v =\n C.set s (I.to_path i []) (to_bytes v) >|=? fun t -> C.project t\n\n let init s i v =\n C.init s (I.to_path i []) (to_bytes v) >|=? fun t -> C.project t\n\n let init_set s i v =\n C.init_set s (I.to_path i []) (to_bytes v) >|= fun t -> C.project t\n\n let set_option s i v =\n C.set_option s (I.to_path i []) (Option.map to_bytes v)\n >|= fun t -> C.project t\n\n let remove s i = C.remove s (I.to_path i []) >|= fun t -> C.project t\n\n let delete s i = C.delete s (I.to_path i []) >|=? fun t -> C.project t\n\n let clear s = C.remove_rec s [] >|= fun t -> C.project t\n\n let fold_keys s ~init ~f =\n let rec dig i path acc =\n if Compare.Int.(i <= 1) then\n C.fold s path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir _ ->\n Lwt.return acc\n | `Key file -> (\n match I.of_path file with\n | None ->\n assert false\n | Some path ->\n f path acc ))\n else\n C.fold s path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir k ->\n dig (i - 1) k acc\n | `Key _ ->\n Lwt.return acc)\n in\n dig I.path_length [] init\n\n let fold s ~init ~f =\n let f path acc =\n get s path\n >>= function\n | Error _ ->\n (* FIXME: silently ignore unparsable data *)\n Lwt.return acc\n | Ok v ->\n f path v acc\n in\n fold_keys s ~init ~f\n\n let bindings s =\n fold s ~init:[] ~f:(fun p v acc -> Lwt.return ((p, v) :: acc))\n\n let keys s = fold_keys s ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc))\n\n let () =\n let open Storage_description in\n let unpack = unpack I.args in\n register_value\n ~get:(fun c ->\n let (c, k) = unpack c in\n get_option c k)\n (register_indexed_subcontext\n ~list:(fun c -> keys c >|= ok)\n C.description\n I.args)\n V.encoding\nend\n\n(* Internal-use-only version of {!Make_indexed_carbonated_data_storage} to\n expose fold_keys_unaccounted *)\nmodule Make_indexed_carbonated_data_storage_INTERNAL\n (C : Raw_context.T)\n (I : INDEX)\n (V : VALUE) =\nstruct\n type t = C.t\n\n type context = t\n\n type key = I.t\n\n type value = V.t\n\n include Make_encoder (V)\n\n let data_key i = I.to_path i [data_name]\n\n let len_key i = I.to_path i [len_name]\n\n let consume_mem_gas c key =\n C.consume_gas\n c\n (Storage_costs.read_access ~path_length:(List.length key) ~read_bytes:0)\n\n let existing_size c i =\n C.get_option c (len_key i)\n >|= function\n | None ->\n ok (0, false)\n | Some len ->\n decode_len_value (len_key i) len >|? fun len -> (len, true)\n\n let consume_read_gas get c i =\n let len_key = len_key i in\n get c len_key\n >>=? fun len ->\n Lwt.return\n ( decode_len_value len_key len\n >>? fun read_bytes ->\n let cost =\n Storage_costs.read_access\n ~path_length:(List.length len_key)\n ~read_bytes\n in\n C.consume_gas c cost )\n\n (* For the future: here, we bill a generic cost for encoding the value\n to bytes. It would be cleaner for users of this functor to provide\n gas costs for the encoding. *)\n let consume_serialize_write_gas set c i v =\n let bytes = to_bytes v in\n let len = Bytes.length bytes in\n C.consume_gas c (Gas_limit_repr.alloc_mbytes_cost len)\n >>?= fun c ->\n let cost = Storage_costs.write_access ~written_bytes:len in\n C.consume_gas c cost\n >>?= fun c ->\n set c (len_key i) (encode_len_value bytes) >|=? fun c -> (c, bytes)\n\n let consume_remove_gas del c i =\n C.consume_gas c (Storage_costs.write_access ~written_bytes:0)\n >>?= fun c -> del c (len_key i)\n\n let mem s i =\n let key = data_key i in\n consume_mem_gas s key\n >>?= fun s -> C.mem s key >|= fun exists -> ok (C.project s, exists)\n\n let get s i =\n consume_read_gas C.get s i\n >>=? fun s ->\n C.get s (data_key i)\n >>=? fun b ->\n let key = C.absolute_key s (data_key i) in\n Lwt.return (of_bytes ~key b >|? fun v -> (C.project s, v))\n\n let get_option s i =\n let key = data_key i in\n consume_mem_gas s key\n >>?= fun s ->\n C.mem s key\n >>= fun exists ->\n if exists then get s i >|=? fun (s, v) -> (s, Some v)\n else return (C.project s, None)\n\n let set s i v =\n existing_size s i\n >>=? fun (prev_size, _) ->\n consume_serialize_write_gas C.set s i v\n >>=? fun (s, bytes) ->\n C.set s (data_key i) bytes\n >|=? fun t ->\n let size_diff = Bytes.length bytes - prev_size in\n (C.project t, size_diff)\n\n let init s i v =\n consume_serialize_write_gas C.init s i v\n >>=? fun (s, bytes) ->\n C.init s (data_key i) bytes\n >|=? fun t ->\n let size = Bytes.length bytes in\n (C.project t, size)\n\n let init_set s i v =\n let init_set s i v = C.init_set s i v >|= ok in\n existing_size s i\n >>=? fun (prev_size, existed) ->\n consume_serialize_write_gas init_set s i v\n >>=? fun (s, bytes) ->\n init_set s (data_key i) bytes\n >|=? fun t ->\n let size_diff = Bytes.length bytes - prev_size in\n (C.project t, size_diff, existed)\n\n let remove s i =\n let remove s i = C.remove s i >|= ok in\n existing_size s i\n >>=? fun (prev_size, existed) ->\n consume_remove_gas remove s i\n >>=? fun s ->\n remove s (data_key i) >|=? fun t -> (C.project t, prev_size, existed)\n\n let delete s i =\n existing_size s i\n >>=? fun (prev_size, _) ->\n consume_remove_gas C.delete s i\n >>=? fun s -> C.delete s (data_key i) >|=? fun t -> (C.project t, prev_size)\n\n let set_option s i v =\n match v with None -> remove s i | Some v -> init_set s i v\n\n let fold_keys_unaccounted s ~init ~f =\n let rec dig i path acc =\n if Compare.Int.(i <= 0) then\n C.fold s path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir _ ->\n Lwt.return acc\n | `Key file -> (\n match List.rev file with\n | last :: _ when Compare.String.(last = len_name) ->\n Lwt.return acc\n | last :: rest when Compare.String.(last = data_name) -> (\n let file = List.rev rest in\n match I.of_path file with\n | None ->\n assert false\n | Some path ->\n f path acc )\n | _ ->\n assert false ))\n else\n C.fold s path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir k ->\n dig (i - 1) k acc\n | `Key _ ->\n Lwt.return acc)\n in\n dig I.path_length [] init\n\n let keys_unaccounted s =\n fold_keys_unaccounted s ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc))\n\n let () =\n let open Storage_description in\n let unpack = unpack I.args in\n register_value (* TODO export consumed gas ?? *)\n ~get:(fun c ->\n let (c, k) = unpack c in\n get_option c k >|=? fun (_, v) -> v)\n (register_indexed_subcontext\n ~list:(fun c -> keys_unaccounted c >|= ok)\n C.description\n I.args)\n V.encoding\nend\n\nmodule Make_indexed_carbonated_data_storage : functor\n (C : Raw_context.T)\n (I : INDEX)\n (V : VALUE)\n ->\n Non_iterable_indexed_carbonated_data_storage\n with type t = C.t\n and type key = I.t\n and type value = V.t =\n Make_indexed_carbonated_data_storage_INTERNAL\n\nmodule Make_carbonated_data_set_storage (C : Raw_context.T) (I : INDEX) :\n Carbonated_data_set_storage with type t = C.t and type elt = I.t = struct\n module V = struct\n type t = unit\n\n let encoding = Data_encoding.unit\n end\n\n module M = Make_indexed_carbonated_data_storage_INTERNAL (C) (I) (V)\n\n type t = M.t\n\n type context = t\n\n type elt = I.t\n\n let mem = M.mem\n\n let init s i = M.init s i ()\n\n let del s i = M.remove s i\n\n let fold_keys_unaccounted = M.fold_keys_unaccounted\nend\n\nmodule Make_indexed_data_snapshotable_storage\n (C : Raw_context.T)\n (Snapshot_index : INDEX)\n (I : INDEX)\n (V : VALUE) :\n Indexed_data_snapshotable_storage\n with type t = C.t\n and type snapshot = Snapshot_index.t\n and type key = I.t\n and type value = V.t = struct\n type snapshot = Snapshot_index.t\n\n let data_name = [\"current\"]\n\n let snapshot_name = [\"snapshot\"]\n\n module C_data =\n Make_subcontext (Registered) (C)\n (struct\n let name = data_name\n end)\n\n module C_snapshot =\n Make_subcontext (Registered) (C)\n (struct\n let name = snapshot_name\n end)\n\n include Make_indexed_data_storage (C_data) (I) (V)\n module Snapshot =\n Make_indexed_data_storage (C_snapshot) (Pair (Snapshot_index) (I)) (V)\n\n let snapshot_path id = snapshot_name @ Snapshot_index.to_path id []\n\n let snapshot_exists s id = C.dir_mem s (snapshot_path id)\n\n let snapshot s id =\n C.copy s ~from:data_name ~to_:(snapshot_path id) >|=? fun t -> C.project t\n\n let delete_snapshot s id =\n C.remove_rec s (snapshot_path id) >|= fun t -> C.project t\nend\n\nmodule Make_indexed_subcontext (C : Raw_context.T) (I : INDEX) :\n Indexed_raw_context\n with type t = C.t\n and type key = I.t\n and type 'a ipath = 'a I.ipath = struct\n type t = C.t\n\n type context = t\n\n type key = I.t\n\n type 'a ipath = 'a I.ipath\n\n let clear t = C.remove_rec t [] >|= fun t -> C.project t\n\n let fold_keys t ~init ~f =\n let rec dig i path acc =\n if Compare.Int.(i <= 0) then\n match I.of_path path with\n | None ->\n assert false\n | Some path ->\n f path acc\n else\n C.fold t path ~init:acc ~f:(fun k acc ->\n match k with\n | `Dir k ->\n dig (i - 1) k acc\n | `Key _ ->\n Lwt.return acc)\n in\n dig I.path_length [] init\n\n let keys t = fold_keys t ~init:[] ~f:(fun i acc -> Lwt.return (i :: acc))\n\n let list t k = C.fold t k ~init:[] ~f:(fun k acc -> Lwt.return (k :: acc))\n\n let remove_rec t k = C.remove_rec t (I.to_path k [])\n\n let copy t ~from ~to_ =\n C.copy t ~from:(I.to_path from []) ~to_:(I.to_path to_ [])\n\n let description =\n Storage_description.register_indexed_subcontext\n ~list:(fun c -> keys c >|= ok)\n C.description\n I.args\n\n let unpack = Storage_description.unpack I.args\n\n let pack = Storage_description.pack I.args\n\n module Raw_context = struct\n type t = C.t I.ipath\n\n type context = t\n\n let to_key i k = I.to_path i k\n\n let of_key k = Misc.remove_elem_from_list I.path_length k\n\n let mem c k =\n let (t, i) = unpack c in\n C.mem t (to_key i k)\n\n let dir_mem c k =\n let (t, i) = unpack c in\n C.dir_mem t (to_key i k)\n\n let get c k =\n let (t, i) = unpack c in\n C.get t (to_key i k)\n\n let get_option c k =\n let (t, i) = unpack c in\n C.get_option t (to_key i k)\n\n let init c k v =\n let (t, i) = unpack c in\n C.init t (to_key i k) v >|=? fun t -> pack t i\n\n let set c k v =\n let (t, i) = unpack c in\n C.set t (to_key i k) v >|=? fun t -> pack t i\n\n let init_set c k v =\n let (t, i) = unpack c in\n C.init_set t (to_key i k) v >|= fun t -> pack t i\n\n let set_option c k v =\n let (t, i) = unpack c in\n C.set_option t (to_key i k) v >|= fun t -> pack t i\n\n let delete c k =\n let (t, i) = unpack c in\n C.delete t (to_key i k) >|=? fun t -> pack t i\n\n let remove c k =\n let (t, i) = unpack c in\n C.remove t (to_key i k) >|= fun t -> pack t i\n\n let remove_rec c k =\n let (t, i) = unpack c in\n C.remove_rec t (to_key i k) >|= fun t -> pack t i\n\n let copy c ~from ~to_ =\n let (t, i) = unpack c in\n C.copy t ~from:(to_key i from) ~to_:(to_key i to_) >|=? fun t -> pack t i\n\n let fold c k ~init ~f =\n let (t, i) = unpack c in\n C.fold t (to_key i k) ~init ~f:(fun k acc -> f (map_key of_key k) acc)\n\n let keys c k =\n let (t, i) = unpack c in\n C.keys t (to_key i k) >|= fun keys -> List.map of_key keys\n\n let fold_keys c k ~init ~f =\n let (t, i) = unpack c in\n C.fold_keys t (to_key i k) ~init ~f:(fun k acc -> f (of_key k) acc)\n\n let project c =\n let (t, _) = unpack c in\n C.project t\n\n let absolute_key c k =\n let (t, i) = unpack c in\n C.absolute_key t (to_key i k)\n\n let consume_gas c g =\n let (t, i) = unpack c in\n C.consume_gas t g >>? fun t -> ok (pack t i)\n\n let check_enough_gas c g =\n let (t, _i) = unpack c in\n C.check_enough_gas t g\n\n let description = description\n end\n\n let resolve t prefix =\n let rec loop i prefix = function\n | [] when Compare.Int.(i = I.path_length) -> (\n match I.of_path prefix with\n | None ->\n assert false\n | Some path ->\n Lwt.return [path] )\n | [] ->\n list t prefix\n >>= fun prefixes ->\n Lwt_list.map_s\n (function `Key prefix | `Dir prefix -> loop (i + 1) prefix [])\n prefixes\n >|= List.flatten\n | [d] when Compare.Int.(i = I.path_length - 1) ->\n if Compare.Int.(i >= I.path_length) then invalid_arg \"IO.resolve\" ;\n list t prefix\n >>= fun prefixes ->\n Lwt_list.map_s\n (function\n | `Key prefix | `Dir prefix -> (\n match\n Misc.remove_prefix ~prefix:d (List.hd (List.rev prefix))\n with\n | None ->\n Lwt.return_nil\n | Some _ ->\n loop (i + 1) prefix [] ))\n prefixes\n >|= List.flatten\n | \"\" :: ds ->\n list t prefix\n >>= fun prefixes ->\n Lwt_list.map_s\n (function `Key prefix | `Dir prefix -> loop (i + 1) prefix ds)\n prefixes\n >|= List.flatten\n | d :: ds -> (\n if Compare.Int.(i >= I.path_length) then invalid_arg \"IO.resolve\" ;\n C.dir_mem t (prefix @ [d])\n >>= function\n | true -> loop (i + 1) (prefix @ [d]) ds | false -> Lwt.return_nil )\n in\n loop 0 [] prefix\n\n module Make_set (R : REGISTER) (N : NAME) = struct\n type t = C.t\n\n type context = t\n\n type elt = I.t\n\n let inited = Bytes.of_string \"inited\"\n\n let mem s i = Raw_context.mem (pack s i) N.name\n\n let add s i =\n Raw_context.init_set (pack s i) N.name inited\n >|= fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let del s i =\n Raw_context.remove (pack s i) N.name\n >|= fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let set s i = function true -> add s i | false -> del s i\n\n let clear s =\n fold_keys s ~init:s ~f:(fun i s ->\n Raw_context.remove (pack s i) N.name\n >|= fun c ->\n let (s, _) = unpack c in\n s)\n >|= fun t -> C.project t\n\n let fold s ~init ~f =\n fold_keys s ~init ~f:(fun i acc ->\n mem s i >>= function true -> f i acc | false -> Lwt.return acc)\n\n let elements s = fold s ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc))\n\n let () =\n let open Storage_description in\n let unpack = unpack I.args in\n let description =\n if R.ghost then Storage_description.create ()\n else Raw_context.description\n in\n register_value\n ~get:(fun c ->\n let (c, k) = unpack c in\n mem c k\n >>= function true -> return_some true | false -> return_none)\n (register_named_subcontext description N.name)\n Data_encoding.bool\n end\n\n module Make_map (N : NAME) (V : VALUE) = struct\n type t = C.t\n\n type context = t\n\n type key = I.t\n\n type value = V.t\n\n include Make_encoder (V)\n\n let mem s i = Raw_context.mem (pack s i) N.name\n\n let get s i =\n Raw_context.get (pack s i) N.name\n >>=? fun b ->\n let key = Raw_context.absolute_key (pack s i) N.name in\n Lwt.return (of_bytes ~key b)\n\n let get_option s i =\n Raw_context.get_option (pack s i) N.name\n >|= function\n | None ->\n ok_none\n | Some b ->\n let key = Raw_context.absolute_key (pack s i) N.name in\n of_bytes ~key b >|? fun v -> Some v\n\n let set s i v =\n Raw_context.set (pack s i) N.name (to_bytes v)\n >|=? fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let init s i v =\n Raw_context.init (pack s i) N.name (to_bytes v)\n >|=? fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let init_set s i v =\n Raw_context.init_set (pack s i) N.name (to_bytes v)\n >|= fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let set_option s i v =\n Raw_context.set_option (pack s i) N.name (Option.map to_bytes v)\n >|= fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let remove s i =\n Raw_context.remove (pack s i) N.name\n >|= fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let delete s i =\n Raw_context.delete (pack s i) N.name\n >|=? fun c ->\n let (s, _) = unpack c in\n C.project s\n\n let clear s =\n fold_keys s ~init:s ~f:(fun i s ->\n Raw_context.remove (pack s i) N.name\n >|= fun c ->\n let (s, _) = unpack c in\n s)\n >|= fun t -> C.project t\n\n let fold s ~init ~f =\n fold_keys s ~init ~f:(fun i acc ->\n get s i >>= function Error _ -> Lwt.return acc | Ok v -> f i v acc)\n\n let bindings s =\n fold s ~init:[] ~f:(fun p v acc -> Lwt.return ((p, v) :: acc))\n\n let fold_keys s ~init ~f =\n fold_keys s ~init ~f:(fun i acc ->\n mem s i >>= function false -> Lwt.return acc | true -> f i acc)\n\n let keys s = fold_keys s ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc))\n\n let () =\n let open Storage_description in\n let unpack = unpack I.args in\n register_value\n ~get:(fun c ->\n let (c, k) = unpack c in\n get_option c k)\n (register_named_subcontext Raw_context.description N.name)\n V.encoding\n end\n\n module Make_carbonated_map (N : NAME) (V : VALUE) = struct\n type t = C.t\n\n type context = t\n\n type key = I.t\n\n type value = V.t\n\n include Make_encoder (V)\n\n let len_name = len_name :: N.name\n\n let data_name = data_name :: N.name\n\n let path_length = List.length N.name + 1\n\n let consume_mem_gas c =\n Raw_context.consume_gas\n c\n (Storage_costs.read_access ~path_length ~read_bytes:0)\n\n let existing_size c =\n Raw_context.get_option c len_name\n >|= function\n | None ->\n ok (0, false)\n | Some len ->\n decode_len_value len_name len >|? fun len -> (len, true)\n\n let consume_read_gas get c =\n get c len_name\n >>=? fun len ->\n Lwt.return\n ( decode_len_value len_name len\n >>? fun read_bytes ->\n Raw_context.consume_gas\n c\n (Storage_costs.read_access ~path_length ~read_bytes) )\n\n let consume_write_gas set c v =\n let bytes = to_bytes v in\n let len = Bytes.length bytes in\n Raw_context.consume_gas c (Storage_costs.write_access ~written_bytes:len)\n >>?= fun c ->\n set c len_name (encode_len_value bytes) >|=? fun c -> (c, bytes)\n\n let consume_remove_gas del c =\n Raw_context.consume_gas c (Storage_costs.write_access ~written_bytes:0)\n >>?= fun c -> del c len_name\n\n let mem s i =\n consume_mem_gas (pack s i)\n >>?= fun c ->\n Raw_context.mem c data_name >|= fun res -> ok (Raw_context.project c, res)\n\n let get s i =\n consume_read_gas Raw_context.get (pack s i)\n >>=? fun c ->\n Raw_context.get c data_name\n >>=? fun b ->\n let key = Raw_context.absolute_key c data_name in\n Lwt.return (of_bytes ~key b >|? fun v -> (Raw_context.project c, v))\n\n let get_option s i =\n consume_mem_gas (pack s i)\n >>?= fun c ->\n let (s, _) = unpack c in\n Raw_context.mem (pack s i) data_name\n >>= fun exists ->\n if exists then get s i >|=? fun (s, v) -> (s, Some v)\n else return (C.project s, None)\n\n let set s i v =\n existing_size (pack s i)\n >>=? fun (prev_size, _) ->\n consume_write_gas Raw_context.set (pack s i) v\n >>=? fun (c, bytes) ->\n Raw_context.set c data_name bytes\n >|=? fun c ->\n let size_diff = Bytes.length bytes - prev_size in\n (Raw_context.project c, size_diff)\n\n let init s i v =\n consume_write_gas Raw_context.init (pack s i) v\n >>=? fun (c, bytes) ->\n Raw_context.init c data_name bytes\n >|=? fun c ->\n let size = Bytes.length bytes in\n (Raw_context.project c, size)\n\n let init_set s i v =\n let init_set c k v = Raw_context.init_set c k v >|= ok in\n existing_size (pack s i)\n >>=? fun (prev_size, existed) ->\n consume_write_gas init_set (pack s i) v\n >>=? fun (c, bytes) ->\n init_set c data_name bytes\n >|=? fun c ->\n let size_diff = Bytes.length bytes - prev_size in\n (Raw_context.project c, size_diff, existed)\n\n let remove s i =\n let remove c k = Raw_context.remove c k >|= ok in\n existing_size (pack s i)\n >>=? fun (prev_size, existed) ->\n consume_remove_gas remove (pack s i)\n >>=? fun c ->\n remove c data_name\n >|=? fun c -> (Raw_context.project c, prev_size, existed)\n\n let delete s i =\n existing_size (pack s i)\n >>=? fun (prev_size, _) ->\n consume_remove_gas Raw_context.delete (pack s i)\n >>=? fun c ->\n Raw_context.delete c data_name\n >|=? fun c -> (Raw_context.project c, prev_size)\n\n let set_option s i v =\n match v with None -> remove s i | Some v -> init_set s i v\n\n let () =\n let open Storage_description in\n let unpack = unpack I.args in\n register_value\n ~get:(fun c ->\n let (c, k) = unpack c in\n get_option c k >|=? fun (_, v) -> v)\n (register_named_subcontext Raw_context.description N.name)\n V.encoding\n end\nend\n\nmodule type WRAPPER = sig\n type t\n\n type key\n\n val wrap : t -> key\n\n val unwrap : key -> t option\nend\n\nmodule Wrap_indexed_data_storage\n (C : Indexed_data_storage)\n (K : WRAPPER with type key := C.key) =\nstruct\n type t = C.t\n\n type context = C.t\n\n type key = K.t\n\n type value = C.value\n\n let mem ctxt k = C.mem ctxt (K.wrap k)\n\n let get ctxt k = C.get ctxt (K.wrap k)\n\n let get_option ctxt k = C.get_option ctxt (K.wrap k)\n\n let set ctxt k v = C.set ctxt (K.wrap k) v\n\n let init ctxt k v = C.init ctxt (K.wrap k) v\n\n let init_set ctxt k v = C.init_set ctxt (K.wrap k) v\n\n let set_option ctxt k v = C.set_option ctxt (K.wrap k) v\n\n let delete ctxt k = C.delete ctxt (K.wrap k)\n\n let remove ctxt k = C.remove ctxt (K.wrap k)\n\n let clear ctxt = C.clear ctxt\n\n let fold ctxt ~init ~f =\n C.fold ctxt ~init ~f:(fun k v acc ->\n match K.unwrap k with None -> Lwt.return acc | Some k -> f k v acc)\n\n let bindings s =\n fold s ~init:[] ~f:(fun p v acc -> Lwt.return ((p, v) :: acc))\n\n let fold_keys s ~init ~f =\n C.fold_keys s ~init ~f:(fun k acc ->\n match K.unwrap k with None -> Lwt.return acc | Some k -> f k acc)\n\n let keys s = fold_keys s ~init:[] ~f:(fun p acc -> Lwt.return (p :: acc))\nend\n" ;
} ;
{ name = "Storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Tezos Protocol Implementation - Typed storage\n\n This module hides the hierarchical (key x value) database under\n pre-allocated typed accessors for all persistent entities of the\n tezos context.\n\n This interface enforces no invariant on the contents of the\n database. Its goal is to centralize all accessors in order to have\n a complete view over the database contents and avoid key\n collisions. *)\n\nopen Storage_sigs\n\nmodule Block_priority : sig\n val get : Raw_context.t -> int tzresult Lwt.t\n\n val set : Raw_context.t -> int -> Raw_context.t tzresult Lwt.t\n\n val init : Raw_context.t -> int -> Raw_context.t tzresult Lwt.t\nend\n\nmodule Roll : sig\n (** Storage from this submodule must only be accessed through the\n module `Roll`. *)\n\n module Owner :\n Indexed_data_snapshotable_storage\n with type key = Roll_repr.t\n and type snapshot = Cycle_repr.t * int\n and type value = Signature.Public_key.t\n and type t := Raw_context.t\n\n val clear : Raw_context.t -> Raw_context.t Lwt.t\n\n (** The next roll to be allocated. *)\n module Next :\n Single_data_storage\n with type value = Roll_repr.t\n and type t := Raw_context.t\n\n (** Rolls linked lists represent both account owned and free rolls.\n All rolls belongs either to the limbo list or to an owned list. *)\n\n (** Head of the linked list of rolls in limbo *)\n module Limbo :\n Single_data_storage\n with type value = Roll_repr.t\n and type t := Raw_context.t\n\n (** Rolls associated to contracts, a linked list per contract *)\n module Delegate_roll_list :\n Indexed_data_storage\n with type key = Signature.Public_key_hash.t\n and type value = Roll_repr.t\n and type t := Raw_context.t\n\n (** Use this to iter on a linked list of rolls *)\n module Successor :\n Indexed_data_storage\n with type key = Roll_repr.t\n and type value = Roll_repr.t\n and type t := Raw_context.t\n\n (** The tez of a contract that are not assigned to rolls *)\n module Delegate_change :\n Indexed_data_storage\n with type key = Signature.Public_key_hash.t\n and type value = Tez_repr.t\n and type t := Raw_context.t\n\n (** Index of the randomly selected roll snapshot of a given cycle. *)\n module Snapshot_for_cycle :\n Indexed_data_storage\n with type key = Cycle_repr.t\n and type value = int\n and type t := Raw_context.t\n\n (** Last roll in the snapshoted roll allocation of a given cycle. *)\n module Last_for_snapshot :\n Indexed_data_storage\n with type key = int\n and type value = Roll_repr.t\n and type t = Raw_context.t * Cycle_repr.t\nend\n\nmodule Contract : sig\n (** Storage from this submodule must only be accessed through the\n module `Contract`. *)\n\n module Global_counter : sig\n val get : Raw_context.t -> Z.t tzresult Lwt.t\n\n val set : Raw_context.t -> Z.t -> Raw_context.t tzresult Lwt.t\n\n val init : Raw_context.t -> Z.t -> Raw_context.t tzresult Lwt.t\n end\n\n (** The domain of alive contracts *)\n val fold :\n Raw_context.t ->\n init:'a ->\n f:(Contract_repr.t -> 'a -> 'a Lwt.t) ->\n 'a Lwt.t\n\n val list : Raw_context.t -> Contract_repr.t list Lwt.t\n\n (** All the tez possessed by a contract, including rolls and change *)\n module Balance :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Tez_repr.t\n and type t := Raw_context.t\n\n (** Frozen balance, see 'delegate_storage.mli' for more explanation.\n Always update `Delegates_with_frozen_balance` accordingly. *)\n module Frozen_deposits :\n Indexed_data_storage\n with type key = Cycle_repr.t\n and type value = Tez_repr.t\n and type t = Raw_context.t * Contract_repr.t\n\n module Frozen_fees :\n Indexed_data_storage\n with type key = Cycle_repr.t\n and type value = Tez_repr.t\n and type t = Raw_context.t * Contract_repr.t\n\n module Frozen_rewards :\n Indexed_data_storage\n with type key = Cycle_repr.t\n and type value = Tez_repr.t\n and type t = Raw_context.t * Contract_repr.t\n\n (** The manager of a contract *)\n module Manager :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Manager_repr.t\n and type t := Raw_context.t\n\n (** The delegate of a contract, if any. *)\n module Delegate :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Signature.Public_key_hash.t\n and type t := Raw_context.t\n\n (** All contracts (implicit and originated) that are delegated, if any *)\n module Delegated :\n Data_set_storage\n with type elt = Contract_repr.t\n and type t = Raw_context.t * Contract_repr.t\n\n module Inactive_delegate :\n Data_set_storage with type elt = Contract_repr.t and type t = Raw_context.t\n\n (** The cycle where the delegate should be deactivated. *)\n module Delegate_desactivation :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Cycle_repr.t\n and type t := Raw_context.t\n\n module Counter :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Z.t\n and type t := Raw_context.t\n\n module Code :\n Non_iterable_indexed_carbonated_data_storage\n with type key = Contract_repr.t\n and type value = Script_repr.lazy_expr\n and type t := Raw_context.t\n\n module Storage :\n Non_iterable_indexed_carbonated_data_storage\n with type key = Contract_repr.t\n and type value = Script_repr.lazy_expr\n and type t := Raw_context.t\n\n (** Current storage space in bytes.\n Includes code, global storage and big map elements. *)\n module Used_storage_space :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Z.t\n and type t := Raw_context.t\n\n (** Maximal space available without needing to burn new fees. *)\n module Paid_storage_space :\n Indexed_data_storage\n with type key = Contract_repr.t\n and type value = Z.t\n and type t := Raw_context.t\nend\n\nmodule Big_map : sig\n type id = Lazy_storage_kind.Big_map.Id.t\n\n module Next : sig\n val incr : Raw_context.t -> (Raw_context.t * id) tzresult Lwt.t\n\n val init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n end\n\n (** The domain of alive big maps *)\n val fold : Raw_context.t -> init:'a -> f:(id -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n val list : Raw_context.t -> id list Lwt.t\n\n val remove_rec : Raw_context.t -> id -> Raw_context.t Lwt.t\n\n val copy : Raw_context.t -> from:id -> to_:id -> Raw_context.t tzresult Lwt.t\n\n type key = Raw_context.t * id\n\n val rpc_arg : id RPC_arg.t\n\n module Contents :\n Non_iterable_indexed_carbonated_data_storage\n with type key = Script_expr_hash.t\n and type value = Script_repr.expr\n and type t := key\n\n module Total_bytes :\n Indexed_data_storage\n with type key = id\n and type value = Z.t\n and type t := Raw_context.t\n\n module Key_type :\n Indexed_data_storage\n with type key = id\n and type value = Script_repr.expr\n and type t := Raw_context.t\n\n module Value_type :\n Indexed_data_storage\n with type key = id\n and type value = Script_repr.expr\n and type t := Raw_context.t\nend\n\nmodule Sapling : sig\n type id = Lazy_storage_kind.Sapling_state.Id.t\n\n val rpc_arg : id RPC_arg.t\n\n module Next : sig\n val incr : Raw_context.t -> (Raw_context.t * id) tzresult Lwt.t\n\n val init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n end\n\n val remove_rec : Raw_context.t -> id -> Raw_context.t Lwt.t\n\n val copy : Raw_context.t -> from:id -> to_:id -> Raw_context.t tzresult Lwt.t\n\n module Total_bytes :\n Indexed_data_storage\n with type key = id\n and type value = Z.t\n and type t := Raw_context.t\n\n (* Used by both Commitments and Ciphertexts *)\n module Commitments_size :\n Single_data_storage\n with type t := Raw_context.t * id\n and type value = int64\n\n module Memo_size :\n Single_data_storage with type t := Raw_context.t * id and type value = int\n\n module Commitments :\n Non_iterable_indexed_carbonated_data_storage\n with type t := Raw_context.t * id\n and type key = int64\n and type value = Sapling.Hash.t\n\n val commitments_init : Raw_context.t -> id -> Raw_context.t Lwt.t\n\n module Ciphertexts :\n Non_iterable_indexed_carbonated_data_storage\n with type t := Raw_context.t * id\n and type key = int64\n and type value = Sapling.Ciphertext.t\n\n val ciphertexts_init : Raw_context.t -> id -> Raw_context.t Lwt.t\n\n module Nullifiers_size :\n Single_data_storage\n with type t := Raw_context.t * id\n and type value = int64\n\n module Nullifiers_ordered :\n Non_iterable_indexed_data_storage\n with type t := Raw_context.t * id\n and type key = int64\n and type value = Sapling.Nullifier.t\n\n module Nullifiers_hashed :\n Carbonated_data_set_storage\n with type t := Raw_context.t * id\n and type elt = Sapling.Nullifier.t\n\n val nullifiers_init : Raw_context.t -> id -> Raw_context.t Lwt.t\n\n module Roots :\n Non_iterable_indexed_data_storage\n with type t := Raw_context.t * id\n and type key = int32\n and type value = Sapling.Hash.t\n\n module Roots_pos :\n Single_data_storage\n with type t := Raw_context.t * id\n and type value = int32\n\n module Roots_level :\n Single_data_storage\n with type t := Raw_context.t * id\n and type value = Raw_level_repr.t\nend\n\n(** Set of all registered delegates. *)\nmodule Delegates :\n Data_set_storage\n with type t := Raw_context.t\n and type elt = Signature.Public_key_hash.t\n\n(** Set of all active delegates with rolls. *)\nmodule Active_delegates_with_rolls :\n Data_set_storage\n with type t := Raw_context.t\n and type elt = Signature.Public_key_hash.t\n\n(** Set of all the delegates with frozen rewards/bonds/fees for a given cycle. *)\nmodule Delegates_with_frozen_balance :\n Data_set_storage\n with type t = Raw_context.t * Cycle_repr.t\n and type elt = Signature.Public_key_hash.t\n\n(** Votes *)\n\nmodule Vote : sig\n module Pred_period_kind :\n Single_data_storage\n with type value = Voting_period_repr.kind\n and type t := Raw_context.t\n\n module Current_period_kind_007 :\n Single_data_storage\n with type value = Voting_period_repr.kind\n and type t := Raw_context.t\n\n module Current_period :\n Single_data_storage\n with type value = Voting_period_repr.t\n and type t := Raw_context.t\n\n (** Participation exponential moving average, in centile of percentage *)\n module Participation_ema :\n Single_data_storage with type value = int32 and type t := Raw_context.t\n\n module Current_proposal :\n Single_data_storage\n with type value = Protocol_hash.t\n and type t := Raw_context.t\n\n (** Sum of all rolls of all delegates. *)\n module Listings_size :\n Single_data_storage with type value = int32 and type t := Raw_context.t\n\n (** Contains all delegates with their assigned number of rolls. *)\n module Listings :\n Indexed_data_storage\n with type key = Signature.Public_key_hash.t\n and type value = int32\n and type t := Raw_context.t\n\n (** Set of protocol proposal with corresponding proposer delegate *)\n module Proposals :\n Data_set_storage\n with type elt = Protocol_hash.t * Signature.Public_key_hash.t\n and type t := Raw_context.t\n\n (** Keeps for each delegate the number of proposed protocols *)\n module Proposals_count :\n Indexed_data_storage\n with type key = Signature.Public_key_hash.t\n and type value = int\n and type t := Raw_context.t\n\n (** Contains for each delegate its ballot *)\n module Ballots :\n Indexed_data_storage\n with type key = Signature.Public_key_hash.t\n and type value = Vote_repr.ballot\n and type t := Raw_context.t\nend\n\n(** Seed *)\n\nmodule Seed : sig\n (** Storage from this submodule must only be accessed through the\n module `Seed`. *)\n\n type unrevealed_nonce = {\n nonce_hash : Nonce_hash.t;\n delegate : Signature.Public_key_hash.t;\n rewards : Tez_repr.t;\n fees : Tez_repr.t;\n }\n\n type nonce_status =\n | Unrevealed of unrevealed_nonce\n | Revealed of Seed_repr.nonce\n\n module Nonce :\n Non_iterable_indexed_data_storage\n with type key := Level_repr.t\n and type value := nonce_status\n and type t := Raw_context.t\n\n module For_cycle : sig\n val init :\n Raw_context.t ->\n Cycle_repr.t ->\n Seed_repr.seed ->\n Raw_context.t tzresult Lwt.t\n\n val get : Raw_context.t -> Cycle_repr.t -> Seed_repr.seed tzresult Lwt.t\n\n val delete : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t\n end\nend\n\n(** Commitments *)\n\nmodule Commitments :\n Indexed_data_storage\n with type key = Blinded_public_key_hash.t\n and type value = Tez_repr.t\n and type t := Raw_context.t\n\n(** Ramp up security deposits... *)\n\nmodule Ramp_up : sig\n module Rewards :\n Indexed_data_storage\n with type key = Cycle_repr.t\n and type value := Tez_repr.t list * Tez_repr.t list\n (* baking rewards per endorsement * endorsement rewards *)\n and type t := Raw_context.t\n\n module Security_deposits :\n Indexed_data_storage\n with type key = Cycle_repr.t\n and type value = Tez_repr.t * Tez_repr.t\n (* baking * endorsement *)\n and type t := Raw_context.t\nend\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Storage_functors\n\nmodule UInt16 = struct\n type t = int\n\n let encoding = Data_encoding.uint16\nend\n\nmodule Int32 = struct\n include Int32\n\n let encoding = Data_encoding.int32\nend\n\nmodule Int64 = struct\n include Int64\n\n let encoding = Data_encoding.int64\nend\n\nmodule Z = struct\n type t = Z.t\n\n let encoding = Data_encoding.z\nend\n\nmodule Int31_index : INDEX with type t = int = struct\n type t = int\n\n let path_length = 1\n\n let to_path c l = string_of_int c :: l\n\n let of_path = function\n | [] | _ :: _ :: _ ->\n None\n | [c] ->\n int_of_string_opt c\n\n type 'a ipath = 'a * t\n\n let args =\n Storage_description.One\n {\n rpc_arg = RPC_arg.int;\n encoding = Data_encoding.int31;\n compare = Compare.Int.compare;\n }\nend\n\nmodule Make_index (H : Storage_description.INDEX) :\n INDEX with type t = H.t and type 'a ipath = 'a * H.t = struct\n include H\n\n type 'a ipath = 'a * t\n\n let args = Storage_description.One {rpc_arg; encoding; compare}\nend\n\nmodule Block_priority =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"block_priority\"]\n end)\n (UInt16)\n\n(** Contracts handling *)\n\nmodule Contract = struct\n module Raw_context =\n Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"contracts\"]\n end)\n\n module Global_counter =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"global_counter\"]\n end)\n (Z)\n\n module Indexed_context =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"index\"]\n end))\n (Make_index (Contract_repr.Index))\n\n let fold = Indexed_context.fold_keys\n\n let list = Indexed_context.keys\n\n module Balance =\n Indexed_context.Make_map\n (struct\n let name = [\"balance\"]\n end)\n (Tez_repr)\n\n module Frozen_balance_index =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"frozen_balance\"]\n end))\n (Make_index (Cycle_repr.Index))\n\n module Frozen_deposits =\n Frozen_balance_index.Make_map\n (struct\n let name = [\"deposits\"]\n end)\n (Tez_repr)\n\n module Frozen_fees =\n Frozen_balance_index.Make_map\n (struct\n let name = [\"fees\"]\n end)\n (Tez_repr)\n\n module Frozen_rewards =\n Frozen_balance_index.Make_map\n (struct\n let name = [\"rewards\"]\n end)\n (Tez_repr)\n\n module Manager =\n Indexed_context.Make_map\n (struct\n let name = [\"manager\"]\n end)\n (Manager_repr)\n\n module Delegate =\n Indexed_context.Make_map\n (struct\n let name = [\"delegate\"]\n end)\n (Signature.Public_key_hash)\n\n module Inactive_delegate =\n Indexed_context.Make_set\n (Registered)\n (struct\n let name = [\"inactive_delegate\"]\n end)\n\n module Delegate_desactivation =\n Indexed_context.Make_map\n (struct\n let name = [\"delegate_desactivation\"]\n end)\n (Cycle_repr)\n\n module Delegated =\n Make_data_set_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"delegated\"]\n end))\n (Make_index (Contract_repr.Index))\n\n module Counter =\n Indexed_context.Make_map\n (struct\n let name = [\"counter\"]\n end)\n (Z)\n\n (* Consume gas for serialization and deserialization of expr in this\n module *)\n module Make_carbonated_map_expr (N : Storage_sigs.NAME) :\n Storage_sigs.Non_iterable_indexed_carbonated_data_storage\n with type key = Contract_repr.t\n and type value = Script_repr.lazy_expr\n and type t := Raw_context.t = struct\n module I =\n Indexed_context.Make_carbonated_map\n (N)\n (struct\n type t = Script_repr.lazy_expr\n\n let encoding = Script_repr.lazy_expr_encoding\n end)\n\n type context = I.context\n\n type key = I.key\n\n type value = I.value\n\n let mem = I.mem\n\n let delete = I.delete\n\n let remove = I.remove\n\n let consume_deserialize_gas ctxt value =\n Raw_context.check_enough_gas\n ctxt\n (Script_repr.minimal_deserialize_cost value)\n >>? fun () ->\n Script_repr.force_decode value\n >>? fun (_value, value_cost) -> Raw_context.consume_gas ctxt value_cost\n\n let consume_serialize_gas ctxt value =\n Script_repr.force_bytes value\n >>? fun (_value, value_cost) -> Raw_context.consume_gas ctxt value_cost\n\n let get ctxt contract =\n I.get ctxt contract\n >>=? fun (ctxt, value) ->\n Lwt.return\n (consume_deserialize_gas ctxt value >|? fun ctxt -> (ctxt, value))\n\n let get_option ctxt contract =\n I.get_option ctxt contract\n >>=? fun (ctxt, value_opt) ->\n Lwt.return\n @@\n match value_opt with\n | None ->\n ok (ctxt, None)\n | Some value ->\n consume_deserialize_gas ctxt value >|? fun ctxt -> (ctxt, value_opt)\n\n let set ctxt contract value =\n consume_serialize_gas ctxt value\n >>?= fun ctxt -> I.set ctxt contract value\n\n let set_option ctxt contract value_opt =\n match value_opt with\n | None ->\n I.set_option ctxt contract None\n | Some value ->\n consume_serialize_gas ctxt value\n >>?= fun ctxt -> I.set_option ctxt contract value_opt\n\n let init ctxt contract value =\n consume_serialize_gas ctxt value\n >>?= fun ctxt -> I.init ctxt contract value\n\n let init_set ctxt contract value =\n consume_serialize_gas ctxt value\n >>?= fun ctxt -> I.init_set ctxt contract value\n end\n\n module Code = Make_carbonated_map_expr (struct\n let name = [\"code\"]\n end)\n\n module Storage = Make_carbonated_map_expr (struct\n let name = [\"storage\"]\n end)\n\n module Paid_storage_space =\n Indexed_context.Make_map\n (struct\n let name = [\"paid_bytes\"]\n end)\n (Z)\n\n module Used_storage_space =\n Indexed_context.Make_map\n (struct\n let name = [\"used_bytes\"]\n end)\n (Z)\n\n module Roll_list =\n Indexed_context.Make_map\n (struct\n let name = [\"roll_list\"]\n end)\n (Roll_repr)\n\n module Change =\n Indexed_context.Make_map\n (struct\n let name = [\"change\"]\n end)\n (Tez_repr)\nend\n\n(** Big maps handling *)\n\nmodule Big_map = struct\n type id = Lazy_storage_kind.Big_map.Id.t\n\n module Raw_context =\n Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"big_maps\"]\n end)\n\n module Next = struct\n include Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"next\"]\n end)\n (Lazy_storage_kind.Big_map.Id)\n\n let incr ctxt =\n get ctxt\n >>=? fun i ->\n set ctxt (Lazy_storage_kind.Big_map.Id.next i) >|=? fun ctxt -> (ctxt, i)\n\n let init ctxt = init ctxt Lazy_storage_kind.Big_map.Id.init\n end\n\n module Index = struct\n (* After flat storage, just use module Index = Lazy_storage_kind.Big_map.Id *)\n\n include Lazy_storage_kind.Big_map.Id\n\n let path_length = 6 + path_length\n\n let to_path c l =\n let raw_key = Data_encoding.Binary.to_bytes_exn encoding c in\n let (`Hex index_key) = Hex.of_bytes (Raw_hashes.blake2b raw_key) in\n String.sub index_key 0 2 :: String.sub index_key 2 2\n :: String.sub index_key 4 2 :: String.sub index_key 6 2\n :: String.sub index_key 8 2 :: String.sub index_key 10 2 :: to_path c l\n\n let of_path = function\n | []\n | [_]\n | [_; _]\n | [_; _; _]\n | [_; _; _; _]\n | [_; _; _; _; _]\n | [_; _; _; _; _; _]\n | _ :: _ :: _ :: _ :: _ :: _ :: _ :: _ :: _ ->\n None\n | index1 :: index2 :: index3 :: index4 :: index5 :: index6 :: tail ->\n of_path tail\n |> Option.map (fun c ->\n let raw_key = Data_encoding.Binary.to_bytes_exn encoding c in\n let (`Hex index_key) =\n Hex.of_bytes (Raw_hashes.blake2b raw_key)\n in\n assert (Compare.String.(String.sub index_key 0 2 = index1)) ;\n assert (Compare.String.(String.sub index_key 2 2 = index2)) ;\n assert (Compare.String.(String.sub index_key 4 2 = index3)) ;\n assert (Compare.String.(String.sub index_key 6 2 = index4)) ;\n assert (Compare.String.(String.sub index_key 8 2 = index5)) ;\n assert (Compare.String.(String.sub index_key 10 2 = index6)) ;\n c)\n end\n\n module Indexed_context =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"index\"]\n end))\n (Make_index (Index))\n\n let rpc_arg = Index.rpc_arg\n\n let fold = Indexed_context.fold_keys\n\n let list = Indexed_context.keys\n\n let remove_rec ctxt n = Indexed_context.remove_rec ctxt n\n\n let copy ctxt ~from ~to_ = Indexed_context.copy ctxt ~from ~to_\n\n type key = Raw_context.t * Index.t\n\n module Total_bytes =\n Indexed_context.Make_map\n (struct\n let name = [\"total_bytes\"]\n end)\n (Z)\n\n module Key_type =\n Indexed_context.Make_map\n (struct\n let name = [\"key_type\"]\n end)\n (struct\n type t = Script_repr.expr\n\n let encoding = Script_repr.expr_encoding\n end)\n\n module Value_type =\n Indexed_context.Make_map\n (struct\n let name = [\"value_type\"]\n end)\n (struct\n type t = Script_repr.expr\n\n let encoding = Script_repr.expr_encoding\n end)\n\n module Contents = struct\n module I =\n Storage_functors.Make_indexed_carbonated_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"contents\"]\n end))\n (Make_index (Script_expr_hash))\n (struct\n type t = Script_repr.expr\n\n let encoding = Script_repr.expr_encoding\n end)\n\n type context = I.context\n\n type key = I.key\n\n type value = I.value\n\n let mem = I.mem\n\n let delete = I.delete\n\n let remove = I.remove\n\n let set = I.set\n\n let set_option = I.set_option\n\n let init = I.init\n\n let init_set = I.init_set\n\n let consume_deserialize_gas ctxt value =\n Raw_context.consume_gas ctxt (Script_repr.deserialized_cost value)\n\n let get ctxt contract =\n I.get ctxt contract\n >>=? fun (ctxt, value) ->\n Lwt.return\n (consume_deserialize_gas ctxt value >|? fun ctxt -> (ctxt, value))\n\n let get_option ctxt contract =\n I.get_option ctxt contract\n >>=? fun (ctxt, value_opt) ->\n Lwt.return\n @@\n match value_opt with\n | None ->\n ok (ctxt, None)\n | Some value ->\n consume_deserialize_gas ctxt value >|? fun ctxt -> (ctxt, value_opt)\n end\nend\n\nmodule Sapling = struct\n type id = Lazy_storage_kind.Sapling_state.Id.t\n\n module Raw_context =\n Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"sapling\"]\n end)\n\n module Next = struct\n include Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"next\"]\n end)\n (Lazy_storage_kind.Sapling_state.Id)\n\n let incr ctxt =\n get ctxt\n >>=? fun i ->\n set ctxt (Lazy_storage_kind.Sapling_state.Id.next i)\n >|=? fun ctxt -> (ctxt, i)\n\n let init ctxt = init ctxt Lazy_storage_kind.Sapling_state.Id.init\n end\n\n module Index = Lazy_storage_kind.Sapling_state.Id\n\n let rpc_arg = Index.rpc_arg\n\n module Indexed_context =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"index\"]\n end))\n (Make_index (Index))\n\n let remove_rec ctxt n = Indexed_context.remove_rec ctxt n\n\n let copy ctxt ~from ~to_ = Indexed_context.copy ctxt ~from ~to_\n\n module Total_bytes =\n Indexed_context.Make_map\n (struct\n let name = [\"total_bytes\"]\n end)\n (Z)\n\n module Commitments_size =\n Make_single_data_storage (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"commitments_size\"]\n end)\n (Int64)\n\n module Memo_size =\n Make_single_data_storage (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"memo_size\"]\n end)\n (Sapling_repr.Memo_size)\n\n module Commitments =\n Make_indexed_carbonated_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"commitments\"]\n end))\n (Make_index (struct\n type t = int64\n\n let rpc_arg =\n let construct = Int64.to_string in\n let destruct hash =\n match Int64.of_string_opt hash with\n | None ->\n Error \"Cannot parse node position\"\n | Some id ->\n Ok id\n in\n RPC_arg.make\n ~descr:\"The position of a node in a sapling commitment tree\"\n ~name:\"sapling_node_position\"\n ~construct\n ~destruct\n ()\n\n let encoding =\n Data_encoding.def\n \"sapling_node_position\"\n ~title:\"Sapling node position\"\n ~description:\n \"The position of a node in a sapling commitment tree\"\n Data_encoding.int64\n\n let compare = Compare.Int64.compare\n\n let path_length = 1\n\n let to_path c l = Int64.to_string c :: l\n\n let of_path = function [c] -> Int64.of_string_opt c | _ -> None\n end))\n (Sapling.Hash)\n\n let commitments_init ctx id =\n Indexed_context.Raw_context.remove_rec (ctx, id) [\"commitments\"]\n >|= fun (ctx, _id) -> ctx\n\n module Ciphertexts =\n Make_indexed_carbonated_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"ciphertexts\"]\n end))\n (Make_index (struct\n type t = int64\n\n let rpc_arg =\n let construct = Int64.to_string in\n let destruct hash =\n match Int64.of_string_opt hash with\n | None ->\n Error \"Cannot parse ciphertext position\"\n | Some id ->\n Ok id\n in\n RPC_arg.make\n ~descr:\"The position of a sapling ciphertext\"\n ~name:\"sapling_ciphertext_position\"\n ~construct\n ~destruct\n ()\n\n let encoding =\n Data_encoding.def\n \"sapling_ciphertext_position\"\n ~title:\"Sapling ciphertext position\"\n ~description:\"The position of a sapling ciphertext\"\n Data_encoding.int64\n\n let compare = Compare.Int64.compare\n\n let path_length = 1\n\n let to_path c l = Int64.to_string c :: l\n\n let of_path = function [c] -> Int64.of_string_opt c | _ -> None\n end))\n (Sapling.Ciphertext)\n\n let ciphertexts_init ctx id =\n Indexed_context.Raw_context.remove_rec (ctx, id) [\"commitments\"]\n >|= fun (ctx, _id) -> ctx\n\n module Nullifiers_size =\n Make_single_data_storage (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"nullifiers_size\"]\n end)\n (Int64)\n\n (* For sequential access when building a diff *)\n module Nullifiers_ordered =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"nullifiers_ordered\"]\n end))\n (Make_index (struct\n type t = int64\n\n let rpc_arg =\n let construct = Int64.to_string in\n let destruct hash =\n match Int64.of_string_opt hash with\n | None ->\n Error \"Cannot parse nullifier position\"\n | Some id ->\n Ok id\n in\n RPC_arg.make\n ~descr:\"A sapling nullifier position\"\n ~name:\"sapling_nullifier_position\"\n ~construct\n ~destruct\n ()\n\n let encoding =\n Data_encoding.def\n \"sapling_nullifier_position\"\n ~title:\"Sapling nullifier position\"\n ~description:\"Sapling nullifier position\"\n Data_encoding.int64\n\n let compare = Compare.Int64.compare\n\n let path_length = 1\n\n let to_path c l = Int64.to_string c :: l\n\n let of_path = function [c] -> Int64.of_string_opt c | _ -> None\n end))\n (Sapling.Nullifier)\n\n (* Check membership in O(1) for verify_update *)\n module Nullifiers_hashed =\n Make_carbonated_data_set_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"nullifiers_hashed\"]\n end))\n (Make_index (struct\n type t = Sapling.Nullifier.t\n\n let encoding = Sapling.Nullifier.encoding\n\n let of_string hexstring =\n let b = Hex.to_bytes (`Hex hexstring) in\n match Data_encoding.Binary.of_bytes encoding b with\n | None ->\n Error \"Cannot parse sapling nullifier\"\n | Some nf ->\n Ok nf\n\n let to_string nf =\n let b = Data_encoding.Binary.to_bytes_exn encoding nf in\n let (`Hex hexstring) = Hex.of_bytes b in\n hexstring\n\n let rpc_arg =\n RPC_arg.make\n ~descr:\"A sapling nullifier\"\n ~name:\"sapling_nullifier\"\n ~construct:to_string\n ~destruct:of_string\n ()\n\n let compare = Sapling.Nullifier.compare\n\n let path_length = 1\n\n let to_path c l = to_string c :: l\n\n let of_path = function\n | [c] -> (\n match of_string c with Error _ -> None | Ok nf -> Some nf )\n | _ ->\n None\n end))\n\n let nullifiers_init ctx id =\n Nullifiers_size.init_set (ctx, id) Int64.zero\n >>= fun ctx ->\n Indexed_context.Raw_context.remove_rec (ctx, id) [\"nullifiers_ordered\"]\n >>= fun (ctx, id) ->\n Indexed_context.Raw_context.remove_rec (ctx, id) [\"nullifiers_hashed\"]\n >|= fun (ctx, _id) -> ctx\n\n module Roots =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"roots\"]\n end))\n (Make_index (struct\n type t = int32\n\n let rpc_arg =\n let construct = Int32.to_string in\n let destruct hash =\n match Int32.of_string_opt hash with\n | None ->\n Error \"Cannot parse nullifier position\"\n | Some id ->\n Ok id\n in\n RPC_arg.make\n ~descr:\"A sapling root\"\n ~name:\"sapling_root\"\n ~construct\n ~destruct\n ()\n\n let encoding =\n Data_encoding.def\n \"sapling_root\"\n ~title:\"Sapling root\"\n ~description:\"Sapling root\"\n Data_encoding.int32\n\n let compare = Compare.Int32.compare\n\n let path_length = 1\n\n let to_path c l = Int32.to_string c :: l\n\n let of_path = function [c] -> Int32.of_string_opt c | _ -> None\n end))\n (Sapling.Hash)\n\n module Roots_pos =\n Make_single_data_storage (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"roots_pos\"]\n end)\n (Int32)\n\n module Roots_level =\n Make_single_data_storage (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"roots_level\"]\n end)\n (Raw_level_repr)\nend\n\nmodule Delegates =\n Make_data_set_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"delegates\"]\n end))\n (Make_index (Signature.Public_key_hash))\n\nmodule Active_delegates_with_rolls =\n Make_data_set_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"active_delegates_with_rolls\"]\n end))\n (Make_index (Signature.Public_key_hash))\n\nmodule Delegates_with_frozen_balance_index =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"delegates_with_frozen_balance\"]\n end))\n (Make_index (Cycle_repr.Index))\n\nmodule Delegates_with_frozen_balance =\n Make_data_set_storage\n (Delegates_with_frozen_balance_index.Raw_context)\n (Make_index (Signature.Public_key_hash))\n\n(** Rolls *)\n\nmodule Cycle = struct\n module Indexed_context =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"cycle\"]\n end))\n (Make_index (Cycle_repr.Index))\n\n module Last_roll =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"last_roll\"]\n end))\n (Int31_index)\n (Roll_repr)\n\n module Roll_snapshot =\n Indexed_context.Make_map\n (struct\n let name = [\"roll_snapshot\"]\n end)\n (UInt16)\n\n type unrevealed_nonce = {\n nonce_hash : Nonce_hash.t;\n delegate : Signature.Public_key_hash.t;\n rewards : Tez_repr.t;\n fees : Tez_repr.t;\n }\n\n type nonce_status =\n | Unrevealed of unrevealed_nonce\n | Revealed of Seed_repr.nonce\n\n let nonce_status_encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"Unrevealed\"\n (tup4\n Nonce_hash.encoding\n Signature.Public_key_hash.encoding\n Tez_repr.encoding\n Tez_repr.encoding)\n (function\n | Unrevealed {nonce_hash; delegate; rewards; fees} ->\n Some (nonce_hash, delegate, rewards, fees)\n | _ ->\n None)\n (fun (nonce_hash, delegate, rewards, fees) ->\n Unrevealed {nonce_hash; delegate; rewards; fees});\n case\n (Tag 1)\n ~title:\"Revealed\"\n Seed_repr.nonce_encoding\n (function Revealed nonce -> Some nonce | _ -> None)\n (fun nonce -> Revealed nonce) ]\n\n module Nonce =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Indexed_context.Raw_context)\n (struct\n let name = [\"nonces\"]\n end))\n (Make_index (Raw_level_repr.Index))\n (struct\n type t = nonce_status\n\n let encoding = nonce_status_encoding\n end)\n\n module Seed =\n Indexed_context.Make_map\n (struct\n let name = [\"random_seed\"]\n end)\n (struct\n type t = Seed_repr.seed\n\n let encoding = Seed_repr.seed_encoding\n end)\nend\n\nmodule Roll = struct\n module Raw_context =\n Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"rolls\"]\n end)\n\n module Indexed_context =\n Make_indexed_subcontext\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"index\"]\n end))\n (Make_index (Roll_repr.Index))\n\n module Next =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"next\"]\n end)\n (Roll_repr)\n\n module Limbo =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"limbo\"]\n end)\n (Roll_repr)\n\n module Delegate_roll_list =\n Wrap_indexed_data_storage\n (Contract.Roll_list)\n (struct\n type t = Signature.Public_key_hash.t\n\n let wrap = Contract_repr.implicit_contract\n\n let unwrap = Contract_repr.is_implicit\n end)\n\n module Successor =\n Indexed_context.Make_map\n (struct\n let name = [\"successor\"]\n end)\n (Roll_repr)\n\n module Delegate_change =\n Wrap_indexed_data_storage\n (Contract.Change)\n (struct\n type t = Signature.Public_key_hash.t\n\n let wrap = Contract_repr.implicit_contract\n\n let unwrap = Contract_repr.is_implicit\n end)\n\n module Snapshoted_owner_index = struct\n type t = Cycle_repr.t * int\n\n let path_length = Cycle_repr.Index.path_length + 1\n\n let to_path (c, n) s = Cycle_repr.Index.to_path c (string_of_int n :: s)\n\n let of_path l =\n match Misc.take Cycle_repr.Index.path_length l with\n | None | Some (_, ([] | _ :: _ :: _)) ->\n None\n | Some (l1, [l2]) -> (\n match (Cycle_repr.Index.of_path l1, int_of_string_opt l2) with\n | (None, _) | (_, None) ->\n None\n | (Some c, Some i) ->\n Some (c, i) )\n\n type 'a ipath = ('a * Cycle_repr.t) * int\n\n let left_args =\n Storage_description.One\n {\n rpc_arg = Cycle_repr.rpc_arg;\n encoding = Cycle_repr.encoding;\n compare = Cycle_repr.compare;\n }\n\n let right_args =\n Storage_description.One\n {\n rpc_arg = RPC_arg.int;\n encoding = Data_encoding.int31;\n compare = Compare.Int.compare;\n }\n\n let args = Storage_description.(Pair (left_args, right_args))\n end\n\n module Owner =\n Make_indexed_data_snapshotable_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"owner\"]\n end))\n (Snapshoted_owner_index)\n (Make_index (Roll_repr.Index))\n (Signature.Public_key)\n\n module Snapshot_for_cycle = Cycle.Roll_snapshot\n module Last_for_snapshot = Cycle.Last_roll\n\n let clear = Indexed_context.clear\nend\n\n(** Votes *)\n\nmodule Vote = struct\n module Raw_context =\n Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"votes\"]\n end)\n\n module Pred_period_kind =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"pred_period_kind\"]\n end)\n (struct\n type t = Voting_period_repr.kind\n\n let encoding = Voting_period_repr.kind_encoding\n end)\n\n module Current_period_kind_007 =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"current_period_kind\"]\n end)\n (struct\n type t = Voting_period_repr.kind\n\n let encoding = Voting_period_repr.kind_encoding\n end)\n\n module Current_period =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"current_period\"]\n end)\n (struct\n type t = Voting_period_repr.t\n\n let encoding = Voting_period_repr.encoding\n end)\n\n module Participation_ema =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"participation_ema\"]\n end)\n (Int32)\n\n module Current_proposal =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"current_proposal\"]\n end)\n (Protocol_hash)\n\n module Listings_size =\n Make_single_data_storage (Registered) (Raw_context)\n (struct\n let name = [\"listings_size\"]\n end)\n (Int32)\n\n module Listings =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"listings\"]\n end))\n (Make_index (Signature.Public_key_hash))\n (Int32)\n\n module Proposals =\n Make_data_set_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"proposals\"]\n end))\n (Pair\n (Make_index\n (Protocol_hash))\n (Make_index (Signature.Public_key_hash)))\n\n module Proposals_count =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"proposals_count\"]\n end))\n (Make_index (Signature.Public_key_hash))\n (UInt16)\n\n module Ballots =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"ballots\"]\n end))\n (Make_index (Signature.Public_key_hash))\n (struct\n type t = Vote_repr.ballot\n\n let encoding = Vote_repr.ballot_encoding\n end)\nend\n\n(** Seed *)\n\nmodule Seed = struct\n type unrevealed_nonce = Cycle.unrevealed_nonce = {\n nonce_hash : Nonce_hash.t;\n delegate : Signature.Public_key_hash.t;\n rewards : Tez_repr.t;\n fees : Tez_repr.t;\n }\n\n type nonce_status = Cycle.nonce_status =\n | Unrevealed of unrevealed_nonce\n | Revealed of Seed_repr.nonce\n\n module Nonce = struct\n open Level_repr\n\n type context = Raw_context.t\n\n let mem ctxt (l : Level_repr.t) = Cycle.Nonce.mem (ctxt, l.cycle) l.level\n\n let get ctxt (l : Level_repr.t) = Cycle.Nonce.get (ctxt, l.cycle) l.level\n\n let get_option ctxt (l : Level_repr.t) =\n Cycle.Nonce.get_option (ctxt, l.cycle) l.level\n\n let set ctxt (l : Level_repr.t) v =\n Cycle.Nonce.set (ctxt, l.cycle) l.level v\n\n let init ctxt (l : Level_repr.t) v =\n Cycle.Nonce.init (ctxt, l.cycle) l.level v\n\n let init_set ctxt (l : Level_repr.t) v =\n Cycle.Nonce.init_set (ctxt, l.cycle) l.level v\n\n let set_option ctxt (l : Level_repr.t) v =\n Cycle.Nonce.set_option (ctxt, l.cycle) l.level v\n\n let delete ctxt (l : Level_repr.t) =\n Cycle.Nonce.delete (ctxt, l.cycle) l.level\n\n let remove ctxt (l : Level_repr.t) =\n Cycle.Nonce.remove (ctxt, l.cycle) l.level\n end\n\n module For_cycle = Cycle.Seed\nend\n\n(** Commitments *)\n\nmodule Commitments =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"commitments\"]\n end))\n (Make_index (Blinded_public_key_hash.Index))\n (Tez_repr)\n\n(** Ramp up security deposits... *)\n\nmodule Ramp_up = struct\n module Rewards =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"ramp_up\"; \"rewards\"]\n end))\n (Make_index (Cycle_repr.Index))\n (struct\n type t = Tez_repr.t list * Tez_repr.t list\n\n let encoding =\n Data_encoding.(\n obj2\n (req \"baking_reward_per_endorsement\" (list Tez_repr.encoding))\n (req \"endorsement_reward\" (list Tez_repr.encoding)))\n end)\n\n module Security_deposits =\n Make_indexed_data_storage\n (Make_subcontext (Registered) (Raw_context)\n (struct\n let name = [\"ramp_up\"; \"deposits\"]\n end))\n (Make_index (Cycle_repr.Index))\n (struct\n type t = Tez_repr.t * Tez_repr.t\n\n let encoding =\n Data_encoding.tup2 Tez_repr.encoding Tez_repr.encoding\n end)\nend\n" ;
} ;
{ name = "Constants_storage" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet preserved_cycles c =\n let constants = Raw_context.constants c in\n constants.preserved_cycles\n\nlet blocks_per_cycle c =\n let constants = Raw_context.constants c in\n constants.blocks_per_cycle\n\nlet blocks_per_commitment c =\n let constants = Raw_context.constants c in\n constants.blocks_per_commitment\n\nlet blocks_per_roll_snapshot c =\n let constants = Raw_context.constants c in\n constants.blocks_per_roll_snapshot\n\nlet blocks_per_voting_period c =\n let constants = Raw_context.constants c in\n constants.blocks_per_voting_period\n\nlet time_between_blocks c =\n let constants = Raw_context.constants c in\n constants.time_between_blocks\n\nlet endorsers_per_block c =\n let constants = Raw_context.constants c in\n constants.endorsers_per_block\n\nlet initial_endorsers c =\n let constants = Raw_context.constants c in\n constants.initial_endorsers\n\nlet delay_per_missing_endorsement c =\n let constants = Raw_context.constants c in\n constants.delay_per_missing_endorsement\n\nlet hard_gas_limit_per_operation c =\n let constants = Raw_context.constants c in\n constants.hard_gas_limit_per_operation\n\nlet hard_gas_limit_per_block c =\n let constants = Raw_context.constants c in\n constants.hard_gas_limit_per_block\n\nlet cost_per_byte c =\n let constants = Raw_context.constants c in\n constants.cost_per_byte\n\nlet hard_storage_limit_per_operation c =\n let constants = Raw_context.constants c in\n constants.hard_storage_limit_per_operation\n\nlet proof_of_work_threshold c =\n let constants = Raw_context.constants c in\n constants.proof_of_work_threshold\n\nlet tokens_per_roll c =\n let constants = Raw_context.constants c in\n constants.tokens_per_roll\n\nlet michelson_maximum_type_size c =\n let constants = Raw_context.constants c in\n constants.michelson_maximum_type_size\n\nlet seed_nonce_revelation_tip c =\n let constants = Raw_context.constants c in\n constants.seed_nonce_revelation_tip\n\nlet origination_size c =\n let constants = Raw_context.constants c in\n constants.origination_size\n\nlet block_security_deposit c =\n let constants = Raw_context.constants c in\n constants.block_security_deposit\n\nlet endorsement_security_deposit c =\n let constants = Raw_context.constants c in\n constants.endorsement_security_deposit\n\nlet baking_reward_per_endorsement c =\n let constants = Raw_context.constants c in\n constants.baking_reward_per_endorsement\n\nlet endorsement_reward c =\n let constants = Raw_context.constants c in\n constants.endorsement_reward\n\nlet test_chain_duration c =\n let constants = Raw_context.constants c in\n constants.test_chain_duration\n\nlet quorum_min c =\n let constants = Raw_context.constants c in\n constants.quorum_min\n\nlet quorum_max c =\n let constants = Raw_context.constants c in\n constants.quorum_max\n\nlet min_proposal_quorum c =\n let constants = Raw_context.constants c in\n constants.min_proposal_quorum\n\nlet parametric c = Raw_context.constants c\n" ;
} ;
{ name = "Level_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nval current : Raw_context.t -> Level_repr.t\n\nval previous : Raw_context.t -> Level_repr.t\n\nval root : Raw_context.t -> Level_repr.t\n\nval from_raw :\n Raw_context.t -> ?offset:int32 -> Raw_level_repr.t -> Level_repr.t\n\nval pred : Raw_context.t -> Level_repr.t -> Level_repr.t option\n\nval succ : Raw_context.t -> Level_repr.t -> Level_repr.t\n\nval first_level_in_cycle : Raw_context.t -> Cycle_repr.t -> Level_repr.t\n\nval last_level_in_cycle : Raw_context.t -> Cycle_repr.t -> Level_repr.t\n\nval levels_in_cycle : Raw_context.t -> Cycle_repr.t -> Level_repr.t list\n\nval levels_in_current_cycle :\n Raw_context.t -> ?offset:int32 -> unit -> Level_repr.t list\n\nval levels_with_commitments_in_cycle :\n Raw_context.t -> Cycle_repr.t -> Level_repr.t list\n\nval last_allowed_fork_level : Raw_context.t -> Raw_level_repr.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Level_repr\n\nlet from_raw c ?offset l =\n let l =\n match offset with\n | None ->\n l\n | Some o ->\n Raw_level_repr.(of_int32_exn (Int32.add (to_int32 l) o))\n in\n let constants = Raw_context.constants c in\n let first_level = Raw_context.first_level c in\n Level_repr.level_from_raw\n ~first_level\n ~blocks_per_cycle:constants.Constants_repr.blocks_per_cycle\n ~blocks_per_commitment:constants.Constants_repr.blocks_per_commitment\n l\n\nlet root c = Level_repr.root_level (Raw_context.first_level c)\n\nlet succ c (l : Level_repr.t) = from_raw c (Raw_level_repr.succ l.level)\n\nlet pred c (l : Level_repr.t) =\n match Raw_level_repr.pred l.Level_repr.level with\n | None ->\n None\n | Some l ->\n Some (from_raw c l)\n\nlet current ctxt = Raw_context.current_level ctxt\n\nlet previous ctxt =\n let l = current ctxt in\n match pred ctxt l with\n | None ->\n assert false (* We never validate the Genesis... *)\n | Some p ->\n p\n\nlet first_level_in_cycle ctxt c =\n let constants = Raw_context.constants ctxt in\n let first_level = Raw_context.first_level ctxt in\n from_raw\n ctxt\n (Raw_level_repr.of_int32_exn\n (Int32.add\n (Raw_level_repr.to_int32 first_level)\n (Int32.mul\n constants.Constants_repr.blocks_per_cycle\n (Cycle_repr.to_int32 c))))\n\nlet last_level_in_cycle ctxt c =\n match pred ctxt (first_level_in_cycle ctxt (Cycle_repr.succ c)) with\n | None ->\n assert false\n | Some x ->\n x\n\nlet levels_in_cycle ctxt cycle =\n let first = first_level_in_cycle ctxt cycle in\n let rec loop (n : Level_repr.t) acc =\n if Cycle_repr.(n.cycle = first.cycle) then loop (succ ctxt n) (n :: acc)\n else acc\n in\n loop first []\n\nlet levels_in_current_cycle ctxt ?(offset = 0l) () =\n let current_cycle = Cycle_repr.to_int32 (current ctxt).cycle in\n let cycle = Int32.add current_cycle offset in\n if Compare.Int32.(cycle < 0l) then []\n else\n let cycle = Cycle_repr.of_int32_exn cycle in\n levels_in_cycle ctxt cycle\n\nlet levels_with_commitments_in_cycle ctxt c =\n let first = first_level_in_cycle ctxt c in\n let rec loop (n : Level_repr.t) acc =\n if Cycle_repr.(n.cycle = first.cycle) then\n if n.expected_commitment then loop (succ ctxt n) (n :: acc)\n else loop (succ ctxt n) acc\n else acc\n in\n loop first []\n\nlet last_allowed_fork_level c =\n let level = Raw_context.current_level c in\n let preserved_cycles = Constants_storage.preserved_cycles c in\n match Cycle_repr.sub level.cycle preserved_cycles with\n | None ->\n Raw_level_repr.root\n | Some cycle ->\n (first_level_in_cycle c cycle).level\n" ;
} ;
{ name = "Nonce_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error +=\n | Too_late_revelation\n | Too_early_revelation\n | Previously_revealed_nonce\n | Unexpected_nonce\n\ntype t = Seed_repr.nonce\n\ntype nonce = t\n\nval encoding : nonce Data_encoding.t\n\ntype unrevealed = Storage.Seed.unrevealed_nonce = {\n nonce_hash : Nonce_hash.t;\n delegate : Signature.Public_key_hash.t;\n rewards : Tez_repr.t;\n fees : Tez_repr.t;\n}\n\ntype status = Unrevealed of unrevealed | Revealed of Seed_repr.nonce\n\nval get : Raw_context.t -> Level_repr.t -> status tzresult Lwt.t\n\nval record_hash : Raw_context.t -> unrevealed -> Raw_context.t tzresult Lwt.t\n\nval reveal :\n Raw_context.t -> Level_repr.t -> nonce -> Raw_context.t tzresult Lwt.t\n\nval of_bytes : bytes -> nonce tzresult\n\nval hash : nonce -> Nonce_hash.t\n\nval check_hash : nonce -> Nonce_hash.t -> bool\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = Seed_repr.nonce\n\ntype nonce = t\n\nlet encoding = Seed_repr.nonce_encoding\n\ntype error +=\n | Too_late_revelation\n | Too_early_revelation\n | Previously_revealed_nonce\n | Unexpected_nonce\n\nlet () =\n register_error_kind\n `Branch\n ~id:\"nonce.too_late_revelation\"\n ~title:\"Too late nonce revelation\"\n ~description:\"Nonce revelation happens too late\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"This nonce cannot be revealed anymore.\")\n Data_encoding.unit\n (function Too_late_revelation -> Some () | _ -> None)\n (fun () -> Too_late_revelation) ;\n register_error_kind\n `Temporary\n ~id:\"nonce.too_early_revelation\"\n ~title:\"Too early nonce revelation\"\n ~description:\"Nonce revelation happens before cycle end\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"This nonce should not yet be revealed\")\n Data_encoding.unit\n (function Too_early_revelation -> Some () | _ -> None)\n (fun () -> Too_early_revelation) ;\n register_error_kind\n `Branch\n ~id:\"nonce.previously_revealed\"\n ~title:\"Previously revealed nonce\"\n ~description:\"Duplicated revelation for a nonce.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"This nonce was previously revealed\")\n Data_encoding.unit\n (function Previously_revealed_nonce -> Some () | _ -> None)\n (fun () -> Previously_revealed_nonce) ;\n register_error_kind\n `Branch\n ~id:\"nonce.unexpected\"\n ~title:\"Unexpected nonce\"\n ~description:\n \"The provided nonce is inconsistent with the committed nonce hash.\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"This nonce revelation is invalid (inconsistent with the committed \\\n hash)\")\n Data_encoding.unit\n (function Unexpected_nonce -> Some () | _ -> None)\n (fun () -> Unexpected_nonce)\n\n(* checks that the level of a revelation is not too early or too late wrt to the\n current context and that a nonce has not been already revealed for that level *)\nlet get_unrevealed ctxt (level : Level_repr.t) =\n let cur_level = Level_storage.current ctxt in\n match Cycle_repr.pred cur_level.cycle with\n | None ->\n fail Too_early_revelation (* no revelations during cycle 0 *)\n | Some revealed_cycle -> (\n if Cycle_repr.(revealed_cycle < level.Level_repr.cycle) then\n fail Too_early_revelation\n else if Cycle_repr.(level.Level_repr.cycle < revealed_cycle) then\n fail Too_late_revelation\n else\n Storage.Seed.Nonce.get ctxt level\n >>=? function\n | Revealed _ ->\n fail Previously_revealed_nonce\n | Unrevealed status ->\n return status )\n\nlet record_hash ctxt unrevealed =\n let level = Level_storage.current ctxt in\n Storage.Seed.Nonce.init ctxt level (Unrevealed unrevealed)\n\nlet reveal ctxt level nonce =\n get_unrevealed ctxt level\n >>=? fun unrevealed ->\n error_unless\n (Seed_repr.check_hash nonce unrevealed.nonce_hash)\n Unexpected_nonce\n >>?= fun () -> Storage.Seed.Nonce.set ctxt level (Revealed nonce)\n\ntype unrevealed = Storage.Seed.unrevealed_nonce = {\n nonce_hash : Nonce_hash.t;\n delegate : Signature.Public_key_hash.t;\n rewards : Tez_repr.t;\n fees : Tez_repr.t;\n}\n\ntype status = Storage.Seed.nonce_status =\n | Unrevealed of unrevealed\n | Revealed of Seed_repr.nonce\n\nlet get = Storage.Seed.Nonce.get\n\nlet of_bytes = Seed_repr.make_nonce\n\nlet hash = Seed_repr.hash\n\nlet check_hash = Seed_repr.check_hash\n" ;
} ;
{ name = "Seed_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error +=\n | Unknown of {\n oldest : Cycle_repr.t;\n cycle : Cycle_repr.t;\n latest : Cycle_repr.t;\n }\n\n(* `Permanent *)\n\n(** Generates the first [preserved_cycles+2] seeds for which\n there are no nonces. *)\nval init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval for_cycle : Raw_context.t -> Cycle_repr.t -> Seed_repr.seed tzresult Lwt.t\n\n(** If it is the end of the cycle, computes and stores the seed of cycle at\n distance [preserved_cycle+2] in the future using the seed of the previous\n cycle and the revelations of the current one. *)\nval cycle_end :\n Raw_context.t ->\n Cycle_repr.t ->\n (Raw_context.t * Nonce_storage.unrevealed list) tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Misc\n\ntype error +=\n | Unknown of {\n oldest : Cycle_repr.t;\n cycle : Cycle_repr.t;\n latest : Cycle_repr.t;\n }\n\n(* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"seed.unknown_seed\"\n ~title:\"Unknown seed\"\n ~description:\"The requested seed is not available\"\n ~pp:(fun ppf (oldest, cycle, latest) ->\n if Cycle_repr.(cycle < oldest) then\n Format.fprintf\n ppf\n \"The seed for cycle %a has been cleared from the context (oldest \\\n known seed is for cycle %a)\"\n Cycle_repr.pp\n cycle\n Cycle_repr.pp\n oldest\n else\n Format.fprintf\n ppf\n \"The seed for cycle %a has not been computed yet (latest known \\\n seed is for cycle %a)\"\n Cycle_repr.pp\n cycle\n Cycle_repr.pp\n latest)\n Data_encoding.(\n obj3\n (req \"oldest\" Cycle_repr.encoding)\n (req \"requested\" Cycle_repr.encoding)\n (req \"latest\" Cycle_repr.encoding))\n (function\n | Unknown {oldest; cycle; latest} ->\n Some (oldest, cycle, latest)\n | _ ->\n None)\n (fun (oldest, cycle, latest) -> Unknown {oldest; cycle; latest})\n\nlet compute_for_cycle c ~revealed cycle =\n match Cycle_repr.pred cycle with\n | None ->\n assert false (* should not happen *)\n | Some previous_cycle ->\n let levels = Level_storage.levels_with_commitments_in_cycle c revealed in\n let combine (c, random_seed, unrevealed) level =\n Storage.Seed.Nonce.get c level\n >>=? function\n | Revealed nonce ->\n Storage.Seed.Nonce.delete c level\n >|=? fun c -> (c, Seed_repr.nonce random_seed nonce, unrevealed)\n | Unrevealed u ->\n Storage.Seed.Nonce.delete c level\n >|=? fun c -> (c, random_seed, u :: unrevealed)\n in\n Storage.Seed.For_cycle.get c previous_cycle\n >>=? fun prev_seed ->\n let seed = Seed_repr.deterministic_seed prev_seed in\n fold_left_s combine (c, seed, []) levels\n >>=? fun (c, seed, unrevealed) ->\n Storage.Seed.For_cycle.init c cycle seed >|=? fun c -> (c, unrevealed)\n\nlet for_cycle ctxt cycle =\n let preserved = Constants_storage.preserved_cycles ctxt in\n let current_level = Level_storage.current ctxt in\n let current_cycle = current_level.cycle in\n let latest =\n if Cycle_repr.(current_cycle = root) then\n Cycle_repr.add current_cycle (preserved + 1)\n else Cycle_repr.add current_cycle preserved\n in\n let oldest =\n match Cycle_repr.sub current_cycle preserved with\n | None ->\n Cycle_repr.root\n | Some oldest ->\n oldest\n in\n error_unless\n Cycle_repr.(oldest <= cycle && cycle <= latest)\n (Unknown {oldest; cycle; latest})\n >>?= fun () -> Storage.Seed.For_cycle.get ctxt cycle\n\nlet clear_cycle c cycle = Storage.Seed.For_cycle.delete c cycle\n\nlet init ctxt =\n let preserved = Constants_storage.preserved_cycles ctxt in\n List.fold_left2\n (fun ctxt c seed ->\n ctxt\n >>=? fun ctxt ->\n let cycle = Cycle_repr.of_int32_exn (Int32.of_int c) in\n Storage.Seed.For_cycle.init ctxt cycle seed)\n (return ctxt)\n (0 --> (preserved + 1))\n (Seed_repr.initial_seeds (preserved + 2))\n\nlet cycle_end ctxt last_cycle =\n let preserved = Constants_storage.preserved_cycles ctxt in\n ( match Cycle_repr.sub last_cycle preserved with\n | None ->\n return ctxt\n | Some cleared_cycle ->\n clear_cycle ctxt cleared_cycle )\n >>=? fun ctxt ->\n match Cycle_repr.pred last_cycle with\n | None ->\n return (ctxt, [])\n | Some revealed ->\n (* cycle with revelations *)\n let inited_seed_cycle = Cycle_repr.add last_cycle (preserved + 1) in\n compute_for_cycle ctxt ~revealed inited_seed_cycle\n" ;
} ;
{ name = "Roll_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019 Metastate AG <contact@metastate.ch> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(**\n Basic roll manipulation.\n\n If storage related to roll (i.e. `Storage.Roll`) is not used\n outside of this module, this interface enforces the invariant that a\n roll is always either in the limbo list or in a contract list.\n*)\n\ntype error +=\n | (* `Permanent *) Consume_roll_change\n | (* `Permanent *) No_roll_for_delegate\n | (* `Permanent *) No_roll_snapshot_for_cycle of Cycle_repr.t\n | (* `Permanent *) Unregistered_delegate of Signature.Public_key_hash.t\n\nval init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval init_first_cycles : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval cycle_end : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t\n\nval snapshot_rolls : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval fold :\n Raw_context.t ->\n f:(Roll_repr.roll -> Signature.Public_key.t -> 'a -> 'a tzresult Lwt.t) ->\n 'a ->\n 'a tzresult Lwt.t\n\nval baking_rights_owner :\n Raw_context.t ->\n Level_repr.t ->\n priority:int ->\n Signature.Public_key.t tzresult Lwt.t\n\nval endorsement_rights_owner :\n Raw_context.t ->\n Level_repr.t ->\n slot:int ->\n Signature.Public_key.t tzresult Lwt.t\n\nmodule Delegate : sig\n val is_inactive :\n Raw_context.t -> Signature.Public_key_hash.t -> bool tzresult Lwt.t\n\n val add_amount :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\n val remove_amount :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\n val set_inactive :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Raw_context.t tzresult Lwt.t\n\n val set_active :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Raw_context.t tzresult Lwt.t\nend\n\nmodule Contract : sig\n val add_amount :\n Raw_context.t ->\n Contract_repr.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\n val remove_amount :\n Raw_context.t ->\n Contract_repr.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\nend\n\nval delegate_pubkey :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Signature.Public_key.t tzresult Lwt.t\n\nval get_rolls :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Roll_repr.t list tzresult Lwt.t\n\nval get_change :\n Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t\n\nval update_tokens_per_roll :\n Raw_context.t -> Tez_repr.t -> Raw_context.t tzresult Lwt.t\n\n(**/**)\n\nval get_contract_delegate :\n Raw_context.t ->\n Contract_repr.t ->\n Signature.Public_key_hash.t option tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019 Metastate AG <contact@metastate.ch> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Misc\n\ntype error +=\n | (* `Permanent *) Consume_roll_change\n | (* `Permanent *) No_roll_for_delegate\n | (* `Permanent *) No_roll_snapshot_for_cycle of Cycle_repr.t\n | (* `Permanent *) Unregistered_delegate of Signature.Public_key_hash.t\n\nlet () =\n let open Data_encoding in\n (* Consume roll change *)\n register_error_kind\n `Permanent\n ~id:\"contract.manager.consume_roll_change\"\n ~title:\"Consume roll change\"\n ~description:\"Change is not enough to consume a roll.\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"Not enough change to consume a roll.\")\n empty\n (function Consume_roll_change -> Some () | _ -> None)\n (fun () -> Consume_roll_change) ;\n (* No roll for delegate *)\n register_error_kind\n `Permanent\n ~id:\"contract.manager.no_roll_for_delegate\"\n ~title:\"No roll for delegate\"\n ~description:\"Delegate has no roll.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Delegate has no roll.\")\n empty\n (function No_roll_for_delegate -> Some () | _ -> None)\n (fun () -> No_roll_for_delegate) ;\n (* No roll snapshot for cycle *)\n register_error_kind\n `Permanent\n ~id:\"contract.manager.no_roll_snapshot_for_cycle\"\n ~title:\"No roll snapshot for cycle\"\n ~description:\n \"A snapshot of the rolls distribution does not exist for this cycle.\"\n ~pp:(fun ppf c ->\n Format.fprintf\n ppf\n \"A snapshot of the rolls distribution does not exist for cycle %a\"\n Cycle_repr.pp\n c)\n (obj1 (req \"cycle\" Cycle_repr.encoding))\n (function No_roll_snapshot_for_cycle c -> Some c | _ -> None)\n (fun c -> No_roll_snapshot_for_cycle c) ;\n (* Unregistered delegate *)\n register_error_kind\n `Permanent\n ~id:\"contract.manager.unregistered_delegate\"\n ~title:\"Unregistered delegate\"\n ~description:\"A contract cannot be delegated to an unregistered delegate\"\n ~pp:(fun ppf k ->\n Format.fprintf\n ppf\n \"The provided public key (with hash %a) is not registered as valid \\\n delegate key.\"\n Signature.Public_key_hash.pp\n k)\n (obj1 (req \"hash\" Signature.Public_key_hash.encoding))\n (function Unregistered_delegate k -> Some k | _ -> None)\n (fun k -> Unregistered_delegate k)\n\nlet get_contract_delegate ctxt contract =\n Storage.Contract.Delegate.get_option ctxt contract\n\nlet delegate_pubkey ctxt delegate =\n Storage.Contract.Manager.get_option\n ctxt\n (Contract_repr.implicit_contract delegate)\n >>=? function\n | None | Some (Manager_repr.Hash _) ->\n fail (Unregistered_delegate delegate)\n | Some (Manager_repr.Public_key pk) ->\n return pk\n\nlet clear_cycle ctxt cycle =\n Storage.Roll.Snapshot_for_cycle.get ctxt cycle\n >>=? fun index ->\n Storage.Roll.Snapshot_for_cycle.delete ctxt cycle\n >>=? fun ctxt ->\n Storage.Roll.Last_for_snapshot.delete (ctxt, cycle) index\n >>=? fun ctxt ->\n Storage.Roll.Owner.delete_snapshot ctxt (cycle, index) >|= ok\n\nlet fold ctxt ~f init =\n Storage.Roll.Next.get ctxt\n >>=? fun last ->\n let rec loop ctxt roll acc =\n if Roll_repr.(roll = last) then return acc\n else\n Storage.Roll.Owner.get_option ctxt roll\n >>=? function\n | None ->\n loop ctxt (Roll_repr.succ roll) acc\n | Some delegate ->\n f roll delegate acc\n >>=? fun acc -> loop ctxt (Roll_repr.succ roll) acc\n in\n loop ctxt Roll_repr.first init\n\nlet snapshot_rolls_for_cycle ctxt cycle =\n Storage.Roll.Snapshot_for_cycle.get ctxt cycle\n >>=? fun index ->\n Storage.Roll.Snapshot_for_cycle.set ctxt cycle (index + 1)\n >>=? fun ctxt ->\n Storage.Roll.Owner.snapshot ctxt (cycle, index)\n >>=? fun ctxt ->\n Storage.Roll.Next.get ctxt\n >>=? fun last -> Storage.Roll.Last_for_snapshot.init (ctxt, cycle) index last\n\n(* NOTE: Deletes all snapshots for a given cycle that are not randomly selected. *)\nlet freeze_rolls_for_cycle ctxt cycle =\n Storage.Roll.Snapshot_for_cycle.get ctxt cycle\n >>=? fun max_index ->\n Storage.Seed.For_cycle.get ctxt cycle\n >>=? fun seed ->\n let rd = Seed_repr.initialize_new seed [Bytes.of_string \"roll_snapshot\"] in\n let seq = Seed_repr.sequence rd 0l in\n let selected_index =\n Seed_repr.take_int32 seq (Int32.of_int max_index) |> fst |> Int32.to_int\n in\n Storage.Roll.Snapshot_for_cycle.set ctxt cycle selected_index\n >>=? fun ctxt ->\n fold_left_s\n (fun ctxt index ->\n if Compare.Int.(index = selected_index) then return ctxt\n else\n Storage.Roll.Owner.delete_snapshot ctxt (cycle, index)\n >>= fun ctxt ->\n Storage.Roll.Last_for_snapshot.delete (ctxt, cycle) index)\n ctxt\n Misc.(0 --> (max_index - 1))\n\n(* Roll selection *)\nmodule Random = struct\n let int32_to_bytes i =\n let b = Bytes.make 4 '0' in\n TzEndian.set_int32 b 0 i ; b\n\n let level_random seed use (level : Level_repr.t) =\n let position = level.Level_repr.cycle_position in\n Seed_repr.initialize_new\n seed\n [Bytes.of_string (\"level \" ^ use ^ \":\"); int32_to_bytes position]\n\n let owner c kind (level : Level_repr.t) offset =\n let cycle = level.Level_repr.cycle in\n Seed_storage.for_cycle c cycle\n >>=? fun random_seed ->\n let rd = level_random random_seed kind level in\n let sequence = Seed_repr.sequence rd (Int32.of_int offset) in\n Storage.Roll.Snapshot_for_cycle.get c cycle\n >>=? fun index ->\n Storage.Roll.Last_for_snapshot.get (c, cycle) index\n >>=? fun bound ->\n let rec loop sequence =\n let (roll, sequence) = Roll_repr.random sequence ~bound in\n Storage.Roll.Owner.Snapshot.get_option c ((cycle, index), roll)\n >>=? function None -> loop sequence | Some delegate -> return delegate\n in\n Storage.Roll.Owner.snapshot_exists c (cycle, index)\n >>= fun snapshot_exists ->\n error_unless snapshot_exists (No_roll_snapshot_for_cycle cycle)\n >>?= fun () -> loop sequence\nend\n\nlet baking_rights_owner c level ~priority =\n Random.owner c \"baking\" level priority\n\nlet endorsement_rights_owner c level ~slot =\n Random.owner c \"endorsement\" level slot\n\nlet traverse_rolls ctxt head =\n let rec loop acc roll =\n Storage.Roll.Successor.get_option ctxt roll\n >>=? function\n | None -> return (List.rev acc) | Some next -> loop (next :: acc) next\n in\n loop [head] head\n\nlet get_rolls ctxt delegate =\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? function\n | None -> return_nil | Some head_roll -> traverse_rolls ctxt head_roll\n\nlet count_rolls ctxt delegate =\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? function\n | None ->\n return 0\n | Some head_roll ->\n let rec loop acc roll =\n Storage.Roll.Successor.get_option ctxt roll\n >>=? function None -> return acc | Some next -> loop (succ acc) next\n in\n loop 1 head_roll\n\nlet get_change ctxt delegate =\n Storage.Roll.Delegate_change.get_option ctxt delegate\n >|=? Option.value ~default:Tez_repr.zero\n\nmodule Delegate = struct\n let fresh_roll ctxt =\n Storage.Roll.Next.get ctxt\n >>=? fun roll ->\n Storage.Roll.Next.set ctxt (Roll_repr.succ roll)\n >|=? fun ctxt -> (roll, ctxt)\n\n let get_limbo_roll ctxt =\n Storage.Roll.Limbo.get_option ctxt\n >>=? function\n | None ->\n fresh_roll ctxt\n >>=? fun (roll, ctxt) ->\n Storage.Roll.Limbo.init ctxt roll >|=? fun ctxt -> (roll, ctxt)\n | Some roll ->\n return (roll, ctxt)\n\n let consume_roll_change ctxt delegate =\n let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in\n Storage.Roll.Delegate_change.get ctxt delegate\n >>=? fun change ->\n record_trace Consume_roll_change Tez_repr.(change -? tokens_per_roll)\n >>?= fun new_change ->\n Storage.Roll.Delegate_change.set ctxt delegate new_change\n\n let recover_roll_change ctxt delegate =\n let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in\n Storage.Roll.Delegate_change.get ctxt delegate\n >>=? fun change ->\n Tez_repr.(change +? tokens_per_roll)\n >>?= fun new_change ->\n Storage.Roll.Delegate_change.set ctxt delegate new_change\n\n let pop_roll_from_delegate ctxt delegate =\n recover_roll_change ctxt delegate\n >>=? fun ctxt ->\n (* beginning:\n delegate : roll -> successor_roll -> ...\n limbo : limbo_head -> ...\n *)\n Storage.Roll.Limbo.get_option ctxt\n >>=? fun limbo_head ->\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? function\n | None ->\n fail No_roll_for_delegate\n | Some roll ->\n Storage.Roll.Owner.delete ctxt roll\n >>=? fun ctxt ->\n Storage.Roll.Successor.get_option ctxt roll\n >>=? fun successor_roll ->\n Storage.Roll.Delegate_roll_list.set_option ctxt delegate successor_roll\n >>= fun ctxt ->\n (* delegate : successor_roll -> ...\n roll ------^\n limbo : limbo_head -> ... *)\n Storage.Roll.Successor.set_option ctxt roll limbo_head\n >>= fun ctxt ->\n (* delegate : successor_roll -> ...\n roll ------v\n limbo : limbo_head -> ... *)\n Storage.Roll.Limbo.init_set ctxt roll\n >|= fun ctxt ->\n (* delegate : successor_roll -> ...\n limbo : roll -> limbo_head -> ... *)\n ok (roll, ctxt)\n\n let create_roll_in_delegate ctxt delegate delegate_pk =\n consume_roll_change ctxt delegate\n >>=? fun ctxt ->\n (* beginning:\n delegate : delegate_head -> ...\n limbo : roll -> limbo_successor -> ...\n *)\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? fun delegate_head ->\n get_limbo_roll ctxt\n >>=? fun (roll, ctxt) ->\n Storage.Roll.Owner.init ctxt roll delegate_pk\n >>=? fun ctxt ->\n Storage.Roll.Successor.get_option ctxt roll\n >>=? fun limbo_successor ->\n Storage.Roll.Limbo.set_option ctxt limbo_successor\n >>= fun ctxt ->\n (* delegate : delegate_head -> ...\n roll ------v\n limbo : limbo_successor -> ... *)\n Storage.Roll.Successor.set_option ctxt roll delegate_head\n >>= fun ctxt ->\n (* delegate : delegate_head -> ...\n roll ------^\n limbo : limbo_successor -> ... *)\n Storage.Roll.Delegate_roll_list.init_set ctxt delegate roll\n (* delegate : roll -> delegate_head -> ...\n limbo : limbo_successor -> ... *)\n >|= ok\n\n let ensure_inited ctxt delegate =\n Storage.Roll.Delegate_change.mem ctxt delegate\n >>= function\n | true ->\n return ctxt\n | false ->\n Storage.Roll.Delegate_change.init ctxt delegate Tez_repr.zero\n\n let is_inactive ctxt delegate =\n Storage.Contract.Inactive_delegate.mem\n ctxt\n (Contract_repr.implicit_contract delegate)\n >>= fun inactive ->\n if inactive then return inactive\n else\n Storage.Contract.Delegate_desactivation.get_option\n ctxt\n (Contract_repr.implicit_contract delegate)\n >|=? function\n | Some last_active_cycle ->\n let ({Level_repr.cycle = current_cycle} : Level_repr.t) =\n Raw_context.current_level ctxt\n in\n Cycle_repr.(last_active_cycle < current_cycle)\n | None ->\n (* This case is only when called from `set_active`, when creating\n a contract. *)\n false\n\n let add_amount ctxt delegate amount =\n ensure_inited ctxt delegate\n >>=? fun ctxt ->\n let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in\n Storage.Roll.Delegate_change.get ctxt delegate\n >>=? fun change ->\n Tez_repr.(amount +? change)\n >>?= fun change ->\n Storage.Roll.Delegate_change.set ctxt delegate change\n >>=? fun ctxt ->\n delegate_pubkey ctxt delegate\n >>=? fun delegate_pk ->\n let rec loop ctxt change =\n if Tez_repr.(change < tokens_per_roll) then return ctxt\n else\n Tez_repr.(change -? tokens_per_roll)\n >>?= fun change ->\n create_roll_in_delegate ctxt delegate delegate_pk\n >>=? fun ctxt -> loop ctxt change\n in\n is_inactive ctxt delegate\n >>=? fun inactive ->\n if inactive then return ctxt\n else\n loop ctxt change\n >>=? fun ctxt ->\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? fun rolls ->\n match rolls with\n | None ->\n return ctxt\n | Some _ ->\n Storage.Active_delegates_with_rolls.add ctxt delegate >|= ok\n\n let remove_amount ctxt delegate amount =\n let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in\n let rec loop ctxt change =\n if Tez_repr.(amount <= change) then return (ctxt, change)\n else\n pop_roll_from_delegate ctxt delegate\n >>=? fun (_, ctxt) ->\n Tez_repr.(change +? tokens_per_roll)\n >>?= fun change -> loop ctxt change\n in\n Storage.Roll.Delegate_change.get ctxt delegate\n >>=? fun change ->\n is_inactive ctxt delegate\n >>=? fun inactive ->\n ( if inactive then return (ctxt, change)\n else\n loop ctxt change\n >>=? fun (ctxt, change) ->\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? fun rolls ->\n match rolls with\n | None ->\n Storage.Active_delegates_with_rolls.del ctxt delegate\n >|= fun ctxt -> ok (ctxt, change)\n | Some _ ->\n return (ctxt, change) )\n >>=? fun (ctxt, change) ->\n Tez_repr.(change -? amount)\n >>?= fun change -> Storage.Roll.Delegate_change.set ctxt delegate change\n\n let set_inactive ctxt delegate =\n ensure_inited ctxt delegate\n >>=? fun ctxt ->\n let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in\n Storage.Roll.Delegate_change.get ctxt delegate\n >>=? fun change ->\n Storage.Contract.Inactive_delegate.add\n ctxt\n (Contract_repr.implicit_contract delegate)\n >>= fun ctxt ->\n Storage.Active_delegates_with_rolls.del ctxt delegate\n >>= fun ctxt ->\n let rec loop ctxt change =\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? function\n | None ->\n return (ctxt, change)\n | Some _roll ->\n pop_roll_from_delegate ctxt delegate\n >>=? fun (_, ctxt) ->\n Tez_repr.(change +? tokens_per_roll)\n >>?= fun change -> loop ctxt change\n in\n loop ctxt change\n >>=? fun (ctxt, change) ->\n Storage.Roll.Delegate_change.set ctxt delegate change\n\n let set_active ctxt delegate =\n is_inactive ctxt delegate\n >>=? fun inactive ->\n let current_cycle = (Raw_context.current_level ctxt).cycle in\n let preserved_cycles = Constants_storage.preserved_cycles ctxt in\n (* When the delegate is new or inactive, she will become active in\n `1+preserved_cycles`, and we allow `preserved_cycles` for the\n delegate to start baking. When the delegate is active, we only\n give her at least `preserved_cycles` after the current cycle\n before to be deactivated. *)\n Storage.Contract.Delegate_desactivation.get_option\n ctxt\n (Contract_repr.implicit_contract delegate)\n >>=? fun current_expiration ->\n let expiration =\n match current_expiration with\n | None ->\n Cycle_repr.add current_cycle (1 + (2 * preserved_cycles))\n | Some current_expiration ->\n let delay =\n if inactive then 1 + (2 * preserved_cycles)\n else 1 + preserved_cycles\n in\n let updated = Cycle_repr.add current_cycle delay in\n Cycle_repr.max current_expiration updated\n in\n Storage.Contract.Delegate_desactivation.init_set\n ctxt\n (Contract_repr.implicit_contract delegate)\n expiration\n >>= fun ctxt ->\n if not inactive then return ctxt\n else\n ensure_inited ctxt delegate\n >>=? fun ctxt ->\n let tokens_per_roll = Constants_storage.tokens_per_roll ctxt in\n Storage.Roll.Delegate_change.get ctxt delegate\n >>=? fun change ->\n Storage.Contract.Inactive_delegate.del\n ctxt\n (Contract_repr.implicit_contract delegate)\n >>= fun ctxt ->\n delegate_pubkey ctxt delegate\n >>=? fun delegate_pk ->\n let rec loop ctxt change =\n if Tez_repr.(change < tokens_per_roll) then return ctxt\n else\n Tez_repr.(change -? tokens_per_roll)\n >>?= fun change ->\n create_roll_in_delegate ctxt delegate delegate_pk\n >>=? fun ctxt -> loop ctxt change\n in\n loop ctxt change\n >>=? fun ctxt ->\n Storage.Roll.Delegate_roll_list.get_option ctxt delegate\n >>=? fun rolls ->\n match rolls with\n | None ->\n return ctxt\n | Some _ ->\n Storage.Active_delegates_with_rolls.add ctxt delegate >|= ok\nend\n\nmodule Contract = struct\n let add_amount c contract amount =\n get_contract_delegate c contract\n >>=? function\n | None -> return c | Some delegate -> Delegate.add_amount c delegate amount\n\n let remove_amount c contract amount =\n get_contract_delegate c contract\n >>=? function\n | None ->\n return c\n | Some delegate ->\n Delegate.remove_amount c delegate amount\nend\n\nlet init ctxt = Storage.Roll.Next.init ctxt Roll_repr.first\n\nlet init_first_cycles ctxt =\n let preserved = Constants_storage.preserved_cycles ctxt in\n (* Precompute rolls for cycle (0 --> preserved_cycles) *)\n fold_left_s\n (fun ctxt c ->\n let cycle = Cycle_repr.of_int32_exn (Int32.of_int c) in\n Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0\n >>=? fun ctxt ->\n snapshot_rolls_for_cycle ctxt cycle\n >>=? fun ctxt -> freeze_rolls_for_cycle ctxt cycle)\n ctxt\n (0 --> preserved)\n >>=? fun ctxt ->\n let cycle = Cycle_repr.of_int32_exn (Int32.of_int (preserved + 1)) in\n (* Precomputed a snapshot for cycle (preserved_cycles + 1) *)\n Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0\n >>=? fun ctxt ->\n snapshot_rolls_for_cycle ctxt cycle\n >>=? fun ctxt ->\n (* Prepare storage for storing snapshots for cycle (preserved_cycles+2) *)\n let cycle = Cycle_repr.of_int32_exn (Int32.of_int (preserved + 2)) in\n Storage.Roll.Snapshot_for_cycle.init ctxt cycle 0\n\nlet snapshot_rolls ctxt =\n let current_level = Raw_context.current_level ctxt in\n let preserved = Constants_storage.preserved_cycles ctxt in\n let cycle = Cycle_repr.add current_level.cycle (preserved + 2) in\n snapshot_rolls_for_cycle ctxt cycle\n\nlet cycle_end ctxt last_cycle =\n let preserved = Constants_storage.preserved_cycles ctxt in\n ( match Cycle_repr.sub last_cycle preserved with\n | None ->\n return ctxt\n | Some cleared_cycle ->\n clear_cycle ctxt cleared_cycle )\n >>=? fun ctxt ->\n let frozen_roll_cycle = Cycle_repr.add last_cycle (preserved + 1) in\n freeze_rolls_for_cycle ctxt frozen_roll_cycle\n >>=? fun ctxt ->\n Storage.Roll.Snapshot_for_cycle.init\n ctxt\n (Cycle_repr.succ (Cycle_repr.succ frozen_roll_cycle))\n 0\n\nlet update_tokens_per_roll ctxt new_tokens_per_roll =\n let constants = Raw_context.constants ctxt in\n let old_tokens_per_roll = constants.tokens_per_roll in\n Raw_context.patch_constants ctxt (fun constants ->\n {constants with Constants_repr.tokens_per_roll = new_tokens_per_roll})\n >>= fun ctxt ->\n let decrease = Tez_repr.(new_tokens_per_roll < old_tokens_per_roll) in\n ( if decrease then Tez_repr.(old_tokens_per_roll -? new_tokens_per_roll)\n else Tez_repr.(new_tokens_per_roll -? old_tokens_per_roll) )\n >>?= fun abs_diff ->\n Storage.Delegates.fold ctxt (Ok ctxt) (fun pkh ctxt_opt ->\n ctxt_opt\n >>?= fun ctxt ->\n count_rolls ctxt pkh\n >>=? fun rolls ->\n Tez_repr.(abs_diff *? Int64.of_int rolls)\n >>?= fun amount ->\n if decrease then Delegate.add_amount ctxt pkh amount\n else Delegate.remove_amount ctxt pkh amount)\n" ;
} ;
{ name = "Delegate_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Places where tezzies can be found in the ledger's state. *)\ntype balance =\n | Contract of Contract_repr.t\n | Rewards of Signature.Public_key_hash.t * Cycle_repr.t\n | Fees of Signature.Public_key_hash.t * Cycle_repr.t\n | Deposits of Signature.Public_key_hash.t * Cycle_repr.t\n\n(** A credit or debit of tezzies to a balance. *)\ntype balance_update = Debited of Tez_repr.t | Credited of Tez_repr.t\n\n(** A list of balance updates. Duplicates may happen. *)\ntype balance_updates = (balance * balance_update) list\n\nval balance_updates_encoding : balance_updates Data_encoding.t\n\n(** Remove zero-valued balances from a list of updates. *)\nval cleanup_balance_updates : balance_updates -> balance_updates\n\ntype frozen_balance = {\n deposit : Tez_repr.t;\n fees : Tez_repr.t;\n rewards : Tez_repr.t;\n}\n\n(** Allow to register a delegate when creating an account. *)\nval init :\n Raw_context.t ->\n Contract_repr.t ->\n Signature.Public_key_hash.t ->\n Raw_context.t tzresult Lwt.t\n\n(** Cleanup delegation when deleting a contract. *)\nval remove : Raw_context.t -> Contract_repr.t -> Raw_context.t tzresult Lwt.t\n\n(** Reading the current delegate of a contract. *)\nval get :\n Raw_context.t ->\n Contract_repr.t ->\n Signature.Public_key_hash.t option tzresult Lwt.t\n\nval registered :\n Raw_context.t -> Signature.Public_key_hash.t -> bool tzresult Lwt.t\n\n(** Updating the delegate of a contract.\n\n When calling this function on an \"implicit contract\" and setting\n the delegate to the contract manager registers it as a delegate. One\n cannot unregister a delegate for now. The associate contract is now\n 'undeletable'. *)\nval set :\n Raw_context.t ->\n Contract_repr.t ->\n Signature.Public_key_hash.t option ->\n Raw_context.t tzresult Lwt.t\n\ntype error +=\n | No_deletion of Signature.Public_key_hash.t (* `Permanent *)\n | Active_delegate (* `Temporary *)\n | Current_delegate (* `Temporary *)\n | Empty_delegate_account of Signature.Public_key_hash.t (* `Temporary *)\n | Balance_too_low_for_deposit of {\n delegate : Signature.Public_key_hash.t;\n deposit : Tez_repr.t;\n balance : Tez_repr.t;\n }\n\n(* `Temporary *)\n\n(** Iterate on all registered delegates. *)\nval fold :\n Raw_context.t ->\n init:'a ->\n f:(Signature.Public_key_hash.t -> 'a -> 'a Lwt.t) ->\n 'a Lwt.t\n\n(** List all registered delegates. *)\nval list : Raw_context.t -> Signature.Public_key_hash.t list Lwt.t\n\n(** Various functions to 'freeze' tokens. A frozen 'deposit' keeps its\n associated rolls. When frozen, 'fees' may trigger new rolls\n allocation. Rewards won't trigger new rolls allocation until\n unfrozen. *)\nval freeze_deposit :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\nval freeze_fees :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\nval freeze_rewards :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\n(** Trigger the context maintenance at the end of cycle 'n', i.e.:\n unfreeze deposit/fees/rewards from 'n - preserved_cycle' ; punish the\n provided unrevealed seeds (typically seed from cycle 'n - 1').\n Returns a list of account with the amount that was unfrozen for each\n and the list of deactivated delegates. *)\nval cycle_end :\n Raw_context.t ->\n Cycle_repr.t ->\n Nonce_storage.unrevealed list ->\n (Raw_context.t * balance_updates * Signature.Public_key_hash.t list) tzresult\n Lwt.t\n\n(** Burn all then frozen deposit/fees/rewards for a delegate at a given\n cycle. Returns the burned amounts. *)\nval punish :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Cycle_repr.t ->\n (Raw_context.t * frozen_balance) tzresult Lwt.t\n\n(** Has the given key some frozen tokens in its implicit contract? *)\nval has_frozen_balance :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Cycle_repr.t ->\n bool tzresult Lwt.t\n\n(** Returns the amount of frozen deposit, fees and rewards associated\n to a given delegate. *)\nval frozen_balance :\n Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t\n\nval frozen_balance_encoding : frozen_balance Data_encoding.t\n\nval frozen_balance_by_cycle_encoding :\n frozen_balance Cycle_repr.Map.t Data_encoding.t\n\n(** Returns the amount of frozen deposit, fees and rewards associated\n to a given delegate, indexed by the cycle by which at the end the\n balance will be unfrozen. *)\nval frozen_balance_by_cycle :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n frozen_balance Cycle_repr.Map.t Lwt.t\n\n(** Returns the full 'balance' of the implicit contract associated to\n a given key, i.e. the sum of the spendable balance and of the\n frozen balance. *)\nval full_balance :\n Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t\n\nval staking_balance :\n Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t\n\n(** Returns the list of contracts (implicit or originated) that delegated towards a given delegate *)\nval delegated_contracts :\n Raw_context.t -> Signature.Public_key_hash.t -> Contract_repr.t list Lwt.t\n\nval delegated_balance :\n Raw_context.t -> Signature.Public_key_hash.t -> Tez_repr.t tzresult Lwt.t\n\nval deactivated :\n Raw_context.t -> Signature.Public_key_hash.t -> bool tzresult Lwt.t\n\nval grace_period :\n Raw_context.t -> Signature.Public_key_hash.t -> Cycle_repr.t tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype balance =\n | Contract of Contract_repr.t\n | Rewards of Signature.Public_key_hash.t * Cycle_repr.t\n | Fees of Signature.Public_key_hash.t * Cycle_repr.t\n | Deposits of Signature.Public_key_hash.t * Cycle_repr.t\n\nlet balance_encoding =\n let open Data_encoding in\n def \"operation_metadata.alpha.balance\"\n @@ union\n [ case\n (Tag 0)\n ~title:\"Contract\"\n (obj2\n (req \"kind\" (constant \"contract\"))\n (req \"contract\" Contract_repr.encoding))\n (function Contract c -> Some ((), c) | _ -> None)\n (fun ((), c) -> Contract c);\n case\n (Tag 1)\n ~title:\"Rewards\"\n (obj4\n (req \"kind\" (constant \"freezer\"))\n (req \"category\" (constant \"rewards\"))\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"cycle\" Cycle_repr.encoding))\n (function Rewards (d, l) -> Some ((), (), d, l) | _ -> None)\n (fun ((), (), d, l) -> Rewards (d, l));\n case\n (Tag 2)\n ~title:\"Fees\"\n (obj4\n (req \"kind\" (constant \"freezer\"))\n (req \"category\" (constant \"fees\"))\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"cycle\" Cycle_repr.encoding))\n (function Fees (d, l) -> Some ((), (), d, l) | _ -> None)\n (fun ((), (), d, l) -> Fees (d, l));\n case\n (Tag 3)\n ~title:\"Deposits\"\n (obj4\n (req \"kind\" (constant \"freezer\"))\n (req \"category\" (constant \"deposits\"))\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"cycle\" Cycle_repr.encoding))\n (function Deposits (d, l) -> Some ((), (), d, l) | _ -> None)\n (fun ((), (), d, l) -> Deposits (d, l)) ]\n\ntype balance_update = Debited of Tez_repr.t | Credited of Tez_repr.t\n\nlet balance_update_encoding =\n let open Data_encoding in\n def \"operation_metadata.alpha.balance_update\"\n @@ obj1\n (req\n \"change\"\n (conv\n (function\n | Credited v ->\n Tez_repr.to_mutez v\n | Debited v ->\n Int64.neg (Tez_repr.to_mutez v))\n ( Json.wrap_error\n @@ fun v ->\n if Compare.Int64.(v < 0L) then\n match Tez_repr.of_mutez (Int64.neg v) with\n | Some v ->\n Debited v\n | None ->\n failwith \"Qty.of_mutez\"\n else\n match Tez_repr.of_mutez v with\n | Some v ->\n Credited v\n | None ->\n failwith \"Qty.of_mutez\" )\n int64))\n\ntype balance_updates = (balance * balance_update) list\n\nlet balance_updates_encoding =\n let open Data_encoding in\n def \"operation_metadata.alpha.balance_updates\"\n @@ list (merge_objs balance_encoding balance_update_encoding)\n\nlet cleanup_balance_updates balance_updates =\n List.filter\n (fun (_, (Credited update | Debited update)) ->\n not (Tez_repr.equal update Tez_repr.zero))\n balance_updates\n\ntype frozen_balance = {\n deposit : Tez_repr.t;\n fees : Tez_repr.t;\n rewards : Tez_repr.t;\n}\n\nlet frozen_balance_encoding =\n let open Data_encoding in\n conv\n (fun {deposit; fees; rewards} -> (deposit, fees, rewards))\n (fun (deposit, fees, rewards) -> {deposit; fees; rewards})\n (obj3\n (req \"deposit\" Tez_repr.encoding)\n (req \"fees\" Tez_repr.encoding)\n (req \"rewards\" Tez_repr.encoding))\n\ntype error +=\n | No_deletion of Signature.Public_key_hash.t (* `Permanent *)\n | Active_delegate (* `Temporary *)\n | Current_delegate (* `Temporary *)\n | Empty_delegate_account of Signature.Public_key_hash.t (* `Temporary *)\n | Balance_too_low_for_deposit of {\n delegate : Signature.Public_key_hash.t;\n deposit : Tez_repr.t;\n balance : Tez_repr.t;\n }\n\n(* `Temporary *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"delegate.no_deletion\"\n ~title:\"Forbidden delegate deletion\"\n ~description:\"Tried to unregister a delegate\"\n ~pp:(fun ppf delegate ->\n Format.fprintf\n ppf\n \"Delegate deletion is forbidden (%a)\"\n Signature.Public_key_hash.pp\n delegate)\n Data_encoding.(obj1 (req \"delegate\" Signature.Public_key_hash.encoding))\n (function No_deletion c -> Some c | _ -> None)\n (fun c -> No_deletion c) ;\n register_error_kind\n `Temporary\n ~id:\"delegate.already_active\"\n ~title:\"Delegate already active\"\n ~description:\"Useless delegate reactivation\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"The delegate is still active, no need to refresh it\")\n Data_encoding.empty\n (function Active_delegate -> Some () | _ -> None)\n (fun () -> Active_delegate) ;\n register_error_kind\n `Temporary\n ~id:\"delegate.unchanged\"\n ~title:\"Unchanged delegated\"\n ~description:\"Contract already delegated to the given delegate\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"The contract is already delegated to the same delegate\")\n Data_encoding.empty\n (function Current_delegate -> Some () | _ -> None)\n (fun () -> Current_delegate) ;\n register_error_kind\n `Permanent\n ~id:\"delegate.empty_delegate_account\"\n ~title:\"Empty delegate account\"\n ~description:\n \"Cannot register a delegate when its implicit account is empty\"\n ~pp:(fun ppf delegate ->\n Format.fprintf\n ppf\n \"Delegate registration is forbidden when the delegate\\n\\\n \\ implicit account is empty (%a)\"\n Signature.Public_key_hash.pp\n delegate)\n Data_encoding.(obj1 (req \"delegate\" Signature.Public_key_hash.encoding))\n (function Empty_delegate_account c -> Some c | _ -> None)\n (fun c -> Empty_delegate_account c) ;\n register_error_kind\n `Temporary\n ~id:\"delegate.balance_too_low_for_deposit\"\n ~title:\"Balance too low for deposit\"\n ~description:\"Cannot freeze deposit when the balance is too low\"\n ~pp:(fun ppf (delegate, balance, deposit) ->\n Format.fprintf\n ppf\n \"Delegate %a has a too low balance (%a) to deposit %a\"\n Signature.Public_key_hash.pp\n delegate\n Tez_repr.pp\n balance\n Tez_repr.pp\n deposit)\n Data_encoding.(\n obj3\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"balance\" Tez_repr.encoding)\n (req \"deposit\" Tez_repr.encoding))\n (function\n | Balance_too_low_for_deposit {delegate; balance; deposit} ->\n Some (delegate, balance, deposit)\n | _ ->\n None)\n (fun (delegate, balance, deposit) ->\n Balance_too_low_for_deposit {delegate; balance; deposit})\n\nlet link c contract delegate =\n Storage.Contract.Balance.get c contract\n >>=? fun balance ->\n Roll_storage.Delegate.add_amount c delegate balance\n >>=? fun c ->\n Storage.Contract.Delegated.add\n (c, Contract_repr.implicit_contract delegate)\n contract\n >|= ok\n\nlet unlink c contract =\n Storage.Contract.Balance.get c contract\n >>=? fun balance ->\n Storage.Contract.Delegate.get_option c contract\n >>=? function\n | None ->\n return c\n | Some delegate ->\n (* Removes the balance of the contract from the delegate *)\n Roll_storage.Delegate.remove_amount c delegate balance\n >>=? fun c ->\n Storage.Contract.Delegated.del\n (c, Contract_repr.implicit_contract delegate)\n contract\n >|= ok\n\nlet known c delegate =\n Storage.Contract.Manager.get_option\n c\n (Contract_repr.implicit_contract delegate)\n >>=? function\n | None | Some (Manager_repr.Hash _) ->\n return_false\n | Some (Manager_repr.Public_key _) ->\n return_true\n\n(* A delegate is registered if its \"implicit account\" delegates to itself. *)\nlet registered c delegate =\n Storage.Contract.Delegate.get_option\n c\n (Contract_repr.implicit_contract delegate)\n >|=? function\n | Some current_delegate ->\n Signature.Public_key_hash.equal delegate current_delegate\n | None ->\n false\n\nlet init ctxt contract delegate =\n known ctxt delegate\n >>=? fun known_delegate ->\n error_unless known_delegate (Roll_storage.Unregistered_delegate delegate)\n >>?= fun () ->\n registered ctxt delegate\n >>=? fun is_registered ->\n error_unless is_registered (Roll_storage.Unregistered_delegate delegate)\n >>?= fun () ->\n Storage.Contract.Delegate.init ctxt contract delegate\n >>=? fun ctxt -> link ctxt contract delegate\n\nlet get = Roll_storage.get_contract_delegate\n\nlet set c contract delegate =\n match delegate with\n | None -> (\n let delete () =\n unlink c contract\n >>=? fun c -> Storage.Contract.Delegate.remove c contract >|= ok\n in\n match Contract_repr.is_implicit contract with\n | Some pkh ->\n (* check if contract is a registered delegate *)\n registered c pkh\n >>=? fun is_registered ->\n if is_registered then fail (No_deletion pkh) else delete ()\n | None ->\n delete () )\n | Some delegate ->\n known c delegate\n >>=? fun known_delegate ->\n registered c delegate\n >>=? fun registered_delegate ->\n let self_delegation =\n match Contract_repr.is_implicit contract with\n | Some pkh ->\n Signature.Public_key_hash.equal pkh delegate\n | None ->\n false\n in\n if (not known_delegate) || not (registered_delegate || self_delegation)\n then fail (Roll_storage.Unregistered_delegate delegate)\n else\n Storage.Contract.Delegate.get_option c contract\n >>=? (function\n | Some current_delegate\n when Signature.Public_key_hash.equal delegate current_delegate\n ->\n if self_delegation then\n Roll_storage.Delegate.is_inactive c delegate\n >>=? function\n | true -> return_unit | false -> fail Active_delegate\n else fail Current_delegate\n | None | Some _ ->\n return_unit)\n >>=? fun () ->\n (* check if contract is a registered delegate *)\n ( match Contract_repr.is_implicit contract with\n | Some pkh ->\n registered c pkh\n >>=? fun is_registered ->\n (* allow self-delegation to re-activate *)\n if (not self_delegation) && is_registered then\n fail (No_deletion pkh)\n else return_unit\n | None ->\n return_unit )\n >>=? fun () ->\n Storage.Contract.Balance.mem c contract\n >>= fun exists ->\n error_when\n (self_delegation && not exists)\n (Empty_delegate_account delegate)\n >>?= fun () ->\n unlink c contract\n >>=? fun c ->\n Storage.Contract.Delegate.init_set c contract delegate\n >>= fun c ->\n link c contract delegate\n >>=? fun c ->\n if self_delegation then\n Storage.Delegates.add c delegate\n >>= fun c -> Roll_storage.Delegate.set_active c delegate\n else return c\n\nlet remove ctxt contract = unlink ctxt contract\n\nlet delegated_contracts ctxt delegate =\n let contract = Contract_repr.implicit_contract delegate in\n Storage.Contract.Delegated.elements (ctxt, contract)\n\nlet get_frozen_deposit ctxt contract cycle =\n Storage.Contract.Frozen_deposits.get_option (ctxt, contract) cycle\n >|=? Option.value ~default:Tez_repr.zero\n\nlet credit_frozen_deposit ctxt delegate cycle amount =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_deposit ctxt contract cycle\n >>=? fun old_amount ->\n Tez_repr.(old_amount +? amount)\n >>?= fun new_amount ->\n Storage.Contract.Frozen_deposits.init_set (ctxt, contract) cycle new_amount\n >>= fun ctxt ->\n Storage.Delegates_with_frozen_balance.add (ctxt, cycle) delegate >|= ok\n\nlet freeze_deposit ctxt delegate amount =\n let ({Level_repr.cycle; _} : Level_repr.t) = Level_storage.current ctxt in\n Roll_storage.Delegate.set_active ctxt delegate\n >>=? fun ctxt ->\n let contract = Contract_repr.implicit_contract delegate in\n Storage.Contract.Balance.get ctxt contract\n >>=? fun balance ->\n record_trace\n (Balance_too_low_for_deposit {delegate; deposit = amount; balance})\n Tez_repr.(balance -? amount)\n >>?= fun new_balance ->\n Storage.Contract.Balance.set ctxt contract new_balance\n >>=? fun ctxt -> credit_frozen_deposit ctxt delegate cycle amount\n\nlet get_frozen_fees ctxt contract cycle =\n Storage.Contract.Frozen_fees.get_option (ctxt, contract) cycle\n >|=? Option.value ~default:Tez_repr.zero\n\nlet credit_frozen_fees ctxt delegate cycle amount =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_fees ctxt contract cycle\n >>=? fun old_amount ->\n Tez_repr.(old_amount +? amount)\n >>?= fun new_amount ->\n Storage.Contract.Frozen_fees.init_set (ctxt, contract) cycle new_amount\n >>= fun ctxt ->\n Storage.Delegates_with_frozen_balance.add (ctxt, cycle) delegate >|= ok\n\nlet freeze_fees ctxt delegate amount =\n let ({Level_repr.cycle; _} : Level_repr.t) = Level_storage.current ctxt in\n Roll_storage.Delegate.add_amount ctxt delegate amount\n >>=? fun ctxt -> credit_frozen_fees ctxt delegate cycle amount\n\nlet burn_fees ctxt delegate cycle amount =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_fees ctxt contract cycle\n >>=? fun old_amount ->\n ( match Tez_repr.(old_amount -? amount) with\n | Ok new_amount ->\n Roll_storage.Delegate.remove_amount ctxt delegate amount\n >|=? fun ctxt -> (new_amount, ctxt)\n | Error _ ->\n Roll_storage.Delegate.remove_amount ctxt delegate old_amount\n >|=? fun ctxt -> (Tez_repr.zero, ctxt) )\n >>=? fun (new_amount, ctxt) ->\n Storage.Contract.Frozen_fees.init_set (ctxt, contract) cycle new_amount\n >|= ok\n\nlet get_frozen_rewards ctxt contract cycle =\n Storage.Contract.Frozen_rewards.get_option (ctxt, contract) cycle\n >|=? Option.value ~default:Tez_repr.zero\n\nlet credit_frozen_rewards ctxt delegate cycle amount =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_rewards ctxt contract cycle\n >>=? fun old_amount ->\n Tez_repr.(old_amount +? amount)\n >>?= fun new_amount ->\n Storage.Contract.Frozen_rewards.init_set (ctxt, contract) cycle new_amount\n >>= fun ctxt ->\n Storage.Delegates_with_frozen_balance.add (ctxt, cycle) delegate >|= ok\n\nlet freeze_rewards ctxt delegate amount =\n let ({Level_repr.cycle; _} : Level_repr.t) = Level_storage.current ctxt in\n credit_frozen_rewards ctxt delegate cycle amount\n\nlet burn_rewards ctxt delegate cycle amount =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_rewards ctxt contract cycle\n >>=? fun old_amount ->\n let new_amount =\n match Tez_repr.(old_amount -? amount) with\n | Error _ ->\n Tez_repr.zero\n | Ok new_amount ->\n new_amount\n in\n Storage.Contract.Frozen_rewards.init_set (ctxt, contract) cycle new_amount\n >|= ok\n\nlet unfreeze ctxt delegate cycle =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_deposit ctxt contract cycle\n >>=? fun deposit ->\n get_frozen_fees ctxt contract cycle\n >>=? fun fees ->\n get_frozen_rewards ctxt contract cycle\n >>=? fun rewards ->\n Storage.Contract.Balance.get ctxt contract\n >>=? fun balance ->\n Tez_repr.(deposit +? fees)\n >>?= fun unfrozen_amount ->\n Tez_repr.(unfrozen_amount +? rewards)\n >>?= fun unfrozen_amount ->\n Tez_repr.(balance +? unfrozen_amount)\n >>?= fun balance ->\n Storage.Contract.Balance.set ctxt contract balance\n >>=? fun ctxt ->\n Roll_storage.Delegate.add_amount ctxt delegate rewards\n >>=? fun ctxt ->\n Storage.Contract.Frozen_deposits.remove (ctxt, contract) cycle\n >>= fun ctxt ->\n Storage.Contract.Frozen_fees.remove (ctxt, contract) cycle\n >>= fun ctxt ->\n Storage.Contract.Frozen_rewards.remove (ctxt, contract) cycle\n >|= fun ctxt ->\n ok\n ( ctxt,\n cleanup_balance_updates\n [ (Deposits (delegate, cycle), Debited deposit);\n (Fees (delegate, cycle), Debited fees);\n (Rewards (delegate, cycle), Debited rewards);\n ( Contract (Contract_repr.implicit_contract delegate),\n Credited unfrozen_amount ) ] )\n\nlet cycle_end ctxt last_cycle unrevealed =\n let preserved = Constants_storage.preserved_cycles ctxt in\n ( match Cycle_repr.pred last_cycle with\n | None ->\n return (ctxt, [])\n | Some revealed_cycle ->\n fold_left_s\n (fun (ctxt, balance_updates) (u : Nonce_storage.unrevealed) ->\n burn_fees ctxt u.delegate revealed_cycle u.fees\n >>=? fun ctxt ->\n burn_rewards ctxt u.delegate revealed_cycle u.rewards\n >|=? fun ctxt ->\n let bus =\n [ (Fees (u.delegate, revealed_cycle), Debited u.fees);\n (Rewards (u.delegate, revealed_cycle), Debited u.rewards) ]\n in\n (ctxt, bus @ balance_updates))\n (ctxt, [])\n unrevealed )\n >>=? fun (ctxt, balance_updates) ->\n match Cycle_repr.sub last_cycle preserved with\n | None ->\n return (ctxt, balance_updates, [])\n | Some unfrozen_cycle ->\n Storage.Delegates_with_frozen_balance.fold\n (ctxt, unfrozen_cycle)\n ~init:(Ok (ctxt, balance_updates))\n ~f:(fun delegate acc ->\n acc\n >>?= fun (ctxt, bus) ->\n unfreeze ctxt delegate unfrozen_cycle\n >|=? fun (ctxt, balance_updates) -> (ctxt, balance_updates @ bus))\n >>=? fun (ctxt, balance_updates) ->\n Storage.Delegates_with_frozen_balance.clear (ctxt, unfrozen_cycle)\n >>= fun ctxt ->\n Storage.Active_delegates_with_rolls.fold\n ctxt\n ~init:(Ok (ctxt, []))\n ~f:(fun delegate acc ->\n acc\n >>?= fun (ctxt, deactivated) ->\n Storage.Contract.Delegate_desactivation.get\n ctxt\n (Contract_repr.implicit_contract delegate)\n >>=? fun cycle ->\n if Cycle_repr.(cycle <= last_cycle) then\n Roll_storage.Delegate.set_inactive ctxt delegate\n >|=? fun ctxt -> (ctxt, delegate :: deactivated)\n else return (ctxt, deactivated))\n >|=? fun (ctxt, deactivated) -> (ctxt, balance_updates, deactivated)\n\nlet punish ctxt delegate cycle =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_deposit ctxt contract cycle\n >>=? fun deposit ->\n get_frozen_fees ctxt contract cycle\n >>=? fun fees ->\n get_frozen_rewards ctxt contract cycle\n >>=? fun rewards ->\n Roll_storage.Delegate.remove_amount ctxt delegate deposit\n >>=? fun ctxt ->\n Roll_storage.Delegate.remove_amount ctxt delegate fees\n >>=? fun ctxt ->\n (* Rewards are not accounted in the delegate's rolls yet... *)\n Storage.Contract.Frozen_deposits.remove (ctxt, contract) cycle\n >>= fun ctxt ->\n Storage.Contract.Frozen_fees.remove (ctxt, contract) cycle\n >>= fun ctxt ->\n Storage.Contract.Frozen_rewards.remove (ctxt, contract) cycle\n >|= fun ctxt -> ok (ctxt, {deposit; fees; rewards})\n\nlet has_frozen_balance ctxt delegate cycle =\n let contract = Contract_repr.implicit_contract delegate in\n get_frozen_deposit ctxt contract cycle\n >>=? fun deposit ->\n if Tez_repr.(deposit <> zero) then return_true\n else\n get_frozen_fees ctxt contract cycle\n >>=? fun fees ->\n if Tez_repr.(fees <> zero) then return_true\n else\n get_frozen_rewards ctxt contract cycle\n >|=? fun rewards -> Tez_repr.(rewards <> zero)\n\nlet frozen_balance_by_cycle_encoding =\n let open Data_encoding in\n conv\n Cycle_repr.Map.bindings\n (List.fold_left\n (fun m (c, b) -> Cycle_repr.Map.add c b m)\n Cycle_repr.Map.empty)\n (list\n (merge_objs\n (obj1 (req \"cycle\" Cycle_repr.encoding))\n frozen_balance_encoding))\n\nlet empty_frozen_balance =\n {deposit = Tez_repr.zero; fees = Tez_repr.zero; rewards = Tez_repr.zero}\n\nlet frozen_balance_by_cycle ctxt delegate =\n let contract = Contract_repr.implicit_contract delegate in\n let map = Cycle_repr.Map.empty in\n Storage.Contract.Frozen_deposits.fold\n (ctxt, contract)\n ~init:map\n ~f:(fun cycle amount map ->\n Lwt.return\n (Cycle_repr.Map.add\n cycle\n {empty_frozen_balance with deposit = amount}\n map))\n >>= fun map ->\n Storage.Contract.Frozen_fees.fold\n (ctxt, contract)\n ~init:map\n ~f:(fun cycle amount map ->\n let balance =\n match Cycle_repr.Map.find_opt cycle map with\n | None ->\n empty_frozen_balance\n | Some balance ->\n balance\n in\n Lwt.return (Cycle_repr.Map.add cycle {balance with fees = amount} map))\n >>= fun map ->\n Storage.Contract.Frozen_rewards.fold\n (ctxt, contract)\n ~init:map\n ~f:(fun cycle amount map ->\n let balance =\n match Cycle_repr.Map.find_opt cycle map with\n | None ->\n empty_frozen_balance\n | Some balance ->\n balance\n in\n Lwt.return (Cycle_repr.Map.add cycle {balance with rewards = amount} map))\n\nlet frozen_balance ctxt delegate =\n let contract = Contract_repr.implicit_contract delegate in\n let balance = Ok Tez_repr.zero in\n Storage.Contract.Frozen_deposits.fold\n (ctxt, contract)\n ~init:balance\n ~f:(fun _cycle amount acc ->\n Lwt.return (acc >>? fun acc -> Tez_repr.(acc +? amount)))\n >>= fun balance ->\n Storage.Contract.Frozen_fees.fold\n (ctxt, contract)\n ~init:balance\n ~f:(fun _cycle amount acc ->\n Lwt.return (acc >>? fun acc -> Tez_repr.(acc +? amount)))\n >>= fun balance ->\n Storage.Contract.Frozen_rewards.fold\n (ctxt, contract)\n ~init:balance\n ~f:(fun _cycle amount acc ->\n Lwt.return (acc >>? fun acc -> Tez_repr.(acc +? amount)))\n\nlet full_balance ctxt delegate =\n let contract = Contract_repr.implicit_contract delegate in\n frozen_balance ctxt delegate\n >>=? fun frozen_balance ->\n Storage.Contract.Balance.get ctxt contract\n >>=? fun balance -> Lwt.return Tez_repr.(frozen_balance +? balance)\n\nlet deactivated = Roll_storage.Delegate.is_inactive\n\nlet grace_period ctxt delegate =\n let contract = Contract_repr.implicit_contract delegate in\n Storage.Contract.Delegate_desactivation.get ctxt contract\n\nlet staking_balance ctxt delegate =\n let token_per_rolls = Constants_storage.tokens_per_roll ctxt in\n Roll_storage.get_rolls ctxt delegate\n >>=? fun rolls ->\n Roll_storage.get_change ctxt delegate\n >>=? fun change ->\n let rolls = Int64.of_int (List.length rolls) in\n Lwt.return\n ( Tez_repr.(token_per_rolls *? rolls)\n >>? fun balance -> Tez_repr.(balance +? change) )\n\nlet delegated_balance ctxt delegate =\n let contract = Contract_repr.implicit_contract delegate in\n staking_balance ctxt delegate\n >>=? fun staking_balance ->\n Storage.Contract.Balance.get ctxt contract\n >>= fun self_staking_balance ->\n Storage.Contract.Frozen_deposits.fold\n (ctxt, contract)\n ~init:self_staking_balance\n ~f:(fun _cycle amount acc ->\n Lwt.return (acc >>? fun acc -> Tez_repr.(acc +? amount)))\n >>= fun self_staking_balance ->\n Storage.Contract.Frozen_fees.fold\n (ctxt, contract)\n ~init:self_staking_balance\n ~f:(fun _cycle amount acc ->\n Lwt.return (acc >>? fun acc -> Tez_repr.(acc +? amount)))\n >>=? fun self_staking_balance ->\n Lwt.return Tez_repr.(staking_balance -? self_staking_balance)\n\nlet fold = Storage.Delegates.fold\n\nlet list = Storage.Delegates.elements\n" ;
} ;
{ name = "Sapling_storage" ;
interface = None ;
implementation = "(* The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE. *)\n\nmodule Commitments : sig\n val init : Raw_context.t -> Storage.Sapling.id -> Raw_context.t Lwt.t\n\n val default_root : Sapling.Hash.t\n\n val get_root :\n Raw_context.t ->\n Storage.Sapling.id ->\n (Raw_context.t * Sapling.Hash.t) tzresult Lwt.t\n\n val add :\n Raw_context.t ->\n Storage.Sapling.id ->\n Sapling.Commitment.t list ->\n int64 ->\n (Raw_context.t * int) tzresult Lwt.t\n\n val get_from :\n Raw_context.t ->\n Storage.Sapling.id ->\n int64 ->\n Sapling.Commitment.t list tzresult Lwt.t\nend = struct\n module H = Sapling.Hash\n\n (** Incremental Merkle Tree\n *\n * A tree of height h contains 2^h leaves and h+1 levels of nodes with\n * leaves at level 0 and root at level h.\n *\n * The leaves are commitments and the tree it is treated as always filled\n * with a default value H.uncommitted. This allows to have proofs of\n * membership, or witnesses, of fixed size.\n *\n * All the nodes at the same level of an empty tree have the same hash,\n * which can be computed from the default value of the leaves. This is\n * stored in the [uncommitted] list.\n *\n * Any subtree filled with default values is represented by the Empty\n * constructor and given its height it's possible to compute its hash\n * using the [uncommitted] list.\n *\n * The leaves are indexed by their position [pos], ranging from 0 to\n * (2^h)-1. The encoding of [pos] limits the possible size of the tree.\n * In any case the only valid height for the Sapling library is 32, so even\n * if the library encodes positions as uint64, they never exceed uint32.\n *\n * The tree is incremental in the sense that leaves cannot be modified but\n * only added and exclusively in successive positions.\n *\n * Given that elements are added and retrieved by position, it is possible\n * to use this information to efficiently navigate the tree.\n * Given a tree of height [h] and a position [pos], if pos < pow2 (h-1) only\n * the left subtree needs to be inspected recursively. Otherwise only the\n * right needs to be visited, decreasing [pos] by [pow2 (h-1)].\n *\n * In order to avoid storing the height for each subtree (or worse\n * recomputing it), each function with suffix `_height` expects the height\n * of the tree as parameter. These functions are only for internal use and\n * are later aliased by functions using the default height of a Sapling\n * incremental Merkle tree.\n *\n * Each node of the tree is indexed starting from the root at index 1,\n * followed by its left child at index 2, right child at index 3 and so on\n * until the last leaf at index 2^(depth+1)-1, or in terms of height\n * 2^(32 - height +1) -1.\n * The functions left and right return the index of the left and right child\n * of a node.\n *)\n\n let pow2 h = Int64.(shift_left 1L h)\n\n let max_height = 32\n\n let max_size = pow2 max_height\n\n let assert_node node height =\n assert (\n let first_of_height = pow2 (max_height - height) in\n let first_of_next_height = Int64.shift_left first_of_height 1 in\n Compare.Int64.(node >= first_of_height && node < first_of_next_height) )\n\n let assert_height height =\n assert (Compare.Int.(height >= 0 && height <= max_height))\n\n let assert_pos pos height =\n assert (Compare.Int64.(pos >= 0L && pos <= pow2 height))\n\n let default_root = H.uncommitted max_height\n\n let init = Storage.Sapling.commitments_init\n\n let get_root_height ctx id node height =\n assert_node node height ;\n assert_height height ;\n Storage.Sapling.Commitments.get_option (ctx, id) node\n >|=? function\n | (ctx, None) ->\n let hash = H.uncommitted height in\n (ctx, hash)\n | (ctx, Some hash) ->\n (ctx, hash)\n\n let left node = Int64.mul node 2L\n\n let right node = Int64.(add (mul node 2L) 1L)\n\n (* Not tail-recursive *)\n let rec split_at n l =\n if Compare.Int64.(n = 0L) then ([], l)\n else\n match l with\n | [] ->\n ([], l)\n | x :: xs ->\n let (l1, l2) = split_at Int64.(pred n) xs in\n (x :: l1, l2)\n\n (* [insert tree height pos cms] inserts the list of commitments\n [cms] in the tree [tree] of height [height] at the next position [pos].\n Returns the context, the size of the added storage, and the hash of the\n node. Not tail-recursive.\n Pre: incremental tree /\\\n size tree + List.length cms <= pow2 height /\\\n pos = size tree /\\\n Post: incremental tree /\\\n to_list (insert tree height pos cms) = to_list t @ cms *)\n let rec insert ctx id node height pos cms =\n assert_node node height ;\n assert_height height ;\n assert_pos pos height ;\n match (height, cms) with\n | (_, []) ->\n get_root_height ctx id node height >|=? fun (ctx, h) -> (ctx, 0, h)\n | (0, [cm]) ->\n let h = H.of_commitment cm in\n Storage.Sapling.Commitments.init (ctx, id) node h\n >|=? fun (ctx, size) -> (ctx, size, h)\n | _ ->\n let height = height - 1 in\n ( if Compare.Int64.(pos < pow2 height) then\n let at = Int64.(sub (pow2 height) pos) in\n let (cml, cmr) = split_at at cms in\n insert ctx id (left node) height pos cml\n >>=? fun (ctx, size_l, hl) ->\n insert ctx id (right node) height 0L cmr\n >|=? fun (ctx, size_r, hr) -> (ctx, size_l + size_r, hl, hr)\n else\n get_root_height ctx id (left node) height\n >>=? fun (ctx, hl) ->\n let pos = Int64.(sub pos (pow2 height)) in\n insert ctx id (right node) height pos cms\n >|=? fun (ctx, size_r, hr) -> (ctx, size_r, hl, hr) )\n >>=? fun (ctx, size_children, hl, hr) ->\n let h = H.merkle_hash ~height hl hr in\n Storage.Sapling.Commitments.init_set (ctx, id) node h\n >|=? fun (ctx, size, _existing) -> (ctx, size + size_children, h)\n\n let rec fold_from_height ctx id node ~pos ~f ~acc height =\n assert_node node height ;\n assert_height height ;\n assert_pos pos height ;\n Storage.Sapling.Commitments.get_option (ctx, id) node\n (* we don't count gas for this function, it is called only by RPC *)\n >>=? function\n | (_ctx, None) ->\n return acc\n | (_ctx, Some h) ->\n if Compare.Int.(height = 0) then return (f acc h)\n else\n let full = pow2 (height - 1) in\n if Compare.Int64.(pos < full) then\n fold_from_height ctx id (left node) ~pos ~f ~acc (height - 1)\n >>=? fun acc ->\n (* Setting pos to 0 folds on the whole right subtree *)\n fold_from_height ctx id (right node) ~pos:0L ~f ~acc (height - 1)\n else\n let pos = Int64.(sub pos full) in\n fold_from_height ctx id (right node) ~pos ~f ~acc (height - 1)\n\n let root_node = 1L\n\n let get_root ctx id = get_root_height ctx id root_node max_height\n\n (* Expects pos to be the next position to insert. Pos is also the number of\n inserted leaves.\n A commitment should always be added together with a corresponding\n ciphertext in the same position.\n [insert] is not tail-recursive so we put a hard limit on the size of the\n list of commitments. The use of [split_at] has O(n logn) complexity that is\n less relevant on a smaller list. *)\n let add ctx id cms pos =\n let l = List.length cms in\n assert (Compare.Int.(l <= 1000)) ;\n let n' = Int64.(add pos (of_int l)) in\n assert (Compare.Int64.(n' <= max_size)) ;\n insert ctx id root_node max_height pos cms\n >|=? fun (ctx, size, _h) -> (ctx, size)\n\n let get_from ctx id pos =\n fold_from_height\n ctx\n id\n root_node\n ~pos\n ~f:(fun acc c -> H.to_commitment c :: acc)\n ~acc:[]\n max_height\n >|=? fun l -> List.rev l\nend\n\nmodule Ciphertexts = struct\n let init ctx id = Storage.Sapling.ciphertexts_init ctx id\n\n (* a ciphertext should always be added together with a corresponding\n commitment in the same position *)\n let add ctx id c pos = Storage.Sapling.Ciphertexts.init (ctx, id) pos c\n\n let get_from ctx id offset =\n let rec aux (ctx, acc) pos =\n Storage.Sapling.Ciphertexts.get_option (ctx, id) pos\n >>=? fun (ctx, c) ->\n match c with\n | None ->\n return (ctx, List.rev acc)\n | Some c ->\n aux (ctx, c :: acc) (Int64.succ pos)\n in\n aux (ctx, []) offset\nend\n\n(* Collection of nullifiers w/o duplicates, append-only. It has a dual\n implementation with a hash map for constant `mem` and with a ordered set to\n retrieve by position. *)\nmodule Nullifiers = struct\n let init = Storage.Sapling.nullifiers_init\n\n let size ctx id = Storage.Sapling.Nullifiers_size.get (ctx, id)\n\n let mem ctx id nf = Storage.Sapling.Nullifiers_hashed.mem (ctx, id) nf\n\n (* Allows for duplicates as they are already checked by verify_update before\n updating the state.\n Not tail-recursive so we put a hard limit on the size of the\n list of nullifiers. *)\n let add ctx id nfs =\n assert (Compare.Int.(List.length nfs <= 1000)) ;\n size ctx id\n >>=? fun nf_start_pos ->\n fold_right_s\n (fun nf (ctx, pos, acc_size) ->\n Storage.Sapling.Nullifiers_hashed.init (ctx, id) nf\n >>=? fun (ctx, size) ->\n Storage.Sapling.Nullifiers_ordered.init (ctx, id) pos nf\n >|=? fun ctx -> (ctx, Int64.succ pos, Z.add acc_size (Z.of_int size)))\n nfs\n (ctx, nf_start_pos, Z.zero)\n >>=? fun (ctx, nf_end_pos, size) ->\n Storage.Sapling.Nullifiers_size.set (ctx, id) nf_end_pos\n >|=? fun ctx -> (ctx, size)\n\n let get_from ctx id offset =\n let rec aux acc pos =\n Storage.Sapling.Nullifiers_ordered.get_option (ctx, id) pos\n >>=? function\n | None ->\n return @@ List.rev acc\n | Some c ->\n aux (c :: acc) (Int64.succ pos)\n in\n aux [] offset\nend\n\n(** Bounded queue of roots. The full size is initialized with the default\n uncommitted root, that's why roots storage doesn't need to be carbonated.\n A maximum of one new root is added per protocol level.\n If multiple transactions for the same shielded pool are processed during the\n same contract call or several calls in the same block, only the last root\n will be stored.\n This property prevents transactions in the same block from depending on each\n other and guarantees that a transaction will be valid for a least two hours\n (hence the 120 size) after being forged. *)\nmodule Roots = struct\n let size = 120l\n\n (* pos is the index of the last inserted element *)\n\n let get ctx id =\n Storage.Sapling.Roots_pos.get (ctx, id)\n >>=? fun pos -> Storage.Sapling.Roots.get (ctx, id) pos\n\n let init ctx id =\n let rec aux ctx pos =\n if Compare.Int32.(pos < 0l) then return ctx\n else\n Storage.Sapling.Roots.init (ctx, id) pos Commitments.default_root\n >>=? fun ctx -> aux ctx (Int32.pred pos)\n in\n aux ctx (Int32.pred size)\n >>=? fun ctx ->\n Storage.Sapling.Roots_pos.init (ctx, id) 0l\n >>=? fun ctx ->\n let level = (Raw_context.current_level ctx).level in\n Storage.Sapling.Roots_level.init (ctx, id) level\n\n let mem ctx id root =\n Storage.Sapling.Roots_pos.get (ctx, id)\n >>=? fun start_pos ->\n let rec aux pos =\n Storage.Sapling.Roots.get (ctx, id) pos\n >>=? fun hash ->\n if Compare.Int.(Sapling.Hash.compare hash root = 0) then return true\n else\n let pos = Int32.(pred pos) in\n let pos = if Compare.Int32.(pos < 0l) then Int32.pred size else pos in\n if Compare.Int32.(pos = start_pos) then return false else aux pos\n in\n aux start_pos\n\n (* allows duplicates *)\n let add ctx id root =\n Storage.Sapling.Roots_pos.get (ctx, id)\n >>=? fun pos ->\n let level = (Raw_context.current_level ctx).level in\n Storage.Sapling.Roots_level.get (ctx, id)\n >>=? fun stored_level ->\n if Raw_level_repr.(stored_level = level) then\n (* if there is another add during the same level, it will over-write on\n the same position *)\n Storage.Sapling.Roots.init_set (ctx, id) pos root >|= ok\n else\n (* it's the first add for this level *)\n Storage.Sapling.Roots_level.set (ctx, id) level\n >>=? fun ctx ->\n let pos = Int32.rem (Int32.succ pos) size in\n Storage.Sapling.Roots_pos.set (ctx, id) pos\n >>=? fun ctx -> Storage.Sapling.Roots.init_set (ctx, id) pos root >|= ok\nend\n\n(** This type links the permanent state stored in the context at the specified\n id together with the ephemeral diff managed by the Michelson\n interpreter. After a successful execution the diff can be applied to update\n the state at id. The first time a state is created its id is None, one will\n be assigned after the first application. *)\ntype state = {\n id : Lazy_storage_kind.Sapling_state.Id.t option;\n diff : Sapling_repr.diff;\n memo_size : Sapling_repr.Memo_size.t;\n}\n\nlet empty_diff =\n Sapling_repr.{commitments_and_ciphertexts = []; nullifiers = []}\n\nlet empty_state ?id ~memo_size () = {id; diff = empty_diff; memo_size}\n\n(** Returns a state from an existing id. *)\nlet state_from_id ctxt id =\n Storage.Sapling.Memo_size.get (ctxt, id)\n >|=? fun memo_size -> ({id = Some id; diff = empty_diff; memo_size}, ctxt)\n\nlet rpc_arg = Storage.Sapling.rpc_arg\n\nlet get_memo_size ctx id = Storage.Sapling.Memo_size.get (ctx, id)\n\nlet init ctx id ~memo_size =\n Storage.Sapling.Memo_size.init_set (ctx, id) memo_size\n >>= fun ctx ->\n Storage.Sapling.Commitments_size.init_set (ctx, id) Int64.zero\n >>= fun ctx ->\n Commitments.init ctx id\n >>= fun ctx ->\n Nullifiers.init ctx id\n >>= fun ctx ->\n Roots.init ctx id >>=? fun ctx -> Ciphertexts.init ctx id >|= ok\n\n(* Gas costs for apply_diff. *)\nlet sapling_apply_diff_cost ~inputs ~outputs =\n Z.add\n (Z.of_int 1_300_000)\n (Z.add\n (Z.mul (Z.of_int inputs) (Z.of_int 5_000))\n (Z.mul (Z.of_int outputs) (Z.of_int 55_000)))\n\n(** Applies a diff to a state id stored in the context. Updates Commitments,\n Ciphertexts and Nullifiers using the diff and updates the Roots using the\n new Commitments tree. *)\nlet apply_diff ctx id diff =\n let open Sapling_repr in\n let nb_commitments = List.length diff.commitments_and_ciphertexts in\n let nb_nullifiers = List.length diff.nullifiers in\n Raw_context.consume_gas\n ctx\n (sapling_apply_diff_cost ~inputs:nb_nullifiers ~outputs:nb_commitments)\n >>?= fun ctx ->\n Storage.Sapling.Commitments_size.get (ctx, id)\n >>=? fun cm_start_pos ->\n let cms = List.rev_map fst diff.commitments_and_ciphertexts in\n Commitments.add ctx id cms cm_start_pos\n >>=? fun (ctx, size) ->\n Storage.Sapling.Commitments_size.set\n (ctx, id)\n (Int64.add cm_start_pos (Int64.of_int nb_commitments))\n >>=? fun ctx ->\n fold_right_s\n (fun (_cm, cp) (ctx, pos, acc_size) ->\n Ciphertexts.add ctx id cp pos\n >|=? fun (ctx, size) ->\n (ctx, Int64.succ pos, Z.add acc_size (Z.of_int size)))\n diff.commitments_and_ciphertexts\n (ctx, cm_start_pos, Z.of_int size)\n >>=? fun (ctx, _ct_end_pos, size) ->\n Nullifiers.add ctx id diff.nullifiers\n >>=? fun (ctx, size_nf) ->\n let size = Z.add size size_nf in\n match diff.commitments_and_ciphertexts with\n | [] ->\n (* avoids adding duplicates to Roots *)\n return (ctx, size)\n | _ :: _ ->\n Commitments.get_root ctx id\n >>=? fun (ctx, root) -> Roots.add ctx id root >|=? fun ctx -> (ctx, size)\n\nlet add {id; diff; memo_size} cm_cipher_list =\n assert (\n List.for_all\n (fun (_cm, cipher) ->\n Compare.Int.(Sapling.Ciphertext.get_memo_size cipher = memo_size))\n cm_cipher_list ) ;\n {\n id;\n diff =\n {\n diff with\n commitments_and_ciphertexts =\n List.rev cm_cipher_list @ diff.commitments_and_ciphertexts;\n };\n memo_size;\n }\n\nlet root_mem ctx {id} tested_root =\n match id with\n | Some id ->\n Roots.mem ctx id tested_root\n | None ->\n return\n Compare.Int.(\n Sapling.Hash.compare tested_root Commitments.default_root = 0)\n\n(* to avoid a double spend we need to check the disk AND the diff *)\nlet nullifiers_mem ctx {id; diff} nf =\n let exists_in_diff =\n List.exists\n (fun v -> Compare.Int.(Sapling.Nullifier.compare nf v = 0))\n diff.nullifiers\n in\n if exists_in_diff then return (ctx, true)\n else\n match id with\n | None ->\n return (ctx, false)\n | Some id ->\n Nullifiers.mem ctx id nf\n\n(* Allows for duplicates as they are already checked by verify_update before\n updating the state. *)\nlet nullifiers_add {id; diff; memo_size} nf =\n {id; diff = {diff with nullifiers = nf :: diff.nullifiers}; memo_size}\n\ntype root = Sapling.Hash.t\n\nlet root_encoding = Sapling.Hash.encoding\n\nlet get_diff ctx id ?(offset_commitment = 0L) ?(offset_nullifier = 0L) () =\n if\n not\n Sapling.Commitment.(\n valid_position offset_commitment && valid_position offset_nullifier)\n then failwith \"Invalid argument.\"\n else\n Commitments.get_from ctx id offset_commitment\n >>=? fun commitments ->\n Roots.get ctx id\n >>=? fun root ->\n Nullifiers.get_from ctx id offset_nullifier\n >>=? fun nullifiers ->\n Ciphertexts.get_from ctx id offset_commitment\n (* we don't count gas for RPCs *)\n >|=? fun (_ctx, ciphertexts) ->\n let commitments_and_ciphertexts = List.combine commitments ciphertexts in\n (root, Sapling_repr.{commitments_and_ciphertexts; nullifiers})\n" ;
} ;
{ name = "Lazy_storage_diff" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining 'a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(**\n See [Lazy_storage_kind] for an introduction on lazy storage.\n\n This module defines operations on lazy storage types and diffs.\n*)\n\ntype ('id, 'alloc) init = Existing | Copy of {src : 'id} | Alloc of 'alloc\n\ntype ('id, 'alloc, 'updates) diff =\n | Remove\n | Update of {init : ('id, 'alloc) init; updates : 'updates}\n\n(* Exposing this type is needed only for legacy big map diff. *)\ntype diffs_item = private\n | Item :\n ('i, 'a, 'u) Lazy_storage_kind.t * 'i * ('i, 'a, 'u) diff\n -> diffs_item\n\nval make :\n ('i, 'a, 'u) Lazy_storage_kind.t -> 'i -> ('i, 'a, 'u) diff -> diffs_item\n\ntype diffs = diffs_item list\n\nval encoding : diffs Data_encoding.t\n\n(**\n The returned [Z.t] is the size added by the application of the diffs.\n*)\nval apply : Raw_context.t -> diffs -> (Raw_context.t * Z.t) tzresult Lwt.t\n\nval fresh :\n ('id, _, _) Lazy_storage_kind.t ->\n temporary:bool ->\n Raw_context.t ->\n (Raw_context.t * 'id) tzresult Lwt.t\n\n(**\n Initializes the storage for all lazy storage kind. \n This is useful for genesis only.\n Protocol updates need to initialize new lazy storage kinds.\n*)\nval init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval cleanup_temporaries : Raw_context.t -> Raw_context.t Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule type Next = sig\n type id\n\n val init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\n val incr : Raw_context.t -> (Raw_context.t * id) tzresult Lwt.t\nend\n\nmodule type Total_bytes = sig\n type id\n\n val init : Raw_context.t -> id -> Z.t -> Raw_context.t tzresult Lwt.t\n\n val get : Raw_context.t -> id -> Z.t tzresult Lwt.t\n\n val set : Raw_context.t -> id -> Z.t -> Raw_context.t tzresult Lwt.t\nend\n\n(** Operations to be defined on a lazy storage type. *)\nmodule type OPS = sig\n module Id : Lazy_storage_kind.ID\n\n type alloc\n\n type updates\n\n val title : string\n\n val alloc_encoding : alloc Data_encoding.t\n\n val updates_encoding : updates Data_encoding.t\n\n val bytes_size_for_empty : Z.t\n\n val alloc : Raw_context.t -> id:Id.t -> alloc -> Raw_context.t tzresult Lwt.t\n\n val apply_updates :\n Raw_context.t -> id:Id.t -> updates -> (Raw_context.t * Z.t) tzresult Lwt.t\n\n module Next : Next with type id := Id.t\n\n module Total_bytes : Total_bytes with type id := Id.t\n\n (** Deep copy. *)\n val copy :\n Raw_context.t -> from:Id.t -> to_:Id.t -> Raw_context.t tzresult Lwt.t\n\n (** Deep deletion. *)\n val remove_rec : Raw_context.t -> Id.t -> Raw_context.t Lwt.t\nend\n\nmodule Big_map = struct\n include Lazy_storage_kind.Big_map\n\n let bytes_size_for_big_map_key = 65\n\n let bytes_size_for_empty =\n let bytes_size_for_big_map = 33 in\n Z.of_int bytes_size_for_big_map\n\n let alloc ctxt ~id {key_type; value_type} =\n (* Annotations are erased to allow sharing on [Copy]. The types from the\n contract code are used, these ones are only used to make sure they are\n compatible during transmissions between contracts, and only need to be\n compatible, annotations notwithstanding. *)\n let key_type =\n Micheline.strip_locations\n (Script_repr.strip_annotations (Micheline.root key_type))\n in\n let value_type =\n Micheline.strip_locations\n (Script_repr.strip_annotations (Micheline.root value_type))\n in\n Storage.Big_map.Key_type.init ctxt id key_type\n >>=? fun ctxt -> Storage.Big_map.Value_type.init ctxt id value_type\n\n let apply_update ctxt ~id\n { key = _key_is_shown_only_on_the_receipt_in_print_big_map_diff;\n key_hash;\n value } =\n match value with\n | None ->\n Storage.Big_map.Contents.remove (ctxt, id) key_hash\n >|=? fun (ctxt, freed, existed) ->\n let freed =\n if existed then freed + bytes_size_for_big_map_key else freed\n in\n (ctxt, Z.of_int ~-freed)\n | Some v ->\n Storage.Big_map.Contents.init_set (ctxt, id) key_hash v\n >|=? fun (ctxt, size_diff, existed) ->\n let size_diff =\n if existed then size_diff else size_diff + bytes_size_for_big_map_key\n in\n (ctxt, Z.of_int size_diff)\n\n let apply_updates ctxt ~id updates =\n fold_left_s\n (fun (ctxt, size) update ->\n apply_update ctxt ~id update\n >|=? fun (ctxt, added_size) -> (ctxt, Z.add size added_size))\n (ctxt, Z.zero)\n updates\n\n include Storage.Big_map\nend\n\ntype ('id, 'alloc, 'updates) ops =\n (module OPS\n with type Id.t = 'id\n and type alloc = 'alloc\n and type updates = 'updates)\n\nmodule Sapling_state = struct\n include Lazy_storage_kind.Sapling_state\n\n let bytes_size_for_empty = Z.of_int 33\n\n let alloc ctxt ~id {memo_size} = Sapling_storage.init ctxt id ~memo_size\n\n let apply_updates ctxt ~id updates =\n Sapling_storage.apply_diff ctxt id updates\n\n include Storage.Sapling\nend\n\n(*\n To add a new lazy storage kind here, you only need to create a module similar\n to [Big_map] above and add a case to [get_ops] below.\n*)\n\nlet get_ops : type i a u. (i, a, u) Lazy_storage_kind.t -> (i, a, u) ops =\n function\n | Big_map ->\n (module Big_map)\n | Sapling_state ->\n (module Sapling_state)\n [@@coq_axiom \"gadt\"]\n\ntype ('id, 'alloc) init = Existing | Copy of {src : 'id} | Alloc of 'alloc\n\ntype ('id, 'alloc, 'updates) diff =\n | Remove\n | Update of {init : ('id, 'alloc) init; updates : 'updates}\n\nlet diff_encoding : type i a u. (i, a, u) ops -> (i, a, u) diff Data_encoding.t\n =\n fun (module OPS) ->\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"update\"\n (obj2\n (req \"action\" (constant \"update\"))\n (req \"updates\" OPS.updates_encoding))\n (function\n | Update {init = Existing; updates} -> Some ((), updates) | _ -> None)\n (fun ((), updates) -> Update {init = Existing; updates});\n case\n (Tag 1)\n ~title:\"remove\"\n (obj1 (req \"action\" (constant \"remove\")))\n (function Remove -> Some () | _ -> None)\n (fun () -> Remove);\n case\n (Tag 2)\n ~title:\"copy\"\n (obj3\n (req \"action\" (constant \"copy\"))\n (req \"source\" OPS.Id.encoding)\n (req \"updates\" OPS.updates_encoding))\n (function\n | Update {init = Copy {src}; updates} ->\n Some ((), src, updates)\n | _ ->\n None)\n (fun ((), src, updates) -> Update {init = Copy {src}; updates});\n case\n (Tag 3)\n ~title:\"alloc\"\n (merge_objs\n (obj2\n (req \"action\" (constant \"alloc\"))\n (req \"updates\" OPS.updates_encoding))\n OPS.alloc_encoding)\n (function\n | Update {init = Alloc alloc; updates} ->\n Some (((), updates), alloc)\n | _ ->\n None)\n (fun (((), updates), alloc) -> Update {init = Alloc alloc; updates}) ]\n\n(**\n [apply_updates ctxt ops ~id init] applies the updates [updates] on lazy\n storage [id] on storage context [ctxt] using operations [ops] and returns the\n updated storage context and the added size in bytes (may be negative).\n*)\nlet apply_updates :\n type i a u.\n Raw_context.t ->\n (i, a, u) ops ->\n id:i ->\n u ->\n (Raw_context.t * Z.t) tzresult Lwt.t =\n fun ctxt (module OPS) ~id updates ->\n OPS.apply_updates ctxt ~id updates\n >>=? fun (ctxt, updates_size) ->\n if Z.(equal updates_size zero) then return (ctxt, updates_size)\n else\n OPS.Total_bytes.get ctxt id\n >>=? fun size ->\n OPS.Total_bytes.set ctxt id (Z.add size updates_size)\n >|=? fun ctxt -> (ctxt, updates_size)\n\n(**\n [apply_init ctxt ops ~id init] applies the initialization [init] on lazy\n storage [id] on storage context [ctxt] using operations [ops] and returns the\n updated storage context and the added size in bytes (may be negative).\n\n If [id] represents a temporary lazy storage, the added size may be wrong.\n*)\nlet apply_init :\n type i a u.\n Raw_context.t ->\n (i, a, u) ops ->\n id:i ->\n (i, a) init ->\n (Raw_context.t * Z.t) tzresult Lwt.t =\n fun ctxt (module OPS) ~id init ->\n match init with\n | Existing ->\n return (ctxt, Z.zero)\n | Copy {src} ->\n OPS.copy ctxt ~from:src ~to_:id\n >>=? fun ctxt ->\n if OPS.Id.is_temp id then return (ctxt, Z.zero)\n else\n OPS.Total_bytes.get ctxt src\n >>=? fun copy_size ->\n return (ctxt, Z.add copy_size OPS.bytes_size_for_empty)\n | Alloc alloc ->\n OPS.Total_bytes.init ctxt id Z.zero\n >>=? fun ctxt ->\n OPS.alloc ctxt id alloc\n >>=? fun ctxt -> return (ctxt, OPS.bytes_size_for_empty)\n\n(**\n [apply_diff ctxt ops ~id diff] applies the diff [diff] on lazy storage [id]\n on storage context [ctxt] using operations [ops] and returns the updated\n storage context and the added size in bytes (may be negative).\n\n If [id] represents a temporary lazy storage, the added size may be wrong.\n*)\nlet apply_diff :\n type i a u.\n Raw_context.t ->\n (i, a, u) ops ->\n id:i ->\n (i, a, u) diff ->\n (Raw_context.t * Z.t) tzresult Lwt.t =\n fun ctxt ((module OPS) as ops) ~id diff ->\n match diff with\n | Remove ->\n if OPS.Id.is_temp id then\n OPS.remove_rec ctxt id >|= fun ctxt -> ok (ctxt, Z.zero)\n else\n OPS.Total_bytes.get ctxt id\n >>=? fun size ->\n OPS.remove_rec ctxt id\n >>= fun ctxt ->\n return (ctxt, Z.neg (Z.add size OPS.bytes_size_for_empty))\n | Update {init; updates} ->\n apply_init ctxt ops ~id init\n >>=? fun (ctxt, init_size) ->\n apply_updates ctxt ops ~id updates\n >>=? fun (ctxt, updates_size) ->\n return (ctxt, Z.add init_size updates_size)\n\ntype diffs_item =\n | Item :\n ('i, 'a, 'u) Lazy_storage_kind.t * 'i * ('i, 'a, 'u) diff\n -> diffs_item\n\nlet make :\n type i a u.\n (i, a, u) Lazy_storage_kind.t -> i -> (i, a, u) diff -> diffs_item =\n fun k id diff -> Item (k, id, diff)\n\nlet item_encoding =\n let open Data_encoding in\n union\n @@ List.map\n (fun (tag, Lazy_storage_kind.Ex_Kind k) ->\n let ops = get_ops k in\n let (module OPS) = ops in\n let title = OPS.title in\n case\n (Tag tag)\n ~title\n (obj3\n (req \"kind\" (constant title))\n (req \"id\" OPS.Id.encoding)\n (req \"diff\" (diff_encoding ops)))\n (fun (Item (kind, id, diff)) ->\n match Lazy_storage_kind.equal k kind with\n | Eq ->\n Some ((), id, diff)\n | Neq ->\n None)\n (fun ((), id, diff) -> Item (k, id, diff)))\n Lazy_storage_kind.all\n [@@coq_axiom \"gadt\"]\n\ntype diffs = diffs_item list\n\nlet encoding =\n let open Data_encoding in\n def \"lazy_storage_diff\" @@ list item_encoding\n\nlet apply ctxt diffs =\n fold_left_s\n (fun (ctxt, total_size) (Item (k, id, diff)) ->\n let ops = get_ops k in\n apply_diff ctxt ops id diff\n >|=? fun (ctxt, added_size) ->\n let (module OPS) = ops in\n ( ctxt,\n if OPS.Id.is_temp id then total_size else Z.add total_size added_size\n ))\n (ctxt, Z.zero)\n diffs\n\nlet fresh :\n type i a u.\n (i, a, u) Lazy_storage_kind.t ->\n temporary:bool ->\n Raw_context.t ->\n (Raw_context.t * i) tzresult Lwt.t =\n fun kind ~temporary ctxt ->\n if temporary then\n return\n (Raw_context.fold_map_temporary_lazy_storage_ids ctxt (fun temp_ids ->\n Lazy_storage_kind.Temp_ids.fresh kind temp_ids))\n else\n let (module OPS) = get_ops kind in\n OPS.Next.incr ctxt\n [@@coq_axiom \"gadt\"]\n\nlet init ctxt =\n fold_left_s\n (fun ctxt (_tag, Lazy_storage_kind.Ex_Kind k) ->\n let (module OPS) = get_ops k in\n OPS.Next.init ctxt)\n ctxt\n Lazy_storage_kind.all\n [@@coq_axiom \"gadt\"]\n\nlet cleanup_temporaries ctxt =\n Raw_context.map_temporary_lazy_storage_ids_s ctxt (fun temp_ids ->\n Lwt_list.fold_left_s\n (fun ctxt (_tag, Lazy_storage_kind.Ex_Kind k) ->\n let (module OPS) = get_ops k in\n Lazy_storage_kind.Temp_ids.fold_s k OPS.remove_rec temp_ids ctxt)\n ctxt\n Lazy_storage_kind.all\n >|= fun ctxt -> (ctxt, Lazy_storage_kind.Temp_ids.init))\n [@@coq_axiom \"gadt\"]\n" ;
} ;
{ name = "Contract_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error +=\n | Balance_too_low of Contract_repr.contract * Tez_repr.t * Tez_repr.t\n | (* `Temporary *)\n Counter_in_the_past of Contract_repr.contract * Z.t * Z.t\n | (* `Branch *)\n Counter_in_the_future of Contract_repr.contract * Z.t * Z.t\n | (* `Temporary *)\n Unspendable_contract of Contract_repr.contract\n | (* `Permanent *)\n Non_existing_contract of Contract_repr.contract\n | (* `Temporary *)\n Empty_implicit_contract of Signature.Public_key_hash.t\n | (* `Temporary *)\n Empty_implicit_delegated_contract of\n Signature.Public_key_hash.t\n | (* `Temporary *)\n Empty_transaction of Contract_repr.t (* `Temporary *)\n | Inconsistent_hash of\n Signature.Public_key.t\n * Signature.Public_key_hash.t\n * Signature.Public_key_hash.t\n | (* `Permanent *)\n Inconsistent_public_key of\n Signature.Public_key.t * Signature.Public_key.t\n | (* `Permanent *)\n Failure of string (* `Permanent *)\n | Previously_revealed_key of Contract_repr.t (* `Permanent *)\n | Unrevealed_manager_key of Contract_repr.t\n\n(* `Permanent *)\n\nval exists : Raw_context.t -> Contract_repr.t -> bool tzresult Lwt.t\n\nval must_exist : Raw_context.t -> Contract_repr.t -> unit tzresult Lwt.t\n\nval allocated : Raw_context.t -> Contract_repr.t -> bool tzresult Lwt.t\n\nval must_be_allocated : Raw_context.t -> Contract_repr.t -> unit tzresult Lwt.t\n\nval list : Raw_context.t -> Contract_repr.t list Lwt.t\n\nval check_counter_increment :\n Raw_context.t -> Signature.Public_key_hash.t -> Z.t -> unit tzresult Lwt.t\n\nval increment_counter :\n Raw_context.t -> Signature.Public_key_hash.t -> Raw_context.t tzresult Lwt.t\n\nval get_manager_key :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Signature.Public_key.t tzresult Lwt.t\n\nval is_manager_key_revealed :\n Raw_context.t -> Signature.Public_key_hash.t -> bool tzresult Lwt.t\n\nval reveal_manager_key :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Signature.Public_key.t ->\n Raw_context.t tzresult Lwt.t\n\nval get_balance : Raw_context.t -> Contract_repr.t -> Tez_repr.t tzresult Lwt.t\n\nval get_balance_carbonated :\n Raw_context.t ->\n Contract_repr.t ->\n (Raw_context.t * Tez_repr.t) tzresult Lwt.t\n\nval get_counter :\n Raw_context.t -> Signature.Public_key_hash.t -> Z.t tzresult Lwt.t\n\nval get_script_code :\n Raw_context.t ->\n Contract_repr.t ->\n (Raw_context.t * Script_repr.lazy_expr option) tzresult Lwt.t\n\nval get_script :\n Raw_context.t ->\n Contract_repr.t ->\n (Raw_context.t * Script_repr.t option) tzresult Lwt.t\n\nval get_storage :\n Raw_context.t ->\n Contract_repr.t ->\n (Raw_context.t * Script_repr.expr option) tzresult Lwt.t\n\nmodule Legacy_big_map_diff : sig\n type item = private\n | Update of {\n big_map : Z.t;\n diff_key : Script_repr.expr;\n diff_key_hash : Script_expr_hash.t;\n diff_value : Script_repr.expr option;\n }\n | Clear of Z.t\n | Copy of {src : Z.t; dst : Z.t}\n | Alloc of {\n big_map : Z.t;\n key_type : Script_repr.expr;\n value_type : Script_repr.expr;\n }\n\n type t = item list\n\n val encoding : t Data_encoding.t\n\n val to_lazy_storage_diff : t -> Lazy_storage_diff.diffs\n\n val of_lazy_storage_diff : Lazy_storage_diff.diffs -> t\nend\n\nval update_script_storage :\n Raw_context.t ->\n Contract_repr.t ->\n Script_repr.expr ->\n Lazy_storage_diff.diffs option ->\n Raw_context.t tzresult Lwt.t\n\nval credit :\n Raw_context.t ->\n Contract_repr.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\nval spend :\n Raw_context.t ->\n Contract_repr.t ->\n Tez_repr.t ->\n Raw_context.t tzresult Lwt.t\n\nval raw_originate :\n Raw_context.t ->\n ?prepaid_bootstrap_storage:bool ->\n Contract_repr.t ->\n balance:Tez_repr.t ->\n script:Script_repr.t * Lazy_storage_diff.diffs option ->\n delegate:Signature.Public_key_hash.t option ->\n Raw_context.t tzresult Lwt.t\n\nval fresh_contract_from_current_nonce :\n Raw_context.t -> (Raw_context.t * Contract_repr.t) tzresult\n\nval originated_from_current_nonce :\n since:Raw_context.t ->\n until:Raw_context.t ->\n Contract_repr.t list tzresult Lwt.t\n\nval init : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval used_storage_space : Raw_context.t -> Contract_repr.t -> Z.t tzresult Lwt.t\n\nval paid_storage_space : Raw_context.t -> Contract_repr.t -> Z.t tzresult Lwt.t\n\nval set_paid_storage_space_and_return_fees_to_pay :\n Raw_context.t ->\n Contract_repr.t ->\n Z.t ->\n (Z.t * Raw_context.t) tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error +=\n | Balance_too_low of Contract_repr.contract * Tez_repr.t * Tez_repr.t\n | (* `Temporary *)\n Counter_in_the_past of Contract_repr.contract * Z.t * Z.t\n | (* `Branch *)\n Counter_in_the_future of Contract_repr.contract * Z.t * Z.t\n | (* `Temporary *)\n Unspendable_contract of Contract_repr.contract\n | (* `Permanent *)\n Non_existing_contract of Contract_repr.contract\n | (* `Temporary *)\n Empty_implicit_contract of Signature.Public_key_hash.t\n | (* `Temporary *)\n Empty_implicit_delegated_contract of\n Signature.Public_key_hash.t\n | (* `Temporary *)\n Empty_transaction of Contract_repr.t (* `Temporary *)\n | Inconsistent_hash of\n Signature.Public_key.t\n * Signature.Public_key_hash.t\n * Signature.Public_key_hash.t\n | (* `Permanent *)\n Inconsistent_public_key of\n Signature.Public_key.t * Signature.Public_key.t\n | (* `Permanent *)\n Failure of string (* `Permanent *)\n | Previously_revealed_key of Contract_repr.t (* `Permanent *)\n | Unrevealed_manager_key of Contract_repr.t\n\n(* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"contract.unspendable_contract\"\n ~title:\"Unspendable contract\"\n ~description:\n \"An operation tried to spend tokens from an unspendable contract\"\n ~pp:(fun ppf c ->\n Format.fprintf\n ppf\n \"The tokens of contract %a can only be spent by its script\"\n Contract_repr.pp\n c)\n Data_encoding.(obj1 (req \"contract\" Contract_repr.encoding))\n (function Unspendable_contract c -> Some c | _ -> None)\n (fun c -> Unspendable_contract c) ;\n register_error_kind\n `Temporary\n ~id:\"contract.balance_too_low\"\n ~title:\"Balance too low\"\n ~description:\n \"An operation tried to spend more tokens than the contract has\"\n ~pp:(fun ppf (c, b, a) ->\n Format.fprintf\n ppf\n \"Balance of contract %a too low (%a) to spend %a\"\n Contract_repr.pp\n c\n Tez_repr.pp\n b\n Tez_repr.pp\n a)\n Data_encoding.(\n obj3\n (req \"contract\" Contract_repr.encoding)\n (req \"balance\" Tez_repr.encoding)\n (req \"amount\" Tez_repr.encoding))\n (function Balance_too_low (c, b, a) -> Some (c, b, a) | _ -> None)\n (fun (c, b, a) -> Balance_too_low (c, b, a)) ;\n register_error_kind\n `Temporary\n ~id:\"contract.counter_in_the_future\"\n ~title:\"Invalid counter (not yet reached) in a manager operation\"\n ~description:\"An operation assumed a contract counter in the future\"\n ~pp:(fun ppf (contract, exp, found) ->\n Format.fprintf\n ppf\n \"Counter %a not yet reached for contract %a (expected %a)\"\n Z.pp_print\n found\n Contract_repr.pp\n contract\n Z.pp_print\n exp)\n Data_encoding.(\n obj3\n (req \"contract\" Contract_repr.encoding)\n (req \"expected\" z)\n (req \"found\" z))\n (function Counter_in_the_future (c, x, y) -> Some (c, x, y) | _ -> None)\n (fun (c, x, y) -> Counter_in_the_future (c, x, y)) ;\n register_error_kind\n `Branch\n ~id:\"contract.counter_in_the_past\"\n ~title:\"Invalid counter (already used) in a manager operation\"\n ~description:\"An operation assumed a contract counter in the past\"\n ~pp:(fun ppf (contract, exp, found) ->\n Format.fprintf\n ppf\n \"Counter %a already used for contract %a (expected %a)\"\n Z.pp_print\n found\n Contract_repr.pp\n contract\n Z.pp_print\n exp)\n Data_encoding.(\n obj3\n (req \"contract\" Contract_repr.encoding)\n (req \"expected\" z)\n (req \"found\" z))\n (function Counter_in_the_past (c, x, y) -> Some (c, x, y) | _ -> None)\n (fun (c, x, y) -> Counter_in_the_past (c, x, y)) ;\n register_error_kind\n `Temporary\n ~id:\"contract.non_existing_contract\"\n ~title:\"Non existing contract\"\n ~description:\n \"A contract handle is not present in the context (either it never was \\\n or it has been destroyed)\"\n ~pp:(fun ppf contract ->\n Format.fprintf ppf \"Contract %a does not exist\" Contract_repr.pp contract)\n Data_encoding.(obj1 (req \"contract\" Contract_repr.encoding))\n (function Non_existing_contract c -> Some c | _ -> None)\n (fun c -> Non_existing_contract c) ;\n register_error_kind\n `Permanent\n ~id:\"contract.manager.inconsistent_hash\"\n ~title:\"Inconsistent public key hash\"\n ~description:\n \"A revealed manager public key is inconsistent with the announced hash\"\n ~pp:(fun ppf (k, eh, ph) ->\n Format.fprintf\n ppf\n \"The hash of the manager public key %s is not %a as announced but %a\"\n (Signature.Public_key.to_b58check k)\n Signature.Public_key_hash.pp\n ph\n Signature.Public_key_hash.pp\n eh)\n Data_encoding.(\n obj3\n (req \"public_key\" Signature.Public_key.encoding)\n (req \"expected_hash\" Signature.Public_key_hash.encoding)\n (req \"provided_hash\" Signature.Public_key_hash.encoding))\n (function Inconsistent_hash (k, eh, ph) -> Some (k, eh, ph) | _ -> None)\n (fun (k, eh, ph) -> Inconsistent_hash (k, eh, ph)) ;\n register_error_kind\n `Permanent\n ~id:\"contract.manager.inconsistent_public_key\"\n ~title:\"Inconsistent public key\"\n ~description:\n \"A provided manager public key is different with the public key stored \\\n in the contract\"\n ~pp:(fun ppf (eh, ph) ->\n Format.fprintf\n ppf\n \"Expected manager public key %s but %s was provided\"\n (Signature.Public_key.to_b58check ph)\n (Signature.Public_key.to_b58check eh))\n Data_encoding.(\n obj2\n (req \"public_key\" Signature.Public_key.encoding)\n (req \"expected_public_key\" Signature.Public_key.encoding))\n (function Inconsistent_public_key (eh, ph) -> Some (eh, ph) | _ -> None)\n (fun (eh, ph) -> Inconsistent_public_key (eh, ph)) ;\n register_error_kind\n `Permanent\n ~id:\"contract.failure\"\n ~title:\"Contract storage failure\"\n ~description:\"Unexpected contract storage error\"\n ~pp:(fun ppf s -> Format.fprintf ppf \"Contract_storage.Failure %S\" s)\n Data_encoding.(obj1 (req \"message\" string))\n (function Failure s -> Some s | _ -> None)\n (fun s -> Failure s) ;\n register_error_kind\n `Branch\n ~id:\"contract.unrevealed_key\"\n ~title:\"Manager operation precedes key revelation\"\n ~description:\n \"One tried to apply a manager operation without revealing the manager \\\n public key\"\n ~pp:(fun ppf s ->\n Format.fprintf\n ppf\n \"Unrevealed manager key for contract %a.\"\n Contract_repr.pp\n s)\n Data_encoding.(obj1 (req \"contract\" Contract_repr.encoding))\n (function Unrevealed_manager_key s -> Some s | _ -> None)\n (fun s -> Unrevealed_manager_key s) ;\n register_error_kind\n `Branch\n ~id:\"contract.previously_revealed_key\"\n ~title:\"Manager operation already revealed\"\n ~description:\"One tried to revealed twice a manager public key\"\n ~pp:(fun ppf s ->\n Format.fprintf\n ppf\n \"Previously revealed manager key for contract %a.\"\n Contract_repr.pp\n s)\n Data_encoding.(obj1 (req \"contract\" Contract_repr.encoding))\n (function Previously_revealed_key s -> Some s | _ -> None)\n (fun s -> Previously_revealed_key s) ;\n register_error_kind\n `Branch\n ~id:\"implicit.empty_implicit_contract\"\n ~title:\"Empty implicit contract\"\n ~description:\n \"No manager operations are allowed on an empty implicit contract.\"\n ~pp:(fun ppf implicit ->\n Format.fprintf\n ppf\n \"Empty implicit contract (%a)\"\n Signature.Public_key_hash.pp\n implicit)\n Data_encoding.(obj1 (req \"implicit\" Signature.Public_key_hash.encoding))\n (function Empty_implicit_contract c -> Some c | _ -> None)\n (fun c -> Empty_implicit_contract c) ;\n register_error_kind\n `Branch\n ~id:\"implicit.empty_implicit_delegated_contract\"\n ~title:\"Empty implicit delegated contract\"\n ~description:\"Emptying an implicit delegated account is not allowed.\"\n ~pp:(fun ppf implicit ->\n Format.fprintf\n ppf\n \"Emptying implicit delegated contract (%a)\"\n Signature.Public_key_hash.pp\n implicit)\n Data_encoding.(obj1 (req \"implicit\" Signature.Public_key_hash.encoding))\n (function Empty_implicit_delegated_contract c -> Some c | _ -> None)\n (fun c -> Empty_implicit_delegated_contract c) ;\n register_error_kind\n `Branch\n ~id:\"contract.empty_transaction\"\n ~title:\"Empty transaction\"\n ~description:\"Forbidden to credit 0\234\156\169 to a contract without code.\"\n ~pp:(fun ppf contract ->\n Format.fprintf\n ppf\n \"Transaction of 0\234\156\169 towards a contract without code are forbidden \\\n (%a).\"\n Contract_repr.pp\n contract)\n Data_encoding.(obj1 (req \"contract\" Contract_repr.encoding))\n (function Empty_transaction c -> Some c | _ -> None)\n (fun c -> Empty_transaction c)\n\nlet failwith msg = fail (Failure msg)\n\nmodule Legacy_big_map_diff = struct\n (*\n Big_map_diff receipt as it was represented in 006 and earlier.\n It is kept here for now for backward compatibility of tools. *)\n\n type item =\n | Update of {\n big_map : Z.t;\n diff_key : Script_repr.expr;\n diff_key_hash : Script_expr_hash.t;\n diff_value : Script_repr.expr option;\n }\n | Clear of Z.t\n | Copy of {src : Z.t; dst : Z.t}\n | Alloc of {\n big_map : Z.t;\n key_type : Script_repr.expr;\n value_type : Script_repr.expr;\n }\n\n type t = item list\n\n let item_encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"update\"\n (obj5\n (req \"action\" (constant \"update\"))\n (req \"big_map\" z)\n (req \"key_hash\" Script_expr_hash.encoding)\n (req \"key\" Script_repr.expr_encoding)\n (opt \"value\" Script_repr.expr_encoding))\n (function\n | Update {big_map; diff_key_hash; diff_key; diff_value} ->\n Some ((), big_map, diff_key_hash, diff_key, diff_value)\n | _ ->\n None)\n (fun ((), big_map, diff_key_hash, diff_key, diff_value) ->\n Update {big_map; diff_key_hash; diff_key; diff_value});\n case\n (Tag 1)\n ~title:\"remove\"\n (obj2 (req \"action\" (constant \"remove\")) (req \"big_map\" z))\n (function Clear big_map -> Some ((), big_map) | _ -> None)\n (fun ((), big_map) -> Clear big_map);\n case\n (Tag 2)\n ~title:\"copy\"\n (obj3\n (req \"action\" (constant \"copy\"))\n (req \"source_big_map\" z)\n (req \"destination_big_map\" z))\n (function Copy {src; dst} -> Some ((), src, dst) | _ -> None)\n (fun ((), src, dst) -> Copy {src; dst});\n case\n (Tag 3)\n ~title:\"alloc\"\n (obj4\n (req \"action\" (constant \"alloc\"))\n (req \"big_map\" z)\n (req \"key_type\" Script_repr.expr_encoding)\n (req \"value_type\" Script_repr.expr_encoding))\n (function\n | Alloc {big_map; key_type; value_type} ->\n Some ((), big_map, key_type, value_type)\n | _ ->\n None)\n (fun ((), big_map, key_type, value_type) ->\n Alloc {big_map; key_type; value_type}) ]\n\n let encoding = Data_encoding.list item_encoding\n\n let to_lazy_storage_diff legacy_diffs =\n let rev_head (diffs : (_ * (_, _, _) Lazy_storage_diff.diff) list) =\n match diffs with\n | [] ->\n []\n | (_, Remove) :: _ ->\n diffs\n | (id, Update {init; updates}) :: rest ->\n (id, Update {init; updates = List.rev updates}) :: rest\n in\n (* Invariant:\n Updates are collected one by one, in reverse order, on the head diff\n item. So only and exactly the head diff item has its updates reversed.\n *)\n List.fold_left\n (fun (new_diff : (_ * (_, _, _) Lazy_storage_diff.diff) list) item ->\n match item with\n | Clear id ->\n (id, Lazy_storage_diff.Remove) :: rev_head new_diff\n | Copy {src; dst} ->\n let src =\n Lazy_storage_kind.Big_map.Id\n .of_legacy_USE_ONLY_IN_Legacy_big_map_diff\n src\n in\n (dst, Lazy_storage_diff.Update {init = Copy {src}; updates = []})\n :: rev_head new_diff\n | Alloc {big_map; key_type; value_type} ->\n ( big_map,\n Lazy_storage_diff.(\n Update\n {\n init =\n Alloc Lazy_storage_kind.Big_map.{key_type; value_type};\n updates = [];\n }) )\n :: rev_head new_diff\n | Update\n { big_map;\n diff_key = key;\n diff_key_hash = key_hash;\n diff_value = value } -> (\n match new_diff with\n | (id, diff) :: rest when Compare.Z.(id = big_map) ->\n let diff =\n match diff with\n | Remove ->\n assert false\n | Update {init; updates} ->\n let updates =\n Lazy_storage_kind.Big_map.{key; key_hash; value}\n :: updates\n in\n Lazy_storage_diff.Update {init; updates}\n in\n (id, diff) :: rest\n | new_diff ->\n let updates =\n [Lazy_storage_kind.Big_map.{key; key_hash; value}]\n in\n (big_map, Update {init = Existing; updates}) :: rev_head new_diff\n ))\n []\n legacy_diffs\n |> rev_head\n |> List.rev_map (fun (id, diff) ->\n let id =\n Lazy_storage_kind.Big_map.Id\n .of_legacy_USE_ONLY_IN_Legacy_big_map_diff\n id\n in\n Lazy_storage_diff.make Lazy_storage_kind.Big_map id diff)\n\n let of_lazy_storage_diff diffs =\n List.fold_left\n (fun legacy_diffs (Lazy_storage_diff.Item (kind, id, diff)) ->\n let diffs =\n match kind with\n | Lazy_storage_kind.Big_map -> (\n let id =\n Lazy_storage_kind.Big_map.Id\n .to_legacy_USE_ONLY_IN_Legacy_big_map_diff\n id\n in\n match diff with\n | Remove ->\n [Clear id]\n | Update {init; updates} -> (\n let updates =\n List.rev_map\n (fun {Lazy_storage_kind.Big_map.key; key_hash; value} ->\n Update\n {\n big_map = id;\n diff_key = key;\n diff_key_hash = key_hash;\n diff_value = value;\n })\n updates\n in\n match init with\n | Existing ->\n updates\n | Copy {src} ->\n let src =\n Lazy_storage_kind.Big_map.Id\n .to_legacy_USE_ONLY_IN_Legacy_big_map_diff\n src\n in\n Copy {src; dst = id} :: updates\n | Alloc {key_type; value_type} ->\n Alloc {big_map = id; key_type; value_type} :: updates ) )\n | _ ->\n (* Not a Big_map *) []\n in\n diffs :: legacy_diffs)\n []\n diffs\n |> List.rev |> List.flatten\n [@@coq_axiom \"gadt\"]\nend\n\nlet update_script_lazy_storage c = function\n | None ->\n return (c, Z.zero)\n | Some diffs ->\n Lazy_storage_diff.apply c diffs\n\nlet create_base c ?(prepaid_bootstrap_storage = false)\n (* Free space for bootstrap contracts *)\n contract ~balance ~manager ~delegate ?script () =\n ( match Contract_repr.is_implicit contract with\n | None ->\n return c\n | Some _ ->\n Storage.Contract.Global_counter.get c\n >>=? fun counter -> Storage.Contract.Counter.init c contract counter )\n >>=? fun c ->\n Storage.Contract.Balance.init c contract balance\n >>=? fun c ->\n ( match manager with\n | Some manager ->\n Storage.Contract.Manager.init c contract (Manager_repr.Hash manager)\n | None ->\n return c )\n >>=? fun c ->\n ( match delegate with\n | None ->\n return c\n | Some delegate ->\n Delegate_storage.init c contract delegate )\n >>=? fun c ->\n match script with\n | Some ({Script_repr.code; storage}, lazy_storage_diff) ->\n Storage.Contract.Code.init c contract code\n >>=? fun (c, code_size) ->\n Storage.Contract.Storage.init c contract storage\n >>=? fun (c, storage_size) ->\n update_script_lazy_storage c lazy_storage_diff\n >>=? fun (c, lazy_storage_size) ->\n let total_size =\n Z.add\n (Z.add (Z.of_int code_size) (Z.of_int storage_size))\n lazy_storage_size\n in\n assert (Compare.Z.(total_size >= Z.zero)) ;\n let prepaid_bootstrap_storage =\n if prepaid_bootstrap_storage then total_size else Z.zero\n in\n Storage.Contract.Paid_storage_space.init\n c\n contract\n prepaid_bootstrap_storage\n >>=? fun c ->\n Storage.Contract.Used_storage_space.init c contract total_size\n | None ->\n return c\n\nlet raw_originate c ?prepaid_bootstrap_storage contract ~balance ~script\n ~delegate =\n create_base\n c\n ?prepaid_bootstrap_storage\n contract\n ~balance\n ~manager:None\n ~delegate\n ~script\n ()\n\nlet create_implicit c manager ~balance =\n create_base\n c\n (Contract_repr.implicit_contract manager)\n ~balance\n ~manager:(Some manager)\n ?script:None\n ~delegate:None\n ()\n\nlet delete c contract =\n match Contract_repr.is_implicit contract with\n | None ->\n (* For non implicit contract Big_map should be cleared *)\n failwith \"Non implicit contracts cannot be removed\"\n | Some _ ->\n Delegate_storage.remove c contract\n >>=? fun c ->\n Storage.Contract.Balance.delete c contract\n >>=? fun c ->\n Storage.Contract.Manager.delete c contract\n >>=? fun c ->\n Storage.Contract.Counter.delete c contract\n >>=? fun c ->\n Storage.Contract.Code.remove c contract\n >>=? fun (c, _, _) ->\n Storage.Contract.Storage.remove c contract\n >>=? fun (c, _, _) ->\n Storage.Contract.Paid_storage_space.remove c contract\n >>= fun c -> Storage.Contract.Used_storage_space.remove c contract >|= ok\n\nlet allocated c contract =\n Storage.Contract.Balance.get_option c contract\n >>=? function None -> return_false | Some _ -> return_true\n\nlet exists c contract =\n match Contract_repr.is_implicit contract with\n | Some _ ->\n return_true\n | None ->\n allocated c contract\n\nlet must_exist c contract =\n exists c contract\n >>=? function\n | true -> return_unit | false -> fail (Non_existing_contract contract)\n\nlet must_be_allocated c contract =\n allocated c contract\n >>=? function\n | true ->\n return_unit\n | false -> (\n match Contract_repr.is_implicit contract with\n | Some pkh ->\n fail (Empty_implicit_contract pkh)\n | None ->\n fail (Non_existing_contract contract) )\n\nlet list c = Storage.Contract.list c\n\nlet fresh_contract_from_current_nonce c =\n Raw_context.increment_origination_nonce c\n >|? fun (c, nonce) -> (c, Contract_repr.originated_contract nonce)\n\nlet originated_from_current_nonce ~since:ctxt_since ~until:ctxt_until =\n Raw_context.origination_nonce ctxt_since\n >>?= fun since ->\n Raw_context.origination_nonce ctxt_until\n >>?= fun until ->\n filter_s\n (fun contract -> exists ctxt_until contract)\n (Contract_repr.originated_contracts ~since ~until)\n\nlet check_counter_increment c manager counter =\n let contract = Contract_repr.implicit_contract manager in\n Storage.Contract.Counter.get c contract\n >>=? fun contract_counter ->\n let expected = Z.succ contract_counter in\n if Compare.Z.(expected = counter) then return_unit\n else if Compare.Z.(expected > counter) then\n fail (Counter_in_the_past (contract, expected, counter))\n else fail (Counter_in_the_future (contract, expected, counter))\n\nlet increment_counter c manager =\n let contract = Contract_repr.implicit_contract manager in\n Storage.Contract.Global_counter.get c\n >>=? fun global_counter ->\n Storage.Contract.Global_counter.set c (Z.succ global_counter)\n >>=? fun c ->\n Storage.Contract.Counter.get c contract\n >>=? fun contract_counter ->\n Storage.Contract.Counter.set c contract (Z.succ contract_counter)\n\nlet get_script_code c contract = Storage.Contract.Code.get_option c contract\n\nlet get_script c contract =\n Storage.Contract.Code.get_option c contract\n >>=? fun (c, code) ->\n Storage.Contract.Storage.get_option c contract\n >>=? fun (c, storage) ->\n match (code, storage) with\n | (None, None) ->\n return (c, None)\n | (Some code, Some storage) ->\n return (c, Some {Script_repr.code; storage})\n | (None, Some _) | (Some _, None) ->\n failwith \"get_script\"\n\nlet get_storage ctxt contract =\n Storage.Contract.Storage.get_option ctxt contract\n >>=? function\n | (ctxt, None) ->\n return (ctxt, None)\n | (ctxt, Some storage) ->\n Lwt.return (Script_repr.force_decode storage)\n >>=? fun (storage, cost) ->\n Lwt.return (Raw_context.consume_gas ctxt cost)\n >>=? fun ctxt -> return (ctxt, Some storage)\n\nlet get_counter c manager =\n let contract = Contract_repr.implicit_contract manager in\n Storage.Contract.Counter.get_option c contract\n >>=? function\n | None -> (\n match Contract_repr.is_implicit contract with\n | Some _ ->\n Storage.Contract.Global_counter.get c\n | None ->\n failwith \"get_counter\" )\n | Some v ->\n return v\n\nlet get_manager_key c manager =\n let contract = Contract_repr.implicit_contract manager in\n Storage.Contract.Manager.get_option c contract\n >>=? function\n | None ->\n failwith \"get_manager_key\"\n | Some (Manager_repr.Hash _) ->\n fail (Unrevealed_manager_key contract)\n | Some (Manager_repr.Public_key v) ->\n return v\n\nlet is_manager_key_revealed c manager =\n let contract = Contract_repr.implicit_contract manager in\n Storage.Contract.Manager.get_option c contract\n >>=? function\n | None ->\n return_false\n | Some (Manager_repr.Hash _) ->\n return_false\n | Some (Manager_repr.Public_key _) ->\n return_true\n\nlet reveal_manager_key c manager public_key =\n let contract = Contract_repr.implicit_contract manager in\n Storage.Contract.Manager.get c contract\n >>=? function\n | Public_key _ ->\n fail (Previously_revealed_key contract)\n | Hash v ->\n let actual_hash = Signature.Public_key.hash public_key in\n if Signature.Public_key_hash.equal actual_hash v then\n let v = Manager_repr.Public_key public_key in\n Storage.Contract.Manager.set c contract v\n else fail (Inconsistent_hash (public_key, v, actual_hash))\n\nlet get_balance c contract =\n Storage.Contract.Balance.get_option c contract\n >>=? function\n | None -> (\n match Contract_repr.is_implicit contract with\n | Some _ ->\n return Tez_repr.zero\n | None ->\n failwith \"get_balance\" )\n | Some v ->\n return v\n\nlet get_balance_carbonated c contract =\n (* Reading an int64 from /contracts/pkh/balance\n NB: this cost assumes a flattened storage structure. *)\n Raw_context.consume_gas\n c\n (Storage_costs.read_access ~path_length:3 ~read_bytes:8)\n >>?= fun c -> get_balance c contract >>=? fun balance -> return (c, balance)\n\nlet update_script_storage c contract storage lazy_storage_diff =\n let storage = Script_repr.lazy_expr storage in\n update_script_lazy_storage c lazy_storage_diff\n >>=? fun (c, lazy_storage_size_diff) ->\n Storage.Contract.Storage.set c contract storage\n >>=? fun (c, size_diff) ->\n Storage.Contract.Used_storage_space.get c contract\n >>=? fun previous_size ->\n let new_size =\n Z.add previous_size (Z.add lazy_storage_size_diff (Z.of_int size_diff))\n in\n Storage.Contract.Used_storage_space.set c contract new_size\n\nlet spend c contract amount =\n Storage.Contract.Balance.get c contract\n >>=? fun balance ->\n match Tez_repr.(balance -? amount) with\n | Error _ ->\n fail (Balance_too_low (contract, balance, amount))\n | Ok new_balance -> (\n Storage.Contract.Balance.set c contract new_balance\n >>=? fun c ->\n Roll_storage.Contract.remove_amount c contract amount\n >>=? fun c ->\n if Tez_repr.(new_balance > Tez_repr.zero) then return c\n else\n match Contract_repr.is_implicit contract with\n | None ->\n return c (* Never delete originated contracts *)\n | Some pkh -> (\n Delegate_storage.get c contract\n >>=? function\n | Some pkh' ->\n if Signature.Public_key_hash.equal pkh pkh' then return c\n else\n (* Delegated implicit accounts cannot be emptied *)\n fail (Empty_implicit_delegated_contract pkh)\n | None ->\n (* Delete empty implicit contract *)\n delete c contract ) )\n\nlet credit c contract amount =\n ( if Tez_repr.(amount <> Tez_repr.zero) then return c\n else\n must_exist c contract\n >>=? fun () ->\n Storage.Contract.Code.mem c contract\n >>=? fun (c, target_has_code) ->\n Lwt.return\n ( error_unless target_has_code (Empty_transaction contract)\n >|? fun () -> c ) )\n >>=? fun c ->\n Storage.Contract.Balance.get_option c contract\n >>=? function\n | None -> (\n match Contract_repr.is_implicit contract with\n | None ->\n fail (Non_existing_contract contract)\n | Some manager ->\n create_implicit c manager ~balance:amount )\n | Some balance ->\n Tez_repr.(amount +? balance)\n >>?= fun balance ->\n Storage.Contract.Balance.set c contract balance\n >>=? fun c -> Roll_storage.Contract.add_amount c contract amount\n\nlet init c =\n Storage.Contract.Global_counter.init c Z.zero\n >>=? fun c -> Lazy_storage_diff.init c\n\nlet used_storage_space c contract =\n Storage.Contract.Used_storage_space.get_option c contract\n >|=? Option.value ~default:Z.zero\n\nlet paid_storage_space c contract =\n Storage.Contract.Paid_storage_space.get_option c contract\n >|=? Option.value ~default:Z.zero\n\nlet set_paid_storage_space_and_return_fees_to_pay c contract new_storage_space\n =\n Storage.Contract.Paid_storage_space.get c contract\n >>=? fun already_paid_space ->\n if Compare.Z.(already_paid_space >= new_storage_space) then return (Z.zero, c)\n else\n let to_pay = Z.sub new_storage_space already_paid_space in\n Storage.Contract.Paid_storage_space.set c contract new_storage_space\n >|=? fun c -> (to_pay, c)\n" ;
} ;
{ name = "Bootstrap_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nval init :\n Raw_context.t ->\n typecheck:(Raw_context.t ->\n Script_repr.t ->\n ((Script_repr.t * Lazy_storage_diff.diffs option) * Raw_context.t)\n tzresult\n Lwt.t) ->\n ?ramp_up_cycles:int ->\n ?no_reward_cycles:int ->\n Parameters_repr.bootstrap_account list ->\n Parameters_repr.bootstrap_contract list ->\n Raw_context.t tzresult Lwt.t\n\nval cycle_end : Raw_context.t -> Cycle_repr.t -> Raw_context.t tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Misc\n\nlet init_account ctxt\n ({public_key_hash; public_key; amount} : Parameters_repr.bootstrap_account)\n =\n let contract = Contract_repr.implicit_contract public_key_hash in\n Contract_storage.credit ctxt contract amount\n >>=? fun ctxt ->\n match public_key with\n | Some public_key ->\n Contract_storage.reveal_manager_key ctxt public_key_hash public_key\n >>=? fun ctxt ->\n Delegate_storage.set ctxt contract (Some public_key_hash)\n | None ->\n return ctxt\n\nlet init_contract ~typecheck ctxt\n ({delegate; amount; script} : Parameters_repr.bootstrap_contract) =\n Contract_storage.fresh_contract_from_current_nonce ctxt\n >>?= fun (ctxt, contract) ->\n typecheck ctxt script\n >>=? fun (script, ctxt) ->\n Contract_storage.raw_originate\n ctxt\n contract\n ~balance:amount\n ~prepaid_bootstrap_storage:true\n ~script\n ~delegate:(Some delegate)\n\nlet init ctxt ~typecheck ?ramp_up_cycles ?no_reward_cycles accounts contracts =\n let nonce =\n Operation_hash.hash_bytes [Bytes.of_string \"Un festival de GADT.\"]\n in\n let ctxt = Raw_context.init_origination_nonce ctxt nonce in\n fold_left_s init_account ctxt accounts\n >>=? fun ctxt ->\n fold_left_s (init_contract ~typecheck) ctxt contracts\n >>=? fun ctxt ->\n ( match no_reward_cycles with\n | None ->\n return ctxt\n | Some cycles ->\n (* Store pending ramp ups. *)\n let constants = Raw_context.constants ctxt in\n (* Start without rewards *)\n Raw_context.patch_constants ctxt (fun c ->\n {\n c with\n baking_reward_per_endorsement = [Tez_repr.zero];\n endorsement_reward = [Tez_repr.zero];\n })\n >>= fun ctxt ->\n (* Store the final reward. *)\n Storage.Ramp_up.Rewards.init\n ctxt\n (Cycle_repr.of_int32_exn (Int32.of_int cycles))\n (constants.baking_reward_per_endorsement, constants.endorsement_reward)\n )\n >>=? fun ctxt ->\n match ramp_up_cycles with\n | None ->\n return ctxt\n | Some cycles ->\n (* Store pending ramp ups. *)\n let constants = Raw_context.constants ctxt in\n Tez_repr.(constants.block_security_deposit /? Int64.of_int cycles)\n >>?= fun block_step ->\n Tez_repr.(constants.endorsement_security_deposit /? Int64.of_int cycles)\n >>?= fun endorsement_step ->\n (* Start without security_deposit *)\n Raw_context.patch_constants ctxt (fun c ->\n {\n c with\n block_security_deposit = Tez_repr.zero;\n endorsement_security_deposit = Tez_repr.zero;\n })\n >>= fun ctxt ->\n fold_left_s\n (fun ctxt cycle ->\n Tez_repr.(block_step *? Int64.of_int cycle)\n >>?= fun block_security_deposit ->\n Tez_repr.(endorsement_step *? Int64.of_int cycle)\n >>?= fun endorsement_security_deposit ->\n let cycle = Cycle_repr.of_int32_exn (Int32.of_int cycle) in\n Storage.Ramp_up.Security_deposits.init\n ctxt\n cycle\n (block_security_deposit, endorsement_security_deposit))\n ctxt\n (1 --> (cycles - 1))\n >>=? fun ctxt ->\n (* Store the final security deposits. *)\n Storage.Ramp_up.Security_deposits.init\n ctxt\n (Cycle_repr.of_int32_exn (Int32.of_int cycles))\n ( constants.block_security_deposit,\n constants.endorsement_security_deposit )\n\nlet cycle_end ctxt last_cycle =\n let next_cycle = Cycle_repr.succ last_cycle in\n Storage.Ramp_up.Rewards.get_option ctxt next_cycle\n >>=? (function\n | None ->\n return ctxt\n | Some (baking_reward_per_endorsement, endorsement_reward) ->\n Storage.Ramp_up.Rewards.delete ctxt next_cycle\n >>=? fun ctxt ->\n Raw_context.patch_constants ctxt (fun c ->\n {c with baking_reward_per_endorsement; endorsement_reward})\n >|= ok)\n >>=? fun ctxt ->\n Storage.Ramp_up.Security_deposits.get_option ctxt next_cycle\n >>=? function\n | None ->\n return ctxt\n | Some (block_security_deposit, endorsement_security_deposit) ->\n Storage.Ramp_up.Security_deposits.delete ctxt next_cycle\n >>=? fun ctxt ->\n Raw_context.patch_constants ctxt (fun c ->\n {c with block_security_deposit; endorsement_security_deposit})\n >|= ok\n" ;
} ;
{ name = "Fitness_storage" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet current = Raw_context.current_fitness\n\nlet increase ctxt =\n let fitness = current ctxt in\n Raw_context.set_current_fitness ctxt (Int64.succ fitness)\n" ;
} ;
{ name = "Voting_period_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nval init :\n Raw_context.t -> Voting_period_repr.t -> Raw_context.t tzresult Lwt.t\n\n(** Sets the initial period to [{voting_period = root; kind = Proposal;\n start_position}]. *)\nval init_first_period :\n Raw_context.t -> start_position:Int32.t -> Raw_context.t tzresult Lwt.t\n\n(** Increment the index by one and set the kind to Proposal. *)\nval reset : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\n(** Increment the index by one and set the kind to its successor. *)\nval succ : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval get_current : Raw_context.t -> Voting_period_repr.t tzresult Lwt.t\n\nval get_current_kind : Raw_context.t -> Voting_period_repr.kind tzresult Lwt.t\n\n(** Returns true if the context level is the last of current voting period. *)\nval is_last_block : Raw_context.t -> bool tzresult Lwt.t\n\n(* Given the issue explained in voting_period_storage.ml this function behaves\n currectly during the validation of a block but returns inconsistent info if\n called after the finalization of the block.\n For this reason when used by the RPC `votes/current_period_kind` gives an\n unintuitive result: after the validation of the last block of a voting period\n (e.g. proposal), it returns the kind of the next period (e.g. testing_vote).\n To fix this, at least part of the current vote finalization should be moved\n at the beginning of the block validation.\n For retro-compatibility, we keep this function but we provide two new fixed\n functions to reply correctly to RPCs [get_rpc_fixed_current_info] and\n [get_rpc_fixed_succ_info]. *)\nval get_current_info : Raw_context.t -> Voting_period_repr.info tzresult Lwt.t\n\n(* In order to avoid the problem of `get_current_info` explained above, this\n function provides the corrent behavior for the new RPC `votes/current_period`.\n*)\nval get_rpc_fixed_current_info :\n Raw_context.t -> Voting_period_repr.info tzresult Lwt.t\n\n(* In order to avoid the problem of `get_current_info` explained above, this\n function provides the corrent behavior for the new RPC `votes/successor_period`.\n*)\nval get_rpc_fixed_succ_info :\n Raw_context.t -> Voting_period_repr.info tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(*\n The shell uses the convention that a context at level n is the resulting\n context of the application of block n.\n Therefore when using an RPC on the last level of a voting period, the context\n that is inspected is the resulting one.\n\n However [Amendment.may_start_new_voting_period] is run at the end of voting\n period and it has to prepare the context for validating operations of the next\n period. This causes the counter-intuitive result that the info returned by RPCs\n at last level of a voting period mention data of the next voting period.\n\n For example, when validating the last block of a proposal period at level n\n we have:\n - Input context:\n\n voting_period = { kind = Proposal;\n index = i;\n start_position = n - blocks_per_voting_period}\n\n - position = n - start_position = blocks_per_voting_period\n - remaining = blocks_per_voting_period - (position + 1) = 0\n\n - Output context:\n\n voting_period = { kind = Testing_vote;\n index = i + 1;\n start_position = n + 1}\n\n Now if we calculate position and remaining in the voting period we get\n strange results:\n - position = n - (n + 1) = -1\n - remaining = blocks_per_voting_period\n\n In order to have the correct value for the RPCs a fix has been applied in\n [voting_service] by calling a specific function\n [voting_period_storage.get_rpc_fixed_current_info].\n\n This odd behaviour could be fixed if [Amendment.may_start_new_voting_period]\n was called when we start validating a block instead that at the end.\n This should be carefully done because the voting period listing depends on\n the rolls and it might break some invariant.\n\n When this is implemented one should:\n - remove the function [voting_period_storage.get_rpc_fixed_current_info]\n - edit the function [reset_current] and [inc_current] to use the\n current level and not the next one.\n - remove the storage for pred_kind\n - make Voting_period_repr.t abstract\n\n You can also look at the MR description here:\n https://gitlab.com/metastatedev/tezos/-/merge_requests/333\n *)\n\nlet set_current = Storage.Vote.Current_period.set\n\nlet get_current = Storage.Vote.Current_period.get\n\nlet init = Storage.Vote.Current_period.init\n\nlet init_first_period ctxt ~start_position =\n init ctxt @@ Voting_period_repr.root ~start_position\n >>=? fun ctxt ->\n Storage.Vote.Pred_period_kind.init ctxt Voting_period_repr.Proposal\n\nlet common ctxt =\n get_current ctxt\n >>=? fun current_period ->\n Storage.Vote.Pred_period_kind.set ctxt current_period.kind\n >|=? fun ctxt ->\n let start_position =\n (* because we are preparing the voting period for the next block we need to\n use the next level. *)\n Int32.succ (Level_storage.current ctxt).level_position\n in\n (ctxt, current_period, start_position)\n\nlet reset ctxt =\n common ctxt\n >>=? fun (ctxt, current_period, start_position) ->\n Voting_period_repr.reset current_period ~start_position |> set_current ctxt\n\nlet succ ctxt =\n common ctxt\n >>=? fun (ctxt, current_period, start_position) ->\n Voting_period_repr.succ current_period ~start_position |> set_current ctxt\n\nlet get_current_kind ctxt = get_current ctxt >|=? fun {kind; _} -> kind\n\nlet get_current_info ctxt =\n get_current ctxt\n >|=? fun voting_period ->\n let blocks_per_voting_period =\n Constants_storage.blocks_per_voting_period ctxt\n in\n let level = Level_storage.current ctxt in\n let position = Voting_period_repr.position_since level voting_period in\n let remaining =\n Voting_period_repr.remaining_blocks\n level\n voting_period\n blocks_per_voting_period\n in\n Voting_period_repr.{voting_period; position; remaining}\n\nlet get_current_remaining ctxt =\n get_current ctxt\n >|=? fun voting_period ->\n let blocks_per_voting_period =\n Constants_storage.blocks_per_voting_period ctxt\n in\n Voting_period_repr.remaining_blocks\n (Level_storage.current ctxt)\n voting_period\n blocks_per_voting_period\n\nlet is_last_block ctxt =\n get_current_remaining ctxt\n >|=? fun remaining -> Compare.Int32.(remaining = 0l)\n\nlet get_rpc_fixed_current_info ctxt =\n get_current_info ctxt\n >>=? fun ({voting_period; position; _} as voting_period_info) ->\n if Compare.Int32.(position = Int32.minus_one) then\n let level = Level_storage.current ctxt in\n let blocks_per_voting_period =\n Constants_storage.blocks_per_voting_period ctxt\n in\n Storage.Vote.Pred_period_kind.get ctxt\n >|=? fun pred_kind ->\n let voting_period : Voting_period_repr.t =\n {\n index = Int32.pred voting_period.index;\n kind = pred_kind;\n start_position =\n Int32.(sub voting_period.start_position blocks_per_voting_period);\n }\n in\n let position = Voting_period_repr.position_since level voting_period in\n let remaining =\n Voting_period_repr.remaining_blocks\n level\n voting_period\n ~blocks_per_voting_period\n in\n ({voting_period; remaining; position} : Voting_period_repr.info)\n else return voting_period_info\n\nlet get_rpc_fixed_succ_info ctxt =\n get_current ctxt\n >|=? fun voting_period ->\n let blocks_per_voting_period =\n Constants_storage.blocks_per_voting_period ctxt\n in\n let level =\n Level_storage.from_raw ctxt ~offset:1l (Level_storage.current ctxt).level\n in\n let position = Voting_period_repr.position_since level voting_period in\n let remaining =\n Voting_period_repr.remaining_blocks\n level\n voting_period\n blocks_per_voting_period\n in\n Voting_period_repr.{voting_period; position; remaining}\n" ;
} ;
{ name = "Vote_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Manages all the voting related storage in Storage.Vote. *)\n\n(** Records a protocol proposal with the delegate that proposed it. *)\nval record_proposal :\n Raw_context.t ->\n Protocol_hash.t ->\n Signature.Public_key_hash.t ->\n Raw_context.t tzresult Lwt.t\n\nval recorded_proposal_count_for_delegate :\n Raw_context.t -> Signature.Public_key_hash.t -> int tzresult Lwt.t\n\n(** Computes for each proposal how many delegates proposed it. *)\nval get_proposals : Raw_context.t -> int32 Protocol_hash.Map.t tzresult Lwt.t\n\nval clear_proposals : Raw_context.t -> Raw_context.t Lwt.t\n\n(** Counts of the votes *)\ntype ballots = {yay : int32; nay : int32; pass : int32}\n\nval ballots_encoding : ballots Data_encoding.t\n\nval has_recorded_ballot :\n Raw_context.t -> Signature.Public_key_hash.t -> bool Lwt.t\n\n(** Records a vote for a delegate, returns a {!Storage_error Existing_key} if\n the vote was already registered *)\nval record_ballot :\n Raw_context.t ->\n Signature.Public_key_hash.t ->\n Vote_repr.ballot ->\n Raw_context.t tzresult Lwt.t\n\n(** Computes the sum of the current ballots weighted by stake. *)\nval get_ballots : Raw_context.t -> ballots tzresult Lwt.t\n\nval get_ballot_list :\n Raw_context.t -> (Signature.Public_key_hash.t * Vote_repr.ballot) list Lwt.t\n\nval clear_ballots : Raw_context.t -> Raw_context.t Lwt.t\n\nval listings_encoding :\n (Signature.Public_key_hash.t * int32) list Data_encoding.t\n\n(** Populates [!Storage.Vote.Listings] using the currently existing rolls and\n sets Listings_size. Delegates without rolls are not included in the listing. *)\nval update_listings : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\n(** Returns the sum of all rolls of all delegates. *)\nval listing_size : Raw_context.t -> int32 tzresult Lwt.t\n\n(** Verifies the presence of a delegate in the listing. *)\nval in_listings : Raw_context.t -> Signature.Public_key_hash.t -> bool Lwt.t\n\nval get_listings :\n Raw_context.t -> (Signature.Public_key_hash.t * int32) list Lwt.t\n\nval get_voting_power_free :\n Raw_context.t -> Signature.public_key_hash -> int32 tzresult Lwt.t\n\nval get_voting_power :\n Raw_context.t ->\n Signature.public_key_hash ->\n (Raw_context.t * int32) tzresult Lwt.t\n\nval get_total_voting_power_free : Raw_context.t -> int32 tzresult Lwt.t\n\nval get_total_voting_power :\n Raw_context.t -> (Raw_context.t * int32) tzresult Lwt.t\n\nval get_current_quorum : Raw_context.t -> int32 tzresult Lwt.t\n\nval get_participation_ema : Raw_context.t -> int32 tzresult Lwt.t\n\nval set_participation_ema :\n Raw_context.t -> int32 -> Raw_context.t tzresult Lwt.t\n\nval get_current_proposal : Raw_context.t -> Protocol_hash.t tzresult Lwt.t\n\nval init_current_proposal :\n Raw_context.t -> Protocol_hash.t -> Raw_context.t tzresult Lwt.t\n\nval clear_current_proposal : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\n(** Sets the initial quorum to 80% and period kind to proposal. *)\nval init :\n Raw_context.t -> start_position:Int32.t -> Raw_context.t tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet recorded_proposal_count_for_delegate ctxt proposer =\n Storage.Vote.Proposals_count.get_option ctxt proposer\n >|=? Option.value ~default:0\n\nlet record_proposal ctxt proposal proposer =\n recorded_proposal_count_for_delegate ctxt proposer\n >>=? fun count ->\n Storage.Vote.Proposals_count.init_set ctxt proposer (count + 1)\n >>= fun ctxt -> Storage.Vote.Proposals.add ctxt (proposal, proposer) >|= ok\n\nlet get_proposals ctxt =\n Storage.Vote.Proposals.fold\n ctxt\n ~init:(ok Protocol_hash.Map.empty)\n ~f:(fun (proposal, delegate) acc ->\n (* Assuming the same listings is used at votings *)\n Storage.Vote.Listings.get ctxt delegate\n >>=? fun weight ->\n Lwt.return\n ( acc\n >|? fun acc ->\n let previous =\n match Protocol_hash.Map.find_opt proposal acc with\n | None ->\n 0l\n | Some x ->\n x\n in\n Protocol_hash.Map.add proposal (Int32.add weight previous) acc ))\n\nlet clear_proposals ctxt =\n Storage.Vote.Proposals_count.clear ctxt\n >>= fun ctxt -> Storage.Vote.Proposals.clear ctxt\n\ntype ballots = {yay : int32; nay : int32; pass : int32}\n\nlet ballots_encoding =\n let open Data_encoding in\n conv\n (fun {yay; nay; pass} -> (yay, nay, pass))\n (fun (yay, nay, pass) -> {yay; nay; pass})\n @@ obj3 (req \"yay\" int32) (req \"nay\" int32) (req \"pass\" int32)\n\nlet has_recorded_ballot = Storage.Vote.Ballots.mem\n\nlet record_ballot = Storage.Vote.Ballots.init\n\nlet get_ballots ctxt =\n Storage.Vote.Ballots.fold\n ctxt\n ~f:(fun delegate ballot (ballots : ballots tzresult) ->\n (* Assuming the same listings is used at votings *)\n Storage.Vote.Listings.get ctxt delegate\n >>=? fun weight ->\n let count = Int32.add weight in\n Lwt.return\n ( ballots\n >|? fun ballots ->\n match ballot with\n | Yay ->\n {ballots with yay = count ballots.yay}\n | Nay ->\n {ballots with nay = count ballots.nay}\n | Pass ->\n {ballots with pass = count ballots.pass} ))\n ~init:(ok {yay = 0l; nay = 0l; pass = 0l})\n\nlet get_ballot_list = Storage.Vote.Ballots.bindings\n\nlet clear_ballots = Storage.Vote.Ballots.clear\n\nlet listings_encoding =\n Data_encoding.(\n list\n (obj2 (req \"pkh\" Signature.Public_key_hash.encoding) (req \"rolls\" int32)))\n\nlet update_listings ctxt =\n Storage.Vote.Listings.clear ctxt\n >>= fun ctxt ->\n Roll_storage.fold ctxt (ctxt, 0l) ~f:(fun _roll delegate (ctxt, total) ->\n (* TODO use snapshots *)\n let delegate = Signature.Public_key.hash delegate in\n Storage.Vote.Listings.get_option ctxt delegate\n >|=? Option.value ~default:0l\n >>=? fun count ->\n Storage.Vote.Listings.init_set ctxt delegate (Int32.succ count)\n >|= fun ctxt -> ok (ctxt, Int32.succ total))\n >>=? fun (ctxt, total) ->\n Storage.Vote.Listings_size.init_set ctxt total >>= fun ctxt -> return ctxt\n\nlet listing_size = Storage.Vote.Listings_size.get\n\nlet in_listings = Storage.Vote.Listings.mem\n\nlet get_listings = Storage.Vote.Listings.bindings\n\nlet get_voting_power_free ctxt owner =\n Storage.Vote.Listings.get_option ctxt owner >|=? Option.value ~default:0l\n\n(* This function bypasses the carbonated functors to account for gas consumption.\n This is a temporary situation intended to be fixed by adding the right\n carbonated functors in a future amendment *)\nlet get_voting_power ctxt owner =\n let open Raw_context in\n (* Always consume read access to memory *)\n (* Accessing an int32 at /votes/listings/pkh *)\n consume_gas ctxt (Storage_costs.read_access ~path_length:3 ~read_bytes:4)\n >>?= fun ctxt ->\n Storage.Vote.Listings.get_option ctxt owner\n >|=? function None -> (ctxt, 0l) | Some power -> (ctxt, power)\n\nlet get_total_voting_power_free = listing_size\n\n(* This function bypasses the carbonated functors to account for gas consumption.\n This is a temporary situation intended to be fixed by adding the right\n carbonated functors in a future amendment *)\nlet get_total_voting_power ctxt =\n let open Raw_context in\n (* Accessing an int32 at /votes/listings_size *)\n consume_gas ctxt (Storage_costs.read_access ~path_length:2 ~read_bytes:4)\n >>?= fun ctxt ->\n get_total_voting_power_free ctxt\n >|=? fun total_voting_power -> (ctxt, total_voting_power)\n\nlet get_current_quorum ctxt =\n Storage.Vote.Participation_ema.get ctxt\n >|=? fun participation_ema ->\n let quorum_min = Constants_storage.quorum_min ctxt in\n let quorum_max = Constants_storage.quorum_max ctxt in\n let quorum_diff = Int32.sub quorum_max quorum_min in\n Int32.(add quorum_min (div (mul participation_ema quorum_diff) 100_00l))\n\nlet get_participation_ema = Storage.Vote.Participation_ema.get\n\nlet set_participation_ema = Storage.Vote.Participation_ema.set\n\nlet get_current_proposal = Storage.Vote.Current_proposal.get\n\nlet init_current_proposal = Storage.Vote.Current_proposal.init\n\nlet clear_current_proposal = Storage.Vote.Current_proposal.delete\n\nlet init ctxt ~start_position =\n (* participation EMA is in centile of a percentage *)\n let participation_ema = Constants_storage.quorum_max ctxt in\n Storage.Vote.Participation_ema.init ctxt participation_ema\n >>=? fun ctxt -> Voting_period_storage.init_first_period ctxt ~start_position\n" ;
} ;
{ name = "Commitment_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nval init :\n Raw_context.t -> Commitment_repr.t list -> Raw_context.t tzresult Lwt.t\n\nval get_opt :\n Raw_context.t ->\n Blinded_public_key_hash.t ->\n Tez_repr.t option tzresult Lwt.t\n\nval delete :\n Raw_context.t -> Blinded_public_key_hash.t -> Raw_context.t tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nlet get_opt = Storage.Commitments.get_option\n\nlet delete = Storage.Commitments.delete\n\nlet init ctxt commitments =\n let init_commitment ctxt Commitment_repr.{blinded_public_key_hash; amount} =\n Storage.Commitments.init ctxt blinded_public_key_hash amount\n in\n fold_left_s init_commitment ctxt commitments\n" ;
} ;
{ name = "Init_storage" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* This is the genesis protocol: initialise the state *)\nlet prepare_first_block ctxt ~typecheck ~level ~timestamp ~fitness =\n Raw_context.prepare_first_block ~level ~timestamp ~fitness ctxt\n >>=? fun (previous_protocol, ctxt, prev_blocks_per_voting_period) ->\n match previous_protocol with\n | Genesis param ->\n Commitment_storage.init ctxt param.commitments\n >>=? fun ctxt ->\n Roll_storage.init ctxt\n >>=? fun ctxt ->\n Seed_storage.init ctxt\n >>=? fun ctxt ->\n Contract_storage.init ctxt\n >>=? fun ctxt ->\n Bootstrap_storage.init\n ctxt\n ~typecheck\n ?ramp_up_cycles:param.security_deposit_ramp_up_cycles\n ?no_reward_cycles:param.no_reward_cycles\n param.bootstrap_accounts\n param.bootstrap_contracts\n >>=? fun ctxt ->\n Roll_storage.init_first_cycles ctxt\n >>=? fun ctxt ->\n Vote_storage.init\n ctxt\n ~start_position:(Level_storage.current ctxt).level_position\n >>=? fun ctxt ->\n Storage.Block_priority.init ctxt 0\n >>=? fun ctxt -> Vote_storage.update_listings ctxt\n | Delphi_007 ->\n Storage.Vote.Current_period_kind_007.delete ctxt\n >>=? fun ctxt ->\n let level_position = (Level_storage.current ctxt).level_position in\n let voting_period_index =\n Int32.(div (succ level_position) prev_blocks_per_voting_period)\n in\n let start_position = level_position in\n Storage.Vote.Current_period.init\n ctxt\n {index = voting_period_index; kind = Proposal; start_position}\n >>=? fun ctxt ->\n Storage.Vote.Pred_period_kind.init ctxt Promotion_vote\n >>=? fun ctxt -> Storage.Sapling.Next.init ctxt\n\nlet prepare ctxt ~level ~predecessor_timestamp ~timestamp ~fitness =\n Raw_context.prepare ~level ~predecessor_timestamp ~timestamp ~fitness ctxt\n" ;
} ;
{ name = "Fees_storage" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error += Cannot_pay_storage_fee (* `Temporary *)\n\ntype error += Operation_quota_exceeded (* `Temporary *)\n\ntype error += Storage_limit_too_high (* `Permanent *)\n\n(** Does not burn, only adds the burn to storage space to be paid *)\nval origination_burn : Raw_context.t -> (Raw_context.t * Tez_repr.t) tzresult\n\n(** The returned Tez quantity is for logging purpose only *)\nval record_paid_storage_space :\n Raw_context.t ->\n Contract_repr.t ->\n (Raw_context.t * Z.t * Z.t * Tez_repr.t) tzresult Lwt.t\n\nval check_storage_limit : Raw_context.t -> storage_limit:Z.t -> unit tzresult\n\nval start_counting_storage_fees : Raw_context.t -> Raw_context.t\n\nval burn_storage_fees :\n Raw_context.t ->\n storage_limit:Z.t ->\n payer:Contract_repr.t ->\n Raw_context.t tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype error += Cannot_pay_storage_fee (* `Temporary *)\n\ntype error += Operation_quota_exceeded (* `Temporary *)\n\ntype error += Storage_limit_too_high (* `Permanent *)\n\nlet () =\n let open Data_encoding in\n register_error_kind\n `Temporary\n ~id:\"contract.cannot_pay_storage_fee\"\n ~title:\"Cannot pay storage fee\"\n ~description:\"The storage fee is higher than the contract balance\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Cannot pay storage storage fee\")\n Data_encoding.empty\n (function Cannot_pay_storage_fee -> Some () | _ -> None)\n (fun () -> Cannot_pay_storage_fee) ;\n register_error_kind\n `Temporary\n ~id:\"storage_exhausted.operation\"\n ~title:\"Storage quota exceeded for the operation\"\n ~description:\n \"A script or one of its callee wrote more bytes than the operation said \\\n it would\"\n Data_encoding.empty\n (function Operation_quota_exceeded -> Some () | _ -> None)\n (fun () -> Operation_quota_exceeded) ;\n register_error_kind\n `Permanent\n ~id:\"storage_limit_too_high\"\n ~title:\"Storage limit out of protocol hard bounds\"\n ~description:\"A transaction tried to exceed the hard limit on storage\"\n empty\n (function Storage_limit_too_high -> Some () | _ -> None)\n (fun () -> Storage_limit_too_high)\n\nlet origination_burn c =\n let origination_size = Constants_storage.origination_size c in\n let cost_per_byte = Constants_storage.cost_per_byte c in\n (* the origination burn, measured in bytes *)\n Tez_repr.(cost_per_byte *? Int64.of_int origination_size)\n >|? fun to_be_paid ->\n (Raw_context.update_allocated_contracts_count c, to_be_paid)\n\nlet record_paid_storage_space c contract =\n Contract_storage.used_storage_space c contract\n >>=? fun size ->\n Contract_storage.set_paid_storage_space_and_return_fees_to_pay\n c\n contract\n size\n >>=? fun (to_be_paid, c) ->\n let c = Raw_context.update_storage_space_to_pay c to_be_paid in\n let cost_per_byte = Constants_storage.cost_per_byte c in\n Lwt.return\n ( Tez_repr.(cost_per_byte *? Z.to_int64 to_be_paid)\n >|? fun to_burn -> (c, size, to_be_paid, to_burn) )\n\nlet burn_storage_fees c ~storage_limit ~payer =\n let origination_size = Constants_storage.origination_size c in\n let (c, storage_space_to_pay, allocated_contracts) =\n Raw_context.clear_storage_space_to_pay c\n in\n let storage_space_for_allocated_contracts =\n Z.mul (Z.of_int allocated_contracts) (Z.of_int origination_size)\n in\n let consumed =\n Z.add storage_space_to_pay storage_space_for_allocated_contracts\n in\n let remaining = Z.sub storage_limit consumed in\n if Compare.Z.(remaining < Z.zero) then fail Operation_quota_exceeded\n else\n let cost_per_byte = Constants_storage.cost_per_byte c in\n Tez_repr.(cost_per_byte *? Z.to_int64 consumed)\n >>?= fun to_burn ->\n (* Burning the fees... *)\n if Tez_repr.(to_burn = Tez_repr.zero) then\n (* If the payer was was deleted by transferring all its balance, and no space was used,\n burning zero would fail *)\n return c\n else\n trace\n Cannot_pay_storage_fee\n ( Contract_storage.must_exist c payer\n >>=? fun () -> Contract_storage.spend c payer to_burn )\n\nlet check_storage_limit c ~storage_limit =\n if\n Compare.Z.(\n storage_limit\n > (Raw_context.constants c).hard_storage_limit_per_operation)\n || Compare.Z.(storage_limit < Z.zero)\n then error Storage_limit_too_high\n else ok_unit\n\nlet start_counting_storage_fees c = Raw_context.init_storage_space_to_pay c\n" ;
} ;
{ name = "Sapling_validator" ;
interface = None ;
implementation = "(* The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE. *)\n\n(* Check that each nullifier is not already present in the state and add it.\n Important to avoid spending the same input twice in a transaction. *)\nlet rec check_and_update_nullifiers ctxt state inputs =\n match inputs with\n | [] ->\n return (ctxt, Some state)\n | input :: inputs -> (\n Sapling_storage.nullifiers_mem ctxt state Sapling.UTXO.(input.nf)\n >>=? function\n | (ctxt, true) ->\n return (ctxt, None)\n | (ctxt, false) ->\n let state =\n Sapling_storage.nullifiers_add state Sapling.UTXO.(input.nf)\n in\n check_and_update_nullifiers ctxt state inputs )\n\nlet verify_update :\n Raw_context.t ->\n Sapling_storage.state ->\n Sapling_repr.transaction ->\n string ->\n (Raw_context.t * (Int64.t * Sapling_storage.state) option) tzresult Lwt.t =\n fun ctxt state transaction key ->\n (* Check the transaction *)\n (* To avoid overflowing the balance, the number of inputs and outputs must be\n bounded.\n Ciphertexts' memo_size must match the state's memo_size.\n These constraints are already enforced at the encoding level. *)\n assert (Compare.Int.(List.compare_length_with transaction.inputs 5208 <= 0)) ;\n assert (Compare.Int.(List.compare_length_with transaction.outputs 2019 <= 0)) ;\n let pass =\n List.for_all\n (fun output ->\n Compare.Int.(\n Sapling.Ciphertext.get_memo_size Sapling.UTXO.(output.ciphertext)\n = state.memo_size))\n transaction.outputs\n in\n if not pass then return (ctxt, None)\n else\n (* Check the root is a recent state *)\n Sapling_storage.root_mem ctxt state transaction.root\n >>=? fun pass ->\n if not pass then return (ctxt, None)\n else\n check_and_update_nullifiers ctxt state transaction.inputs\n >|=? function\n | (ctxt, None) ->\n (ctxt, None)\n | (ctxt, Some state) ->\n Sapling.Verification.with_verification_ctx (fun vctx ->\n let pass =\n (* Check all the output ZK proofs *)\n List.for_all\n (fun output -> Sapling.Verification.check_output vctx output)\n transaction.outputs\n in\n if not pass then (ctxt, None)\n else\n let pass =\n (* Check all the input Zk proofs and signatures *)\n List.for_all\n (fun input ->\n Sapling.Verification.check_spend\n vctx\n input\n transaction.root\n key)\n transaction.inputs\n in\n if not pass then (ctxt, None)\n else\n let pass =\n (* Check the signature and balance of the whole transaction *)\n Sapling.Verification.final_check vctx transaction key\n in\n if not pass then (ctxt, None)\n else\n (* update tree *)\n let list_to_add =\n List.map\n (fun output ->\n Sapling.UTXO.(output.cm, output.ciphertext))\n transaction.outputs\n in\n let state = Sapling_storage.add state list_to_add in\n (ctxt, Some (transaction.balance, state)))\n" ;
} ;
{ name = "Alpha_context" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nmodule type BASIC_DATA = sig\n type t\n\n include Compare.S with type t := t\n\n val encoding : t Data_encoding.t\n\n val pp : Format.formatter -> t -> unit\nend\n\ntype t\n\ntype context = t\n\ntype public_key = Signature.Public_key.t\n\ntype public_key_hash = Signature.Public_key_hash.t\n\ntype signature = Signature.t\n\nmodule Tez : sig\n include BASIC_DATA\n\n type tez = t\n\n val zero : tez\n\n val one_mutez : tez\n\n val one_cent : tez\n\n val fifty_cents : tez\n\n val one : tez\n\n val ( -? ) : tez -> tez -> tez tzresult\n\n val ( +? ) : tez -> tez -> tez tzresult\n\n val ( *? ) : tez -> int64 -> tez tzresult\n\n val ( /? ) : tez -> int64 -> tez tzresult\n\n val of_string : string -> tez option\n\n val to_string : tez -> string\n\n val of_mutez : int64 -> tez option\n\n val to_mutez : tez -> int64\nend\n\nmodule Period : sig\n include BASIC_DATA\n\n type period = t\n\n val rpc_arg : period RPC_arg.arg\n\n val of_seconds : int64 -> period tzresult\n\n val to_seconds : period -> int64\n\n val mult : int32 -> period -> period tzresult\n\n val zero : period\n\n val one_second : period\n\n val one_minute : period\n\n val one_hour : period\nend\n\nmodule Timestamp : sig\n include BASIC_DATA with type t = Time.t\n\n type time = t\n\n val ( +? ) : time -> Period.t -> time tzresult\n\n val ( -? ) : time -> time -> Period.t tzresult\n\n val of_notation : string -> time option\n\n val to_notation : time -> string\n\n val of_seconds_string : string -> time option\n\n val to_seconds_string : time -> string\n\n val current : context -> time\nend\n\nmodule Raw_level : sig\n include BASIC_DATA\n\n type raw_level = t\n\n val rpc_arg : raw_level RPC_arg.arg\n\n val diff : raw_level -> raw_level -> int32\n\n val root : raw_level\n\n val succ : raw_level -> raw_level\n\n val pred : raw_level -> raw_level option\n\n val to_int32 : raw_level -> int32\n\n val of_int32 : int32 -> raw_level tzresult\nend\n\nmodule Cycle : sig\n include BASIC_DATA\n\n type cycle = t\n\n val rpc_arg : cycle RPC_arg.arg\n\n val root : cycle\n\n val succ : cycle -> cycle\n\n val pred : cycle -> cycle option\n\n val add : cycle -> int -> cycle\n\n val sub : cycle -> int -> cycle option\n\n val to_int32 : cycle -> int32\n\n module Map : S.MAP with type key = cycle\nend\n\nmodule Gas : sig\n module Arith : Fixed_point_repr.Safe\n\n type t = private Unaccounted | Limited of {remaining : Arith.fp}\n\n val encoding : t Data_encoding.encoding\n\n val pp : Format.formatter -> t -> unit\n\n type cost\n\n val cost_encoding : cost Data_encoding.encoding\n\n val pp_cost : Format.formatter -> cost -> unit\n\n type error += Block_quota_exceeded (* `Temporary *)\n\n type error += Operation_quota_exceeded (* `Temporary *)\n\n type error += Gas_limit_too_high (* `Permanent *)\n\n val free : cost\n\n val atomic_step_cost : Z.t -> cost\n\n val step_cost : Z.t -> cost\n\n val alloc_cost : Z.t -> cost\n\n val alloc_bytes_cost : int -> cost\n\n val alloc_mbytes_cost : int -> cost\n\n val read_bytes_cost : Z.t -> cost\n\n val write_bytes_cost : Z.t -> cost\n\n val ( *@ ) : Z.t -> cost -> cost\n\n val ( +@ ) : cost -> cost -> cost\n\n val check_limit : context -> 'a Arith.t -> unit tzresult\n\n val set_limit : context -> 'a Arith.t -> context\n\n val set_unlimited : context -> context\n\n val consume : context -> cost -> context tzresult\n\n val check_enough : context -> cost -> unit tzresult\n\n val level : context -> t\n\n val consumed : since:context -> until:context -> Arith.fp\n\n val block_level : context -> Arith.fp\n\n val cost_of_repr : Gas_limit_repr.cost -> cost\nend\n\nmodule Script_int : module type of Script_int_repr\n\nmodule Script_timestamp : sig\n open Script_int\n\n type t\n\n val compare : t -> t -> int\n\n val to_string : t -> string\n\n val to_notation : t -> string option\n\n val to_num_str : t -> string\n\n val of_string : string -> t option\n\n val diff : t -> t -> z num\n\n val add_delta : t -> z num -> t\n\n val sub_delta : t -> z num -> t\n\n val now : context -> t\n\n val to_zint : t -> Z.t\n\n val of_zint : Z.t -> t\nend\n\nmodule Script : sig\n type prim = Michelson_v1_primitives.prim =\n | K_parameter\n | K_storage\n | K_code\n | D_False\n | D_Elt\n | D_Left\n | D_None\n | D_Pair\n | D_Right\n | D_Some\n | D_True\n | D_Unit\n | I_PACK\n | I_UNPACK\n | I_BLAKE2B\n | I_SHA256\n | I_SHA512\n | I_ABS\n | I_ADD\n | I_AMOUNT\n | I_AND\n | I_BALANCE\n | I_CAR\n | I_CDR\n | I_CHAIN_ID\n | I_CHECK_SIGNATURE\n | I_COMPARE\n | I_CONCAT\n | I_CONS\n | I_CREATE_ACCOUNT\n | I_CREATE_CONTRACT\n | I_IMPLICIT_ACCOUNT\n | I_DIP\n | I_DROP\n | I_DUP\n | I_EDIV\n | I_EMPTY_BIG_MAP\n | I_EMPTY_MAP\n | I_EMPTY_SET\n | I_EQ\n | I_EXEC\n | I_APPLY\n | I_FAILWITH\n | I_GE\n | I_GET\n | I_GET_AND_UPDATE\n | I_GT\n | I_HASH_KEY\n | I_IF\n | I_IF_CONS\n | I_IF_LEFT\n | I_IF_NONE\n | I_INT\n | I_LAMBDA\n | I_LE\n | I_LEFT\n | I_LEVEL\n | I_LOOP\n | I_LSL\n | I_LSR\n | I_LT\n | I_MAP\n | I_MEM\n | I_MUL\n | I_NEG\n | I_NEQ\n | I_NIL\n | I_NONE\n | I_NOT\n | I_NOW\n | I_OR\n | I_PAIR\n | I_UNPAIR\n | I_PUSH\n | I_RIGHT\n | I_SIZE\n | I_SOME\n | I_SOURCE\n | I_SENDER\n | I_SELF\n | I_SELF_ADDRESS\n | I_SLICE\n | I_STEPS_TO_QUOTA\n | I_SUB\n | I_SWAP\n | I_TRANSFER_TOKENS\n | I_SET_DELEGATE\n | I_UNIT\n | I_UPDATE\n | I_XOR\n | I_ITER\n | I_LOOP_LEFT\n | I_ADDRESS\n | I_CONTRACT\n | I_ISNAT\n | I_CAST\n | I_RENAME\n | I_SAPLING_EMPTY_STATE\n | I_SAPLING_VERIFY_UPDATE\n | I_DIG\n | I_DUG\n | I_NEVER\n | I_VOTING_POWER\n | I_TOTAL_VOTING_POWER\n | I_KECCAK\n | I_SHA3\n | I_PAIRING_CHECK\n | I_TICKET\n | I_READ_TICKET\n | I_SPLIT_TICKET\n | I_JOIN_TICKETS\n | T_bool\n | T_contract\n | T_int\n | T_key\n | T_key_hash\n | T_lambda\n | T_list\n | T_map\n | T_big_map\n | T_nat\n | T_option\n | T_or\n | T_pair\n | T_set\n | T_signature\n | T_string\n | T_bytes\n | T_mutez\n | T_timestamp\n | T_unit\n | T_operation\n | T_address\n | T_sapling_transaction\n | T_sapling_state\n | T_chain_id\n | T_never\n | T_bls12_381_g1\n | T_bls12_381_g2\n | T_bls12_381_fr\n | T_ticket\n\n type location = Micheline.canonical_location\n\n type annot = Micheline.annot\n\n type expr = prim Micheline.canonical\n\n type lazy_expr = expr Data_encoding.lazy_t\n\n val lazy_expr : expr -> lazy_expr\n\n type node = (location, prim) Micheline.node\n\n type t = {code : lazy_expr; storage : lazy_expr}\n\n val location_encoding : location Data_encoding.t\n\n val expr_encoding : expr Data_encoding.t\n\n val prim_encoding : prim Data_encoding.t\n\n val encoding : t Data_encoding.t\n\n val lazy_expr_encoding : lazy_expr Data_encoding.t\n\n val deserialized_cost : expr -> Gas.cost\n\n val serialized_cost : bytes -> Gas.cost\n\n val traversal_cost : node -> Gas.cost\n\n val int_node_cost : Z.t -> Gas.cost\n\n val int_node_cost_of_numbits : int -> Gas.cost\n\n val string_node_cost : string -> Gas.cost\n\n val string_node_cost_of_length : int -> Gas.cost\n\n val bytes_node_cost : bytes -> Gas.cost\n\n val bytes_node_cost_of_length : int -> Gas.cost\n\n val prim_node_cost_nonrec : expr list -> annot -> Gas.cost\n\n val seq_node_cost_nonrec : expr list -> Gas.cost\n\n val seq_node_cost_nonrec_of_length : int -> Gas.cost\n\n val minimal_deserialize_cost : lazy_expr -> Gas.cost\n\n val force_decode_in_context :\n context -> lazy_expr -> (expr * context) tzresult\n\n val force_bytes_in_context :\n context -> lazy_expr -> (bytes * context) tzresult\n\n val unit_parameter : lazy_expr\n\n val micheline_nodes : node -> int\n\n val strip_locations_cost : node -> Gas.cost\nend\n\nmodule Constants : sig\n (** Fixed constants *)\n type fixed = {\n proof_of_work_nonce_size : int;\n nonce_length : int;\n max_anon_ops_per_block : int;\n max_operation_data_length : int;\n max_proposals_per_delegate : int;\n }\n\n val fixed_encoding : fixed Data_encoding.t\n\n val fixed : fixed\n\n val proof_of_work_nonce_size : int\n\n val nonce_length : int\n\n val max_anon_ops_per_block : int\n\n val max_operation_data_length : int\n\n val max_proposals_per_delegate : int\n\n (** Constants parameterized by context *)\n type parametric = {\n preserved_cycles : int;\n blocks_per_cycle : int32;\n blocks_per_commitment : int32;\n blocks_per_roll_snapshot : int32;\n blocks_per_voting_period : int32;\n time_between_blocks : Period.t list;\n endorsers_per_block : int;\n hard_gas_limit_per_operation : Gas.Arith.integral;\n hard_gas_limit_per_block : Gas.Arith.integral;\n proof_of_work_threshold : int64;\n tokens_per_roll : Tez.t;\n michelson_maximum_type_size : int;\n seed_nonce_revelation_tip : Tez.t;\n origination_size : int;\n block_security_deposit : Tez.t;\n endorsement_security_deposit : Tez.t;\n baking_reward_per_endorsement : Tez.t list;\n endorsement_reward : Tez.t list;\n cost_per_byte : Tez.t;\n hard_storage_limit_per_operation : Z.t;\n test_chain_duration : int64;\n quorum_min : int32;\n quorum_max : int32;\n min_proposal_quorum : int32;\n initial_endorsers : int;\n delay_per_missing_endorsement : Period.t;\n }\n\n val parametric_encoding : parametric Data_encoding.t\n\n val parametric : context -> parametric\n\n val preserved_cycles : context -> int\n\n val blocks_per_cycle : context -> int32\n\n val blocks_per_commitment : context -> int32\n\n val blocks_per_roll_snapshot : context -> int32\n\n val blocks_per_voting_period : context -> int32\n\n val time_between_blocks : context -> Period.t list\n\n val endorsers_per_block : context -> int\n\n val initial_endorsers : context -> int\n\n val delay_per_missing_endorsement : context -> Period.t\n\n val hard_gas_limit_per_operation : context -> Gas.Arith.integral\n\n val hard_gas_limit_per_block : context -> Gas.Arith.integral\n\n val cost_per_byte : context -> Tez.t\n\n val hard_storage_limit_per_operation : context -> Z.t\n\n val proof_of_work_threshold : context -> int64\n\n val tokens_per_roll : context -> Tez.t\n\n val michelson_maximum_type_size : context -> int\n\n val baking_reward_per_endorsement : context -> Tez.t list\n\n val endorsement_reward : context -> Tez.t list\n\n val seed_nonce_revelation_tip : context -> Tez.t\n\n val origination_size : context -> int\n\n val block_security_deposit : context -> Tez.t\n\n val endorsement_security_deposit : context -> Tez.t\n\n val test_chain_duration : context -> int64\n\n val quorum_min : context -> int32\n\n val quorum_max : context -> int32\n\n val min_proposal_quorum : context -> int32\n\n (** All constants: fixed and parametric *)\n type t = {fixed : fixed; parametric : parametric}\n\n val encoding : t Data_encoding.t\nend\n\nmodule Level : sig\n type t = private {\n level : Raw_level.t;\n level_position : int32;\n cycle : Cycle.t;\n cycle_position : int32;\n expected_commitment : bool;\n }\n\n include BASIC_DATA with type t := t\n\n val pp_full : Format.formatter -> t -> unit\n\n type level = t\n\n val root : context -> level\n\n val succ : context -> level -> level\n\n val pred : context -> level -> level option\n\n val from_raw : context -> ?offset:int32 -> Raw_level.t -> level\n\n val diff : level -> level -> int32\n\n val current : context -> level\n\n val last_level_in_cycle : context -> Cycle.t -> level\n\n val levels_in_cycle : context -> Cycle.t -> level list\n\n val levels_in_current_cycle : context -> ?offset:int32 -> unit -> level list\n\n val last_allowed_fork_level : context -> Raw_level.t\n\n type compat_t = {\n level : Raw_level.t;\n level_position : int32;\n cycle : Cycle.t;\n cycle_position : int32;\n voting_period : int32;\n voting_period_position : int32;\n expected_commitment : bool;\n }\n\n val compat_encoding : compat_t Data_encoding.t\n\n val to_deprecated_type :\n t -> voting_period_index:int32 -> voting_period_position:int32 -> compat_t\nend\n\nmodule Fitness : sig\n include module type of Fitness\n\n type fitness = t\n\n val increase : context -> context\n\n val current : context -> int64\n\n val to_int64 : fitness -> int64 tzresult\nend\n\nmodule Nonce : sig\n type t\n\n type nonce = t\n\n val encoding : nonce Data_encoding.t\n\n type unrevealed = {\n nonce_hash : Nonce_hash.t;\n delegate : public_key_hash;\n rewards : Tez.t;\n fees : Tez.t;\n }\n\n val record_hash : context -> unrevealed -> context tzresult Lwt.t\n\n val reveal : context -> Level.t -> nonce -> context tzresult Lwt.t\n\n type status = Unrevealed of unrevealed | Revealed of nonce\n\n val get : context -> Level.t -> status tzresult Lwt.t\n\n val of_bytes : bytes -> nonce tzresult\n\n val hash : nonce -> Nonce_hash.t\n\n val check_hash : nonce -> Nonce_hash.t -> bool\nend\n\nmodule Seed : sig\n type seed\n\n type error +=\n | Unknown of {oldest : Cycle.t; cycle : Cycle.t; latest : Cycle.t}\n\n val for_cycle : context -> Cycle.t -> seed tzresult Lwt.t\n\n val cycle_end :\n context -> Cycle.t -> (context * Nonce.unrevealed list) tzresult Lwt.t\n\n val seed_encoding : seed Data_encoding.t\nend\n\nmodule Big_map : sig\n module Id : sig\n type t\n\n val encoding : t Data_encoding.t\n\n val rpc_arg : t RPC_arg.arg\n\n (** In the protocol, to be used in parse_data only *)\n val parse_z : Z.t -> t\n\n (** In the protocol, to be used in unparse_data only *)\n val unparse_to_z : t -> Z.t\n end\n\n val fresh : temporary:bool -> context -> (context * Id.t) tzresult Lwt.t\n\n val mem :\n context -> Id.t -> Script_expr_hash.t -> (context * bool) tzresult Lwt.t\n\n val get_opt :\n context ->\n Id.t ->\n Script_expr_hash.t ->\n (context * Script.expr option) tzresult Lwt.t\n\n val exists :\n context ->\n Id.t ->\n (context * (Script.expr * Script.expr) option) tzresult Lwt.t\n\n type update = {\n key : Script_repr.expr;\n key_hash : Script_expr_hash.t;\n value : Script_repr.expr option;\n }\n\n type updates = update list\n\n type alloc = {key_type : Script_repr.expr; value_type : Script_repr.expr}\nend\n\nmodule Sapling : sig\n module Id : sig\n type t\n\n val encoding : t Data_encoding.t\n\n val rpc_arg : t RPC_arg.arg\n\n val parse_z : Z.t -> t (* To be used in parse_data only *)\n\n val unparse_to_z : t -> Z.t (* To be used in unparse_data only *)\n end\n\n val fresh : temporary:bool -> context -> (context * Id.t) tzresult Lwt.t\n\n type diff = private {\n commitments_and_ciphertexts :\n (Sapling.Commitment.t * Sapling.Ciphertext.t) list;\n nullifiers : Sapling.Nullifier.t list;\n }\n\n val diff_encoding : diff Data_encoding.t\n\n module Memo_size : sig\n type t\n\n val encoding : t Data_encoding.t\n\n val equal : t -> t -> bool\n\n val parse_z : Z.t -> (t, string) result\n\n val unparse_to_z : t -> Z.t\n end\n\n type state = private {id : Id.t option; diff : diff; memo_size : Memo_size.t}\n\n (**\n Returns a [state] with fields filled accordingly.\n [id] should only be used by [extract_lazy_storage_updates].\n *)\n val empty_state : ?id:Id.t -> memo_size:Memo_size.t -> unit -> state\n\n type transaction = Sapling.UTXO.transaction\n\n val transaction_encoding : transaction Data_encoding.t\n\n val transaction_get_memo_size : transaction -> Memo_size.t option\n\n (**\n Tries to fetch a state from the storage.\n *)\n val state_from_id : context -> Id.t -> (state * context) tzresult Lwt.t\n\n val rpc_arg : Id.t RPC_arg.t\n\n type root = Sapling.Hash.t\n\n val root_encoding : root Data_encoding.t\n\n (* Function exposed as RPC. Returns the root and a diff of a state starting\n from an optional offset which is zero by default. *)\n val get_diff :\n context ->\n Id.t ->\n ?offset_commitment:Int64.t ->\n ?offset_nullifier:Int64.t ->\n unit ->\n (root * diff) tzresult Lwt.t\n\n val verify_update :\n context ->\n state ->\n transaction ->\n string ->\n (context * (Int64.t * state) option) tzresult Lwt.t\n\n type alloc = {memo_size : Memo_size.t}\n\n type updates = diff\nend\n\nmodule Lazy_storage : sig\n module Kind : sig\n type ('id, 'alloc, 'updates) t =\n | Big_map : (Big_map.Id.t, Big_map.alloc, Big_map.updates) t\n | Sapling_state : (Sapling.Id.t, Sapling.alloc, Sapling.updates) t\n end\n\n module IdSet : sig\n type t\n\n type 'acc fold_f = {\n f : 'i 'a 'u. ('i, 'a, 'u) Kind.t -> 'i -> 'acc -> 'acc;\n }\n\n val empty : t\n\n val mem : ('i, 'a, 'u) Kind.t -> 'i -> t -> bool\n\n val add : ('i, 'a, 'u) Kind.t -> 'i -> t -> t\n\n val diff : t -> t -> t\n\n val fold : ('i, 'a, 'u) Kind.t -> ('i -> 'acc -> 'acc) -> t -> 'acc -> 'acc\n\n val fold_all : 'acc fold_f -> t -> 'acc -> 'acc\n end\n\n type ('id, 'alloc) init = Existing | Copy of {src : 'id} | Alloc of 'alloc\n\n type ('id, 'alloc, 'updates) diff =\n | Remove\n | Update of {init : ('id, 'alloc) init; updates : 'updates}\n\n type diffs_item\n\n val make : ('i, 'a, 'u) Kind.t -> 'i -> ('i, 'a, 'u) diff -> diffs_item\n\n type diffs = diffs_item list\n\n val encoding : diffs Data_encoding.t\n\n val legacy_big_map_diff_encoding : diffs Data_encoding.t\n\n val cleanup_temporaries : context -> context Lwt.t\n\n val apply : t -> diffs -> (t * Z.t) tzresult Lwt.t\nend\n\nmodule Contract : sig\n include BASIC_DATA\n\n type contract = t\n\n val rpc_arg : contract RPC_arg.arg\n\n val to_b58check : contract -> string\n\n val of_b58check : string -> contract tzresult\n\n val implicit_contract : public_key_hash -> contract\n\n val is_implicit : contract -> public_key_hash option\n\n val exists : context -> contract -> bool tzresult Lwt.t\n\n val must_exist : context -> contract -> unit tzresult Lwt.t\n\n val allocated : context -> contract -> bool tzresult Lwt.t\n\n val must_be_allocated : context -> contract -> unit tzresult Lwt.t\n\n val list : context -> contract list Lwt.t\n\n val get_manager_key : context -> public_key_hash -> public_key tzresult Lwt.t\n\n val is_manager_key_revealed :\n context -> public_key_hash -> bool tzresult Lwt.t\n\n val reveal_manager_key :\n context -> public_key_hash -> public_key -> context tzresult Lwt.t\n\n val get_script_code :\n context -> contract -> (context * Script.lazy_expr option) tzresult Lwt.t\n\n val get_script :\n context -> contract -> (context * Script.t option) tzresult Lwt.t\n\n val get_storage :\n context -> contract -> (context * Script.expr option) tzresult Lwt.t\n\n val get_counter : context -> public_key_hash -> Z.t tzresult Lwt.t\n\n val get_balance : context -> contract -> Tez.t tzresult Lwt.t\n\n val get_balance_carbonated :\n context -> contract -> (context * Tez.t) tzresult Lwt.t\n\n val init_origination_nonce : context -> Operation_hash.t -> context\n\n val unset_origination_nonce : context -> context\n\n val fresh_contract_from_current_nonce : context -> (context * t) tzresult\n\n val originated_from_current_nonce :\n since:context -> until:context -> contract list tzresult Lwt.t\n\n module Legacy_big_map_diff : sig\n type item = private\n | Update of {\n big_map : Z.t;\n diff_key : Script.expr;\n diff_key_hash : Script_expr_hash.t;\n diff_value : Script.expr option;\n }\n | Clear of Z.t\n | Copy of {src : Z.t; dst : Z.t}\n | Alloc of {\n big_map : Z.t;\n key_type : Script.expr;\n value_type : Script.expr;\n }\n\n type t = private item list\n\n val of_lazy_storage_diff : Lazy_storage.diffs -> t\n end\n\n val originate :\n context ->\n contract ->\n balance:Tez.t ->\n script:Script.t * Lazy_storage.diffs option ->\n delegate:public_key_hash option ->\n context tzresult Lwt.t\n\n type error += Balance_too_low of contract * Tez.t * Tez.t\n\n val spend : context -> contract -> Tez.t -> context tzresult Lwt.t\n\n val credit : context -> contract -> Tez.t -> context tzresult Lwt.t\n\n val update_script_storage :\n context ->\n contract ->\n Script.expr ->\n Lazy_storage.diffs option ->\n context tzresult Lwt.t\n\n val used_storage_space : context -> t -> Z.t tzresult Lwt.t\n\n val increment_counter : context -> public_key_hash -> context tzresult Lwt.t\n\n val check_counter_increment :\n context -> public_key_hash -> Z.t -> unit tzresult Lwt.t\n\n (**/**)\n\n (* Only for testing *)\n type origination_nonce\n\n val initial_origination_nonce : Operation_hash.t -> origination_nonce\n\n val originated_contract : origination_nonce -> contract\nend\n\nmodule Delegate : sig\n type balance =\n | Contract of Contract.t\n | Rewards of Signature.Public_key_hash.t * Cycle.t\n | Fees of Signature.Public_key_hash.t * Cycle.t\n | Deposits of Signature.Public_key_hash.t * Cycle.t\n\n type balance_update = Debited of Tez.t | Credited of Tez.t\n\n type balance_updates = (balance * balance_update) list\n\n val balance_updates_encoding : balance_updates Data_encoding.t\n\n val cleanup_balance_updates : balance_updates -> balance_updates\n\n val get : context -> Contract.t -> public_key_hash option tzresult Lwt.t\n\n val set :\n context -> Contract.t -> public_key_hash option -> context tzresult Lwt.t\n\n val fold :\n context -> init:'a -> f:(public_key_hash -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n val list : context -> public_key_hash list Lwt.t\n\n val freeze_deposit :\n context -> public_key_hash -> Tez.t -> context tzresult Lwt.t\n\n val freeze_rewards :\n context -> public_key_hash -> Tez.t -> context tzresult Lwt.t\n\n val freeze_fees :\n context -> public_key_hash -> Tez.t -> context tzresult Lwt.t\n\n val cycle_end :\n context ->\n Cycle.t ->\n Nonce.unrevealed list ->\n (context * balance_updates * Signature.Public_key_hash.t list) tzresult\n Lwt.t\n\n type frozen_balance = {deposit : Tez.t; fees : Tez.t; rewards : Tez.t}\n\n val punish :\n context ->\n public_key_hash ->\n Cycle.t ->\n (context * frozen_balance) tzresult Lwt.t\n\n val full_balance : context -> public_key_hash -> Tez.t tzresult Lwt.t\n\n val has_frozen_balance :\n context -> public_key_hash -> Cycle.t -> bool tzresult Lwt.t\n\n val frozen_balance : context -> public_key_hash -> Tez.t tzresult Lwt.t\n\n val frozen_balance_encoding : frozen_balance Data_encoding.t\n\n val frozen_balance_by_cycle_encoding :\n frozen_balance Cycle.Map.t Data_encoding.t\n\n val frozen_balance_by_cycle :\n context -> Signature.Public_key_hash.t -> frozen_balance Cycle.Map.t Lwt.t\n\n val staking_balance :\n context -> Signature.Public_key_hash.t -> Tez.t tzresult Lwt.t\n\n val delegated_contracts :\n context -> Signature.Public_key_hash.t -> Contract_repr.t list Lwt.t\n\n val delegated_balance :\n context -> Signature.Public_key_hash.t -> Tez.t tzresult Lwt.t\n\n val deactivated :\n context -> Signature.Public_key_hash.t -> bool tzresult Lwt.t\n\n val grace_period :\n context -> Signature.Public_key_hash.t -> Cycle.t tzresult Lwt.t\nend\n\nmodule Voting_period : sig\n type kind = Proposal | Testing_vote | Testing | Promotion_vote | Adoption\n\n val kind_encoding : kind Data_encoding.encoding\n\n val pp_kind : Format.formatter -> kind -> unit\n\n (* This type should be abstract *)\n type voting_period = private {\n index : int32;\n kind : kind;\n start_position : int32;\n }\n\n type t = voting_period\n\n include BASIC_DATA with type t := t\n\n val encoding : voting_period Data_encoding.t\n\n val pp : Format.formatter -> voting_period -> unit\n\n val reset : context -> context tzresult Lwt.t\n\n val succ : context -> context tzresult Lwt.t\n\n val get_current : context -> voting_period tzresult Lwt.t\n\n val get_current_kind : context -> kind tzresult Lwt.t\n\n val is_last_block : context -> bool tzresult Lwt.t\n\n type info = {voting_period : t; position : int32; remaining : int32}\n\n val info_encoding : info Data_encoding.t\n\n val pp_info : Format.formatter -> info -> unit\n\n val get_current_info : context -> info tzresult Lwt.t\n\n val get_rpc_fixed_current_info : context -> info tzresult Lwt.t\n\n val get_rpc_fixed_succ_info : context -> info tzresult Lwt.t\nend\n\nmodule Vote : sig\n type proposal = Protocol_hash.t\n\n val record_proposal :\n context -> Protocol_hash.t -> public_key_hash -> context tzresult Lwt.t\n\n val get_proposals : context -> int32 Protocol_hash.Map.t tzresult Lwt.t\n\n val clear_proposals : context -> context Lwt.t\n\n val recorded_proposal_count_for_delegate :\n context -> public_key_hash -> int tzresult Lwt.t\n\n val listings_encoding :\n (Signature.Public_key_hash.t * int32) list Data_encoding.t\n\n val update_listings : context -> context tzresult Lwt.t\n\n val listing_size : context -> int32 tzresult Lwt.t\n\n val in_listings : context -> public_key_hash -> bool Lwt.t\n\n val get_listings : context -> (public_key_hash * int32) list Lwt.t\n\n type ballot = Yay | Nay | Pass\n\n val get_voting_power_free :\n context -> Signature.Public_key_hash.t -> int32 tzresult Lwt.t\n\n val get_voting_power :\n context -> Signature.Public_key_hash.t -> (context * int32) tzresult Lwt.t\n\n val get_total_voting_power_free : context -> int32 tzresult Lwt.t\n\n val get_total_voting_power : context -> (context * int32) tzresult Lwt.t\n\n val ballot_encoding : ballot Data_encoding.t\n\n type ballots = {yay : int32; nay : int32; pass : int32}\n\n val ballots_encoding : ballots Data_encoding.t\n\n val has_recorded_ballot : context -> public_key_hash -> bool Lwt.t\n\n val record_ballot :\n context -> public_key_hash -> ballot -> context tzresult Lwt.t\n\n val get_ballots : context -> ballots tzresult Lwt.t\n\n val get_ballot_list :\n context -> (Signature.Public_key_hash.t * ballot) list Lwt.t\n\n val clear_ballots : context -> context Lwt.t\n\n val get_current_quorum : context -> int32 tzresult Lwt.t\n\n val get_participation_ema : context -> int32 tzresult Lwt.t\n\n val set_participation_ema : context -> int32 -> context tzresult Lwt.t\n\n val get_current_proposal : context -> proposal tzresult Lwt.t\n\n val init_current_proposal : context -> proposal -> context tzresult Lwt.t\n\n val clear_current_proposal : context -> context tzresult Lwt.t\nend\n\nmodule Block_header : sig\n type t = {shell : Block_header.shell_header; protocol_data : protocol_data}\n\n and protocol_data = {contents : contents; signature : Signature.t}\n\n and contents = {\n priority : int;\n seed_nonce_hash : Nonce_hash.t option;\n proof_of_work_nonce : bytes;\n }\n\n type block_header = t\n\n type raw = Block_header.t\n\n type shell_header = Block_header.shell_header\n\n val raw : block_header -> raw\n\n val hash : block_header -> Block_hash.t\n\n val hash_raw : raw -> Block_hash.t\n\n val encoding : block_header Data_encoding.encoding\n\n val raw_encoding : raw Data_encoding.t\n\n val contents_encoding : contents Data_encoding.t\n\n val unsigned_encoding : (shell_header * contents) Data_encoding.t\n\n val protocol_data_encoding : protocol_data Data_encoding.encoding\n\n val shell_header_encoding : shell_header Data_encoding.encoding\n\n (** The maximum size of block headers in bytes *)\n val max_header_length : int\nend\n\nmodule Kind : sig\n type seed_nonce_revelation = Seed_nonce_revelation_kind\n\n type double_endorsement_evidence = Double_endorsement_evidence_kind\n\n type double_baking_evidence = Double_baking_evidence_kind\n\n type activate_account = Activate_account_kind\n\n type endorsement = Endorsement_kind\n\n type proposals = Proposals_kind\n\n type ballot = Ballot_kind\n\n type reveal = Reveal_kind\n\n type transaction = Transaction_kind\n\n type origination = Origination_kind\n\n type delegation = Delegation_kind\n\n type 'a manager =\n | Reveal_manager_kind : reveal manager\n | Transaction_manager_kind : transaction manager\n | Origination_manager_kind : origination manager\n | Delegation_manager_kind : delegation manager\nend\n\ntype 'kind operation = {\n shell : Operation.shell_header;\n protocol_data : 'kind protocol_data;\n}\n\nand 'kind protocol_data = {\n contents : 'kind contents_list;\n signature : Signature.t option;\n}\n\nand _ contents_list =\n | Single : 'kind contents -> 'kind contents_list\n | Cons :\n 'kind Kind.manager contents * 'rest Kind.manager contents_list\n -> ('kind * 'rest) Kind.manager contents_list\n\nand _ contents =\n | Endorsement : {level : Raw_level.t} -> Kind.endorsement contents\n | Seed_nonce_revelation : {\n level : Raw_level.t;\n nonce : Nonce.t;\n }\n -> Kind.seed_nonce_revelation contents\n | Double_endorsement_evidence : {\n op1 : Kind.endorsement operation;\n op2 : Kind.endorsement operation;\n }\n -> Kind.double_endorsement_evidence contents\n | Double_baking_evidence : {\n bh1 : Block_header.t;\n bh2 : Block_header.t;\n }\n -> Kind.double_baking_evidence contents\n | Activate_account : {\n id : Ed25519.Public_key_hash.t;\n activation_code : Blinded_public_key_hash.activation_code;\n }\n -> Kind.activate_account contents\n | Proposals : {\n source : Signature.Public_key_hash.t;\n period : int32;\n proposals : Protocol_hash.t list;\n }\n -> Kind.proposals contents\n | Ballot : {\n source : Signature.Public_key_hash.t;\n period : int32;\n proposal : Protocol_hash.t;\n ballot : Vote.ballot;\n }\n -> Kind.ballot contents\n | Manager_operation : {\n source : Signature.Public_key_hash.t;\n fee : Tez.tez;\n counter : counter;\n operation : 'kind manager_operation;\n gas_limit : Gas.Arith.integral;\n storage_limit : Z.t;\n }\n -> 'kind Kind.manager contents\n\nand _ manager_operation =\n | Reveal : Signature.Public_key.t -> Kind.reveal manager_operation\n | Transaction : {\n amount : Tez.tez;\n parameters : Script.lazy_expr;\n entrypoint : string;\n destination : Contract.contract;\n }\n -> Kind.transaction manager_operation\n | Origination : {\n delegate : Signature.Public_key_hash.t option;\n script : Script.t;\n credit : Tez.tez;\n preorigination : Contract.t option;\n }\n -> Kind.origination manager_operation\n | Delegation :\n Signature.Public_key_hash.t option\n -> Kind.delegation manager_operation\n\nand counter = Z.t\n\ntype 'kind internal_operation = {\n source : Contract.contract;\n operation : 'kind manager_operation;\n nonce : int;\n}\n\ntype packed_manager_operation =\n | Manager : 'kind manager_operation -> packed_manager_operation\n\ntype packed_contents = Contents : 'kind contents -> packed_contents\n\ntype packed_contents_list =\n | Contents_list : 'kind contents_list -> packed_contents_list\n\ntype packed_protocol_data =\n | Operation_data : 'kind protocol_data -> packed_protocol_data\n\ntype packed_operation = {\n shell : Operation.shell_header;\n protocol_data : packed_protocol_data;\n}\n\ntype packed_internal_operation =\n | Internal_operation : 'kind internal_operation -> packed_internal_operation\n\nval manager_kind : 'kind manager_operation -> 'kind Kind.manager\n\nmodule Fees : sig\n val origination_burn : context -> (context * Tez.t) tzresult\n\n val record_paid_storage_space :\n context -> Contract.t -> (context * Z.t * Z.t * Tez.t) tzresult Lwt.t\n\n val start_counting_storage_fees : context -> context\n\n val burn_storage_fees :\n context -> storage_limit:Z.t -> payer:Contract.t -> context tzresult Lwt.t\n\n type error += Cannot_pay_storage_fee (* `Temporary *)\n\n type error += Operation_quota_exceeded (* `Temporary *)\n\n type error += Storage_limit_too_high (* `Permanent *)\n\n val check_storage_limit : context -> storage_limit:Z.t -> unit tzresult\nend\n\nmodule Operation : sig\n type nonrec 'kind contents = 'kind contents\n\n type nonrec packed_contents = packed_contents\n\n val contents_encoding : packed_contents Data_encoding.t\n\n type nonrec 'kind protocol_data = 'kind protocol_data\n\n type nonrec packed_protocol_data = packed_protocol_data\n\n val protocol_data_encoding : packed_protocol_data Data_encoding.t\n\n val unsigned_encoding :\n (Operation.shell_header * packed_contents_list) Data_encoding.t\n\n type raw = Operation.t = {shell : Operation.shell_header; proto : bytes}\n\n val raw_encoding : raw Data_encoding.t\n\n val contents_list_encoding : packed_contents_list Data_encoding.t\n\n type 'kind t = 'kind operation = {\n shell : Operation.shell_header;\n protocol_data : 'kind protocol_data;\n }\n\n type nonrec packed = packed_operation\n\n val encoding : packed Data_encoding.t\n\n val raw : _ operation -> raw\n\n val hash : _ operation -> Operation_hash.t\n\n val hash_raw : raw -> Operation_hash.t\n\n val hash_packed : packed_operation -> Operation_hash.t\n\n val acceptable_passes : packed_operation -> int list\n\n type error += Missing_signature (* `Permanent *)\n\n type error += Invalid_signature (* `Permanent *)\n\n val check_signature :\n public_key -> Chain_id.t -> _ operation -> unit tzresult\n\n val internal_operation_encoding : packed_internal_operation Data_encoding.t\n\n val pack : 'kind operation -> packed_operation\n\n type ('a, 'b) eq = Eq : ('a, 'a) eq\n\n val equal : 'a operation -> 'b operation -> ('a, 'b) eq option\n\n module Encoding : sig\n type 'b case =\n | Case : {\n tag : int;\n name : string;\n encoding : 'a Data_encoding.t;\n select : packed_contents -> 'b contents option;\n proj : 'b contents -> 'a;\n inj : 'a -> 'b contents;\n }\n -> 'b case\n\n val endorsement_case : Kind.endorsement case\n\n val seed_nonce_revelation_case : Kind.seed_nonce_revelation case\n\n val double_endorsement_evidence_case :\n Kind.double_endorsement_evidence case\n\n val double_baking_evidence_case : Kind.double_baking_evidence case\n\n val activate_account_case : Kind.activate_account case\n\n val proposals_case : Kind.proposals case\n\n val ballot_case : Kind.ballot case\n\n val reveal_case : Kind.reveal Kind.manager case\n\n val transaction_case : Kind.transaction Kind.manager case\n\n val origination_case : Kind.origination Kind.manager case\n\n val delegation_case : Kind.delegation Kind.manager case\n\n module Manager_operations : sig\n type 'b case =\n | MCase : {\n tag : int;\n name : string;\n encoding : 'a Data_encoding.t;\n select :\n packed_manager_operation -> 'kind manager_operation option;\n proj : 'kind manager_operation -> 'a;\n inj : 'a -> 'kind manager_operation;\n }\n -> 'kind case\n\n val reveal_case : Kind.reveal case\n\n val transaction_case : Kind.transaction case\n\n val origination_case : Kind.origination case\n\n val delegation_case : Kind.delegation case\n end\n end\n\n val of_list : packed_contents list -> packed_contents_list\n\n val to_list : packed_contents_list -> packed_contents list\nend\n\nmodule Roll : sig\n type t = private int32\n\n type roll = t\n\n val encoding : roll Data_encoding.t\n\n val snapshot_rolls : context -> context tzresult Lwt.t\n\n val cycle_end : context -> Cycle.t -> context tzresult Lwt.t\n\n val baking_rights_owner :\n context -> Level.t -> priority:int -> public_key tzresult Lwt.t\n\n val endorsement_rights_owner :\n context -> Level.t -> slot:int -> public_key tzresult Lwt.t\n\n val delegate_pubkey : context -> public_key_hash -> public_key tzresult Lwt.t\n\n val get_rolls :\n context -> Signature.Public_key_hash.t -> roll list tzresult Lwt.t\n\n val get_change :\n context -> Signature.Public_key_hash.t -> Tez.t tzresult Lwt.t\nend\n\nmodule Commitment : sig\n type t = {\n blinded_public_key_hash : Blinded_public_key_hash.t;\n amount : Tez.tez;\n }\n\n val get_opt :\n context -> Blinded_public_key_hash.t -> Tez.t option tzresult Lwt.t\n\n val delete : context -> Blinded_public_key_hash.t -> context tzresult Lwt.t\nend\n\nmodule Bootstrap : sig\n val cycle_end : context -> Cycle.t -> context tzresult Lwt.t\nend\n\nmodule Global : sig\n val get_block_priority : context -> int tzresult Lwt.t\n\n val set_block_priority : context -> int -> context tzresult Lwt.t\nend\n\nval prepare_first_block :\n Context.t ->\n typecheck:(context ->\n Script.t ->\n ((Script.t * Lazy_storage.diffs option) * context) tzresult Lwt.t) ->\n level:Int32.t ->\n timestamp:Time.t ->\n fitness:Fitness.t ->\n context tzresult Lwt.t\n\nval prepare :\n Context.t ->\n level:Int32.t ->\n predecessor_timestamp:Time.t ->\n timestamp:Time.t ->\n fitness:Fitness.t ->\n context tzresult Lwt.t\n\nval finalize : ?commit_message:string -> context -> Updater.validation_result\n\nval activate : context -> Protocol_hash.t -> context Lwt.t\n\nval fork_test_chain : context -> Protocol_hash.t -> Time.t -> context Lwt.t\n\nval record_endorsement : context -> Signature.Public_key_hash.t -> context\n\nval allowed_endorsements :\n context ->\n (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t\n\nval init_endorsements :\n context ->\n (Signature.Public_key.t * int list * bool) Signature.Public_key_hash.Map.t ->\n context\n\nval included_endorsements : context -> int\n\nval reset_internal_nonce : context -> context\n\nval fresh_internal_nonce : context -> (context * int) tzresult\n\nval record_internal_nonce : context -> int -> context\n\nval internal_nonce_already_recorded : context -> int -> bool\n\nval add_fees : context -> Tez.t -> context tzresult\n\nval add_rewards : context -> Tez.t -> context tzresult\n\nval add_deposit :\n context -> Signature.Public_key_hash.t -> Tez.t -> context tzresult\n\nval get_fees : context -> Tez.t\n\nval get_rewards : context -> Tez.t\n\nval get_deposits : context -> Tez.t Signature.Public_key_hash.Map.t\n\nval description : context Storage_description.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\ntype t = Raw_context.t\n\ntype context = t\n\nmodule type BASIC_DATA = sig\n type t\n\n include Compare.S with type t := t\n\n val encoding : t Data_encoding.t\n\n val pp : Format.formatter -> t -> unit\nend\n\nmodule Tez = Tez_repr\nmodule Period = Period_repr\n\nmodule Timestamp = struct\n include Time_repr\n\n let current = Raw_context.current_timestamp\nend\n\ninclude Operation_repr\n\nmodule Operation = struct\n type 'kind t = 'kind operation = {\n shell : Operation.shell_header;\n protocol_data : 'kind protocol_data;\n }\n\n type packed = packed_operation\n\n let unsigned_encoding = unsigned_operation_encoding\n\n include Operation_repr\nend\n\nmodule Block_header = Block_header_repr\n\nmodule Vote = struct\n include Vote_repr\n include Vote_storage\nend\n\nmodule Raw_level = Raw_level_repr\nmodule Cycle = Cycle_repr\nmodule Script_int = Script_int_repr\n\nmodule Script_timestamp = struct\n include Script_timestamp_repr\n\n let now ctxt =\n let {Constants_repr.time_between_blocks; _} = Raw_context.constants ctxt in\n match time_between_blocks with\n | [] ->\n failwith\n \"Internal error: 'time_between_block' constants is an empty list.\"\n | first_delay :: _ ->\n let current_timestamp = Raw_context.predecessor_timestamp ctxt in\n Time.add current_timestamp (Period_repr.to_seconds first_delay)\n |> Timestamp.to_seconds |> of_int64\nend\n\nmodule Script = struct\n include Michelson_v1_primitives\n include Script_repr\n\n let force_decode_in_context ctxt lexpr =\n Script_repr.force_decode lexpr\n >>? fun (v, cost) ->\n Raw_context.consume_gas ctxt cost >|? fun ctxt -> (v, ctxt)\n\n let force_bytes_in_context ctxt lexpr =\n Script_repr.force_bytes lexpr\n >>? fun (b, cost) ->\n Raw_context.consume_gas ctxt cost >|? fun ctxt -> (b, ctxt)\nend\n\nmodule Fees = Fees_storage\n\ntype public_key = Signature.Public_key.t\n\ntype public_key_hash = Signature.Public_key_hash.t\n\ntype signature = Signature.t\n\nmodule Constants = struct\n include Constants_repr\n include Constants_storage\nend\n\nmodule Voting_period = struct\n include Voting_period_repr\n include Voting_period_storage\nend\n\nmodule Gas = struct\n include Gas_limit_repr\n\n type error += Gas_limit_too_high = Raw_context.Gas_limit_too_high\n\n let check_limit = Raw_context.check_gas_limit\n\n let set_limit = Raw_context.set_gas_limit\n\n let set_unlimited = Raw_context.set_gas_unlimited\n\n let consume = Raw_context.consume_gas\n\n let check_enough = Raw_context.check_enough_gas\n\n let level = Raw_context.gas_level\n\n let consumed = Raw_context.gas_consumed\n\n let block_level = Raw_context.block_gas_level\n\n (* Necessary to inject costs for Storage_costs into Gas.cost *)\n let cost_of_repr cost = cost\nend\n\nmodule Level = struct\n include Level_repr\n include Level_storage\nend\n\nmodule Lazy_storage = struct\n module Kind = Lazy_storage_kind\n module IdSet = Kind.IdSet\n include Lazy_storage_diff\n\n let legacy_big_map_diff_encoding =\n Data_encoding.conv\n Contract_storage.Legacy_big_map_diff.of_lazy_storage_diff\n Contract_storage.Legacy_big_map_diff.to_lazy_storage_diff\n Contract_storage.Legacy_big_map_diff.encoding\nend\n\nmodule Contract = struct\n include Contract_repr\n include Contract_storage\n\n let originate c contract ~balance ~script ~delegate =\n raw_originate c contract ~balance ~script ~delegate\n\n let init_origination_nonce = Raw_context.init_origination_nonce\n\n let unset_origination_nonce = Raw_context.unset_origination_nonce\nend\n\nmodule Big_map = struct\n include Lazy_storage_kind.Big_map\n\n let fresh ~temporary c = Lazy_storage.fresh Big_map ~temporary c\n\n let mem c m k = Storage.Big_map.Contents.mem (c, m) k\n\n let get_opt c m k = Storage.Big_map.Contents.get_option (c, m) k\n\n let exists c id =\n Raw_context.consume_gas c (Gas_limit_repr.read_bytes_cost Z.zero)\n >>?= fun c ->\n Storage.Big_map.Key_type.get_option c id\n >>=? fun kt ->\n match kt with\n | None ->\n return (c, None)\n | Some kt ->\n Storage.Big_map.Value_type.get c id >|=? fun kv -> (c, Some (kt, kv))\nend\n\nmodule Sapling = struct\n include Lazy_storage_kind.Sapling_state\n include Sapling_repr\n include Sapling_storage\n include Sapling_validator\n\n let fresh ~temporary c = Lazy_storage.fresh Sapling_state ~temporary c\nend\n\nmodule Delegate = Delegate_storage\n\nmodule Roll = struct\n include Roll_repr\n include Roll_storage\nend\n\nmodule Nonce = Nonce_storage\n\nmodule Seed = struct\n include Seed_repr\n include Seed_storage\nend\n\nmodule Fitness = struct\n include Fitness_repr\n include Fitness\n\n type fitness = t\n\n include Fitness_storage\nend\n\nmodule Bootstrap = Bootstrap_storage\n\nmodule Commitment = struct\n include Commitment_repr\n include Commitment_storage\nend\n\nmodule Global = struct\n let get_block_priority = Storage.Block_priority.get\n\n let set_block_priority = Storage.Block_priority.set\nend\n\nlet prepare_first_block = Init_storage.prepare_first_block\n\nlet prepare = Init_storage.prepare\n\nlet finalize ?commit_message:message c =\n let fitness = Fitness.from_int64 (Fitness.current c) in\n let context = Raw_context.recover c in\n {\n Updater.context;\n fitness;\n message;\n max_operations_ttl = 60;\n last_allowed_fork_level =\n Raw_level.to_int32 @@ Level.last_allowed_fork_level c;\n }\n\nlet activate = Raw_context.activate\n\nlet fork_test_chain = Raw_context.fork_test_chain\n\nlet record_endorsement = Raw_context.record_endorsement\n\nlet allowed_endorsements = Raw_context.allowed_endorsements\n\nlet init_endorsements = Raw_context.init_endorsements\n\nlet included_endorsements = Raw_context.included_endorsements\n\nlet reset_internal_nonce = Raw_context.reset_internal_nonce\n\nlet fresh_internal_nonce = Raw_context.fresh_internal_nonce\n\nlet record_internal_nonce = Raw_context.record_internal_nonce\n\nlet internal_nonce_already_recorded =\n Raw_context.internal_nonce_already_recorded\n\nlet add_deposit = Raw_context.add_deposit\n\nlet add_fees = Raw_context.add_fees\n\nlet add_rewards = Raw_context.add_rewards\n\nlet get_deposits = Raw_context.get_deposits\n\nlet get_fees = Raw_context.get_fees\n\nlet get_rewards = Raw_context.get_rewards\n\nlet description = Raw_context.description\n" ;
} ;
{ name = "Script_typed_ir" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Script_int\n\n(* ---- Auxiliary types -----------------------------------------------------*)\n\ntype var_annot = Var_annot of string\n\ntype type_annot = Type_annot of string\n\ntype field_annot = Field_annot of string\n\ntype address = Contract.t * string\n\ntype ('a, 'b) pair = 'a * 'b\n\ntype ('a, 'b) union = L of 'a | R of 'b\n\ntype never = |\n\ntype _ comparable_ty =\n | Unit_key : type_annot option -> unit comparable_ty\n | Never_key : type_annot option -> never comparable_ty\n | Int_key : type_annot option -> z num comparable_ty\n | Nat_key : type_annot option -> n num comparable_ty\n | Signature_key : type_annot option -> signature comparable_ty\n | String_key : type_annot option -> string comparable_ty\n | Bytes_key : type_annot option -> Bytes.t comparable_ty\n | Mutez_key : type_annot option -> Tez.t comparable_ty\n | Bool_key : type_annot option -> bool comparable_ty\n | Key_hash_key : type_annot option -> public_key_hash comparable_ty\n | Key_key : type_annot option -> public_key comparable_ty\n | Timestamp_key : type_annot option -> Script_timestamp.t comparable_ty\n | Chain_id_key : type_annot option -> Chain_id.t comparable_ty\n | Address_key : type_annot option -> address comparable_ty\n | Pair_key :\n ('a comparable_ty * field_annot option)\n * ('b comparable_ty * field_annot option)\n * type_annot option\n -> ('a, 'b) pair comparable_ty\n | Union_key :\n ('a comparable_ty * field_annot option)\n * ('b comparable_ty * field_annot option)\n * type_annot option\n -> ('a, 'b) union comparable_ty\n | Option_key :\n 'v comparable_ty * type_annot option\n -> 'v option comparable_ty\n\nmodule type Boxed_set = sig\n type elt\n\n val elt_ty : elt comparable_ty\n\n module OPS : S.SET with type elt = elt\n\n val boxed : OPS.t\n\n val size : int\nend\n\ntype 'elt set = (module Boxed_set with type elt = 'elt)\n\nmodule type Boxed_map = sig\n type key\n\n type value\n\n val key_ty : key comparable_ty\n\n module OPS : S.MAP with type key = key\n\n val boxed : value OPS.t * int\nend\n\ntype ('key, 'value) map =\n (module Boxed_map with type key = 'key and type value = 'value)\n\ntype operation = packed_internal_operation * Lazy_storage.diffs option\n\ntype 'a ticket = {ticketer : address; contents : 'a; amount : n num}\n\ntype ('arg, 'storage) script = {\n code : (('arg, 'storage) pair, (operation boxed_list, 'storage) pair) lambda;\n arg_type : 'arg ty;\n storage : 'storage;\n storage_type : 'storage ty;\n root_name : field_annot option;\n}\n\nand end_of_stack = unit\n\nand ('arg, 'ret) lambda =\n | Lam :\n ('arg * end_of_stack, 'ret * end_of_stack) descr * Script.node\n -> ('arg, 'ret) lambda\n\nand 'arg typed_contract = 'arg ty * address\n\nand 'ty ty =\n | Unit_t : type_annot option -> unit ty\n | Int_t : type_annot option -> z num ty\n | Nat_t : type_annot option -> n num ty\n | Signature_t : type_annot option -> signature ty\n | String_t : type_annot option -> string ty\n | Bytes_t : type_annot option -> bytes ty\n | Mutez_t : type_annot option -> Tez.t ty\n | Key_hash_t : type_annot option -> public_key_hash ty\n | Key_t : type_annot option -> public_key ty\n | Timestamp_t : type_annot option -> Script_timestamp.t ty\n | Address_t : type_annot option -> address ty\n | Bool_t : type_annot option -> bool ty\n | Pair_t :\n ('a ty * field_annot option * var_annot option)\n * ('b ty * field_annot option * var_annot option)\n * type_annot option\n -> ('a, 'b) pair ty\n | Union_t :\n ('a ty * field_annot option)\n * ('b ty * field_annot option)\n * type_annot option\n -> ('a, 'b) union ty\n | Lambda_t : 'arg ty * 'ret ty * type_annot option -> ('arg, 'ret) lambda ty\n | Option_t : 'v ty * type_annot option -> 'v option ty\n | List_t : 'v ty * type_annot option -> 'v boxed_list ty\n | Set_t : 'v comparable_ty * type_annot option -> 'v set ty\n | Map_t : 'k comparable_ty * 'v ty * type_annot option -> ('k, 'v) map ty\n | Big_map_t :\n 'k comparable_ty * 'v ty * type_annot option\n -> ('k, 'v) big_map ty\n | Contract_t : 'arg ty * type_annot option -> 'arg typed_contract ty\n | Sapling_transaction_t :\n Sapling.Memo_size.t * type_annot option\n -> Sapling.transaction ty\n | Sapling_state_t :\n Sapling.Memo_size.t * type_annot option\n -> Sapling.state ty\n | Operation_t : type_annot option -> operation ty\n | Chain_id_t : type_annot option -> Chain_id.t ty\n | Never_t : type_annot option -> never ty\n | Bls12_381_g1_t : type_annot option -> Bls12_381.G1.t ty\n | Bls12_381_g2_t : type_annot option -> Bls12_381.G2.t ty\n | Bls12_381_fr_t : type_annot option -> Bls12_381.Fr.t ty\n | Ticket_t : 'a comparable_ty * type_annot option -> 'a ticket ty\n\nand 'ty stack_ty =\n | Item_t :\n 'ty ty * 'rest stack_ty * var_annot option\n -> ('ty * 'rest) stack_ty\n | Empty_t : end_of_stack stack_ty\n\nand ('key, 'value) big_map = {\n id : Big_map.Id.t option;\n diff : ('key, 'value option) map;\n key_type : 'key comparable_ty;\n value_type : 'value ty;\n}\n\nand 'elt boxed_list = {elements : 'elt list; length : int}\n\n(* ---- Instructions --------------------------------------------------------*)\n\n(* The low-level, typed instructions, as a GADT whose parameters\n encode the typing rules.\n\n The left parameter is the typed shape of the stack before the\n instruction, the right one the shape after. Any program whose\n construction is accepted by OCaml's type-checker is guaranteed to\n be type-safe. Overloadings of the concrete syntax are already\n resolved in this representation, either by using different\n constructors or type witness parameters.\n\n When adding a new instruction, please check whether it is duplicating a data\n (rule of thumb: the type variable appears twice in the after stack, beware\n it might be hidden in a witness).\n If it is, please protect it with [check_dupable_ty].\n*)\nand ('bef, 'aft) instr =\n (* stack ops *)\n | Drop : (_ * 'rest, 'rest) instr\n | Dup : ('top * 'rest, 'top * ('top * 'rest)) instr\n | Swap : ('tip * ('top * 'rest), 'top * ('tip * 'rest)) instr\n | Const : 'ty -> ('rest, 'ty * 'rest) instr\n (* pairs *)\n | Cons_pair : ('car * ('cdr * 'rest), ('car, 'cdr) pair * 'rest) instr\n | Car : (('car, _) pair * 'rest, 'car * 'rest) instr\n | Cdr : ((_, 'cdr) pair * 'rest, 'cdr * 'rest) instr\n | Unpair : (('car, 'cdr) pair * 'rest, 'car * ('cdr * 'rest)) instr\n (* options *)\n | Cons_some : ('v * 'rest, 'v option * 'rest) instr\n | Cons_none : 'a ty -> ('rest, 'a option * 'rest) instr\n | If_none :\n ('bef, 'aft) descr * ('a * 'bef, 'aft) descr\n -> ('a option * 'bef, 'aft) instr\n (* unions *)\n | Cons_left : ('l * 'rest, ('l, 'r) union * 'rest) instr\n | Cons_right : ('r * 'rest, ('l, 'r) union * 'rest) instr\n | If_left :\n ('l * 'bef, 'aft) descr * ('r * 'bef, 'aft) descr\n -> (('l, 'r) union * 'bef, 'aft) instr\n (* lists *)\n | Cons_list : ('a * ('a boxed_list * 'rest), 'a boxed_list * 'rest) instr\n | Nil : ('rest, 'a boxed_list * 'rest) instr\n | If_cons :\n ('a * ('a boxed_list * 'bef), 'aft) descr * ('bef, 'aft) descr\n -> ('a boxed_list * 'bef, 'aft) instr\n | List_map :\n ('a * 'rest, 'b * 'rest) descr\n -> ('a boxed_list * 'rest, 'b boxed_list * 'rest) instr\n | List_iter :\n ('a * 'rest, 'rest) descr\n -> ('a boxed_list * 'rest, 'rest) instr\n | List_size : ('a boxed_list * 'rest, n num * 'rest) instr\n (* sets *)\n | Empty_set : 'a comparable_ty -> ('rest, 'a set * 'rest) instr\n | Set_iter : ('a * 'rest, 'rest) descr -> ('a set * 'rest, 'rest) instr\n | Set_mem : ('elt * ('elt set * 'rest), bool * 'rest) instr\n | Set_update : ('elt * (bool * ('elt set * 'rest)), 'elt set * 'rest) instr\n | Set_size : ('a set * 'rest, n num * 'rest) instr\n (* maps *)\n | Empty_map : 'a comparable_ty * 'v ty -> ('rest, ('a, 'v) map * 'rest) instr\n | Map_map :\n (('a * 'v) * 'rest, 'r * 'rest) descr\n -> (('a, 'v) map * 'rest, ('a, 'r) map * 'rest) instr\n | Map_iter :\n (('a * 'v) * 'rest, 'rest) descr\n -> (('a, 'v) map * 'rest, 'rest) instr\n | Map_mem : ('a * (('a, 'v) map * 'rest), bool * 'rest) instr\n | Map_get : ('a * (('a, 'v) map * 'rest), 'v option * 'rest) instr\n | Map_update\n : ('a * ('v option * (('a, 'v) map * 'rest)), ('a, 'v) map * 'rest) instr\n | Map_get_and_update\n : ( 'a * ('v option * (('a, 'v) map * 'rest)),\n 'v option * (('a, 'v) map * 'rest) )\n instr\n | Map_size : (('a, 'b) map * 'rest, n num * 'rest) instr\n (* big maps *)\n | Empty_big_map :\n 'a comparable_ty * 'v ty\n -> ('rest, ('a, 'v) big_map * 'rest) instr\n | Big_map_mem : ('a * (('a, 'v) big_map * 'rest), bool * 'rest) instr\n | Big_map_get : ('a * (('a, 'v) big_map * 'rest), 'v option * 'rest) instr\n | Big_map_update\n : ( 'key * ('value option * (('key, 'value) big_map * 'rest)),\n ('key, 'value) big_map * 'rest )\n instr\n | Big_map_get_and_update\n : ( 'a * ('v option * (('a, 'v) big_map * 'rest)),\n 'v option * (('a, 'v) big_map * 'rest) )\n instr\n (* string operations *)\n | Concat_string : (string boxed_list * 'rest, string * 'rest) instr\n | Concat_string_pair : (string * (string * 'rest), string * 'rest) instr\n | Slice_string\n : (n num * (n num * (string * 'rest)), string option * 'rest) instr\n | String_size : (string * 'rest, n num * 'rest) instr\n (* bytes operations *)\n | Concat_bytes : (bytes boxed_list * 'rest, bytes * 'rest) instr\n | Concat_bytes_pair : (bytes * (bytes * 'rest), bytes * 'rest) instr\n | Slice_bytes\n : (n num * (n num * (bytes * 'rest)), bytes option * 'rest) instr\n | Bytes_size : (bytes * 'rest, n num * 'rest) instr\n (* timestamp operations *)\n | Add_seconds_to_timestamp\n : ( z num * (Script_timestamp.t * 'rest),\n Script_timestamp.t * 'rest )\n instr\n | Add_timestamp_to_seconds\n : ( Script_timestamp.t * (z num * 'rest),\n Script_timestamp.t * 'rest )\n instr\n | Sub_timestamp_seconds\n : ( Script_timestamp.t * (z num * 'rest),\n Script_timestamp.t * 'rest )\n instr\n | Diff_timestamps\n : ( Script_timestamp.t * (Script_timestamp.t * 'rest),\n z num * 'rest )\n instr\n (* tez operations *)\n | Add_tez : (Tez.t * (Tez.t * 'rest), Tez.t * 'rest) instr\n | Sub_tez : (Tez.t * (Tez.t * 'rest), Tez.t * 'rest) instr\n | Mul_teznat : (Tez.t * (n num * 'rest), Tez.t * 'rest) instr\n | Mul_nattez : (n num * (Tez.t * 'rest), Tez.t * 'rest) instr\n | Ediv_teznat\n : (Tez.t * (n num * 'rest), (Tez.t, Tez.t) pair option * 'rest) instr\n | Ediv_tez\n : (Tez.t * (Tez.t * 'rest), (n num, Tez.t) pair option * 'rest) instr\n (* boolean operations *)\n | Or : (bool * (bool * 'rest), bool * 'rest) instr\n | And : (bool * (bool * 'rest), bool * 'rest) instr\n | Xor : (bool * (bool * 'rest), bool * 'rest) instr\n | Not : (bool * 'rest, bool * 'rest) instr\n (* integer operations *)\n | Is_nat : (z num * 'rest, n num option * 'rest) instr\n | Neg_nat : (n num * 'rest, z num * 'rest) instr\n | Neg_int : (z num * 'rest, z num * 'rest) instr\n | Abs_int : (z num * 'rest, n num * 'rest) instr\n | Int_nat : (n num * 'rest, z num * 'rest) instr\n | Add_intint : (z num * (z num * 'rest), z num * 'rest) instr\n | Add_intnat : (z num * (n num * 'rest), z num * 'rest) instr\n | Add_natint : (n num * (z num * 'rest), z num * 'rest) instr\n | Add_natnat : (n num * (n num * 'rest), n num * 'rest) instr\n | Sub_int : ('s num * ('t num * 'rest), z num * 'rest) instr\n | Mul_intint : (z num * (z num * 'rest), z num * 'rest) instr\n | Mul_intnat : (z num * (n num * 'rest), z num * 'rest) instr\n | Mul_natint : (n num * (z num * 'rest), z num * 'rest) instr\n | Mul_natnat : (n num * (n num * 'rest), n num * 'rest) instr\n | Ediv_intint\n : (z num * (z num * 'rest), (z num, n num) pair option * 'rest) instr\n | Ediv_intnat\n : (z num * (n num * 'rest), (z num, n num) pair option * 'rest) instr\n | Ediv_natint\n : (n num * (z num * 'rest), (z num, n num) pair option * 'rest) instr\n | Ediv_natnat\n : (n num * (n num * 'rest), (n num, n num) pair option * 'rest) instr\n | Lsl_nat : (n num * (n num * 'rest), n num * 'rest) instr\n | Lsr_nat : (n num * (n num * 'rest), n num * 'rest) instr\n | Or_nat : (n num * (n num * 'rest), n num * 'rest) instr\n | And_nat : (n num * (n num * 'rest), n num * 'rest) instr\n | And_int_nat : (z num * (n num * 'rest), n num * 'rest) instr\n | Xor_nat : (n num * (n num * 'rest), n num * 'rest) instr\n | Not_nat : (n num * 'rest, z num * 'rest) instr\n | Not_int : (z num * 'rest, z num * 'rest) instr\n (* control *)\n | Seq : ('bef, 'trans) descr * ('trans, 'aft) descr -> ('bef, 'aft) instr\n | If : ('bef, 'aft) descr * ('bef, 'aft) descr -> (bool * 'bef, 'aft) instr\n | Loop : ('rest, bool * 'rest) descr -> (bool * 'rest, 'rest) instr\n | Loop_left :\n ('a * 'rest, ('a, 'b) union * 'rest) descr\n -> (('a, 'b) union * 'rest, 'b * 'rest) instr\n | Dip : ('bef, 'aft) descr -> ('top * 'bef, 'top * 'aft) instr\n | Exec : ('arg * (('arg, 'ret) lambda * 'rest), 'ret * 'rest) instr\n | Apply :\n 'arg ty\n -> ( 'arg * (('arg * 'remaining, 'ret) lambda * 'rest),\n ('remaining, 'ret) lambda * 'rest )\n instr\n | Lambda : ('arg, 'ret) lambda -> ('rest, ('arg, 'ret) lambda * 'rest) instr\n | Failwith : 'a ty -> ('a * 'rest, 'aft) instr\n | Nop : ('rest, 'rest) instr\n (* comparison *)\n | Compare : 'a comparable_ty -> ('a * ('a * 'rest), z num * 'rest) instr\n (* comparators *)\n | Eq : (z num * 'rest, bool * 'rest) instr\n | Neq : (z num * 'rest, bool * 'rest) instr\n | Lt : (z num * 'rest, bool * 'rest) instr\n | Gt : (z num * 'rest, bool * 'rest) instr\n | Le : (z num * 'rest, bool * 'rest) instr\n | Ge : (z num * 'rest, bool * 'rest) instr\n (* protocol *)\n | Address : (_ typed_contract * 'rest, address * 'rest) instr\n | Contract :\n 'p ty * string\n -> (address * 'rest, 'p typed_contract option * 'rest) instr\n | Transfer_tokens\n : ( 'arg * (Tez.t * ('arg typed_contract * 'rest)),\n operation * 'rest )\n instr\n | Implicit_account\n : (public_key_hash * 'rest, unit typed_contract * 'rest) instr\n | Create_contract :\n 'g ty\n * 'p ty\n * ('p * 'g, operation boxed_list * 'g) lambda\n * field_annot option\n -> ( public_key_hash option * (Tez.t * ('g * 'rest)),\n operation * (address * 'rest) )\n instr\n | Set_delegate : (public_key_hash option * 'rest, operation * 'rest) instr\n | Now : ('rest, Script_timestamp.t * 'rest) instr\n | Balance : ('rest, Tez.t * 'rest) instr\n | Level : ('rest, n num * 'rest) instr\n | Check_signature\n : (public_key * (signature * (bytes * 'rest)), bool * 'rest) instr\n | Hash_key : (public_key * 'rest, public_key_hash * 'rest) instr\n | Pack : 'a ty -> ('a * 'rest, bytes * 'rest) instr\n | Unpack : 'a ty -> (bytes * 'rest, 'a option * 'rest) instr\n | Blake2b : (bytes * 'rest, bytes * 'rest) instr\n | Sha256 : (bytes * 'rest, bytes * 'rest) instr\n | Sha512 : (bytes * 'rest, bytes * 'rest) instr\n | Source : ('rest, address * 'rest) instr\n | Sender : ('rest, address * 'rest) instr\n | Self : 'p ty * string -> ('rest, 'p typed_contract * 'rest) instr\n | Self_address : ('rest, address * 'rest) instr\n | Amount : ('rest, Tez.t * 'rest) instr\n | Sapling_empty_state : {\n memo_size : Sapling.Memo_size.t;\n }\n -> ('rest, Sapling.state * 'rest) instr\n | Sapling_verify_update\n : ( Sapling.transaction * (Sapling.state * 'rest),\n (z num, Sapling.state) pair option * 'rest )\n instr\n | Dig :\n int * ('x * 'rest, 'rest, 'bef, 'aft) stack_prefix_preservation_witness\n -> ('bef, 'x * 'aft) instr\n | Dug :\n int * ('rest, 'x * 'rest, 'bef, 'aft) stack_prefix_preservation_witness\n -> ('x * 'bef, 'aft) instr\n | Dipn :\n int\n * ('fbef, 'faft, 'bef, 'aft) stack_prefix_preservation_witness\n * ('fbef, 'faft) descr\n -> ('bef, 'aft) instr\n | Dropn :\n int * ('rest, 'rest, 'bef, _) stack_prefix_preservation_witness\n -> ('bef, 'rest) instr\n | ChainId : ('rest, Chain_id.t * 'rest) instr\n | Never : (never * 'rest, 'aft) instr\n | Voting_power : (public_key_hash * 'rest, n num * 'rest) instr\n | Total_voting_power : ('rest, n num * 'rest) instr\n | Keccak : (bytes * 'rest, bytes * 'rest) instr\n | Sha3 : (bytes * 'rest, bytes * 'rest) instr\n | Add_bls12_381_g1\n : ( Bls12_381.G1.t * (Bls12_381.G1.t * 'rest),\n Bls12_381.G1.t * 'rest )\n instr\n | Add_bls12_381_g2\n : ( Bls12_381.G2.t * (Bls12_381.G2.t * 'rest),\n Bls12_381.G2.t * 'rest )\n instr\n | Add_bls12_381_fr\n : ( Bls12_381.Fr.t * (Bls12_381.Fr.t * 'rest),\n Bls12_381.Fr.t * 'rest )\n instr\n | Mul_bls12_381_g1\n : ( Bls12_381.G1.t * (Bls12_381.Fr.t * 'rest),\n Bls12_381.G1.t * 'rest )\n instr\n | Mul_bls12_381_g2\n : ( Bls12_381.G2.t * (Bls12_381.Fr.t * 'rest),\n Bls12_381.G2.t * 'rest )\n instr\n | Mul_bls12_381_fr\n : ( Bls12_381.Fr.t * (Bls12_381.Fr.t * 'rest),\n Bls12_381.Fr.t * 'rest )\n instr\n | Mul_bls12_381_z_fr\n : (Bls12_381.Fr.t * (_ num * 'rest), Bls12_381.Fr.t * 'rest) instr\n | Mul_bls12_381_fr_z\n : (_ num * (Bls12_381.Fr.t * 'rest), Bls12_381.Fr.t * 'rest) instr\n | Int_bls12_381_fr : (Bls12_381.Fr.t * 'rest, z num * 'rest) instr\n | Neg_bls12_381_g1 : (Bls12_381.G1.t * 'rest, Bls12_381.G1.t * 'rest) instr\n | Neg_bls12_381_g2 : (Bls12_381.G2.t * 'rest, Bls12_381.G2.t * 'rest) instr\n | Neg_bls12_381_fr : (Bls12_381.Fr.t * 'rest, Bls12_381.Fr.t * 'rest) instr\n | Pairing_check_bls12_381\n : ( (Bls12_381.G1.t, Bls12_381.G2.t) pair boxed_list * 'rest,\n bool * 'rest )\n instr\n | Comb : int * ('before, 'after) comb_gadt_witness -> ('before, 'after) instr\n | Uncomb :\n int * ('before, 'after) uncomb_gadt_witness\n -> ('before, 'after) instr\n | Comb_get :\n int * ('before, 'after) comb_get_gadt_witness\n -> ('before * 'rest, 'after * 'rest) instr\n | Comb_set :\n int * ('value, 'before, 'after) comb_set_gadt_witness\n -> ('value * ('before * 'rest), 'after * 'rest) instr\n | Dup_n :\n int * ('before, 'after) dup_n_gadt_witness\n -> ('before, 'after * 'before) instr\n | Ticket : ('a * (n num * 'rest), 'a ticket * 'rest) instr\n | Read_ticket\n : ( 'a ticket * 'rest,\n (address * ('a * n num)) * ('a ticket * 'rest) )\n instr\n | Split_ticket\n : ( 'a ticket * ((n num * n num) * 'rest),\n ('a ticket * 'a ticket) option * 'rest )\n instr\n | Join_tickets :\n 'a comparable_ty\n -> (('a ticket * 'a ticket) * 'rest, 'a ticket option * 'rest) instr\n\nand ('before, 'after) comb_gadt_witness =\n | Comb_one : ('a * 'before, 'a * 'before) comb_gadt_witness\n | Comb_succ :\n ('before, 'b * 'after) comb_gadt_witness\n -> ('a * 'before, ('a * 'b) * 'after) comb_gadt_witness\n\nand ('before, 'after) uncomb_gadt_witness =\n | Uncomb_one : ('rest, 'rest) uncomb_gadt_witness\n | Uncomb_succ :\n ('b * 'before, 'after) uncomb_gadt_witness\n -> (('a * 'b) * 'before, 'a * 'after) uncomb_gadt_witness\n\nand ('before, 'after) comb_get_gadt_witness =\n | Comb_get_zero : ('b, 'b) comb_get_gadt_witness\n | Comb_get_one : ('a * 'b, 'a) comb_get_gadt_witness\n | Comb_get_plus_two :\n ('before, 'after) comb_get_gadt_witness\n -> ('a * 'before, 'after) comb_get_gadt_witness\n\nand ('value, 'before, 'after) comb_set_gadt_witness =\n | Comb_set_zero : ('value, _, 'value) comb_set_gadt_witness\n | Comb_set_one : ('value, 'hd * 'tl, 'value * 'tl) comb_set_gadt_witness\n | Comb_set_plus_two :\n ('value, 'before, 'after) comb_set_gadt_witness\n -> ('value, 'a * 'before, 'a * 'after) comb_set_gadt_witness\n\nand ('before, 'after) dup_n_gadt_witness =\n | Dup_n_zero : ('a * 'rest, 'a) dup_n_gadt_witness\n | Dup_n_succ :\n ('before, 'b) dup_n_gadt_witness\n -> ('a * 'before, 'b) dup_n_gadt_witness\n\n(* Type witness for operations that work deep in the stack ignoring\n (and preserving) a prefix.\n\n The two right parameters are the shape of the stack with the (same)\n prefix before and after the transformation. The two left\n parameters are the shape of the stack without the prefix before and\n after. The inductive definition makes it so by construction. *)\nand ('bef, 'aft, 'bef_suffix, 'aft_suffix) stack_prefix_preservation_witness =\n | Prefix :\n ('fbef, 'faft, 'bef, 'aft) stack_prefix_preservation_witness\n -> ('fbef, 'faft, 'x * 'bef, 'x * 'aft) stack_prefix_preservation_witness\n | Rest : ('bef, 'aft, 'bef, 'aft) stack_prefix_preservation_witness\n\nand ('bef, 'aft) descr = {\n loc : Script.location;\n bef : 'bef stack_ty;\n aft : 'aft stack_ty;\n instr : ('bef, 'aft) instr;\n}\n" ;
} ;
{ name = "Script_tc_errors" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Script\n\n(* ---- Error definitions ---------------------------------------------------*)\n\ntype kind = Int_kind | String_kind | Bytes_kind | Prim_kind | Seq_kind\n\ntype unparsed_stack_ty = (Script.expr * Script.annot) list\n\ntype type_map = (int * (unparsed_stack_ty * unparsed_stack_ty)) list\n\n(* Structure errors *)\ntype error += Invalid_arity of Script.location * prim * int * int\n\ntype error += Invalid_seq_arity of Script.location * int * int\n\ntype error +=\n | Invalid_namespace of\n Script.location\n * prim\n * Michelson_v1_primitives.namespace\n * Michelson_v1_primitives.namespace\n\ntype error += Invalid_primitive of Script.location * prim list * prim\n\ntype error += Invalid_kind of Script.location * kind list * kind\n\ntype error += Invalid_never_expr of Script.location\n\ntype error += Missing_field of prim\n\ntype error += Duplicate_field of Script.location * prim\n\ntype error += Unexpected_lazy_storage of Script.location\n\ntype error += Unexpected_operation of Script.location\n\ntype error += Unexpected_contract of Script.location\n\ntype error += No_such_entrypoint of string\n\ntype error += Duplicate_entrypoint of string\n\ntype error += Unreachable_entrypoint of prim list\n\ntype error += Entrypoint_name_too_long of string\n\n(* Instruction typing errors *)\ntype error += Fail_not_in_tail_position of Script.location\n\ntype error +=\n | Undefined_binop :\n Script.location * prim * Script.expr * Script.expr\n -> error\n\ntype error += Undefined_unop : Script.location * prim * Script.expr -> error\n\ntype error +=\n | Bad_return : Script.location * unparsed_stack_ty * Script.expr -> error\n\ntype error +=\n | Bad_stack : Script.location * prim * int * unparsed_stack_ty -> error\n\ntype error +=\n | Unmatched_branches :\n Script.location * unparsed_stack_ty * unparsed_stack_ty\n -> error\n\ntype error += Self_in_lambda of Script.location\n\ntype error += Bad_stack_length\n\ntype error += Bad_stack_item of int\n\ntype error += Inconsistent_annotations of string * string\n\ntype error +=\n | Inconsistent_type_annotations :\n Script.location * Script.expr * Script.expr\n -> error\n\ntype error += Inconsistent_field_annotations of string * string\n\ntype error += Unexpected_annotation of Script.location\n\ntype error += Ungrouped_annotations of Script.location\n\ntype error += Invalid_map_body : Script.location * unparsed_stack_ty -> error\n\ntype error += Invalid_map_block_fail of Script.location\n\ntype error +=\n | Invalid_iter_body :\n Script.location * unparsed_stack_ty * unparsed_stack_ty\n -> error\n\ntype error += Type_too_large : Script.location * int * int -> error\n\ntype error += Pair_bad_argument of Script.location\n\ntype error += Unpair_bad_argument of Script.location\n\ntype error += Dup_n_bad_argument of Script.location\n\ntype error += Dup_n_bad_stack of Script.location\n\n(* Value typing errors *)\ntype error +=\n | Invalid_constant : Script.location * Script.expr * Script.expr -> error\n\ntype error +=\n | Invalid_syntactic_constant :\n Script.location * Script.expr * string\n -> error\n\ntype error += Invalid_contract of Script.location * Contract.t\n\ntype error += Invalid_big_map of Script.location * Big_map.Id.t\n\ntype error +=\n | Comparable_type_expected : Script.location * Script.expr -> error\n\ntype error += Inconsistent_types : Script.expr * Script.expr -> error\n\ntype error +=\n | Inconsistent_memo_sizes :\n Sapling.Memo_size.t * Sapling.Memo_size.t\n -> error\n\ntype error += Unordered_map_keys of Script.location * Script.expr\n\ntype error += Unordered_set_values of Script.location * Script.expr\n\ntype error += Duplicate_map_keys of Script.location * Script.expr\n\ntype error += Duplicate_set_values of Script.location * Script.expr\n\n(* Toplevel errors *)\ntype error +=\n | Ill_typed_data : string option * Script.expr * Script.expr -> error\n\ntype error +=\n | Ill_formed_type of string option * Script.expr * Script.location\n\ntype error += Ill_typed_contract : Script.expr * type_map -> error\n\n(* Gas related errors *)\ntype error += Cannot_serialize_error\n\n(* Deprecation errors *)\ntype error += Deprecated_instruction of prim\n\n(* Stackoverflow errors *)\ntype error += Typechecking_too_many_recursive_calls\n\ntype error += Unparsing_too_many_recursive_calls\n\n(* Ticket errors *)\ntype error += Unexpected_ticket of Script.location\n\ntype error += Unexpected_forged_value of Script.location\n\ntype error += Non_dupable_type of Script.location * Script.expr\n\n(* Impossible errors *)\ntype error += Unparsing_invariant_violated\n" ;
} ;
{ name = "Michelson_v1_gas" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nmodule Cost_of : sig\n val manager_operation : Gas.cost\n\n module Interpreter : sig\n val drop : Gas.cost\n\n val dup : Gas.cost\n\n val swap : Gas.cost\n\n val push : Gas.cost\n\n val cons_some : Gas.cost\n\n val cons_none : Gas.cost\n\n val if_none : Gas.cost\n\n val cons_pair : Gas.cost\n\n val unpair : Gas.cost\n\n val car : Gas.cost\n\n val cdr : Gas.cost\n\n val cons_left : Gas.cost\n\n val cons_right : Gas.cost\n\n val if_left : Gas.cost\n\n val cons_list : Gas.cost\n\n val nil : Gas.cost\n\n val if_cons : Gas.cost\n\n val list_map : 'a Script_typed_ir.boxed_list -> Gas.cost\n\n val list_size : Gas.cost\n\n val list_iter : 'a Script_typed_ir.boxed_list -> Gas.cost\n\n val empty_set : Gas.cost\n\n val set_iter : 'a Script_typed_ir.set -> Gas.cost\n\n val set_mem : 'a -> 'a Script_typed_ir.set -> Gas.cost\n\n val set_update : 'a -> 'a Script_typed_ir.set -> Gas.cost\n\n val set_size : Gas.cost\n\n val empty_map : Gas.cost\n\n val map_map : ('k, 'v) Script_typed_ir.map -> Gas.cost\n\n val map_iter : ('k, 'v) Script_typed_ir.map -> Gas.cost\n\n val map_mem : 'k -> ('k, 'v) Script_typed_ir.map -> Gas.cost\n\n val map_get : 'k -> ('k, 'v) Script_typed_ir.map -> Gas.cost\n\n val map_update : 'k -> ('k, 'v) Script_typed_ir.map -> Gas.cost\n\n val map_get_and_update : 'k -> ('k, 'v) Script_typed_ir.map -> Gas.cost\n\n val map_size : Gas.cost\n\n val add_seconds_timestamp :\n 'a Script_int.num -> Script_timestamp.t -> Gas.cost\n\n val sub_seconds_timestamp :\n 'a Script_int.num -> Script_timestamp.t -> Gas.cost\n\n val diff_timestamps : Script_timestamp.t -> Script_timestamp.t -> Gas.cost\n\n val concat_string_pair : string -> string -> Gas.cost\n\n val slice_string : string -> Gas.cost\n\n val string_size : Gas.cost\n\n val concat_bytes_pair : bytes -> bytes -> Gas.cost\n\n val slice_bytes : bytes -> Gas.cost\n\n val bytes_size : Gas.cost\n\n val add_tez : Gas.cost\n\n val sub_tez : Gas.cost\n\n val mul_teznat : 'a Script_int.num -> Gas.cost\n\n val bool_or : Gas.cost\n\n val bool_and : Gas.cost\n\n val bool_xor : Gas.cost\n\n val bool_not : Gas.cost\n\n val is_nat : Gas.cost\n\n val abs_int : 'a Script_int.num -> Gas.cost\n\n val int_nat : Gas.cost\n\n val neg_int : 'a Script_int.num -> Gas.cost\n\n val neg_nat : 'a Script_int.num -> Gas.cost\n\n val add_bigint : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val sub_bigint : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val mul_bigint : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val ediv_teznat : 'a -> 'b Script_int.num -> Gas.cost\n\n val ediv_tez : Gas.cost\n\n val ediv_bigint : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val eq : Gas.cost\n\n val lsl_nat : 'a Script_int.num -> Gas.cost\n\n val lsr_nat : 'a Script_int.num -> Gas.cost\n\n val or_nat : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val and_nat : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val xor_nat : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n val not_int : 'a Script_int.num -> Gas.cost\n\n val not_nat : 'a Script_int.num -> Gas.cost\n\n val seq : Gas.cost\n\n val if_ : Gas.cost\n\n val loop : Gas.cost\n\n val loop_left : Gas.cost\n\n val dip : Gas.cost\n\n val check_signature : Signature.public_key -> bytes -> Gas.cost\n\n val blake2b : bytes -> Gas.cost\n\n val sha256 : bytes -> Gas.cost\n\n val sha512 : bytes -> Gas.cost\n\n val dign : int -> Gas.cost\n\n val dugn : int -> Gas.cost\n\n val dipn : int -> Gas.cost\n\n val dropn : int -> Gas.cost\n\n val voting_power : Gas.cost\n\n val total_voting_power : Gas.cost\n\n val keccak : bytes -> Gas.cost\n\n val sha3 : bytes -> Gas.cost\n\n val add_bls12_381_g1 : Gas.cost\n\n val add_bls12_381_g2 : Gas.cost\n\n val add_bls12_381_fr : Gas.cost\n\n val mul_bls12_381_g1 : Gas.cost\n\n val mul_bls12_381_g2 : Gas.cost\n\n val mul_bls12_381_fr : Gas.cost\n\n val mul_bls12_381_fr_z : Gas.cost\n\n val int_bls12_381_fr : Gas.cost\n\n val neg_bls12_381_g1 : Gas.cost\n\n val neg_bls12_381_g2 : Gas.cost\n\n val neg_bls12_381_fr : Gas.cost\n\n val neq : Gas.cost\n\n val nop : Gas.cost\n\n val pairing_check_bls12_381 : 'a Script_typed_ir.boxed_list -> Gas.cost\n\n val comb : int -> Gas.cost\n\n val uncomb : int -> Gas.cost\n\n val comb_get : int -> Gas.cost\n\n val comb_set : int -> Gas.cost\n\n val dupn : int -> Gas.cost\n\n val compare : 'a Script_typed_ir.comparable_ty -> 'a -> 'a -> Gas.cost\n\n val concat_string_precheck : 'a Script_typed_ir.boxed_list -> Gas.cost\n\n val concat_string : Z.t -> Gas.cost\n\n val concat_bytes : Z.t -> Gas.cost\n\n val exec : Gas.cost\n\n val apply : Gas.cost\n\n val lambda : Gas.cost\n\n val address : Gas.cost\n\n val contract : Gas.cost\n\n val transfer_tokens : Gas.cost\n\n val implicit_account : Gas.cost\n\n val create_contract : Gas.cost\n\n val set_delegate : Gas.cost\n\n val balance : Gas.cost\n\n val level : Gas.cost\n\n val now : Gas.cost\n\n val hash_key : Signature.Public_key.t -> Gas.cost\n\n val source : Gas.cost\n\n val sender : Gas.cost\n\n val self : Gas.cost\n\n val self_address : Gas.cost\n\n val amount : Gas.cost\n\n val chain_id : Gas.cost\n\n val unpack_failed : bytes -> Gas.cost\n\n val sapling_empty_state : Gas.cost\n\n val sapling_verify_update : inputs:int -> outputs:int -> Gas.cost\n\n val ticket : Gas.cost\n\n val read_ticket : Gas.cost\n\n val split_ticket :\n 'a Script_int.num -> 'a Script_int.num -> 'a Script_int.num -> Gas.cost\n\n val join_tickets :\n 'a Script_typed_ir.comparable_ty ->\n 'a Script_typed_ir.ticket ->\n 'a Script_typed_ir.ticket ->\n Gas.cost\n end\n\n module Typechecking : sig\n val public_key_optimized : Gas.cost\n\n val public_key_readable : Gas.cost\n\n val key_hash_optimized : Gas.cost\n\n val key_hash_readable : Gas.cost\n\n val signature_optimized : Gas.cost\n\n val signature_readable : Gas.cost\n\n val chain_id_optimized : Gas.cost\n\n val chain_id_readable : Gas.cost\n\n val address_optimized : Gas.cost\n\n val contract_optimized : Gas.cost\n\n val contract_readable : Gas.cost\n\n val bls12_381_g1 : Gas.cost\n\n val bls12_381_g2 : Gas.cost\n\n val bls12_381_fr : Gas.cost\n\n val check_printable : string -> Gas.cost\n\n val merge_cycle : Gas.cost\n\n val parse_type_cycle : Gas.cost\n\n val parse_instr_cycle : Gas.cost\n\n val parse_data_cycle : Gas.cost\n\n val comparable_ty_of_ty_cycle : Gas.cost\n\n val check_dupable_cycle : Gas.cost\n\n val bool : Gas.cost\n\n val unit : Gas.cost\n\n val timestamp_readable : Gas.cost\n\n val contract : Gas.cost\n\n val contract_exists : Gas.cost\n\n val proof_argument : int -> Gas.cost\n end\n\n module Unparsing : sig\n val public_key_optimized : Gas.cost\n\n val public_key_readable : Gas.cost\n\n val key_hash_optimized : Gas.cost\n\n val key_hash_readable : Gas.cost\n\n val signature_optimized : Gas.cost\n\n val signature_readable : Gas.cost\n\n val chain_id_optimized : Gas.cost\n\n val chain_id_readable : Gas.cost\n\n val timestamp_readable : Gas.cost\n\n val address_optimized : Gas.cost\n\n val contract_optimized : Gas.cost\n\n val contract_readable : Gas.cost\n\n val bls12_381_g1 : Gas.cost\n\n val bls12_381_g2 : Gas.cost\n\n val bls12_381_fr : Gas.cost\n\n val unparse_type_cycle : Gas.cost\n\n val unparse_instr_cycle : Gas.cost\n\n val unparse_data_cycle : Gas.cost\n\n val unit : Gas.cost\n\n val contract : Gas.cost\n\n val operation : bytes -> Gas.cost\n\n val sapling_transaction : Sapling.transaction -> Gas.cost\n\n val sapling_diff : Sapling.diff -> Gas.cost\n end\nend\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Gas\n\nmodule Cost_of = struct\n module Z_syntax = struct\n (* This is a good enough approximation. Z.numbits 0 = 0 *)\n let log2 x = Z.of_int (1 + Z.numbits x)\n\n let ( + ) = Z.add\n\n let ( * ) = Z.mul\n\n let ( lsr ) = Z.shift_right\n end\n\n let z_bytes (z : Z.t) =\n let bits = Z.numbits z in\n (7 + bits) / 8\n\n let int_bytes (z : 'a Script_int.num) = z_bytes (Script_int.to_zint z)\n\n let timestamp_bytes (t : Script_timestamp.t) =\n let z = Script_timestamp.to_zint t in\n z_bytes z\n\n (* Upper-bound on the time to compare the given value.\n For now, returns size in bytes, but this could get more complicated... *)\n let rec size_of_comparable :\n type a. a Script_typed_ir.comparable_ty -> a -> Z.t =\n fun wit v ->\n match (wit, v) with\n | (Unit_key _, _) ->\n Z.of_int 1\n | (Never_key _, _) ->\n .\n | (Int_key _, _) ->\n Z.of_int (int_bytes v)\n | (Nat_key _, _) ->\n Z.of_int (int_bytes v)\n | (Signature_key _, _) ->\n Z.of_int Signature.size\n | (String_key _, _) ->\n Z.of_int (String.length v)\n | (Bytes_key _, _) ->\n Z.of_int (Bytes.length v)\n | (Bool_key _, _) ->\n Z.of_int 8\n | (Key_hash_key _, _) ->\n Z.of_int Signature.Public_key_hash.size\n | (Key_key _, k) ->\n Z.of_int (Signature.Public_key.size k)\n | (Timestamp_key _, _) ->\n Z.of_int (timestamp_bytes v)\n | (Address_key _, _) ->\n Z.of_int Signature.Public_key_hash.size\n | (Mutez_key _, _) ->\n Z.of_int 8\n | (Chain_id_key _, _) ->\n Z.of_int Chain_id.size\n | (Pair_key ((l, _), (r, _), _), (lval, rval)) ->\n Z.add (size_of_comparable l lval) (size_of_comparable r rval)\n | (Union_key ((t, _), _, _), L x) ->\n Z.add (Z.of_int 1) (size_of_comparable t x)\n | (Union_key (_, (t, _), _), R x) ->\n Z.add (Z.of_int 1) (size_of_comparable t x)\n | (Option_key _, None) ->\n Z.of_int 1\n | (Option_key (t, _), Some x) ->\n Z.add (Z.of_int 1) (size_of_comparable t x)\n\n let manager_operation = step_cost @@ Z.of_int 1_000\n\n (* FIXME: hardcoded constant, available in next environment version.\n Set to a reasonable upper bound. *)\n let public_key_size = 64\n\n module Generated_costs_007 = struct\n (* Automatically generated costs functions. *)\n\n (* model N_Abs_int *)\n (* Approximating 0.068306 x term *)\n let cost_N_Abs_int size = Z.of_int @@ (80 + (size lsr 4))\n\n (* model N_Add_bls12_381_fr *)\n\n let cost_N_Add_bls12_381_fr = Z.of_int 230\n\n (* model N_Add_bls12_381_g1 *)\n\n let cost_N_Add_bls12_381_g1 = Z.of_int 9_300\n\n (* model N_Add_bls12_381_g2 *)\n\n let cost_N_Add_bls12_381_g2 = Z.of_int 13_000\n\n (* model N_Add_intint *)\n (* Approximating 0.082158 x term *)\n let cost_N_Add_intint size1 size2 =\n let v0 = Compare.Int.max size1 size2 in\n Z.of_int (80 + ((v0 lsr 4) + (v0 lsr 6)))\n\n (* model N_Add_tez *)\n let cost_N_Add_tez = Z.of_int 100\n\n (* model N_And *)\n let cost_N_And = Z.of_int 100\n\n (* model N_And_nat *)\n (* Approximating 0.079325 x term *)\n let cost_N_And_nat size1 size2 =\n let v0 = Compare.Int.min size1 size2 in\n Z.of_int (80 + ((v0 lsr 4) + (v0 lsr 6)))\n\n (* model N_Blake2b *)\n (* Approximating 1.366428 x term *)\n let cost_N_Blake2b size =\n let open Z_syntax in\n let size = Z.of_int size in\n Z.of_int 500 + (size + (size lsr 2))\n\n (* model N_Car *)\n let cost_N_Car = Z.of_int 80\n\n (* model N_Cdr *)\n let cost_N_Cdr = Z.of_int 80\n\n (* model N_Check_signature_ed25519 *)\n (* Approximating 1.372685 x term *)\n let cost_N_Check_signature_ed25519 size =\n let open Z_syntax in\n let size = Z.of_int size in\n Z.of_int 270_000 + (size + (size lsr 2))\n\n (* model N_Check_signature_p256 *)\n (* Approximating 1.385771 x term *)\n let cost_N_Check_signature_p256 size =\n let open Z_syntax in\n let size = Z.of_int size in\n Z.of_int 600_000 + (size + (size lsr 2) + (size lsr 3))\n\n (* model N_Check_signature_secp256k1 *)\n (* Approximating 1.372411 x term *)\n let cost_N_Check_signature_secp256k1 size =\n let open Z_syntax in\n let size = Z.of_int size in\n Z.of_int 60_000 + (size + (size lsr 2))\n\n (* model N_Comb *)\n (* Approximating 3.275337 x term *)\n let cost_N_Comb size = Z.of_int (80 + ((3 * size) + (size lsr 2)))\n\n (* model N_Comb_get *)\n (* Approximating 0.553178 x term *)\n let cost_N_Comb_get size = Z.of_int (80 + ((size lsr 1) + (size lsr 4)))\n\n (* model N_Comb_set *)\n (* Approximating 1.282976 x term *)\n let cost_N_Comb_set size = Z.of_int (80 + (size + (size lsr 2)))\n\n (* model N_Compare_address *)\n let cost_N_Compare_address size1 size2 =\n Z.of_int (80 + (2 * Compare.Int.min size1 size2))\n\n (* model N_Compare_bool *)\n let cost_N_Compare_bool size1 size2 =\n Z.of_int (80 + (128 * Compare.Int.min size1 size2))\n\n (* model N_Compare_int *)\n (* Approximating 0.073657 x term *)\n let cost_N_Compare_int size1 size2 =\n let v0 = Compare.Int.min size1 size2 in\n Z.of_int (150 + ((v0 lsr 4) + (v0 lsr 7)))\n\n (* model N_Compare_key_hash *)\n let cost_N_Compare_key_hash size1 size2 =\n Z.of_int (80 + (2 * Compare.Int.min size1 size2))\n\n (* model N_Compare_mutez *)\n let cost_N_Compare_mutez size1 size2 =\n Z.of_int (13 * Compare.Int.min size1 size2)\n\n (* model N_Compare_string *)\n (* Approximating 0.039389 x term *)\n let cost_N_Compare_string size1 size2 =\n let v0 = Compare.Int.min size1 size2 in\n Z.of_int (120 + ((v0 lsr 5) + (v0 lsr 7)))\n\n (* model N_Compare_timestamp *)\n (* Approximating 0.072483 x term *)\n let cost_N_Compare_timestamp size1 size2 =\n let v0 = Compare.Int.min size1 size2 in\n Z.of_int (140 + ((v0 lsr 4) + (v0 lsr 7)))\n\n (* model N_Concat_string_pair *)\n (* Approximating 0.068808 x term *)\n let cost_N_Concat_string_pair size1 size2 =\n let open Z_syntax in\n let v0 = Z.of_int size1 + Z.of_int size2 in\n Z.of_int 80 + (v0 lsr 4)\n\n (* model N_Cons_list *)\n let cost_N_Cons_list = Z.of_int 80\n\n (* model N_Cons_none *)\n let cost_N_Cons_none = Z.of_int 80\n\n (* model N_Cons_pair *)\n let cost_N_Cons_pair = Z.of_int 80\n\n (* model N_Cons_some *)\n let cost_N_Cons_some = Z.of_int 80\n\n (* model N_Const *)\n let cost_N_Const = Z.of_int 80\n\n (* model N_Dig *)\n let cost_N_Dig size = Z.of_int (100 + (4 * size))\n\n (* model N_Dip *)\n let cost_N_Dip = Z.of_int 100\n\n (* model N_DipN *)\n let cost_N_DipN size = Z.of_int (100 + (4 * size))\n\n (* model N_Drop *)\n let cost_N_Drop = Z.of_int 80\n\n (* model N_DropN *)\n let cost_N_DropN size = Z.of_int (100 + (4 * size))\n\n (* model N_Dug *)\n let cost_N_Dug size = Z.of_int (100 + (4 * size))\n\n (* model N_Dup *)\n let cost_N_Dup = Z.of_int 80\n\n (* model N_DupN *)\n (* Approximating 1.299969 x term *)\n let cost_N_DupN size = Z.of_int (60 + size + (size lsr 2))\n\n (* model N_Ediv_natnat *)\n (* Approximating 0.001599 x term *)\n let cost_N_Ediv_natnat size1 size2 =\n let q = size1 - size2 in\n if Compare.Int.(q < 0) then Z.of_int 300\n else\n let open Z_syntax in\n let v0 = Z.of_int q * Z.of_int size2 in\n Z.of_int 300 + (v0 lsr 10) + (v0 lsr 11) + (v0 lsr 13)\n\n (* model N_Ediv_tez *)\n let cost_N_Ediv_tez = Z.of_int 200\n\n (* model N_Ediv_teznat *)\n (* Extracted by hand from the empirical data *)\n let cost_N_Ediv_teznat = Z.of_int 300\n\n (* model N_Empty_map *)\n let cost_N_Empty_map = Z.of_int 240\n\n (* model N_Empty_set *)\n let cost_N_Empty_set = Z.of_int 240\n\n (* model N_Eq *)\n let cost_N_Eq = Z.of_int 80\n\n (* model N_If *)\n let cost_N_If = Z.of_int 60\n\n (* model N_If_cons *)\n let cost_N_If_cons = Z.of_int 110\n\n (* model N_If_left *)\n let cost_N_If_left = Z.of_int 90\n\n (* model N_If_none *)\n let cost_N_If_none = Z.of_int 80\n\n (* model N_Int_nat *)\n let cost_N_Int_nat = Z.of_int 80\n\n (* model N_Is_nat *)\n let cost_N_Is_nat = Z.of_int 80\n\n (* model N_Keccak *)\n let cost_N_Keccak size =\n let open Z_syntax in\n Z.of_int 1_400 + (Z.of_int 30 * Z.of_int size)\n\n (* model N_Left *)\n let cost_N_Left = Z.of_int 80\n\n (* model N_List_iter *)\n let cost_N_List_iter size =\n let open Z_syntax in\n Z.of_int 500 + (Z.of_int 7 * Z.of_int size)\n\n (* model N_List_map *)\n let cost_N_List_map size =\n let open Z_syntax in\n Z.of_int 500 + (Z.of_int 12 * Z.of_int size)\n\n (* model N_List_size *)\n let cost_N_List_size = Z.of_int 80\n\n (* model N_Loop *)\n let cost_N_Loop = Z.of_int 70\n\n (* model N_Loop_left *)\n let cost_N_Loop_left = Z.of_int 80\n\n (* model N_Lsl_nat *)\n (* Approximating 0.129443 x term *)\n let cost_N_Lsl_nat size = Z.of_int (150 + (size lsr 3))\n\n (* model N_Lsr_nat *)\n (* Approximating 0.129435 x term *)\n let cost_N_Lsr_nat size = Z.of_int (150 + (size lsr 3))\n\n (* model N_Map_get *)\n (* Approximating 0.057548 x term *)\n let cost_N_Map_get size1 size2 =\n let open Z_syntax in\n let v0 = size1 * log2 (Z.of_int size2) in\n Z.of_int 80 + (v0 lsr 5) + (v0 lsr 6) + (v0 lsr 7)\n\n (* model N_Map_iter *)\n let cost_N_Map_iter size =\n let open Z_syntax in\n Z.of_int 80 + (Z.of_int 40 * Z.of_int size)\n\n (* model N_Map_map *)\n let cost_N_Map_map size =\n let open Z_syntax in\n Z.of_int 80 + (Z.of_int 761 * Z.of_int size)\n\n (* model N_Map_mem *)\n (* Approximating 0.058563 x term *)\n let cost_N_Map_mem size1 size2 =\n let open Z_syntax in\n let v0 = size1 * log2 (Z.of_int size2) in\n Z.of_int 80 + (v0 lsr 5) + (v0 lsr 6) + (v0 lsr 7)\n\n (* model N_Map_size *)\n let cost_N_Map_size = Z.of_int 90\n\n (* model N_Map_update *)\n (* Approximating 0.119968 x term *)\n let cost_N_Map_update size1 size2 =\n let open Z_syntax in\n let v0 = size1 * log2 (Z.of_int size2) in\n Z.of_int 80 + (v0 lsr 4) + (v0 lsr 5) + (v0 lsr 6) + (v0 lsr 7)\n\n (* model N_Mul_bls12_381_fr *)\n\n let cost_N_Mul_bls12_381_fr = Z.of_int 260\n\n (* model N_Mul_bls12_381_g1 *)\n\n let cost_N_Mul_bls12_381_g1 = Z.of_int 265_000\n\n (* model N_Mul_bls12_381_g2 *)\n\n let cost_N_Mul_bls12_381_g2 = Z.of_int 850_000\n\n (* Converting fr from/to Z.t *)\n let cost_bls12_381_fr_of_z = Z.of_int 130\n\n let cost_bls12_381_fr_to_z = Z.of_int 30\n\n let cost_N_Mul_bls12_381_fr_z =\n Z.add cost_bls12_381_fr_of_z cost_N_Mul_bls12_381_fr\n\n let cost_N_Int_bls12_381_fr = cost_bls12_381_fr_to_z\n\n (* model N_Mul_intint *)\n let cost_N_Mul_intint size1 size2 =\n let open Z_syntax in\n let a = Z.of_int size1 + Z.of_int size2 in\n Z.of_int 80 + (a * log2 a)\n\n (* model N_Mul_teznat *)\n let cost_N_Mul_teznat size =\n let open Z_syntax in\n Z.of_int 200 + (Z.of_int 133 * Z.of_int size)\n\n (* model N_Neg_bls12_381_fr *)\n\n let cost_N_Neg_bls12_381_fr = Z.of_int 180\n\n (* model N_Neg_bls12_381_g1 *)\n\n let cost_N_Neg_bls12_381_g1 = Z.of_int 410\n\n (* model N_Neg_bls12_381_g2 *)\n\n let cost_N_Neg_bls12_381_g2 = Z.of_int 715\n\n (* model N_Neg_int *)\n (* Approximating 0.068419 x term *)\n let cost_N_Neg_int size = Z.of_int (80 + (size lsr 4))\n\n (* model N_Neq *)\n let cost_N_Neq = Z.of_int 80\n\n (* model N_Nil *)\n let cost_N_Nil = Z.of_int 80\n\n (* model N_Nop *)\n let cost_N_Nop = Z.of_int 70\n\n (* model N_Not *)\n let cost_N_Not = Z.of_int 90\n\n (* model N_Not_int *)\n (* Approximating 0.076564 x term *)\n let cost_N_Not_int size = Z.of_int (55 + ((size lsr 4) + (size lsr 7)))\n\n (* model N_Or *)\n let cost_N_Or = Z.of_int 90\n\n (* model N_Or_nat *)\n (* Approximating 0.078718 x term *)\n let cost_N_Or_nat size1 size2 =\n let v0 = Compare.Int.max size1 size2 in\n Z.of_int (80 + ((v0 lsr 4) + (v0 lsr 6)))\n\n (* model N_Pairing_check_bls12_381 *)\n\n let cost_N_Pairing_check_bls12_381 size =\n Z.add (Z.of_int 1_550_000) (Z.mul (Z.of_int 510_000) (Z.of_int size))\n\n (* model N_Right *)\n let cost_N_Right = Z.of_int 80\n\n (* model N_Seq *)\n let cost_N_Seq = Z.of_int 60\n\n (* model N_Set_iter *)\n let cost_N_Set_iter size =\n let open Z_syntax in\n Z.of_int 80 + (Z.of_int 36 * Z.of_int size)\n\n (* model N_Set_mem *)\n (* Approximating 0.059410 x term *)\n let cost_N_Set_mem size1 size2 =\n let open Z_syntax in\n let v0 = size1 * log2 (Z.of_int size2) in\n Z.of_int 80 + (v0 lsr 5) + (v0 lsr 6) + (v0 lsr 7) + (v0 lsr 8)\n\n (* model N_Set_size *)\n let cost_N_Set_size = Z.of_int 80\n\n (* model N_Set_update *)\n (* Approximating 0.126260 x term *)\n let cost_N_Set_update size1 size2 =\n let open Z_syntax in\n let v0 = size1 * log2 (Z.of_int size2) in\n Z.of_int 80 + (v0 lsr 3)\n\n (* model N_Sha256 *)\n let cost_N_Sha256 size =\n let open Z_syntax in\n Z.of_int 500 + (Z.of_int 5 * Z.of_int size)\n\n (* model N_Sha3 *)\n let cost_N_Sha3 size =\n let open Z_syntax in\n Z.of_int 1_400 + (Z.of_int 32 * Z.of_int size)\n\n (* model N_Sha512 *)\n let cost_N_Sha512 size =\n let open Z_syntax in\n Z.of_int 500 + (Z.of_int 3 * Z.of_int size)\n\n (* model N_Slice_string *)\n (* Approximating 0.067048 x term *)\n let cost_N_Slice_string size = Z.of_int (80 + (size lsr 4))\n\n (* model N_String_size *)\n let cost_N_String_size = Z.of_int 80\n\n (* model N_Sub_int *)\n (* Approximating 0.082399 x term *)\n let cost_N_Sub_int size1 size2 =\n let v0 = Compare.Int.max size1 size2 in\n Z.of_int (80 + ((v0 lsr 4) + (v0 lsr 6)))\n\n (* model N_Sub_tez *)\n let cost_N_Sub_tez = Z.of_int 80\n\n (* model N_Swap *)\n let cost_N_Swap = Z.of_int 70\n\n (* model N_Total_voting_power *)\n let cost_N_Total_voting_power = Z.of_int 400\n\n (* model N_Uncomb *)\n (* Approximating 3.666332 x term *)\n let cost_N_Uncomb size =\n Z.of_int (80 + ((3 * size) + (size lsr 1) + (size lsr 3)))\n\n (* model N_Unpair *)\n let cost_N_Unpair = Z.of_int 80\n\n (* model N_Voting_power *)\n let cost_N_Voting_power = Z.of_int 400\n\n (* model N_Xor *)\n let cost_N_Xor = Z.of_int 100\n\n (* model N_Xor_nat *)\n (* Approximating 0.078258 x term *)\n let cost_N_Xor_nat size1 size2 =\n let v0 = Compare.Int.max size1 size2 in\n Z.of_int (80 + ((v0 lsr 4) + (v0 lsr 6)))\n\n (* model DECODING_BLS_FR *)\n\n let cost_DECODING_BLS_FR = Z.of_int 50\n\n (* model DECODING_BLS_G1 *)\n\n let cost_DECODING_BLS_G1 = Z.of_int 230_000\n\n (* model DECODING_BLS_G2 *)\n\n let cost_DECODING_BLS_G2 = Z.of_int 740_000\n\n (* model B58CHECK_DECODING_CHAIN_ID *)\n let cost_B58CHECK_DECODING_CHAIN_ID = Z.of_int 1_500\n\n (* model B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519 *)\n let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519 = Z.of_int 3_300\n\n (* model B58CHECK_DECODING_PUBLIC_KEY_HASH_p256 *)\n let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_p256 = Z.of_int 3_300\n\n (* model B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1 *)\n let cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1 = Z.of_int 3_300\n\n (* model B58CHECK_DECODING_PUBLIC_KEY_ed25519 *)\n let cost_B58CHECK_DECODING_PUBLIC_KEY_ed25519 = Z.of_int 4_300\n\n (* model B58CHECK_DECODING_PUBLIC_KEY_p256 *)\n let cost_B58CHECK_DECODING_PUBLIC_KEY_p256 = Z.of_int 29_000\n\n (* model B58CHECK_DECODING_PUBLIC_KEY_secp256k1 *)\n let cost_B58CHECK_DECODING_PUBLIC_KEY_secp256k1 = Z.of_int 9_400\n\n (* model B58CHECK_DECODING_SIGNATURE_ed25519 *)\n let cost_B58CHECK_DECODING_SIGNATURE_ed25519 = Z.of_int 6_600\n\n (* model B58CHECK_DECODING_SIGNATURE_p256 *)\n let cost_B58CHECK_DECODING_SIGNATURE_p256 = Z.of_int 6_600\n\n (* model B58CHECK_DECODING_SIGNATURE_secp256k1 *)\n let cost_B58CHECK_DECODING_SIGNATURE_secp256k1 = Z.of_int 6_600\n\n (* model ENCODING_BLS_FR *)\n\n let cost_ENCODING_BLS_FR = Z.of_int 30\n\n (* model ENCODING_BLS_G1 *)\n\n let cost_ENCODING_BLS_G1 = Z.of_int 30\n\n (* model ENCODING_BLS_G2 *)\n\n let cost_ENCODING_BLS_G2 = Z.of_int 30\n\n (* model B58CHECK_ENCODING_CHAIN_ID *)\n let cost_B58CHECK_ENCODING_CHAIN_ID = Z.of_int 1_600\n\n (* model B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519 *)\n let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519 = Z.of_int 3_300\n\n (* model B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256 *)\n let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256 = Z.of_int 3_750\n\n (* model B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1 *)\n let cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1 = Z.of_int 3_300\n\n (* model B58CHECK_ENCODING_PUBLIC_KEY_ed25519 *)\n let cost_B58CHECK_ENCODING_PUBLIC_KEY_ed25519 = Z.of_int 4_500\n\n (* model B58CHECK_ENCODING_PUBLIC_KEY_p256 *)\n let cost_B58CHECK_ENCODING_PUBLIC_KEY_p256 = Z.of_int 5_300\n\n (* model B58CHECK_ENCODING_PUBLIC_KEY_secp256k1 *)\n let cost_B58CHECK_ENCODING_PUBLIC_KEY_secp256k1 = Z.of_int 5_000\n\n (* model B58CHECK_ENCODING_SIGNATURE_ed25519 *)\n let cost_B58CHECK_ENCODING_SIGNATURE_ed25519 = Z.of_int 8_700\n\n (* model B58CHECK_ENCODING_SIGNATURE_p256 *)\n let cost_B58CHECK_ENCODING_SIGNATURE_p256 = Z.of_int 8_700\n\n (* model B58CHECK_ENCODING_SIGNATURE_secp256k1 *)\n let cost_B58CHECK_ENCODING_SIGNATURE_secp256k1 = Z.of_int 8_700\n\n (* model DECODING_CHAIN_ID *)\n let cost_DECODING_CHAIN_ID = Z.of_int 50\n\n (* model DECODING_PUBLIC_KEY_HASH_ed25519 *)\n let cost_DECODING_PUBLIC_KEY_HASH_ed25519 = Z.of_int 50\n\n (* model DECODING_PUBLIC_KEY_HASH_p256 *)\n let cost_DECODING_PUBLIC_KEY_HASH_p256 = Z.of_int 60\n\n (* model DECODING_PUBLIC_KEY_HASH_secp256k1 *)\n let cost_DECODING_PUBLIC_KEY_HASH_secp256k1 = Z.of_int 60\n\n (* model DECODING_PUBLIC_KEY_ed25519 *)\n let cost_DECODING_PUBLIC_KEY_ed25519 = Z.of_int 60\n\n (* model DECODING_PUBLIC_KEY_p256 *)\n let cost_DECODING_PUBLIC_KEY_p256 = Z.of_int 25_000\n\n (* model DECODING_PUBLIC_KEY_secp256k1 *)\n let cost_DECODING_PUBLIC_KEY_secp256k1 = Z.of_int 5_300\n\n (* model DECODING_SIGNATURE_ed25519 *)\n let cost_DECODING_SIGNATURE_ed25519 = Z.of_int 30\n\n (* model DECODING_SIGNATURE_p256 *)\n let cost_DECODING_SIGNATURE_p256 = Z.of_int 30\n\n (* model DECODING_SIGNATURE_secp256k1 *)\n let cost_DECODING_SIGNATURE_secp256k1 = Z.of_int 30\n\n (* model ENCODING_CHAIN_ID *)\n let cost_ENCODING_CHAIN_ID = Z.of_int 50\n\n (* model ENCODING_PUBLIC_KEY_HASH_ed25519 *)\n let cost_ENCODING_PUBLIC_KEY_HASH_ed25519 = Z.of_int 70\n\n (* model ENCODING_PUBLIC_KEY_HASH_p256 *)\n let cost_ENCODING_PUBLIC_KEY_HASH_p256 = Z.of_int 80\n\n (* model ENCODING_PUBLIC_KEY_HASH_secp256k1 *)\n let cost_ENCODING_PUBLIC_KEY_HASH_secp256k1 = Z.of_int 70\n\n (* model ENCODING_PUBLIC_KEY_ed25519 *)\n let cost_ENCODING_PUBLIC_KEY_ed25519 = Z.of_int 80\n\n (* model ENCODING_PUBLIC_KEY_p256 *)\n let cost_ENCODING_PUBLIC_KEY_p256 = Z.of_int 450\n\n (* model ENCODING_PUBLIC_KEY_secp256k1 *)\n let cost_ENCODING_PUBLIC_KEY_secp256k1 = Z.of_int 490\n\n (* model ENCODING_SIGNATURE_ed25519 *)\n let cost_ENCODING_SIGNATURE_ed25519 = Z.of_int 40\n\n (* model ENCODING_SIGNATURE_p256 *)\n let cost_ENCODING_SIGNATURE_p256 = Z.of_int 40\n\n (* model ENCODING_SIGNATURE_secp256k1 *)\n let cost_ENCODING_SIGNATURE_secp256k1 = Z.of_int 40\n\n (* model TIMESTAMP_READABLE_DECODING *)\n let cost_TIMESTAMP_READABLE_DECODING = Z.of_int 130\n\n (* model TIMESTAMP_READABLE_ENCODING *)\n let cost_TIMESTAMP_READABLE_ENCODING = Z.of_int 900\n\n (* model CHECK_PRINTABLE *)\n let cost_CHECK_PRINTABLE size =\n let open Z_syntax in\n Z.of_int 14 + (Z.of_int 10 * Z.of_int size)\n\n (* model MERGE_TYPES\n This is the estimated cost of one iteration of merge_types, extracted\n and copied manually from the parameter fit for the MERGE_TYPES benchmark\n (the model is parametric on the size of the type, which we don't have\n access to in O(1)). *)\n let cost_MERGE_TYPES = Z.of_int 130\n\n (* model TYPECHECKING_CODE\n This is the cost of one iteration of parse_instr, extracted by hand from the\n parameter fit for the TYPECHECKING_CODE benchmark. *)\n let cost_TYPECHECKING_CODE = Z.of_int 375\n\n (* model UNPARSING_CODE\n This is the cost of one iteration of unparse_instr, extracted by hand from the\n parameter fit for the UNPARSING_CODE benchmark. *)\n let cost_UNPARSING_CODE = Z.of_int 200\n\n (* model TYPECHECKING_DATA\n This is the cost of one iteration of parse_data, extracted by hand from the\n parameter fit for the TYPECHECKING_DATA benchmark. *)\n let cost_TYPECHECKING_DATA = Z.of_int 240\n\n (* model UNPARSING_DATA\n This is the cost of one iteration of unparse_data, extracted by hand from the\n parameter fit for the UNPARSING_DATA benchmark. *)\n let cost_UNPARSING_DATA = Z.of_int 140\n\n (* model PARSE_TYPE\n This is the cost of one iteration of parse_ty, extracted by hand from the\n parameter fit for the PARSE_TYPE benchmark. *)\n let cost_PARSE_TYPE = Z.of_int 170\n\n (* model UNPARSE_TYPE\n This is the cost of one iteration of unparse_ty, extracted by hand from the\n parameter fit for the UNPARSE_TYPE benchmark. *)\n let cost_UNPARSE_TYPE = Z.of_int 185\n\n (* TODO: benchmark *)\n let cost_COMPARABLE_TY_OF_TY = Z.of_int 120\n end\n\n module Interpreter = struct\n open Generated_costs_007\n\n let drop = atomic_step_cost cost_N_Drop\n\n let dup = atomic_step_cost cost_N_Dup\n\n let swap = atomic_step_cost cost_N_Swap\n\n let push = atomic_step_cost cost_N_Const\n\n let cons_some = atomic_step_cost cost_N_Cons_some\n\n let cons_none = atomic_step_cost cost_N_Cons_none\n\n let if_none = atomic_step_cost cost_N_If_none\n\n let cons_pair = atomic_step_cost cost_N_Cons_pair\n\n let unpair = atomic_step_cost cost_N_Unpair\n\n let car = atomic_step_cost cost_N_Car\n\n let cdr = atomic_step_cost cost_N_Cdr\n\n let cons_left = atomic_step_cost cost_N_Left\n\n let cons_right = atomic_step_cost cost_N_Right\n\n let if_left = atomic_step_cost cost_N_If_left\n\n let cons_list = atomic_step_cost cost_N_Cons_list\n\n let nil = atomic_step_cost cost_N_Nil\n\n let if_cons = atomic_step_cost cost_N_If_cons\n\n let list_map : 'a Script_typed_ir.boxed_list -> Gas.cost =\n fun {length; _} -> atomic_step_cost (cost_N_List_map length)\n\n let list_size = atomic_step_cost cost_N_List_size\n\n let list_iter : 'a Script_typed_ir.boxed_list -> Gas.cost =\n fun {length; _} -> atomic_step_cost (cost_N_List_iter length)\n\n let empty_set = atomic_step_cost cost_N_Empty_set\n\n let set_iter (type a) ((module Box) : a Script_typed_ir.set) =\n atomic_step_cost (cost_N_Set_iter Box.size)\n\n let set_mem (type a) (elt : a) ((module Box) : a Script_typed_ir.set) =\n let elt_size = size_of_comparable Box.elt_ty elt in\n atomic_step_cost (cost_N_Set_mem elt_size Box.size)\n\n let set_update (type a) (elt : a) ((module Box) : a Script_typed_ir.set) =\n let elt_size = size_of_comparable Box.elt_ty elt in\n atomic_step_cost (cost_N_Set_update elt_size Box.size)\n\n let set_size = atomic_step_cost cost_N_Set_size\n\n let empty_map = atomic_step_cost cost_N_Empty_map\n\n let map_map (type k v) ((module Box) : (k, v) Script_typed_ir.map) =\n atomic_step_cost (cost_N_Map_map (snd Box.boxed))\n\n let map_iter (type k v) ((module Box) : (k, v) Script_typed_ir.map) =\n atomic_step_cost (cost_N_Map_iter (snd Box.boxed))\n\n let map_mem (type k v) (elt : k)\n ((module Box) : (k, v) Script_typed_ir.map) =\n let elt_size = size_of_comparable Box.key_ty elt in\n atomic_step_cost (cost_N_Map_mem elt_size (snd Box.boxed))\n\n let map_get (type k v) (elt : k)\n ((module Box) : (k, v) Script_typed_ir.map) =\n let elt_size = size_of_comparable Box.key_ty elt in\n atomic_step_cost (cost_N_Map_get elt_size (snd Box.boxed))\n\n let map_update (type k v) (elt : k)\n ((module Box) : (k, v) Script_typed_ir.map) =\n let elt_size = size_of_comparable Box.key_ty elt in\n atomic_step_cost (cost_N_Map_update elt_size (snd Box.boxed))\n\n let map_get_and_update (type k v) (elt : k)\n (m : (k, v) Script_typed_ir.map) =\n map_get elt m +@ map_update elt m\n\n let map_size = atomic_step_cost cost_N_Map_size\n\n let add_seconds_timestamp :\n 'a Script_int.num -> Script_timestamp.t -> Gas.cost =\n fun seconds timestamp ->\n let seconds_bytes = int_bytes seconds in\n let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in\n atomic_step_cost (cost_N_Add_intint seconds_bytes timestamp_bytes)\n\n let sub_seconds_timestamp :\n 'a Script_int.num -> Script_timestamp.t -> Gas.cost =\n fun seconds timestamp ->\n let seconds_bytes = int_bytes seconds in\n let timestamp_bytes = z_bytes (Script_timestamp.to_zint timestamp) in\n atomic_step_cost (cost_N_Sub_int seconds_bytes timestamp_bytes)\n\n let diff_timestamps t1 t2 =\n let t1_bytes = z_bytes (Script_timestamp.to_zint t1) in\n let t2_bytes = z_bytes (Script_timestamp.to_zint t2) in\n atomic_step_cost (cost_N_Sub_int t1_bytes t2_bytes)\n\n let concat_string_pair s1 s2 =\n atomic_step_cost\n (cost_N_Concat_string_pair (String.length s1) (String.length s2))\n\n let slice_string s =\n atomic_step_cost (cost_N_Slice_string (String.length s))\n\n let string_size = atomic_step_cost cost_N_String_size\n\n let concat_bytes_pair b1 b2 =\n atomic_step_cost\n (cost_N_Concat_string_pair (Bytes.length b1) (Bytes.length b2))\n\n let slice_bytes b = atomic_step_cost (cost_N_Slice_string (Bytes.length b))\n\n let bytes_size = atomic_step_cost cost_N_String_size\n\n let add_tez = atomic_step_cost cost_N_Add_tez\n\n let sub_tez = atomic_step_cost cost_N_Sub_tez\n\n let mul_teznat n = atomic_step_cost (cost_N_Mul_teznat (int_bytes n))\n\n let bool_or = atomic_step_cost cost_N_Or\n\n let bool_and = atomic_step_cost cost_N_And\n\n let bool_xor = atomic_step_cost cost_N_Xor\n\n let bool_not = atomic_step_cost cost_N_Not\n\n let is_nat = atomic_step_cost cost_N_Is_nat\n\n let abs_int i = atomic_step_cost (cost_N_Abs_int (int_bytes i))\n\n let int_nat = atomic_step_cost cost_N_Int_nat\n\n let neg_int i = atomic_step_cost (cost_N_Neg_int (int_bytes i))\n\n let neg_nat n = atomic_step_cost (cost_N_Neg_int (int_bytes n))\n\n let add_bigint i1 i2 =\n atomic_step_cost (cost_N_Add_intint (int_bytes i1) (int_bytes i2))\n\n let sub_bigint i1 i2 =\n atomic_step_cost (cost_N_Sub_int (int_bytes i1) (int_bytes i2))\n\n let mul_bigint i1 i2 =\n atomic_step_cost (cost_N_Mul_intint (int_bytes i1) (int_bytes i2))\n\n let ediv_teznat _tez _n = atomic_step_cost cost_N_Ediv_teznat\n\n let ediv_tez = atomic_step_cost cost_N_Ediv_tez\n\n let ediv_bigint i1 i2 =\n atomic_step_cost (cost_N_Ediv_natnat (int_bytes i1) (int_bytes i2))\n\n let eq = atomic_step_cost cost_N_Eq\n\n let lsl_nat shifted = atomic_step_cost (cost_N_Lsl_nat (int_bytes shifted))\n\n let lsr_nat shifted = atomic_step_cost (cost_N_Lsr_nat (int_bytes shifted))\n\n let or_nat n1 n2 =\n atomic_step_cost (cost_N_Or_nat (int_bytes n1) (int_bytes n2))\n\n let and_nat n1 n2 =\n atomic_step_cost (cost_N_And_nat (int_bytes n1) (int_bytes n2))\n\n let xor_nat n1 n2 =\n atomic_step_cost (cost_N_Xor_nat (int_bytes n1) (int_bytes n2))\n\n let not_int i = atomic_step_cost (cost_N_Not_int (int_bytes i))\n\n let not_nat = not_int\n\n let seq = atomic_step_cost cost_N_Seq\n\n let if_ = atomic_step_cost cost_N_If\n\n let loop = atomic_step_cost cost_N_Loop\n\n let loop_left = atomic_step_cost cost_N_Loop_left\n\n let dip = atomic_step_cost cost_N_Dip\n\n let check_signature (pkey : Signature.public_key) b =\n let cost =\n match pkey with\n | Ed25519 _ ->\n cost_N_Check_signature_ed25519 (Bytes.length b)\n | Secp256k1 _ ->\n cost_N_Check_signature_secp256k1 (Bytes.length b)\n | P256 _ ->\n cost_N_Check_signature_p256 (Bytes.length b)\n in\n atomic_step_cost cost\n\n let blake2b b = atomic_step_cost (cost_N_Blake2b (Bytes.length b))\n\n let sha256 b = atomic_step_cost (cost_N_Sha256 (Bytes.length b))\n\n let sha512 b = atomic_step_cost (cost_N_Sha512 (Bytes.length b))\n\n let dign n = atomic_step_cost (cost_N_Dig n)\n\n let dugn n = atomic_step_cost (cost_N_Dug n)\n\n let dipn n = atomic_step_cost (cost_N_DipN n)\n\n let dropn n = atomic_step_cost (cost_N_DropN n)\n\n let voting_power = atomic_step_cost cost_N_Voting_power\n\n let total_voting_power = atomic_step_cost cost_N_Total_voting_power\n\n let keccak b = atomic_step_cost (cost_N_Keccak (Bytes.length b))\n\n let sha3 b = atomic_step_cost (cost_N_Sha3 (Bytes.length b))\n\n let add_bls12_381_g1 = atomic_step_cost cost_N_Add_bls12_381_g1\n\n let add_bls12_381_g2 = atomic_step_cost cost_N_Add_bls12_381_g2\n\n let add_bls12_381_fr = atomic_step_cost cost_N_Add_bls12_381_fr\n\n let mul_bls12_381_g1 = atomic_step_cost cost_N_Mul_bls12_381_g1\n\n let mul_bls12_381_g2 = atomic_step_cost cost_N_Mul_bls12_381_g2\n\n let mul_bls12_381_fr = atomic_step_cost cost_N_Mul_bls12_381_fr\n\n let mul_bls12_381_fr_z = atomic_step_cost cost_N_Mul_bls12_381_fr_z\n\n let int_bls12_381_fr = atomic_step_cost cost_N_Int_bls12_381_fr\n\n let neg_bls12_381_g1 = atomic_step_cost cost_N_Neg_bls12_381_g1\n\n let neg_bls12_381_g2 = atomic_step_cost cost_N_Neg_bls12_381_g2\n\n let neg_bls12_381_fr = atomic_step_cost cost_N_Neg_bls12_381_fr\n\n let neq = atomic_step_cost cost_N_Neq\n\n let nop = atomic_step_cost cost_N_Nop\n\n let pairing_check_bls12_381 (l : 'a Script_typed_ir.boxed_list) =\n atomic_step_cost (cost_N_Pairing_check_bls12_381 l.length)\n\n let comb n = atomic_step_cost (cost_N_Comb n)\n\n let uncomb n = atomic_step_cost (cost_N_Uncomb n)\n\n let comb_get n = atomic_step_cost (cost_N_Comb_get n)\n\n let comb_set n = atomic_step_cost (cost_N_Comb_set n)\n\n let dupn n = atomic_step_cost (cost_N_DupN n)\n\n let sapling_verify_update ~inputs ~outputs =\n let open Z_syntax in\n atomic_step_cost\n ( Z.of_int 85_000\n + (Z.of_int inputs * Z.of_int 4)\n + (Z.of_int outputs * Z.of_int 30) )\n\n (* --------------------------------------------------------------------- *)\n (* Semi-hand-crafted models *)\n let compare_unit = atomic_step_cost (Z.of_int 10)\n\n let compare_union_tag = atomic_step_cost (Z.of_int 10)\n\n let compare_option_tag = atomic_step_cost (Z.of_int 10)\n\n let compare_bool = atomic_step_cost (cost_N_Compare_bool 1 1)\n\n let compare_signature = atomic_step_cost (Z.of_int 92)\n\n let compare_string s1 s2 =\n atomic_step_cost\n (cost_N_Compare_string (String.length s1) (String.length s2))\n\n let compare_bytes b1 b2 =\n atomic_step_cost\n (cost_N_Compare_string (Bytes.length b1) (Bytes.length b2))\n\n let compare_mutez = atomic_step_cost (cost_N_Compare_mutez 8 8)\n\n let compare_int i1 i2 =\n atomic_step_cost (cost_N_Compare_int (int_bytes i1) (int_bytes i2))\n\n let compare_nat n1 n2 =\n atomic_step_cost (cost_N_Compare_int (int_bytes n1) (int_bytes n2))\n\n let compare_key_hash =\n let sz = Signature.Public_key_hash.size in\n atomic_step_cost (cost_N_Compare_key_hash sz sz)\n\n let compare_key = atomic_step_cost (Z.of_int 92)\n\n let compare_timestamp t1 t2 =\n atomic_step_cost\n (cost_N_Compare_timestamp\n (z_bytes (Script_timestamp.to_zint t1))\n (z_bytes (Script_timestamp.to_zint t2)))\n\n let compare_address =\n let sz = Signature.Public_key_hash.size + Chain_id.size in\n atomic_step_cost (cost_N_Compare_address sz sz)\n\n let compare_chain_id = atomic_step_cost (Z.of_int 30)\n\n let rec compare : type a. a Script_typed_ir.comparable_ty -> a -> a -> cost\n =\n fun ty x y ->\n match ty with\n | Unit_key _ ->\n compare_unit\n | Never_key _ -> (\n match x with _ -> . )\n | Bool_key _ ->\n compare_bool\n | String_key _ ->\n compare_string x y\n | Signature_key _ ->\n compare_signature\n | Bytes_key _ ->\n compare_bytes x y\n | Mutez_key _ ->\n compare_mutez\n | Int_key _ ->\n compare_int x y\n | Nat_key _ ->\n compare_nat x y\n | Key_hash_key _ ->\n compare_key_hash\n | Key_key _ ->\n compare_key\n | Timestamp_key _ ->\n compare_timestamp x y\n | Address_key _ ->\n compare_address\n | Chain_id_key _ ->\n compare_chain_id\n | Pair_key ((tl, _), (tr, _), _) ->\n (* Reasonable over-approximation of the cost of lexicographic comparison. *)\n let (xl, xr) = x in\n let (yl, yr) = y in\n compare tl xl yl +@ compare tr xr yr\n | Union_key ((tl, _), (tr, _), _) -> (\n compare_union_tag\n +@\n match (x, y) with\n | (L x, L y) ->\n compare tl x y\n | (L _, R _) ->\n free\n | (R _, L _) ->\n free\n | (R x, R y) ->\n compare tr x y )\n | Option_key (t, _) -> (\n compare_option_tag\n +@\n match (x, y) with\n | (None, None) ->\n free\n | (None, Some _) ->\n free\n | (Some _, None) ->\n free\n | (Some x, Some y) ->\n compare t x y )\n\n (* --------------------------------------------------------------------- *)\n (* Hand-crafted models *)\n\n (* The cost functions below where not benchmarked, a cost model was derived\n from looking at similar instructions. *)\n\n let sapling_empty_state = empty_map\n\n (* Cost for Concat_string is paid in two steps: when entering the interpreter,\n the user pays for the cost of computing the information necessary to compute\n the actual gas (so it's meta-gas): indeed, one needs to run through the\n list of strings to compute the total allocated cost.\n [concat_string_precheck] corresponds to the meta-gas cost of this computation.\n *)\n let concat_string_precheck (l : 'a Script_typed_ir.boxed_list) =\n (* we set the precheck to be slightly more expensive than cost_N_List_iter *)\n atomic_step_cost (Z.mul (Z.of_int l.length) (Z.of_int 10))\n\n (* This is the cost of allocating a string and blitting existing ones into it. *)\n let concat_string total_bytes =\n atomic_step_cost\n Z.(add (of_int 100) (fst (ediv_rem total_bytes (of_int 10))))\n\n (* Same story as Concat_string. *)\n let concat_bytes total_bytes =\n atomic_step_cost\n Z.(add (of_int 100) (fst (ediv_rem total_bytes (of_int 10))))\n\n (* Cost of additional call to logger + overhead of setting up call to [interp]. *)\n let exec = atomic_step_cost (Z.of_int 100)\n\n (* Heavy computation happens in the [unparse_data], [unparse_ty]\n functions which are carbonated. We must account for allocating\n the Micheline lambda wrapper. *)\n let apply = atomic_step_cost (Z.of_int 1000)\n\n (* Pushing a pointer on the stack. *)\n let lambda = push\n\n (* Pusing an address on the stack. *)\n let address = push\n\n (* Most computation happens in [parse_contract_from_script], which is carbonated.\n Account for pushing on the stack. *)\n let contract = push\n\n (* Most computation happens in [collect_lazy_storage], [extract_lazy_storage_diff]\n and [unparse_data] which are carbonated. The instruction-specific overhead\n is mostly that of updating the internal nonce, which we approximate by the\n cost of a push. *)\n let transfer_tokens = Gas.(push +@ push)\n\n (* Wrapping a value and pushing it on the stack. *)\n let implicit_account = push\n\n (* As for [transfer_token], most computation happens elsewhere.\n We still account for the overhead of updating the internal_nonce. *)\n let create_contract = Gas.(push +@ push)\n\n (* Increments the internal_nonce counter. *)\n let set_delegate = Gas.(push +@ push)\n\n (* Cost of access taken care of in Contract_storage.get_balance_carbonated *)\n let balance = Gas.free\n\n (* Accessing the raw_context, Small arithmetic & pushing on the stack. *)\n let level = atomic_step_cost (Z.mul (Z.of_int 2) cost_N_Const)\n\n (* Same as [cost_level] *)\n let now = level\n\n (* Public keys are hashed with Blake2b *)\n let hash_key _pk = atomic_step_cost (cost_N_Blake2b public_key_size)\n\n (* Pushes on the stack an element from the [step_constants] record. *)\n let source = push\n\n (* Same as cost_source *)\n let sender = source\n\n (* Same as cost_source *)\n let self = source\n\n (* Same as cost_source *)\n let self_address = source\n\n (* Same as cost_source *)\n let amount = source\n\n (* Same as cost_source *)\n let chain_id = source\n\n (* TODO benchmark *)\n (* FIXME: imported from 006, needs proper benchmarks *)\n let unpack_failed bytes =\n (* We cannot instrument failed deserialization,\n so we take worst case fees: a set of size 1 bytes values. *)\n let len = Z.of_int (Bytes.length bytes) in\n (len *@ alloc_mbytes_cost 1)\n +@ len\n *@ ( Z.of_int (Z.numbits len)\n *@ (alloc_cost (Z.of_int 3) +@ step_cost Z.one) )\n\n let ticket = atomic_step_cost (Z.of_int 80)\n\n let read_ticket = atomic_step_cost (Z.of_int 80)\n\n let split_ticket ticket_amount amount_a amount_b =\n ticket\n +@ add_bigint amount_a amount_b\n +@ compare_nat ticket_amount ticket_amount\n\n let join_tickets :\n 'a Script_typed_ir.comparable_ty ->\n 'a Script_typed_ir.ticket ->\n 'a Script_typed_ir.ticket ->\n Gas.cost =\n fun ty ticket_a ticket_b ->\n ticket +@ compare_address\n +@ add_bigint ticket_a.amount ticket_b.amount\n +@ compare ty ticket_a.contents ticket_b.contents\n end\n\n module Typechecking = struct\n open Generated_costs_007\n\n let public_key_optimized =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_DECODING_PUBLIC_KEY_ed25519\n (max\n cost_DECODING_PUBLIC_KEY_secp256k1\n cost_DECODING_PUBLIC_KEY_p256))\n\n let public_key_readable =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_B58CHECK_DECODING_PUBLIC_KEY_ed25519\n (max\n cost_B58CHECK_DECODING_PUBLIC_KEY_secp256k1\n cost_B58CHECK_DECODING_PUBLIC_KEY_p256))\n\n let key_hash_optimized =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_DECODING_PUBLIC_KEY_HASH_ed25519\n (max\n cost_DECODING_PUBLIC_KEY_HASH_secp256k1\n cost_DECODING_PUBLIC_KEY_HASH_p256))\n\n let key_hash_readable =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_ed25519\n (max\n cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_secp256k1\n cost_B58CHECK_DECODING_PUBLIC_KEY_HASH_p256))\n\n let signature_optimized =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_DECODING_SIGNATURE_ed25519\n (max\n cost_DECODING_SIGNATURE_secp256k1\n cost_DECODING_SIGNATURE_p256))\n\n let signature_readable =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_B58CHECK_DECODING_SIGNATURE_ed25519\n (max\n cost_B58CHECK_DECODING_SIGNATURE_secp256k1\n cost_B58CHECK_DECODING_SIGNATURE_p256))\n\n let chain_id_optimized = atomic_step_cost cost_DECODING_CHAIN_ID\n\n let chain_id_readable = atomic_step_cost cost_B58CHECK_DECODING_CHAIN_ID\n\n (* Reasonable approximation *)\n let address_optimized = key_hash_optimized\n\n (* Reasonable approximation *)\n let contract_optimized = key_hash_optimized\n\n (* Reasonable approximation *)\n let contract_readable = key_hash_readable\n\n let bls12_381_g1 = atomic_step_cost cost_DECODING_BLS_G1\n\n let bls12_381_g2 = atomic_step_cost cost_DECODING_BLS_G2\n\n let bls12_381_fr = atomic_step_cost cost_DECODING_BLS_FR\n\n let check_printable s =\n atomic_step_cost (cost_CHECK_PRINTABLE (String.length s))\n\n let merge_cycle = atomic_step_cost cost_MERGE_TYPES\n\n let parse_type_cycle = atomic_step_cost cost_PARSE_TYPE\n\n let parse_instr_cycle = atomic_step_cost cost_TYPECHECKING_CODE\n\n let parse_data_cycle = atomic_step_cost cost_TYPECHECKING_DATA\n\n let comparable_ty_of_ty_cycle = atomic_step_cost cost_COMPARABLE_TY_OF_TY\n\n (* Cost of a cycle of checking that a type is dupable *)\n (* TODO: bench *)\n let check_dupable_cycle = atomic_step_cost cost_TYPECHECKING_DATA\n\n let bool = free\n\n let unit = free\n\n let timestamp_readable = atomic_step_cost cost_TIMESTAMP_READABLE_DECODING\n\n (* Reasonable estimate. *)\n let contract = Gas.(Z.of_int 2 *@ public_key_readable)\n\n (* Assuming unflattened storage: /contracts/hash1/.../hash6/key/balance,\n balance stored on 64 bits *)\n let contract_exists =\n Gas.cost_of_repr\n @@ Storage_costs.read_access ~path_length:9 ~read_bytes:8\n\n (* Constructing proof arguments consists in a decreasing loop in the result\n monad, allocating at each step. We charge a reasonable overapproximation. *)\n let proof_argument n = atomic_step_cost (Z.mul (Z.of_int n) (Z.of_int 50))\n end\n\n module Unparsing = struct\n open Generated_costs_007\n\n let public_key_optimized =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_ENCODING_PUBLIC_KEY_ed25519\n (max\n cost_ENCODING_PUBLIC_KEY_secp256k1\n cost_ENCODING_PUBLIC_KEY_p256))\n\n let public_key_readable =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_B58CHECK_ENCODING_PUBLIC_KEY_ed25519\n (max\n cost_B58CHECK_ENCODING_PUBLIC_KEY_secp256k1\n cost_B58CHECK_ENCODING_PUBLIC_KEY_p256))\n\n let key_hash_optimized =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_ENCODING_PUBLIC_KEY_HASH_ed25519\n (max\n cost_ENCODING_PUBLIC_KEY_HASH_secp256k1\n cost_ENCODING_PUBLIC_KEY_HASH_p256))\n\n let key_hash_readable =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_ed25519\n (max\n cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_secp256k1\n cost_B58CHECK_ENCODING_PUBLIC_KEY_HASH_p256))\n\n let signature_optimized =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_ENCODING_SIGNATURE_ed25519\n (max\n cost_ENCODING_SIGNATURE_secp256k1\n cost_ENCODING_SIGNATURE_p256))\n\n let signature_readable =\n atomic_step_cost\n @@ Compare.Z.(\n max\n cost_B58CHECK_ENCODING_SIGNATURE_ed25519\n (max\n cost_B58CHECK_ENCODING_SIGNATURE_secp256k1\n cost_B58CHECK_ENCODING_SIGNATURE_p256))\n\n let chain_id_optimized = atomic_step_cost cost_ENCODING_CHAIN_ID\n\n let chain_id_readable = atomic_step_cost cost_B58CHECK_ENCODING_CHAIN_ID\n\n let timestamp_readable = atomic_step_cost cost_TIMESTAMP_READABLE_ENCODING\n\n (* Reasonable approximation *)\n let address_optimized = key_hash_optimized\n\n (* Reasonable approximation *)\n let contract_optimized = key_hash_optimized\n\n (* Reasonable approximation *)\n let contract_readable = key_hash_readable\n\n let bls12_381_g1 = atomic_step_cost cost_ENCODING_BLS_G1\n\n let bls12_381_g2 = atomic_step_cost cost_ENCODING_BLS_G2\n\n let bls12_381_fr = atomic_step_cost cost_ENCODING_BLS_FR\n\n let unparse_type_cycle = atomic_step_cost cost_UNPARSE_TYPE\n\n let unparse_instr_cycle = atomic_step_cost cost_UNPARSING_CODE\n\n let unparse_data_cycle = atomic_step_cost cost_UNPARSING_DATA\n\n let unit = Gas.free\n\n (* Reasonable estimate. *)\n let contract = Gas.(Z.of_int 2 *@ public_key_readable)\n\n (* Reuse 006 costs. *)\n let operation bytes = Script.bytes_node_cost bytes\n\n let sapling_transaction _t =\n (* TODO should it be scaled? *)\n (* let size = Data_encoding.Binary.length Sapling.transaction_encoding t in *)\n (* string_cost size *)\n Gas.free\n\n let sapling_diff _d =\n (* TODO should it be scaled? *)\n (* let size = Data_encoding.Binary.length Sapling.diff_encoding d in *)\n (* string_cost size *)\n Gas.free\n end\nend\n" ;
} ;
{ name = "Script_ir_annot" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Script_typed_ir\n\n(** Default annotations *)\n\nval default_now_annot : var_annot option\n\nval default_amount_annot : var_annot option\n\nval default_balance_annot : var_annot option\n\nval default_level_annot : var_annot option\n\nval default_steps_annot : var_annot option\n\nval default_source_annot : var_annot option\n\nval default_sender_annot : var_annot option\n\nval default_self_annot : var_annot option\n\nval default_arg_annot : var_annot option\n\nval default_param_annot : var_annot option\n\nval default_storage_annot : var_annot option\n\nval default_sapling_state_annot : var_annot option\n\nval default_sapling_balance_annot : var_annot option\n\nval default_car_annot : field_annot option\n\nval default_cdr_annot : field_annot option\n\nval default_contract_annot : field_annot option\n\nval default_addr_annot : field_annot option\n\nval default_manager_annot : field_annot option\n\nval default_pack_annot : field_annot option\n\nval default_unpack_annot : field_annot option\n\nval default_slice_annot : field_annot option\n\nval default_elt_annot : field_annot option\n\nval default_key_annot : field_annot option\n\nval default_hd_annot : field_annot option\n\nval default_tl_annot : field_annot option\n\nval default_some_annot : field_annot option\n\nval default_left_annot : field_annot option\n\nval default_right_annot : field_annot option\n\nval default_binding_annot : field_annot option\n\n(** Unparse annotations to their string representation *)\n\nval unparse_type_annot : type_annot option -> string list\n\nval unparse_var_annot : var_annot option -> string list\n\nval unparse_field_annot : field_annot option -> string list\n\n(** Conversion functions between different annotation kinds *)\n\nval field_to_var_annot : field_annot option -> var_annot option\n\nval type_to_var_annot : type_annot option -> var_annot option\n\nval var_to_field_annot : var_annot option -> field_annot option\n\n(** Replace an annotation by its default value if it is [None] *)\nval default_annot : default:'a option -> 'a option -> 'a option\n\n(** Generate annotation for field accesses, of the form [var.field1.field2] *)\nval gen_access_annot :\n var_annot option ->\n ?default:field_annot option ->\n field_annot option ->\n var_annot option\n\n(** Merge type annotations.\n @return an error {!Inconsistent_type_annotations} if they are both present\n and different, unless [legacy] *)\nval merge_type_annot :\n legacy:bool ->\n type_annot option ->\n type_annot option ->\n type_annot option tzresult\n\n(** Merge field annotations.\n @return an error {!Inconsistent_type_annotations} if they are both present\n and different, unless [legacy] *)\nval merge_field_annot :\n legacy:bool ->\n field_annot option ->\n field_annot option ->\n field_annot option tzresult\n\n(** Merge variable annotations, does not fail ([None] if different). *)\nval merge_var_annot : var_annot option -> var_annot option -> var_annot option\n\n(** @return an error {!Unexpected_annotation} in the monad the list is not empty. *)\nval error_unexpected_annot : int -> 'a list -> unit tzresult\n\n(** Parse a type annotation only. *)\nval parse_type_annot : int -> string list -> type_annot option tzresult\n\n(** Parse a field annotation only. *)\nval parse_field_annot : int -> string list -> field_annot option tzresult\n\n(** Parse an annotation for composed types, of the form\n [:ty_name %field] in any order. *)\nval parse_type_field_annot :\n int -> string list -> (type_annot option * field_annot option) tzresult\n\n(** Parse an annotation for composed types, of the form\n [:ty_name %field1 %field2] in any order. *)\nval parse_composed_type_annot :\n int ->\n string list ->\n (type_annot option * field_annot option * field_annot option) tzresult\n\n(** Extract and remove a field annotation from a node *)\nval extract_field_annot :\n Script.node -> (Script.node * field_annot option) tzresult\n\n(** Check that field annotations match, used for field accesses. *)\nval check_correct_field :\n field_annot option -> field_annot option -> unit tzresult\n\n(** Instruction annotations parsing *)\n\n(** Parse a variable annotation, replaced by a default value if [None]. *)\nval parse_var_annot :\n int -> ?default:var_annot option -> string list -> var_annot option tzresult\n\nval parse_constr_annot :\n int ->\n ?if_special_first:field_annot option ->\n ?if_special_second:field_annot option ->\n string list ->\n ( var_annot option\n * type_annot option\n * field_annot option\n * field_annot option )\n tzresult\n\nval parse_two_var_annot :\n int -> string list -> (var_annot option * var_annot option) tzresult\n\nval parse_destr_annot :\n int ->\n string list ->\n default_accessor:field_annot option ->\n field_name:field_annot option ->\n pair_annot:var_annot option ->\n value_annot:var_annot option ->\n (var_annot option * field_annot option) tzresult\n\nval parse_unpair_annot :\n int ->\n string list ->\n field_name_car:field_annot option ->\n field_name_cdr:field_annot option ->\n pair_annot:var_annot option ->\n value_annot_car:var_annot option ->\n value_annot_cdr:var_annot option ->\n ( var_annot option\n * var_annot option\n * field_annot option\n * field_annot option )\n tzresult\n\nval parse_entrypoint_annot :\n int ->\n ?default:var_annot option ->\n string list ->\n (var_annot option * field_annot option) tzresult\n\nval parse_var_type_annot :\n int -> string list -> (var_annot option * type_annot option) tzresult\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Micheline\nopen Script_tc_errors\nopen Script_typed_ir\n\nlet default_now_annot = Some (Var_annot \"now\")\n\nlet default_amount_annot = Some (Var_annot \"amount\")\n\nlet default_balance_annot = Some (Var_annot \"balance\")\n\nlet default_level_annot = Some (Var_annot \"level\")\n\nlet default_steps_annot = Some (Var_annot \"steps\")\n\nlet default_source_annot = Some (Var_annot \"source\")\n\nlet default_sender_annot = Some (Var_annot \"sender\")\n\nlet default_self_annot = Some (Var_annot \"self\")\n\nlet default_arg_annot = Some (Var_annot \"arg\")\n\nlet default_param_annot = Some (Var_annot \"parameter\")\n\nlet default_storage_annot = Some (Var_annot \"storage\")\n\nlet default_car_annot = Some (Field_annot \"car\")\n\nlet default_cdr_annot = Some (Field_annot \"cdr\")\n\nlet default_contract_annot = Some (Field_annot \"contract\")\n\nlet default_addr_annot = Some (Field_annot \"address\")\n\nlet default_manager_annot = Some (Field_annot \"manager\")\n\nlet default_pack_annot = Some (Field_annot \"packed\")\n\nlet default_unpack_annot = Some (Field_annot \"unpacked\")\n\nlet default_slice_annot = Some (Field_annot \"slice\")\n\nlet default_elt_annot = Some (Field_annot \"elt\")\n\nlet default_key_annot = Some (Field_annot \"key\")\n\nlet default_hd_annot = Some (Field_annot \"hd\")\n\nlet default_tl_annot = Some (Field_annot \"tl\")\n\nlet default_some_annot = Some (Field_annot \"some\")\n\nlet default_left_annot = Some (Field_annot \"left\")\n\nlet default_right_annot = Some (Field_annot \"right\")\n\nlet default_binding_annot = Some (Field_annot \"bnd\")\n\nlet default_sapling_state_annot = Some (Var_annot \"sapling\")\n\nlet default_sapling_balance_annot = Some (Var_annot \"sapling_balance\")\n\nlet unparse_type_annot : type_annot option -> string list = function\n | None ->\n []\n | Some (Type_annot a) ->\n [\":\" ^ a]\n\nlet unparse_var_annot : var_annot option -> string list = function\n | None ->\n []\n | Some (Var_annot a) ->\n [\"@\" ^ a]\n\nlet unparse_field_annot : field_annot option -> string list = function\n | None ->\n []\n | Some (Field_annot a) ->\n [\"%\" ^ a]\n\nlet field_to_var_annot : field_annot option -> var_annot option = function\n | None ->\n None\n | Some (Field_annot s) ->\n Some (Var_annot s)\n\nlet type_to_var_annot : type_annot option -> var_annot option = function\n | None ->\n None\n | Some (Type_annot s) ->\n Some (Var_annot s)\n\nlet var_to_field_annot : var_annot option -> field_annot option = function\n | None ->\n None\n | Some (Var_annot s) ->\n Some (Field_annot s)\n\nlet default_annot ~default = function None -> default | annot -> annot\n\nlet gen_access_annot :\n var_annot option ->\n ?default:field_annot option ->\n field_annot option ->\n var_annot option =\n fun value_annot ?(default = None) field_annot ->\n match (value_annot, field_annot, default) with\n | (None, None, _) | (Some _, None, None) | (None, Some (Field_annot \"\"), _)\n ->\n None\n | (None, Some (Field_annot f), _) ->\n Some (Var_annot f)\n | (Some (Var_annot v), (None | Some (Field_annot \"\")), Some (Field_annot f))\n ->\n Some (Var_annot (String.concat \".\" [v; f]))\n | (Some (Var_annot v), Some (Field_annot f), _) ->\n Some (Var_annot (String.concat \".\" [v; f]))\n\nlet merge_type_annot :\n legacy:bool ->\n type_annot option ->\n type_annot option ->\n type_annot option tzresult =\n fun ~legacy annot1 annot2 ->\n match (annot1, annot2) with\n | (None, None) | (Some _, None) | (None, Some _) ->\n ok_none\n | (Some (Type_annot a1), Some (Type_annot a2)) ->\n if legacy || String.equal a1 a2 then ok annot1\n else error (Inconsistent_annotations (\":\" ^ a1, \":\" ^ a2))\n\nlet merge_field_annot :\n legacy:bool ->\n field_annot option ->\n field_annot option ->\n field_annot option tzresult =\n fun ~legacy annot1 annot2 ->\n match (annot1, annot2) with\n | (None, None) | (Some _, None) | (None, Some _) ->\n ok_none\n | (Some (Field_annot a1), Some (Field_annot a2)) ->\n if legacy || String.equal a1 a2 then ok annot1\n else error (Inconsistent_annotations (\"%\" ^ a1, \"%\" ^ a2))\n\nlet merge_var_annot : var_annot option -> var_annot option -> var_annot option\n =\n fun annot1 annot2 ->\n match (annot1, annot2) with\n | (None, None) | (Some _, None) | (None, Some _) ->\n None\n | (Some (Var_annot a1), Some (Var_annot a2)) ->\n if String.equal a1 a2 then annot1 else None\n\nlet error_unexpected_annot loc annot =\n match annot with\n | [] ->\n ok_unit\n | _ :: _ ->\n error (Unexpected_annotation loc)\n\n(* Check that the predicate p holds on all s.[k] for k >= i *)\nlet string_iter p s i =\n let len = String.length s in\n let rec aux i =\n if Compare.Int.(i >= len) then ok_unit\n else p s.[i] >>? fun () -> aux (i + 1)\n in\n aux i\n\n(* Valid annotation characters as defined by the allowed_annot_char function from lib_micheline/micheline_parser *)\nlet check_char loc = function\n | 'a' .. 'z' | 'A' .. 'Z' | '_' | '.' | '%' | '@' | '0' .. '9' ->\n ok_unit\n | _ ->\n error (Unexpected_annotation loc)\n\n(* This constant is defined in lib_micheline/micheline_parser which is not available in the environment. *)\nlet max_annot_length = 255\n\ntype annot_opt =\n | Field_annot_opt of string option\n | Type_annot_opt of string option\n | Var_annot_opt of string option\n\nlet parse_annots loc ?(allow_special_var = false)\n ?(allow_special_field = false) l =\n (* allow empty annotations as wildcards but otherwise only accept\n annotations that start with [a-zA-Z_] *)\n let sub_or_wildcard ~specials wrap s acc =\n let mem_char c cs = List.exists (Char.equal c) cs in\n let len = String.length s in\n ( if Compare.Int.(len > max_annot_length) then\n error (Unexpected_annotation loc)\n else ok_unit )\n >>? fun () ->\n if Compare.Int.(len = 1) then ok @@ (wrap None :: acc)\n else\n match s.[1] with\n | 'a' .. 'z' | 'A' .. 'Z' | '_' | '0' .. '9' ->\n (* check that all characters are valid*)\n string_iter (check_char loc) s 2\n >>? fun () -> ok @@ (wrap (Some (String.sub s 1 (len - 1))) :: acc)\n | '@' when Compare.Int.(len = 2) && mem_char '@' specials ->\n ok @@ (wrap (Some \"@\") :: acc)\n | '%' when mem_char '%' specials ->\n if Compare.Int.(len = 2) then ok @@ (wrap (Some \"%\") :: acc)\n else if Compare.Int.(len = 3) && Compare.Char.(s.[2] = '%') then\n ok @@ (wrap (Some \"%%\") :: acc)\n else error (Unexpected_annotation loc)\n | _ ->\n error (Unexpected_annotation loc)\n in\n List.fold_left\n (fun acc s ->\n acc\n >>? fun acc ->\n if Compare.Int.(String.length s = 0) then\n error (Unexpected_annotation loc)\n else\n match s.[0] with\n | ':' ->\n sub_or_wildcard ~specials:[] (fun a -> Type_annot_opt a) s acc\n | '@' ->\n sub_or_wildcard\n ~specials:(if allow_special_var then ['%'] else [])\n (fun a -> Var_annot_opt a)\n s\n acc\n | '%' ->\n sub_or_wildcard\n ~specials:(if allow_special_field then ['@'] else [])\n (fun a -> Field_annot_opt a)\n s\n acc\n | _ ->\n error (Unexpected_annotation loc))\n ok_nil\n l\n >|? List.rev\n\nlet opt_var_of_var_opt = function None -> None | Some a -> Some (Var_annot a)\n\nlet opt_field_of_field_opt = function\n | None ->\n None\n | Some a ->\n Some (Field_annot a)\n\nlet opt_type_of_type_opt = function\n | None ->\n None\n | Some a ->\n Some (Type_annot a)\n\nlet classify_annot loc l :\n (var_annot option list * type_annot option list * field_annot option list)\n tzresult =\n try\n let (_, rv, _, rt, _, rf) =\n List.fold_left\n (fun (in_v, rv, in_t, rt, in_f, rf) a ->\n match (a, in_v, rv, in_t, rt, in_f, rf) with\n | (Var_annot_opt a, true, _, _, _, _, _)\n | (Var_annot_opt a, false, [], _, _, _, _) ->\n (true, opt_var_of_var_opt a :: rv, false, rt, false, rf)\n | (Type_annot_opt a, _, _, true, _, _, _)\n | (Type_annot_opt a, _, _, false, [], _, _) ->\n (false, rv, true, opt_type_of_type_opt a :: rt, false, rf)\n | (Field_annot_opt a, _, _, _, _, true, _)\n | (Field_annot_opt a, _, _, _, _, false, []) ->\n (false, rv, false, rt, true, opt_field_of_field_opt a :: rf)\n | _ ->\n raise Exit)\n (false, [], false, [], false, [])\n l\n in\n ok (List.rev rv, List.rev rt, List.rev rf)\n with Exit -> error (Ungrouped_annotations loc)\n\nlet get_one_annot loc = function\n | [] ->\n ok_none\n | [a] ->\n ok a\n | _ ->\n error (Unexpected_annotation loc)\n\nlet get_two_annot loc = function\n | [] ->\n ok (None, None)\n | [a] ->\n ok (a, None)\n | [a; b] ->\n ok (a, b)\n | _ ->\n error (Unexpected_annotation loc)\n\nlet parse_type_annot : int -> string list -> type_annot option tzresult =\n fun loc annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc vars\n >>? fun () ->\n error_unexpected_annot loc fields >>? fun () -> get_one_annot loc types\n\nlet parse_type_field_annot :\n int -> string list -> (type_annot option * field_annot option) tzresult =\n fun loc annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc vars\n >>? fun () ->\n get_one_annot loc types\n >>? fun t -> get_one_annot loc fields >|? fun f -> (t, f)\n\nlet parse_composed_type_annot :\n int ->\n string list ->\n (type_annot option * field_annot option * field_annot option) tzresult =\n fun loc annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc vars\n >>? fun () ->\n get_one_annot loc types\n >>? fun t -> get_two_annot loc fields >|? fun (f1, f2) -> (t, f1, f2)\n\nlet parse_field_annot : int -> string list -> field_annot option tzresult =\n fun loc annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc vars\n >>? fun () ->\n error_unexpected_annot loc types >>? fun () -> get_one_annot loc fields\n\nlet extract_field_annot :\n Script.node -> (Script.node * field_annot option) tzresult = function\n | Prim (loc, prim, args, annot) ->\n let rec extract_first acc = function\n | [] ->\n (None, annot)\n | s :: rest ->\n if Compare.Int.(String.length s > 0) && Compare.Char.(s.[0] = '%')\n then (Some s, List.rev_append acc rest)\n else extract_first (s :: acc) rest\n in\n let (field_annot, annot) = extract_first [] annot in\n ( match field_annot with\n | None ->\n ok_none\n | Some field_annot ->\n parse_field_annot loc [field_annot] )\n >|? fun field_annot -> (Prim (loc, prim, args, annot), field_annot)\n | expr ->\n ok (expr, None)\n\nlet check_correct_field :\n field_annot option -> field_annot option -> unit tzresult =\n fun f1 f2 ->\n match (f1, f2) with\n | (None, _) | (_, None) ->\n ok_unit\n | (Some (Field_annot s1), Some (Field_annot s2)) ->\n if String.equal s1 s2 then ok_unit\n else error (Inconsistent_field_annotations (\"%\" ^ s1, \"%\" ^ s2))\n\nlet parse_var_annot :\n int ->\n ?default:var_annot option ->\n string list ->\n var_annot option tzresult =\n fun loc ?default annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc types\n >>? fun () ->\n error_unexpected_annot loc fields\n >>? fun () ->\n get_one_annot loc vars\n >|? function\n | Some _ as a ->\n a\n | None -> (\n match default with Some a -> a | None -> None )\n\nlet split_last_dot = function\n | None ->\n (None, None)\n | Some (Field_annot s) -> (\n match String.rindex_opt s '.' with\n | None ->\n (None, Some (Field_annot s))\n | Some i ->\n let s1 = String.sub s 0 i in\n let s2 = String.sub s (i + 1) (String.length s - i - 1) in\n let f =\n if Compare.String.equal s2 \"car\" || Compare.String.equal s2 \"cdr\"\n then None\n else Some (Field_annot s2)\n in\n (Some (Var_annot s1), f) )\n\nlet common_prefix v1 v2 =\n match (v1, v2) with\n | (Some (Var_annot s1), Some (Var_annot s2)) when Compare.String.equal s1 s2\n ->\n v1\n | (Some _, None) ->\n v1\n | (None, Some _) ->\n v2\n | (_, _) ->\n None\n\nlet parse_constr_annot :\n int ->\n ?if_special_first:field_annot option ->\n ?if_special_second:field_annot option ->\n string list ->\n ( var_annot option\n * type_annot option\n * field_annot option\n * field_annot option )\n tzresult =\n fun loc ?if_special_first ?if_special_second annot ->\n parse_annots ~allow_special_field:true loc annot\n >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n get_one_annot loc vars\n >>? fun v ->\n get_one_annot loc types\n >>? fun t ->\n get_two_annot loc fields\n >>? fun (f1, f2) ->\n ( match (if_special_first, f1) with\n | (Some special_var, Some (Field_annot \"@\")) ->\n ok (split_last_dot special_var)\n | (None, Some (Field_annot \"@\")) ->\n error (Unexpected_annotation loc)\n | (_, _) ->\n ok (v, f1) )\n >>? fun (v1, f1) ->\n ( match (if_special_second, f2) with\n | (Some special_var, Some (Field_annot \"@\")) ->\n ok (split_last_dot special_var)\n | (None, Some (Field_annot \"@\")) ->\n error (Unexpected_annotation loc)\n | (_, _) ->\n ok (v, f2) )\n >|? fun (v2, f2) ->\n let v = match v with None -> common_prefix v1 v2 | Some _ -> v in\n (v, t, f1, f2)\n\nlet parse_two_var_annot :\n int -> string list -> (var_annot option * var_annot option) tzresult =\n fun loc annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc types\n >>? fun () ->\n error_unexpected_annot loc fields >>? fun () -> get_two_annot loc vars\n\nlet var_annot_from_special :\n field_name:field_annot option ->\n default:var_annot option ->\n value_annot:var_annot option ->\n var_annot option ->\n var_annot option =\n fun ~field_name ~default ~value_annot v ->\n match v with\n | Some (Var_annot \"%\") ->\n field_to_var_annot field_name\n | Some (Var_annot \"%%\") ->\n default\n | Some _ ->\n v\n | None ->\n value_annot\n\nlet parse_destr_annot :\n int ->\n string list ->\n default_accessor:field_annot option ->\n field_name:field_annot option ->\n pair_annot:var_annot option ->\n value_annot:var_annot option ->\n (var_annot option * field_annot option) tzresult =\n fun loc annot ~default_accessor ~field_name ~pair_annot ~value_annot ->\n parse_annots loc ~allow_special_var:true annot\n >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc types\n >>? fun () ->\n get_one_annot loc vars\n >>? fun v ->\n get_one_annot loc fields\n >|? fun f ->\n let default =\n gen_access_annot pair_annot field_name ~default:default_accessor\n in\n let v = var_annot_from_special ~field_name ~default ~value_annot v in\n (v, f)\n\nlet parse_unpair_annot :\n int ->\n string list ->\n field_name_car:field_annot option ->\n field_name_cdr:field_annot option ->\n pair_annot:var_annot option ->\n value_annot_car:var_annot option ->\n value_annot_cdr:var_annot option ->\n ( var_annot option\n * var_annot option\n * field_annot option\n * field_annot option )\n tzresult =\n fun loc\n annot\n ~field_name_car\n ~field_name_cdr\n ~pair_annot\n ~value_annot_car\n ~value_annot_cdr ->\n parse_annots loc ~allow_special_var:true annot\n >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc types\n >>? fun () ->\n get_two_annot loc vars\n >>? fun (vcar, vcdr) ->\n get_two_annot loc fields\n >|? fun (fcar, fcdr) ->\n let default_car =\n gen_access_annot pair_annot field_name_car ~default:default_car_annot\n in\n let default_cdr =\n gen_access_annot pair_annot field_name_cdr ~default:default_cdr_annot\n in\n let vcar =\n var_annot_from_special\n ~field_name:field_name_car\n ~default:default_car\n ~value_annot:value_annot_car\n vcar\n in\n let vcdr =\n var_annot_from_special\n ~field_name:field_name_cdr\n ~default:default_cdr\n ~value_annot:value_annot_cdr\n vcdr\n in\n (vcar, vcdr, fcar, fcdr)\n\nlet parse_entrypoint_annot :\n int ->\n ?default:var_annot option ->\n string list ->\n (var_annot option * field_annot option) tzresult =\n fun loc ?default annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc types\n >>? fun () ->\n get_one_annot loc fields\n >>? fun f ->\n get_one_annot loc vars\n >|? function\n | Some _ as a ->\n (a, f)\n | None -> (\n match default with Some a -> (a, f) | None -> (None, f) )\n\nlet parse_var_type_annot :\n int -> string list -> (var_annot option * type_annot option) tzresult =\n fun loc annot ->\n parse_annots loc annot >>? classify_annot loc\n >>? fun (vars, types, fields) ->\n error_unexpected_annot loc fields\n >>? fun () ->\n get_one_annot loc vars\n >>? fun v -> get_one_annot loc types >|? fun t -> (v, t)\n" ;
} ;
{ name = "Script_ir_translator" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Script_tc_errors\n\ntype ('ta, 'tb) eq = Eq : ('same, 'same) eq\n\ntype ex_comparable_ty =\n | Ex_comparable_ty : 'a Script_typed_ir.comparable_ty -> ex_comparable_ty\n\ntype ex_ty = Ex_ty : 'a Script_typed_ir.ty -> ex_ty\n\ntype ex_stack_ty = Ex_stack_ty : 'a Script_typed_ir.stack_ty -> ex_stack_ty\n\ntype ex_script = Ex_script : ('a, 'b) Script_typed_ir.script -> ex_script\n\ntype ('arg, 'storage) code = {\n code :\n ( ('arg, 'storage) Script_typed_ir.pair,\n ( Script_typed_ir.operation Script_typed_ir.boxed_list,\n 'storage )\n Script_typed_ir.pair )\n Script_typed_ir.lambda;\n arg_type : 'arg Script_typed_ir.ty;\n storage_type : 'storage Script_typed_ir.ty;\n root_name : Script_typed_ir.field_annot option;\n}\n\ntype ex_code = Ex_code : ('a, 'c) code -> ex_code\n\ntype tc_context =\n | Lambda : tc_context\n | Dip : 'a Script_typed_ir.stack_ty * tc_context -> tc_context\n | Toplevel : {\n storage_type : 'sto Script_typed_ir.ty;\n param_type : 'param Script_typed_ir.ty;\n root_name : Script_typed_ir.field_annot option;\n legacy_create_contract_literal : bool;\n }\n -> tc_context\n\ntype 'bef judgement =\n | Typed : ('bef, 'aft) Script_typed_ir.descr -> 'bef judgement\n | Failed : {\n descr :\n 'aft. 'aft Script_typed_ir.stack_ty ->\n ('bef, 'aft) Script_typed_ir.descr;\n }\n -> 'bef judgement\n\ntype unparsing_mode = Optimized | Readable | Optimized_legacy\n\ntype type_logger =\n int ->\n (Script.expr * Script.annot) list ->\n (Script.expr * Script.annot) list ->\n unit\n\n(* ---- Lists, Sets and Maps ----------------------------------------------- *)\n\nval list_empty : 'a Script_typed_ir.boxed_list\n\nval list_cons :\n 'a -> 'a Script_typed_ir.boxed_list -> 'a Script_typed_ir.boxed_list\n\nval empty_set : 'a Script_typed_ir.comparable_ty -> 'a Script_typed_ir.set\n\nval set_fold :\n ('elt -> 'acc -> 'acc) -> 'elt Script_typed_ir.set -> 'acc -> 'acc\n\nval set_update : 'a -> bool -> 'a Script_typed_ir.set -> 'a Script_typed_ir.set\n\nval set_mem : 'elt -> 'elt Script_typed_ir.set -> bool\n\nval set_size : 'elt Script_typed_ir.set -> Script_int.n Script_int.num\n\nval empty_map :\n 'a Script_typed_ir.comparable_ty -> ('a, 'b) Script_typed_ir.map\n\nval map_fold :\n ('key -> 'value -> 'acc -> 'acc) ->\n ('key, 'value) Script_typed_ir.map ->\n 'acc ->\n 'acc\n\nval map_update :\n 'a ->\n 'b option ->\n ('a, 'b) Script_typed_ir.map ->\n ('a, 'b) Script_typed_ir.map\n\nval map_mem : 'key -> ('key, 'value) Script_typed_ir.map -> bool\n\nval map_get : 'key -> ('key, 'value) Script_typed_ir.map -> 'value option\n\nval map_key_ty :\n ('a, 'b) Script_typed_ir.map -> 'a Script_typed_ir.comparable_ty\n\nval map_size : ('a, 'b) Script_typed_ir.map -> Script_int.n Script_int.num\n\nval empty_big_map :\n 'a Script_typed_ir.comparable_ty ->\n 'b Script_typed_ir.ty ->\n ('a, 'b) Script_typed_ir.big_map\n\nval big_map_mem :\n context ->\n 'key ->\n ('key, 'value) Script_typed_ir.big_map ->\n (bool * context) tzresult Lwt.t\n\nval big_map_get :\n context ->\n 'key ->\n ('key, 'value) Script_typed_ir.big_map ->\n ('value option * context) tzresult Lwt.t\n\nval big_map_update :\n 'key ->\n 'value option ->\n ('key, 'value) Script_typed_ir.big_map ->\n ('key, 'value) Script_typed_ir.big_map\n\nval ty_eq :\n context ->\n Script.location ->\n 'ta Script_typed_ir.ty ->\n 'tb Script_typed_ir.ty ->\n (('ta Script_typed_ir.ty, 'tb Script_typed_ir.ty) eq * context) tzresult\n\nval compare_address : Script_typed_ir.address -> Script_typed_ir.address -> int\n\nval compare_comparable : 'a Script_typed_ir.comparable_ty -> 'a -> 'a -> int\n\nval parse_comparable_data :\n ?type_logger:type_logger ->\n context ->\n 'a Script_typed_ir.comparable_ty ->\n Script.node ->\n ('a * context) tzresult Lwt.t\n\nval parse_data :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n allow_forged:bool ->\n 'a Script_typed_ir.ty ->\n Script.node ->\n ('a * context) tzresult Lwt.t\n\nval unparse_data :\n context ->\n unparsing_mode ->\n 'a Script_typed_ir.ty ->\n 'a ->\n (Script.node * context) tzresult Lwt.t\n\nval unparse_code :\n context ->\n unparsing_mode ->\n Script.node ->\n (Script.node * context) tzresult Lwt.t\n\nval parse_instr :\n ?type_logger:type_logger ->\n tc_context ->\n context ->\n legacy:bool ->\n Script.node ->\n 'bef Script_typed_ir.stack_ty ->\n ('bef judgement * context) tzresult Lwt.t\n\n(**\n [parse_ty] specialized for the right-hand side part of a big map type, i.e.\n the `value` in `big_map key value`.\n*)\nval parse_big_map_value_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult\n\nval parse_packable_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult\n\nval parse_parameter_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult\n\nval parse_comparable_ty :\n context -> Script.node -> (ex_comparable_ty * context) tzresult\n\n(** We expose [parse_ty] for convenience to external tools. Please use\n specialized versions such as [parse_packable_ty], [parse_parameter_ty],\n [parse_comparable_ty], or [parse_big_map_value_ty] if possible. *)\nval parse_ty :\n context ->\n legacy:bool ->\n allow_lazy_storage:bool ->\n allow_operation:bool ->\n allow_contract:bool ->\n allow_ticket:bool ->\n Script.node ->\n (ex_ty * context) tzresult\n\nval unparse_ty :\n context -> 'a Script_typed_ir.ty -> (Script.node * context) tzresult\n\nval parse_toplevel :\n legacy:bool ->\n Script.expr ->\n (Script.node * Script.node * Script.node * Script_typed_ir.field_annot option)\n tzresult\n\nval add_field_annot :\n Script_typed_ir.field_annot option ->\n Script_typed_ir.var_annot option ->\n Script.node ->\n Script.node\n\nval typecheck_code :\n legacy:bool -> context -> Script.expr -> (type_map * context) tzresult Lwt.t\n\nval serialize_ty_for_error :\n context -> 'a Script_typed_ir.ty -> (Script.expr * context) tzresult\n\nval parse_code :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n code:Script.lazy_expr ->\n (ex_code * context) tzresult Lwt.t\n\nval parse_storage :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n allow_forged:bool ->\n 'storage Script_typed_ir.ty ->\n storage:Script.lazy_expr ->\n ('storage * context) tzresult Lwt.t\n\n(** Combines [parse_code] and [parse_storage] *)\nval parse_script :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n allow_forged_in_storage:bool ->\n Script.t ->\n (ex_script * context) tzresult Lwt.t\n\n(* Gas accounting may not be perfect in this function, as it is only called by RPCs. *)\nval unparse_script :\n context ->\n unparsing_mode ->\n ('a, 'b) Script_typed_ir.script ->\n (Script.t * context) tzresult Lwt.t\n\nval parse_contract :\n legacy:bool ->\n context ->\n Script.location ->\n 'a Script_typed_ir.ty ->\n Contract.t ->\n entrypoint:string ->\n (context * 'a Script_typed_ir.typed_contract) tzresult Lwt.t\n\nval parse_contract_for_script :\n legacy:bool ->\n context ->\n Script.location ->\n 'a Script_typed_ir.ty ->\n Contract.t ->\n entrypoint:string ->\n (context * 'a Script_typed_ir.typed_contract option) tzresult Lwt.t\n\nval find_entrypoint :\n 't Script_typed_ir.ty ->\n root_name:Script_typed_ir.field_annot option ->\n string ->\n ((Script.node -> Script.node) * ex_ty) tzresult\n\nmodule Entrypoints_map : S.MAP with type key = string\n\nval list_entrypoints :\n 't Script_typed_ir.ty ->\n context ->\n root_name:Script_typed_ir.field_annot option ->\n ( Michelson_v1_primitives.prim list list\n * (Michelson_v1_primitives.prim list * Script.node) Entrypoints_map.t )\n tzresult\n\nval pack_data :\n context -> 'a Script_typed_ir.ty -> 'a -> (bytes * context) tzresult Lwt.t\n\nval hash_comparable_data :\n context ->\n 'a Script_typed_ir.comparable_ty ->\n 'a ->\n (Script_expr_hash.t * context) tzresult Lwt.t\n\nval hash_data :\n context ->\n 'a Script_typed_ir.ty ->\n 'a ->\n (Script_expr_hash.t * context) tzresult Lwt.t\n\ntype lazy_storage_ids\n\nval no_lazy_storage_id : lazy_storage_ids\n\nval collect_lazy_storage :\n context ->\n 'a Script_typed_ir.ty ->\n 'a ->\n (lazy_storage_ids * context) tzresult\n\nval list_of_big_map_ids : lazy_storage_ids -> Big_map.Id.t list\n\nval extract_lazy_storage_diff :\n context ->\n unparsing_mode ->\n temporary:bool ->\n to_duplicate:lazy_storage_ids ->\n to_update:lazy_storage_ids ->\n 'a Script_typed_ir.ty ->\n 'a ->\n ('a * Lazy_storage.diffs option * context) tzresult Lwt.t\n\n(* raise Not_found if none or more than one found *)\nval get_single_sapling_state :\n context -> 'a Script_typed_ir.ty -> 'a -> (Sapling.Id.t * context) tzresult\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Micheline\nopen Script\nopen Script_typed_ir\nopen Script_tc_errors\nopen Script_ir_annot\nmodule Typecheck_costs = Michelson_v1_gas.Cost_of.Typechecking\nmodule Unparse_costs = Michelson_v1_gas.Cost_of.Unparsing\n\ntype ex_comparable_ty =\n | Ex_comparable_ty : 'a comparable_ty -> ex_comparable_ty\n\ntype ex_ty = Ex_ty : 'a ty -> ex_ty\n\ntype ex_stack_ty = Ex_stack_ty : 'a stack_ty -> ex_stack_ty\n\ntype tc_context =\n | Lambda : tc_context\n | Dip : 'a stack_ty * tc_context -> tc_context\n | Toplevel : {\n storage_type : 'sto ty;\n param_type : 'param ty;\n root_name : field_annot option;\n legacy_create_contract_literal : bool;\n }\n -> tc_context\n\ntype unparsing_mode = Optimized | Readable | Optimized_legacy\n\ntype type_logger =\n int ->\n (Script.expr * Script.annot) list ->\n (Script.expr * Script.annot) list ->\n unit\n\nlet add_dip ty annot prev =\n match prev with\n | Lambda | Toplevel _ ->\n Dip (Item_t (ty, Empty_t, annot), prev)\n | Dip (stack, _) ->\n Dip (Item_t (ty, stack, annot), prev)\n\n(* ---- Type size accounting ------------------------------------------------*)\n\nlet rec comparable_type_size : type t. t comparable_ty -> int =\n fun ty ->\n (* No wildcard to force the update when comparable_ty changes. *)\n match ty with\n | Unit_key _ ->\n 1\n | Never_key _ ->\n 1\n | Int_key _ ->\n 1\n | Nat_key _ ->\n 1\n | Signature_key _ ->\n 1\n | String_key _ ->\n 1\n | Bytes_key _ ->\n 1\n | Mutez_key _ ->\n 1\n | Bool_key _ ->\n 1\n | Key_hash_key _ ->\n 1\n | Key_key _ ->\n 1\n | Timestamp_key _ ->\n 1\n | Chain_id_key _ ->\n 1\n | Address_key _ ->\n 1\n | Pair_key ((t1, _), (t2, _), _) ->\n 1 + comparable_type_size t1 + comparable_type_size t2\n | Union_key ((t1, _), (t2, _), _) ->\n 1 + comparable_type_size t1 + comparable_type_size t2\n | Option_key (t, _) ->\n 1 + comparable_type_size t\n\nlet rec type_size : type t. t ty -> int =\n fun ty ->\n match ty with\n | Unit_t _ ->\n 1\n | Int_t _ ->\n 1\n | Nat_t _ ->\n 1\n | Signature_t _ ->\n 1\n | Bytes_t _ ->\n 1\n | String_t _ ->\n 1\n | Mutez_t _ ->\n 1\n | Key_hash_t _ ->\n 1\n | Key_t _ ->\n 1\n | Timestamp_t _ ->\n 1\n | Address_t _ ->\n 1\n | Bool_t _ ->\n 1\n | Operation_t _ ->\n 1\n | Chain_id_t _ ->\n 1\n | Never_t _ ->\n 1\n | Bls12_381_g1_t _ ->\n 1\n | Bls12_381_g2_t _ ->\n 1\n | Bls12_381_fr_t _ ->\n 1\n | Sapling_transaction_t _ ->\n 1\n | Sapling_state_t _ ->\n 1\n | Pair_t ((l, _, _), (r, _, _), _) ->\n 1 + type_size l + type_size r\n | Union_t ((l, _), (r, _), _) ->\n 1 + type_size l + type_size r\n | Lambda_t (arg, ret, _) ->\n 1 + type_size arg + type_size ret\n | Option_t (t, _) ->\n 1 + type_size t\n | List_t (t, _) ->\n 1 + type_size t\n | Ticket_t (t, _) ->\n 1 + comparable_type_size t\n | Set_t (k, _) ->\n 1 + comparable_type_size k\n | Map_t (k, v, _) ->\n 1 + comparable_type_size k + type_size v\n | Big_map_t (k, v, _) ->\n 1 + comparable_type_size k + type_size v\n | Contract_t (arg, _) ->\n 1 + type_size arg\n\nlet rec type_size_of_stack_head : type st. st stack_ty -> up_to:int -> int =\n fun stack ~up_to ->\n match stack with\n | Empty_t ->\n 0\n | Item_t (head, tail, _annot) ->\n if Compare.Int.(up_to > 0) then\n Compare.Int.max\n (type_size head)\n (type_size_of_stack_head tail ~up_to:(up_to - 1))\n else 0\n\n(* This is the depth of the stack to inspect for sizes overflow. We\n only need to check the produced types that can be larger than the\n arguments. That's why Swap is 0 for instance as no type grows.\n Constant sized types are not checked: it is assumed they are lower\n than the bound (otherwise every program would be rejected).\n\n In a [(b, a) instr], it is the number of types in [a] that may exceed the\n limit, knowing that types in [b] don't.\n If the instr is parameterized by [(b', a') descr] then you may assume that\n types in [a'] don't exceed the limit.\n*)\nlet number_of_generated_growing_types : type b a. (b, a) instr -> int =\n function\n (* Constructors *)\n | Const _ ->\n 1\n | Cons_pair ->\n 1\n | Cons_some ->\n 1\n | Cons_none _ ->\n 1\n | Cons_left ->\n 1\n | Cons_right ->\n 1\n | Nil ->\n 1\n | Empty_set _ ->\n 1\n | Empty_map _ ->\n 1\n | Empty_big_map _ ->\n 1\n | Lambda _ ->\n 1\n | Self _ ->\n 1\n | Contract _ ->\n 1\n | Ticket ->\n 1\n | Read_ticket ->\n (* `pair address (pair T nat)` is bigger than `ticket T` *)\n 1\n | Split_ticket ->\n 1\n (* Magic constructor *)\n | Unpack _ ->\n 1\n (* Mappings *)\n | List_map _ ->\n 1\n | Map_map _ ->\n 1\n (* Others:\n - don't add types\n - don't change types\n - decrease type sizes\n - produce only constants\n - have types bounded by parameters\n - etc. *)\n | Drop ->\n 0\n | Dup ->\n 0\n | Swap ->\n 0\n | Unpair ->\n 0\n | Car ->\n 0\n | Cdr ->\n 0\n | If_none _ ->\n 0\n | If_left _ ->\n 0\n | Cons_list ->\n 0\n | If_cons _ ->\n 0\n | List_size ->\n 0\n | List_iter _ ->\n 0\n | Set_iter _ ->\n 0\n | Set_mem ->\n 0\n | Set_update ->\n 0\n | Set_size ->\n 0\n | Map_iter _ ->\n 0\n | Map_mem ->\n 0\n | Map_get ->\n 0\n | Map_update ->\n 0\n | Map_get_and_update ->\n 0\n | Map_size ->\n 0\n | Big_map_get ->\n 0\n | Big_map_update ->\n 0\n | Big_map_get_and_update ->\n 0\n | Big_map_mem ->\n 0\n | Concat_string ->\n 0\n | Concat_string_pair ->\n 0\n | Slice_string ->\n 0\n | String_size ->\n 0\n | Concat_bytes ->\n 0\n | Concat_bytes_pair ->\n 0\n | Slice_bytes ->\n 0\n | Bytes_size ->\n 0\n | Add_seconds_to_timestamp ->\n 0\n | Add_timestamp_to_seconds ->\n 0\n | Sub_timestamp_seconds ->\n 0\n | Diff_timestamps ->\n 0\n | Add_tez ->\n 0\n | Sub_tez ->\n 0\n | Mul_teznat ->\n 0\n | Mul_nattez ->\n 0\n | Ediv_teznat ->\n 0\n | Ediv_tez ->\n 0\n | Or ->\n 0\n | And ->\n 0\n | Xor ->\n 0\n | Not ->\n 0\n | Is_nat ->\n 0\n | Neg_nat ->\n 0\n | Neg_int ->\n 0\n | Abs_int ->\n 0\n | Int_nat ->\n 0\n | Add_intint ->\n 0\n | Add_intnat ->\n 0\n | Add_natint ->\n 0\n | Add_natnat ->\n 0\n | Sub_int ->\n 0\n | Mul_intint ->\n 0\n | Mul_intnat ->\n 0\n | Mul_natint ->\n 0\n | Mul_natnat ->\n 0\n | Ediv_intint ->\n 0\n | Ediv_intnat ->\n 0\n | Ediv_natint ->\n 0\n | Ediv_natnat ->\n 0\n | Lsl_nat ->\n 0\n | Lsr_nat ->\n 0\n | Or_nat ->\n 0\n | And_nat ->\n 0\n | And_int_nat ->\n 0\n | Xor_nat ->\n 0\n | Not_nat ->\n 0\n | Not_int ->\n 0\n | Seq _ ->\n 0\n | If _ ->\n 0\n | Loop _ ->\n 0\n | Loop_left _ ->\n 0\n | Dip _ ->\n 0\n | Exec ->\n 0\n | Apply _ ->\n 0\n | Failwith _ ->\n 0\n | Nop ->\n 0\n | Compare _ ->\n 0\n | Eq ->\n 0\n | Neq ->\n 0\n | Lt ->\n 0\n | Gt ->\n 0\n | Le ->\n 0\n | Ge ->\n 0\n | Address ->\n 0\n | Transfer_tokens ->\n 0\n | Implicit_account ->\n 0\n | Create_contract _ ->\n 0\n | Now ->\n 0\n | Level ->\n 0\n | Balance ->\n 0\n | Check_signature ->\n 0\n | Hash_key ->\n 0\n | Blake2b ->\n 0\n | Sha256 ->\n 0\n | Sha512 ->\n 0\n | Source ->\n 0\n | Sender ->\n 0\n | Amount ->\n 0\n | Self_address ->\n 0\n | Sapling_empty_state _ ->\n 0\n | Sapling_verify_update ->\n 0\n | Set_delegate ->\n 0\n | Pack _ ->\n 0\n | Dig _ ->\n 0\n | Dug _ ->\n 0\n | Dipn _ ->\n 0\n | Dropn _ ->\n 0\n | ChainId ->\n 0\n | Never ->\n 0\n | Voting_power ->\n 0\n | Total_voting_power ->\n 0\n | Keccak ->\n 0\n | Sha3 ->\n 0\n | Add_bls12_381_g1 ->\n 0\n | Add_bls12_381_g2 ->\n 0\n | Add_bls12_381_fr ->\n 0\n | Mul_bls12_381_g1 ->\n 0\n | Mul_bls12_381_g2 ->\n 0\n | Mul_bls12_381_fr ->\n 0\n | Mul_bls12_381_fr_z ->\n 0\n | Mul_bls12_381_z_fr ->\n 0\n | Int_bls12_381_fr ->\n 0\n | Neg_bls12_381_g1 ->\n 0\n | Neg_bls12_381_g2 ->\n 0\n | Neg_bls12_381_fr ->\n 0\n | Pairing_check_bls12_381 ->\n 0\n | Uncomb _ ->\n 0\n | Comb_get _ ->\n 0\n | Comb _ ->\n 1\n | Comb_set _ ->\n 1\n | Dup_n _ ->\n 0\n | Join_tickets _ ->\n 0\n\n(* ---- Error helpers -------------------------------------------------------*)\n\nlet location = function\n | Prim (loc, _, _, _)\n | Int (loc, _)\n | String (loc, _)\n | Bytes (loc, _)\n | Seq (loc, _) ->\n loc\n\nlet kind_equal a b =\n match (a, b) with\n | (Int_kind, Int_kind)\n | (String_kind, String_kind)\n | (Bytes_kind, Bytes_kind)\n | (Prim_kind, Prim_kind)\n | (Seq_kind, Seq_kind) ->\n true\n | _ ->\n false\n\nlet kind = function\n | Int _ ->\n Int_kind\n | String _ ->\n String_kind\n | Bytes _ ->\n Bytes_kind\n | Prim _ ->\n Prim_kind\n | Seq _ ->\n Seq_kind\n\nlet unexpected expr exp_kinds exp_ns exp_prims =\n match expr with\n | Int (loc, _) ->\n Invalid_kind (loc, Prim_kind :: exp_kinds, Int_kind)\n | String (loc, _) ->\n Invalid_kind (loc, Prim_kind :: exp_kinds, String_kind)\n | Bytes (loc, _) ->\n Invalid_kind (loc, Prim_kind :: exp_kinds, Bytes_kind)\n | Seq (loc, _) ->\n Invalid_kind (loc, Prim_kind :: exp_kinds, Seq_kind)\n | Prim (loc, name, _, _) -> (\n let open Michelson_v1_primitives in\n match (namespace name, exp_ns) with\n | (Type_namespace, Type_namespace)\n | (Instr_namespace, Instr_namespace)\n | (Constant_namespace, Constant_namespace) ->\n Invalid_primitive (loc, exp_prims, name)\n | (ns, _) ->\n Invalid_namespace (loc, name, exp_ns, ns) )\n\nlet check_kind kinds expr =\n let kind = kind expr in\n if List.exists (kind_equal kind) kinds then ok_unit\n else\n let loc = location expr in\n error (Invalid_kind (loc, kinds, kind))\n\n(* ---- Lists, Sets and Maps ----------------------------------------------- *)\n\nlet list_empty : 'a Script_typed_ir.boxed_list =\n let open Script_typed_ir in\n {elements = []; length = 0}\n\nlet list_cons :\n 'a -> 'a Script_typed_ir.boxed_list -> 'a Script_typed_ir.boxed_list =\n fun elt l ->\n let open Script_typed_ir in\n {length = 1 + l.length; elements = elt :: l.elements}\n\nlet wrap_compare compare a b =\n let res = compare a b in\n if Compare.Int.(res = 0) then 0 else if Compare.Int.(res > 0) then 1 else -1\n\nlet compare_address (x, ex) (y, ey) =\n let lres = Contract.compare x y in\n if Compare.Int.(lres = 0) then Compare.String.compare ex ey else lres\n\nlet rec compare_comparable : type a. a comparable_ty -> a -> a -> int =\n fun kind ->\n match kind with\n | Unit_key _ ->\n fun () () -> 0\n | Never_key _ -> (\n function _ -> . )\n | Signature_key _ ->\n wrap_compare Signature.compare\n | String_key _ ->\n wrap_compare Compare.String.compare\n | Bool_key _ ->\n wrap_compare Compare.Bool.compare\n | Mutez_key _ ->\n wrap_compare Tez.compare\n | Key_hash_key _ ->\n wrap_compare Signature.Public_key_hash.compare\n | Key_key _ ->\n wrap_compare Signature.Public_key.compare\n | Int_key _ ->\n wrap_compare Script_int.compare\n | Nat_key _ ->\n wrap_compare Script_int.compare\n | Timestamp_key _ ->\n wrap_compare Script_timestamp.compare\n | Address_key _ ->\n wrap_compare compare_address\n | Bytes_key _ ->\n wrap_compare Compare.Bytes.compare\n | Chain_id_key _ ->\n wrap_compare Chain_id.compare\n | Pair_key ((tl, _), (tr, _), _) ->\n fun (lx, rx) (ly, ry) ->\n let lres = compare_comparable tl lx ly in\n if Compare.Int.(lres = 0) then compare_comparable tr rx ry else lres\n | Union_key ((tl, _), (tr, _), _) -> (\n fun x y ->\n match (x, y) with\n | (L x, L y) ->\n compare_comparable tl x y\n | (L _, R _) ->\n -1\n | (R _, L _) ->\n 1\n | (R x, R y) ->\n compare_comparable tr x y )\n | Option_key (t, _) -> (\n fun x y ->\n match (x, y) with\n | (None, None) ->\n 0\n | (None, Some _) ->\n -1\n | (Some _, None) ->\n 1\n | (Some x, Some y) ->\n compare_comparable t x y )\n\nlet empty_set : type a. a comparable_ty -> a set =\n fun ty ->\n let module OPS = Set.Make (struct\n type t = a\n\n let compare = compare_comparable ty\n end) in\n ( module struct\n type elt = a\n\n let elt_ty = ty\n\n module OPS = OPS\n\n let boxed = OPS.empty\n\n let size = 0\n end )\n\nlet set_update : type a. a -> bool -> a set -> a set =\n fun v b (module Box) ->\n ( module struct\n type elt = a\n\n let elt_ty = Box.elt_ty\n\n module OPS = Box.OPS\n\n let boxed =\n if b then Box.OPS.add v Box.boxed else Box.OPS.remove v Box.boxed\n\n let size =\n let mem = Box.OPS.mem v Box.boxed in\n if mem then if b then Box.size else Box.size - 1\n else if b then Box.size + 1\n else Box.size\n end )\n\nlet set_mem : type elt. elt -> elt set -> bool =\n fun v (module Box) -> Box.OPS.mem v Box.boxed\n\nlet set_fold : type elt acc. (elt -> acc -> acc) -> elt set -> acc -> acc =\n fun f (module Box) -> Box.OPS.fold f Box.boxed\n\nlet set_size : type elt. elt set -> Script_int.n Script_int.num =\n fun (module Box) -> Script_int.(abs (of_int Box.size))\n\nlet map_key_ty : type a b. (a, b) map -> a comparable_ty =\n fun (module Box) -> Box.key_ty\n\nlet empty_map : type a b. a comparable_ty -> (a, b) map =\n fun ty ->\n let module OPS = Map.Make (struct\n type t = a\n\n let compare = compare_comparable ty\n end) in\n ( module struct\n type key = a\n\n type value = b\n\n let key_ty = ty\n\n module OPS = OPS\n\n let boxed = (OPS.empty, 0)\n end )\n\nlet map_get : type key value. key -> (key, value) map -> value option =\n fun k (module Box) -> Box.OPS.find_opt k (fst Box.boxed)\n\nlet map_update : type a b. a -> b option -> (a, b) map -> (a, b) map =\n fun k v (module Box) ->\n ( module struct\n type key = a\n\n type value = b\n\n let key_ty = Box.key_ty\n\n module OPS = Box.OPS\n\n let boxed =\n let (map, size) = Box.boxed in\n let contains = Box.OPS.mem k map in\n match v with\n | Some v ->\n (Box.OPS.add k v map, size + if contains then 0 else 1)\n | None ->\n (Box.OPS.remove k map, size - if contains then 1 else 0)\n end )\n\nlet map_set : type a b. a -> b -> (a, b) map -> (a, b) map =\n fun k v (module Box) ->\n ( module struct\n type key = a\n\n type value = b\n\n let key_ty = Box.key_ty\n\n module OPS = Box.OPS\n\n let boxed =\n let (map, size) = Box.boxed in\n (Box.OPS.add k v map, if Box.OPS.mem k map then size else size + 1)\n end )\n\nlet map_mem : type key value. key -> (key, value) map -> bool =\n fun k (module Box) -> Box.OPS.mem k (fst Box.boxed)\n\nlet map_fold :\n type key value acc.\n (key -> value -> acc -> acc) -> (key, value) map -> acc -> acc =\n fun f (module Box) -> Box.OPS.fold f (fst Box.boxed)\n\nlet map_size : type key value. (key, value) map -> Script_int.n Script_int.num\n =\n fun (module Box) -> Script_int.(abs (of_int (snd Box.boxed)))\n\n(* ---- Unparsing (Typed IR -> Untyped expressions) of types -----------------*)\n\nlet rec ty_of_comparable_ty : type a. a comparable_ty -> a ty = function\n | Unit_key tname ->\n Unit_t tname\n | Never_key tname ->\n Never_t tname\n | Int_key tname ->\n Int_t tname\n | Nat_key tname ->\n Nat_t tname\n | Signature_key tname ->\n Signature_t tname\n | String_key tname ->\n String_t tname\n | Bytes_key tname ->\n Bytes_t tname\n | Mutez_key tname ->\n Mutez_t tname\n | Bool_key tname ->\n Bool_t tname\n | Key_hash_key tname ->\n Key_hash_t tname\n | Key_key tname ->\n Key_t tname\n | Timestamp_key tname ->\n Timestamp_t tname\n | Address_key tname ->\n Address_t tname\n | Chain_id_key tname ->\n Chain_id_t tname\n | Pair_key ((l, al), (r, ar), tname) ->\n Pair_t\n ( (ty_of_comparable_ty l, al, None),\n (ty_of_comparable_ty r, ar, None),\n tname )\n | Union_key ((l, al), (r, ar), tname) ->\n Union_t ((ty_of_comparable_ty l, al), (ty_of_comparable_ty r, ar), tname)\n | Option_key (t, tname) ->\n Option_t (ty_of_comparable_ty t, tname)\n\nlet add_field_annot a var = function\n | Prim (loc, prim, args, annots) ->\n Prim\n ( loc,\n prim,\n args,\n annots @ unparse_field_annot a @ unparse_var_annot var )\n | expr ->\n expr\n\nlet rec unparse_comparable_ty : type a. a comparable_ty -> Script.node =\n function\n | Unit_key tname ->\n Prim (-1, T_unit, [], unparse_type_annot tname)\n | Never_key tname ->\n Prim (-1, T_never, [], unparse_type_annot tname)\n | Int_key tname ->\n Prim (-1, T_int, [], unparse_type_annot tname)\n | Nat_key tname ->\n Prim (-1, T_nat, [], unparse_type_annot tname)\n | Signature_key tname ->\n Prim (-1, T_signature, [], unparse_type_annot tname)\n | String_key tname ->\n Prim (-1, T_string, [], unparse_type_annot tname)\n | Bytes_key tname ->\n Prim (-1, T_bytes, [], unparse_type_annot tname)\n | Mutez_key tname ->\n Prim (-1, T_mutez, [], unparse_type_annot tname)\n | Bool_key tname ->\n Prim (-1, T_bool, [], unparse_type_annot tname)\n | Key_hash_key tname ->\n Prim (-1, T_key_hash, [], unparse_type_annot tname)\n | Key_key tname ->\n Prim (-1, T_key, [], unparse_type_annot tname)\n | Timestamp_key tname ->\n Prim (-1, T_timestamp, [], unparse_type_annot tname)\n | Address_key tname ->\n Prim (-1, T_address, [], unparse_type_annot tname)\n | Chain_id_key tname ->\n Prim (-1, T_chain_id, [], unparse_type_annot tname)\n | Pair_key ((l, al), (r, ar), pname) -> (\n let tl = add_field_annot al None (unparse_comparable_ty l) in\n let tr = add_field_annot ar None (unparse_comparable_ty r) in\n (* Fold [pair a1 (pair ... (pair an-1 an))] into [pair a1 ... an] *)\n (* Note that the folding does not happen if the pair on the right has a\n field annotation because this annotation would be lost *)\n match tr with\n | Prim (_, T_pair, ts, []) ->\n Prim (-1, T_pair, tl :: ts, unparse_type_annot pname)\n | _ ->\n Prim (-1, T_pair, [tl; tr], unparse_type_annot pname) )\n | Union_key ((l, al), (r, ar), tname) ->\n let tl = add_field_annot al None (unparse_comparable_ty l) in\n let tr = add_field_annot ar None (unparse_comparable_ty r) in\n Prim (-1, T_or, [tl; tr], unparse_type_annot tname)\n | Option_key (t, tname) ->\n Prim (-1, T_option, [unparse_comparable_ty t], unparse_type_annot tname)\n\nlet unparse_memo_size memo_size =\n let z = Sapling.Memo_size.unparse_to_z memo_size in\n Int (-1, z)\n\nlet rec unparse_ty :\n type a. context -> a ty -> (Script.node * context) tzresult =\n fun ctxt ty ->\n Gas.consume ctxt Unparse_costs.unparse_type_cycle\n >>? fun ctxt ->\n let return ctxt (name, args, annot) =\n let result = Prim (-1, name, args, annot) in\n ok (result, ctxt)\n in\n match ty with\n | Unit_t tname ->\n return ctxt (T_unit, [], unparse_type_annot tname)\n | Int_t tname ->\n return ctxt (T_int, [], unparse_type_annot tname)\n | Nat_t tname ->\n return ctxt (T_nat, [], unparse_type_annot tname)\n | Signature_t tname ->\n return ctxt (T_signature, [], unparse_type_annot tname)\n | String_t tname ->\n return ctxt (T_string, [], unparse_type_annot tname)\n | Bytes_t tname ->\n return ctxt (T_bytes, [], unparse_type_annot tname)\n | Mutez_t tname ->\n return ctxt (T_mutez, [], unparse_type_annot tname)\n | Bool_t tname ->\n return ctxt (T_bool, [], unparse_type_annot tname)\n | Key_hash_t tname ->\n return ctxt (T_key_hash, [], unparse_type_annot tname)\n | Key_t tname ->\n return ctxt (T_key, [], unparse_type_annot tname)\n | Timestamp_t tname ->\n return ctxt (T_timestamp, [], unparse_type_annot tname)\n | Address_t tname ->\n return ctxt (T_address, [], unparse_type_annot tname)\n | Operation_t tname ->\n return ctxt (T_operation, [], unparse_type_annot tname)\n | Chain_id_t tname ->\n return ctxt (T_chain_id, [], unparse_type_annot tname)\n | Never_t tname ->\n return ctxt (T_never, [], unparse_type_annot tname)\n | Bls12_381_g1_t tname ->\n return ctxt (T_bls12_381_g1, [], unparse_type_annot tname)\n | Bls12_381_g2_t tname ->\n return ctxt (T_bls12_381_g2, [], unparse_type_annot tname)\n | Bls12_381_fr_t tname ->\n return ctxt (T_bls12_381_fr, [], unparse_type_annot tname)\n | Contract_t (ut, tname) ->\n unparse_ty ctxt ut\n >>? fun (t, ctxt) ->\n return ctxt (T_contract, [t], unparse_type_annot tname)\n | Pair_t ((utl, l_field, l_var), (utr, r_field, r_var), tname) ->\n let annot = unparse_type_annot tname in\n unparse_ty ctxt utl\n >>? fun (utl, ctxt) ->\n let tl = add_field_annot l_field l_var utl in\n unparse_ty ctxt utr\n >>? fun (utr, ctxt) ->\n let tr = add_field_annot r_field r_var utr in\n (* Fold [pair a1 (pair ... (pair an-1 an))] into [pair a1 ... an] *)\n (* Note that the folding does not happen if the pair on the right has an\n annotation because this annotation would be lost *)\n return\n ctxt\n ( match tr with\n | Prim (_, T_pair, ts, []) ->\n (T_pair, tl :: ts, annot)\n | _ ->\n (T_pair, [tl; tr], annot) )\n | Union_t ((utl, l_field), (utr, r_field), tname) ->\n let annot = unparse_type_annot tname in\n unparse_ty ctxt utl\n >>? fun (utl, ctxt) ->\n let tl = add_field_annot l_field None utl in\n unparse_ty ctxt utr\n >>? fun (utr, ctxt) ->\n let tr = add_field_annot r_field None utr in\n return ctxt (T_or, [tl; tr], annot)\n | Lambda_t (uta, utr, tname) ->\n unparse_ty ctxt uta\n >>? fun (ta, ctxt) ->\n unparse_ty ctxt utr\n >>? fun (tr, ctxt) ->\n return ctxt (T_lambda, [ta; tr], unparse_type_annot tname)\n | Option_t (ut, tname) ->\n let annot = unparse_type_annot tname in\n unparse_ty ctxt ut\n >>? fun (ut, ctxt) -> return ctxt (T_option, [ut], annot)\n | List_t (ut, tname) ->\n unparse_ty ctxt ut\n >>? fun (t, ctxt) -> return ctxt (T_list, [t], unparse_type_annot tname)\n | Ticket_t (ut, tname) ->\n let t = unparse_comparable_ty ut in\n return ctxt (T_ticket, [t], unparse_type_annot tname)\n | Set_t (ut, tname) ->\n let t = unparse_comparable_ty ut in\n return ctxt (T_set, [t], unparse_type_annot tname)\n | Map_t (uta, utr, tname) ->\n let ta = unparse_comparable_ty uta in\n unparse_ty ctxt utr\n >>? fun (tr, ctxt) ->\n return ctxt (T_map, [ta; tr], unparse_type_annot tname)\n | Big_map_t (uta, utr, tname) ->\n let ta = unparse_comparable_ty uta in\n unparse_ty ctxt utr\n >>? fun (tr, ctxt) ->\n return ctxt (T_big_map, [ta; tr], unparse_type_annot tname)\n | Sapling_transaction_t (memo_size, tname) ->\n return\n ctxt\n ( T_sapling_transaction,\n [unparse_memo_size memo_size],\n unparse_type_annot tname )\n | Sapling_state_t (memo_size, tname) ->\n return\n ctxt\n ( T_sapling_state,\n [unparse_memo_size memo_size],\n unparse_type_annot tname )\n\nlet rec strip_var_annots = function\n | (Int _ | String _ | Bytes _) as atom ->\n atom\n | Seq (loc, args) ->\n Seq (loc, List.map strip_var_annots args)\n | Prim (loc, name, args, annots) ->\n let not_var_annot s = Compare.Char.(s.[0] <> '@') in\n let annots = List.filter not_var_annot annots in\n Prim (loc, name, List.map strip_var_annots args, annots)\n\nlet serialize_ty_for_error ctxt ty =\n unparse_ty ctxt ty\n >>? (fun (ty, ctxt) ->\n Gas.consume ctxt (Script.strip_locations_cost ty)\n >|? fun ctxt -> (Micheline.strip_locations (strip_var_annots ty), ctxt))\n |> record_trace Cannot_serialize_error\n\nlet rec comparable_ty_of_ty :\n type a.\n context -> Script.location -> a ty -> (a comparable_ty * context) tzresult\n =\n fun ctxt loc ty ->\n Gas.consume ctxt Typecheck_costs.comparable_ty_of_ty_cycle\n >>? fun ctxt ->\n match ty with\n | Unit_t tname ->\n ok ((Unit_key tname : a comparable_ty), ctxt)\n | Never_t tname ->\n ok (Never_key tname, ctxt)\n | Int_t tname ->\n ok (Int_key tname, ctxt)\n | Nat_t tname ->\n ok (Nat_key tname, ctxt)\n | Signature_t tname ->\n ok (Signature_key tname, ctxt)\n | String_t tname ->\n ok (String_key tname, ctxt)\n | Bytes_t tname ->\n ok (Bytes_key tname, ctxt)\n | Mutez_t tname ->\n ok (Mutez_key tname, ctxt)\n | Bool_t tname ->\n ok (Bool_key tname, ctxt)\n | Key_hash_t tname ->\n ok (Key_hash_key tname, ctxt)\n | Key_t tname ->\n ok (Key_key tname, ctxt)\n | Timestamp_t tname ->\n ok (Timestamp_key tname, ctxt)\n | Address_t tname ->\n ok (Address_key tname, ctxt)\n | Chain_id_t tname ->\n ok (Chain_id_key tname, ctxt)\n | Pair_t ((l, al, _), (r, ar, _), pname) ->\n comparable_ty_of_ty ctxt loc l\n >>? fun (lty, ctxt) ->\n comparable_ty_of_ty ctxt loc r\n >|? fun (rty, ctxt) -> (Pair_key ((lty, al), (rty, ar), pname), ctxt)\n | Union_t ((l, al), (r, ar), tname) ->\n comparable_ty_of_ty ctxt loc l\n >>? fun (lty, ctxt) ->\n comparable_ty_of_ty ctxt loc r\n >|? fun (rty, ctxt) -> (Union_key ((lty, al), (rty, ar), tname), ctxt)\n | Option_t (tt, tname) ->\n comparable_ty_of_ty ctxt loc tt\n >|? fun (ty, ctxt) -> (Option_key (ty, tname), ctxt)\n | Lambda_t _\n | List_t _\n | Ticket_t _\n | Set_t _\n | Map_t _\n | Big_map_t _\n | Contract_t _\n | Operation_t _\n | Bls12_381_fr_t _\n | Bls12_381_g1_t _\n | Bls12_381_g2_t _\n | Sapling_state_t _\n | Sapling_transaction_t _ ->\n serialize_ty_for_error ctxt ty\n >>? fun (t, _ctxt) -> error (Comparable_type_expected (loc, t))\n\nlet rec unparse_stack :\n type a.\n context ->\n a stack_ty ->\n ((Script.expr * Script.annot) list * context) tzresult =\n fun ctxt -> function\n | Empty_t ->\n ok ([], ctxt)\n | Item_t (ty, rest, annot) ->\n unparse_ty ctxt ty\n >>? fun (uty, ctxt) ->\n unparse_stack ctxt rest\n >|? fun (urest, ctxt) ->\n ((strip_locations uty, unparse_var_annot annot) :: urest, ctxt)\n\nlet serialize_stack_for_error ctxt stack_ty =\n record_trace Cannot_serialize_error (unparse_stack ctxt stack_ty)\n\nlet name_of_ty : type a. a ty -> type_annot option = function\n | Unit_t tname ->\n tname\n | Int_t tname ->\n tname\n | Nat_t tname ->\n tname\n | String_t tname ->\n tname\n | Bytes_t tname ->\n tname\n | Mutez_t tname ->\n tname\n | Bool_t tname ->\n tname\n | Key_hash_t tname ->\n tname\n | Key_t tname ->\n tname\n | Timestamp_t tname ->\n tname\n | Address_t tname ->\n tname\n | Signature_t tname ->\n tname\n | Operation_t tname ->\n tname\n | Chain_id_t tname ->\n tname\n | Never_t tname ->\n tname\n | Contract_t (_, tname) ->\n tname\n | Pair_t (_, _, tname) ->\n tname\n | Union_t (_, _, tname) ->\n tname\n | Lambda_t (_, _, tname) ->\n tname\n | Option_t (_, tname) ->\n tname\n | List_t (_, tname) ->\n tname\n | Ticket_t (_, tname) ->\n tname\n | Set_t (_, tname) ->\n tname\n | Map_t (_, _, tname) ->\n tname\n | Big_map_t (_, _, tname) ->\n tname\n | Bls12_381_g1_t tname ->\n tname\n | Bls12_381_g2_t tname ->\n tname\n | Bls12_381_fr_t tname ->\n tname\n | Sapling_state_t (_, tname) ->\n tname\n | Sapling_transaction_t (_, tname) ->\n tname\n\n(* ---- Tickets ------------------------------------------------------------ *)\n\n(*\n All comparable types are dupable, this function exists only to not forget\n checking this property when adding new types.\n*)\nlet check_dupable_comparable_ty : type a. a comparable_ty -> unit = function\n | Unit_key _\n | Never_key _\n | Int_key _\n | Nat_key _\n | Signature_key _\n | String_key _\n | Bytes_key _\n | Mutez_key _\n | Bool_key _\n | Key_hash_key _\n | Key_key _\n | Timestamp_key _\n | Chain_id_key _\n | Address_key _\n | Pair_key _\n | Union_key _\n | Option_key _ ->\n ()\n\nlet rec check_dupable_ty :\n type a. context -> location -> a ty -> context tzresult =\n fun ctxt loc ty ->\n Gas.consume ctxt Typecheck_costs.check_dupable_cycle\n >>? fun ctxt ->\n match ty with\n | Unit_t _ ->\n ok ctxt\n | Int_t _ ->\n ok ctxt\n | Nat_t _ ->\n ok ctxt\n | Signature_t _ ->\n ok ctxt\n | String_t _ ->\n ok ctxt\n | Bytes_t _ ->\n ok ctxt\n | Mutez_t _ ->\n ok ctxt\n | Key_hash_t _ ->\n ok ctxt\n | Key_t _ ->\n ok ctxt\n | Timestamp_t _ ->\n ok ctxt\n | Address_t _ ->\n ok ctxt\n | Bool_t _ ->\n ok ctxt\n | Contract_t (_, _) ->\n ok ctxt\n | Operation_t _ ->\n ok ctxt\n | Chain_id_t _ ->\n ok ctxt\n | Never_t _ ->\n ok ctxt\n | Bls12_381_g1_t _ ->\n ok ctxt\n | Bls12_381_g2_t _ ->\n ok ctxt\n | Bls12_381_fr_t _ ->\n ok ctxt\n | Sapling_state_t _ ->\n ok ctxt\n | Sapling_transaction_t _ ->\n ok ctxt\n | Ticket_t _ ->\n error (Unexpected_ticket loc)\n | Pair_t ((ty_a, _, _), (ty_b, _, _), _) ->\n check_dupable_ty ctxt loc ty_a\n >>? fun ctxt -> check_dupable_ty ctxt loc ty_b\n | Union_t ((ty_a, _), (ty_b, _), _) ->\n check_dupable_ty ctxt loc ty_a\n >>? fun ctxt -> check_dupable_ty ctxt loc ty_b\n | Lambda_t (_, _, _) ->\n (*\n Lambda are dupable as long as:\n - they don't contain non-dupable values, e.g. in `PUSH`\n (mosty non-dupable values should probably be considered forged)\n - they are not the result of a partial application on a non-dupable\n value. `APPLY` rejects non-packable types (because of `PUSH`).\n Hence non-dupable should imply non-packable.\n *)\n ok ctxt\n | Option_t (ty, _) ->\n check_dupable_ty ctxt loc ty\n | List_t (ty, _) ->\n check_dupable_ty ctxt loc ty\n | Set_t (key_ty, _) ->\n let () = check_dupable_comparable_ty key_ty in\n ok ctxt\n | Map_t (key_ty, val_ty, _) ->\n let () = check_dupable_comparable_ty key_ty in\n check_dupable_ty ctxt loc val_ty\n | Big_map_t (key_ty, val_ty, _) ->\n let () = check_dupable_comparable_ty key_ty in\n check_dupable_ty ctxt loc val_ty\n\n(* ---- Equality witnesses --------------------------------------------------*)\n\ntype ('ta, 'tb) eq = Eq : ('same, 'same) eq\n\nlet record_inconsistent ctxt ta tb =\n record_trace_eval (fun () ->\n serialize_ty_for_error ctxt ta\n >>? fun (ta, ctxt) ->\n serialize_ty_for_error ctxt tb\n >|? fun (tb, _ctxt) -> Inconsistent_types (ta, tb))\n\nlet record_inconsistent_type_annotations ctxt loc ta tb =\n record_trace_eval (fun () ->\n serialize_ty_for_error ctxt ta\n >>? fun (ta, ctxt) ->\n serialize_ty_for_error ctxt tb\n >|? fun (tb, _ctxt) -> Inconsistent_type_annotations (loc, ta, tb))\n\nlet rec merge_comparable_types :\n type ta tb.\n legacy:bool ->\n context ->\n ta comparable_ty ->\n tb comparable_ty ->\n ((ta comparable_ty, tb comparable_ty) eq * ta comparable_ty * context)\n tzresult =\n fun ~legacy ctxt ta tb ->\n Gas.consume ctxt Typecheck_costs.merge_cycle\n >>? fun ctxt ->\n match (ta, tb) with\n | (Unit_key annot_a, Unit_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot ->\n ( (Eq : (ta comparable_ty, tb comparable_ty) eq),\n (Unit_key annot : ta comparable_ty),\n ctxt )\n | (Never_key annot_a, Never_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Never_key annot, ctxt)\n | (Int_key annot_a, Int_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Int_key annot, ctxt)\n | (Nat_key annot_a, Nat_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Nat_key annot, ctxt)\n | (Signature_key annot_a, Signature_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Signature_key annot, ctxt)\n | (String_key annot_a, String_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, String_key annot, ctxt)\n | (Bytes_key annot_a, Bytes_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Bytes_key annot, ctxt)\n | (Mutez_key annot_a, Mutez_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Mutez_key annot, ctxt)\n | (Bool_key annot_a, Bool_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Bool_key annot, ctxt)\n | (Key_hash_key annot_a, Key_hash_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Key_hash_key annot, ctxt)\n | (Key_key annot_a, Key_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Key_key annot, ctxt)\n | (Timestamp_key annot_a, Timestamp_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Timestamp_key annot, ctxt)\n | (Chain_id_key annot_a, Chain_id_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Chain_id_key annot, ctxt)\n | (Address_key annot_a, Address_key annot_b) ->\n merge_type_annot ~legacy annot_a annot_b\n >|? fun annot -> (Eq, Address_key annot, ctxt)\n | ( Pair_key ((left_a, annot_left_a), (right_a, annot_right_a), annot_a),\n Pair_key ((left_b, annot_left_b), (right_b, annot_right_b), annot_b) ) ->\n merge_type_annot ~legacy annot_a annot_b\n >>? fun annot ->\n merge_field_annot ~legacy annot_left_a annot_left_b\n >>? fun annot_left ->\n merge_field_annot ~legacy annot_right_a annot_right_b\n >>? fun annot_right ->\n merge_comparable_types ~legacy ctxt left_a left_b\n >>? fun (Eq, left, ctxt) ->\n merge_comparable_types ~legacy ctxt right_a right_b\n >|? fun (Eq, right, ctxt) ->\n ( (Eq : (ta comparable_ty, tb comparable_ty) eq),\n Pair_key ((left, annot_left), (right, annot_right), annot),\n ctxt )\n | ( Union_key ((left_a, annot_left_a), (right_a, annot_right_a), annot_a),\n Union_key ((left_b, annot_left_b), (right_b, annot_right_b), annot_b) )\n ->\n merge_type_annot ~legacy annot_a annot_b\n >>? fun annot ->\n merge_field_annot ~legacy annot_left_a annot_left_b\n >>? fun annot_left ->\n merge_field_annot ~legacy annot_right_a annot_right_b\n >>? fun annot_right ->\n merge_comparable_types ~legacy ctxt left_a left_b\n >>? fun (Eq, left, ctxt) ->\n merge_comparable_types ~legacy ctxt right_a right_b\n >|? fun (Eq, right, ctxt) ->\n ( (Eq : (ta comparable_ty, tb comparable_ty) eq),\n Union_key ((left, annot_left), (right, annot_right), annot),\n ctxt )\n | (Option_key (ta, annot_a), Option_key (tb, annot_b)) ->\n merge_type_annot ~legacy annot_a annot_b\n >>? fun annot ->\n merge_comparable_types ~legacy ctxt ta tb\n >|? fun (Eq, t, ctxt) ->\n ( (Eq : (ta comparable_ty, tb comparable_ty) eq),\n Option_key (t, annot),\n ctxt )\n | (_, _) ->\n serialize_ty_for_error ctxt (ty_of_comparable_ty ta)\n >>? fun (ta, ctxt) ->\n serialize_ty_for_error ctxt (ty_of_comparable_ty tb)\n >>? fun (tb, _ctxt) -> error (Inconsistent_types (ta, tb))\n\nlet comparable_ty_eq :\n type ta tb.\n context ->\n ta comparable_ty ->\n tb comparable_ty ->\n ((ta comparable_ty, tb comparable_ty) eq * context) tzresult =\n fun ctxt ta tb ->\n merge_comparable_types ~legacy:true ctxt ta tb\n >|? fun (eq, _ty, ctxt) -> (eq, ctxt)\n\nlet merge_memo_sizes ms1 ms2 =\n if Sapling.Memo_size.equal ms1 ms2 then ok ms1\n else error (Inconsistent_memo_sizes (ms1, ms2))\n\nlet merge_types :\n type a b.\n legacy:bool ->\n context ->\n Script.location ->\n a ty ->\n b ty ->\n ((a ty, b ty) eq * a ty * context) tzresult =\n fun ~legacy ctxt loc ty1 ty2 ->\n let merge_type_annot tn1 tn2 =\n merge_type_annot ~legacy tn1 tn2\n |> record_inconsistent_type_annotations ctxt loc ty1 ty2\n in\n let rec help :\n type ta tb.\n context ->\n ta ty ->\n tb ty ->\n ((ta ty, tb ty) eq * ta ty * context) tzresult =\n fun ctxt ty1 ty2 -> help0 ctxt ty1 ty2 |> record_inconsistent ctxt ty1 ty2\n and help0 :\n type ta tb.\n context ->\n ta ty ->\n tb ty ->\n ((ta ty, tb ty) eq * ta ty * context) tzresult =\n fun ctxt ty1 ty2 ->\n Gas.consume ctxt Typecheck_costs.merge_cycle\n >>? fun ctxt ->\n match (ty1, ty2) with\n | (Unit_t tn1, Unit_t tn2) ->\n merge_type_annot tn1 tn2\n >|? fun tname ->\n ((Eq : (ta ty, tb ty) eq), (Unit_t tname : ta ty), ctxt)\n | (Int_t tn1, Int_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Int_t tname, ctxt)\n | (Nat_t tn1, Nat_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Nat_t tname, ctxt)\n | (Key_t tn1, Key_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Key_t tname, ctxt)\n | (Key_hash_t tn1, Key_hash_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Key_hash_t tname, ctxt)\n | (String_t tn1, String_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, String_t tname, ctxt)\n | (Bytes_t tn1, Bytes_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Bytes_t tname, ctxt)\n | (Signature_t tn1, Signature_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Signature_t tname, ctxt)\n | (Mutez_t tn1, Mutez_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Mutez_t tname, ctxt)\n | (Timestamp_t tn1, Timestamp_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Timestamp_t tname, ctxt)\n | (Address_t tn1, Address_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Address_t tname, ctxt)\n | (Bool_t tn1, Bool_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Bool_t tname, ctxt)\n | (Chain_id_t tn1, Chain_id_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Chain_id_t tname, ctxt)\n | (Never_t tn1, Never_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Never_t tname, ctxt)\n | (Operation_t tn1, Operation_t tn2) ->\n merge_type_annot tn1 tn2 >|? fun tname -> (Eq, Operation_t tname, ctxt)\n | (Bls12_381_g1_t tn1, Bls12_381_g1_t tn2) ->\n merge_type_annot tn1 tn2\n >|? fun tname -> (Eq, Bls12_381_g1_t tname, ctxt)\n | (Bls12_381_g2_t tn1, Bls12_381_g2_t tn2) ->\n merge_type_annot tn1 tn2\n >|? fun tname -> (Eq, Bls12_381_g2_t tname, ctxt)\n | (Bls12_381_fr_t tn1, Bls12_381_fr_t tn2) ->\n merge_type_annot tn1 tn2\n >|? fun tname -> (Eq, Bls12_381_fr_t tname, ctxt)\n | (Map_t (tal, tar, tn1), Map_t (tbl, tbr, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n help ctxt tar tbr\n >>? fun (Eq, value, ctxt) ->\n merge_comparable_types ~legacy ctxt tal tbl\n >|? fun (Eq, tk, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Map_t (tk, value, tname), ctxt)\n | (Big_map_t (tal, tar, tn1), Big_map_t (tbl, tbr, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n help ctxt tar tbr\n >>? fun (Eq, value, ctxt) ->\n merge_comparable_types ~legacy ctxt tal tbl\n >|? fun (Eq, tk, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Big_map_t (tk, value, tname), ctxt)\n | (Set_t (ea, tn1), Set_t (eb, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n merge_comparable_types ~legacy ctxt ea eb\n >|? fun (Eq, e, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Set_t (e, tname), ctxt)\n | (Ticket_t (ea, tn1), Ticket_t (eb, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n merge_comparable_types ~legacy ctxt ea eb\n >|? fun (Eq, e, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Ticket_t (e, tname), ctxt)\n | ( Pair_t ((tal, l_field1, l_var1), (tar, r_field1, r_var1), tn1),\n Pair_t ((tbl, l_field2, l_var2), (tbr, r_field2, r_var2), tn2) ) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n merge_field_annot ~legacy l_field1 l_field2\n >>? fun l_field ->\n merge_field_annot ~legacy r_field1 r_field2\n >>? fun r_field ->\n let l_var = merge_var_annot l_var1 l_var2 in\n let r_var = merge_var_annot r_var1 r_var2 in\n help ctxt tal tbl\n >>? fun (Eq, left_ty, ctxt) ->\n help ctxt tar tbr\n >|? fun (Eq, right_ty, ctxt) ->\n ( (Eq : (ta ty, tb ty) eq),\n Pair_t ((left_ty, l_field, l_var), (right_ty, r_field, r_var), tname),\n ctxt )\n | ( Union_t ((tal, tal_annot), (tar, tar_annot), tn1),\n Union_t ((tbl, tbl_annot), (tbr, tbr_annot), tn2) ) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n merge_field_annot ~legacy tal_annot tbl_annot\n >>? fun left_annot ->\n merge_field_annot ~legacy tar_annot tbr_annot\n >>? fun right_annot ->\n help ctxt tal tbl\n >>? fun (Eq, left_ty, ctxt) ->\n help ctxt tar tbr\n >|? fun (Eq, right_ty, ctxt) ->\n ( (Eq : (ta ty, tb ty) eq),\n Union_t ((left_ty, left_annot), (right_ty, right_annot), tname),\n ctxt )\n | (Lambda_t (tal, tar, tn1), Lambda_t (tbl, tbr, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n help ctxt tal tbl\n >>? fun (Eq, left_ty, ctxt) ->\n help ctxt tar tbr\n >|? fun (Eq, right_ty, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Lambda_t (left_ty, right_ty, tname), ctxt)\n | (Contract_t (tal, tn1), Contract_t (tbl, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n help ctxt tal tbl\n >|? fun (Eq, arg_ty, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Contract_t (arg_ty, tname), ctxt)\n | (Option_t (tva, tn1), Option_t (tvb, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n help ctxt tva tvb\n >|? fun (Eq, ty, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), Option_t (ty, tname), ctxt)\n | (List_t (tva, tn1), List_t (tvb, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n help ctxt tva tvb\n >|? fun (Eq, ty, ctxt) ->\n ((Eq : (ta ty, tb ty) eq), List_t (ty, tname), ctxt)\n | (Sapling_state_t (ms1, tn1), Sapling_state_t (ms2, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n merge_memo_sizes ms1 ms2\n >|? fun ms -> (Eq, Sapling_state_t (ms, tname), ctxt)\n | (Sapling_transaction_t (ms1, tn1), Sapling_transaction_t (ms2, tn2)) ->\n merge_type_annot tn1 tn2\n >>? fun tname ->\n merge_memo_sizes ms1 ms2\n >|? fun ms -> (Eq, Sapling_transaction_t (ms, tname), ctxt)\n | (_, _) ->\n serialize_ty_for_error ctxt ty1\n >>? fun (ty1, ctxt) ->\n serialize_ty_for_error ctxt ty2\n >>? fun (ty2, _ctxt) -> error (Inconsistent_types (ty1, ty2))\n in\n help ctxt ty1 ty2\n [@@coq_axiom \"non-top-level mutual recursion\"]\n\nlet ty_eq :\n type ta tb.\n context ->\n Script.location ->\n ta ty ->\n tb ty ->\n ((ta ty, tb ty) eq * context) tzresult =\n fun ctxt loc ta tb ->\n merge_types ~legacy:true ctxt loc ta tb >|? fun (eq, _ty, ctxt) -> (eq, ctxt)\n\nlet merge_stacks :\n type ta tb.\n legacy:bool ->\n Script.location ->\n context ->\n int ->\n ta stack_ty ->\n tb stack_ty ->\n ((ta stack_ty, tb stack_ty) eq * ta stack_ty * context) tzresult =\n fun ~legacy loc ->\n let rec help :\n type a b.\n context ->\n int ->\n a stack_ty ->\n b stack_ty ->\n ((a stack_ty, b stack_ty) eq * a stack_ty * context) tzresult =\n fun ctxt lvl stack1 stack2 ->\n match (stack1, stack2) with\n | (Empty_t, Empty_t) ->\n ok (Eq, Empty_t, ctxt)\n | (Item_t (ty1, rest1, annot1), Item_t (ty2, rest2, annot2)) ->\n merge_types ~legacy ctxt loc ty1 ty2\n |> record_trace (Bad_stack_item lvl)\n >>? fun (Eq, ty, ctxt) ->\n help ctxt (lvl + 1) rest1 rest2\n >|? fun (Eq, rest, ctxt) ->\n let annot = merge_var_annot annot1 annot2 in\n ((Eq : (a stack_ty, b stack_ty) eq), Item_t (ty, rest, annot), ctxt)\n | (_, _) ->\n error Bad_stack_length\n in\n help\n\n(* ---- Type checker results -------------------------------------------------*)\n\ntype 'bef judgement =\n | Typed : ('bef, 'aft) descr -> 'bef judgement\n | Failed : {\n descr : 'aft. 'aft stack_ty -> ('bef, 'aft) descr;\n }\n -> 'bef judgement\n\n(* ---- Type checker (Untyped expressions -> Typed IR) ----------------------*)\n\ntype ('t, 'f, 'b) branch = {\n branch : 'r. ('t, 'r) descr -> ('f, 'r) descr -> ('b, 'r) descr;\n}\n[@@unboxed]\n\nlet merge_branches :\n type bef a b.\n legacy:bool ->\n context ->\n int ->\n a judgement ->\n b judgement ->\n (a, b, bef) branch ->\n (bef judgement * context) tzresult =\n fun ~legacy ctxt loc btr bfr {branch} ->\n match (btr, bfr) with\n | (Typed ({aft = aftbt; _} as dbt), Typed ({aft = aftbf; _} as dbf)) ->\n let unmatched_branches () =\n serialize_stack_for_error ctxt aftbt\n >>? fun (aftbt, ctxt) ->\n serialize_stack_for_error ctxt aftbf\n >|? fun (aftbf, _ctxt) -> Unmatched_branches (loc, aftbt, aftbf)\n in\n record_trace_eval\n unmatched_branches\n ( merge_stacks ~legacy loc ctxt 1 aftbt aftbf\n >|? fun (Eq, merged_stack, ctxt) ->\n ( Typed\n (branch {dbt with aft = merged_stack} {dbf with aft = merged_stack}),\n ctxt ) )\n | (Failed {descr = descrt}, Failed {descr = descrf}) ->\n let descr ret = branch (descrt ret) (descrf ret) in\n ok (Failed {descr}, ctxt)\n | (Typed dbt, Failed {descr = descrf}) ->\n ok (Typed (branch dbt (descrf dbt.aft)), ctxt)\n | (Failed {descr = descrt}, Typed dbf) ->\n ok (Typed (branch (descrt dbf.aft) dbf), ctxt)\n\nlet parse_memo_size (n : (location, _) Micheline.node) :\n Sapling.Memo_size.t tzresult =\n match n with\n | Int (_, z) -> (\n match Sapling.Memo_size.parse_z z with\n | Ok _ as ok_memo_size ->\n ok_memo_size\n | Error msg ->\n error @@ Invalid_syntactic_constant (location n, strip_locations n, msg)\n )\n | _ ->\n error @@ Invalid_kind (location n, [Int_kind], kind n)\n\nlet rec parse_comparable_ty :\n context -> Script.node -> (ex_comparable_ty * context) tzresult =\n fun ctxt ty ->\n Gas.consume ctxt Typecheck_costs.parse_type_cycle\n >>? fun ctxt ->\n match ty with\n | Prim (loc, T_unit, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Unit_key tname), ctxt)\n | Prim (loc, T_never, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Never_key tname), ctxt)\n | Prim (loc, T_int, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Int_key tname), ctxt)\n | Prim (loc, T_nat, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Nat_key tname), ctxt)\n | Prim (loc, T_signature, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Signature_key tname), ctxt)\n | Prim (loc, T_string, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (String_key tname), ctxt)\n | Prim (loc, T_bytes, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Bytes_key tname), ctxt)\n | Prim (loc, T_mutez, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Mutez_key tname), ctxt)\n | Prim (loc, T_bool, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Bool_key tname), ctxt)\n | Prim (loc, T_key_hash, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Key_hash_key tname), ctxt)\n | Prim (loc, T_key, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Key_key tname), ctxt)\n | Prim (loc, T_timestamp, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Timestamp_key tname), ctxt)\n | Prim (loc, T_chain_id, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Chain_id_key tname), ctxt)\n | Prim (loc, T_address, [], annot) ->\n parse_type_annot loc annot\n >|? fun tname -> (Ex_comparable_ty (Address_key tname), ctxt)\n | Prim\n ( loc,\n ( ( T_unit\n | T_never\n | T_int\n | T_nat\n | T_string\n | T_bytes\n | T_mutez\n | T_bool\n | T_key_hash\n | T_timestamp\n | T_address\n | T_chain_id\n | T_signature\n | T_key ) as prim ),\n l,\n _ ) ->\n error (Invalid_arity (loc, prim, 0, List.length l))\n | Prim (loc, T_pair, left :: right, annot) ->\n parse_type_annot loc annot\n >>? fun pname ->\n extract_field_annot left\n >>? fun (left, left_annot) ->\n ( match right with\n | [right] ->\n extract_field_annot right\n | right ->\n (* Unfold [pair t1 ... tn] as [pair t1 (... (pair tn-1 tn))] *)\n ok (Prim (loc, T_pair, right, []), None) )\n >>? fun (right, right_annot) ->\n parse_comparable_ty ctxt right\n >>? fun (Ex_comparable_ty right, ctxt) ->\n parse_comparable_ty ctxt left\n >|? fun (Ex_comparable_ty left, ctxt) ->\n ( Ex_comparable_ty\n (Pair_key ((left, left_annot), (right, right_annot), pname)),\n ctxt )\n | Prim (loc, T_or, [left; right], annot) ->\n parse_type_annot loc annot\n >>? fun pname ->\n extract_field_annot left\n >>? fun (left, left_annot) ->\n extract_field_annot right\n >>? fun (right, right_annot) ->\n parse_comparable_ty ctxt right\n >>? fun (Ex_comparable_ty right, ctxt) ->\n parse_comparable_ty ctxt left\n >|? fun (Ex_comparable_ty left, ctxt) ->\n ( Ex_comparable_ty\n (Union_key ((left, left_annot), (right, right_annot), pname)),\n ctxt )\n | Prim (loc, ((T_pair | T_or) as prim), l, _) ->\n error (Invalid_arity (loc, prim, 2, List.length l))\n | Prim (loc, T_option, [t], annot) ->\n parse_type_annot loc annot\n >>? fun tname ->\n parse_comparable_ty ctxt t\n >|? fun (Ex_comparable_ty t, ctxt) ->\n (Ex_comparable_ty (Option_key (t, tname)), ctxt)\n | Prim (loc, T_option, l, _) ->\n error (Invalid_arity (loc, T_option, 1, List.length l))\n | Prim\n ( loc,\n (T_set | T_map | T_list | T_lambda | T_contract | T_operation),\n _,\n _ ) ->\n error (Comparable_type_expected (loc, Micheline.strip_locations ty))\n | expr ->\n error\n @@ unexpected\n expr\n []\n Type_namespace\n [ T_unit;\n T_never;\n T_int;\n T_nat;\n T_string;\n T_bytes;\n T_mutez;\n T_bool;\n T_key_hash;\n T_timestamp;\n T_address;\n T_pair;\n T_or;\n T_option;\n T_chain_id;\n T_signature;\n T_key ]\n\nand parse_packable_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult =\n fun ctxt ~legacy ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage:false\n ~allow_operation:false\n ~allow_contract:legacy\n ~allow_ticket:false\n\nand parse_parameter_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult =\n fun ctxt ~legacy ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage:true\n ~allow_operation:false\n ~allow_contract:true\n ~allow_ticket:true\n\nand parse_normal_storage_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult =\n fun ctxt ~legacy ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage:true\n ~allow_operation:false\n ~allow_contract:legacy\n ~allow_ticket:true\n\nand parse_any_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult =\n fun ctxt ~legacy ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage:true\n ~allow_operation:true\n ~allow_contract:true\n ~allow_ticket:true\n\nand parse_ty :\n context ->\n legacy:bool ->\n allow_lazy_storage:bool ->\n allow_operation:bool ->\n allow_contract:bool ->\n allow_ticket:bool ->\n Script.node ->\n (ex_ty * context) tzresult =\n fun ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n node ->\n Gas.consume ctxt Typecheck_costs.parse_type_cycle\n >>? fun ctxt ->\n match node with\n | Prim (loc, T_unit, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Unit_t ty_name), ctxt)\n | Prim (loc, T_int, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Int_t ty_name), ctxt)\n | Prim (loc, T_nat, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Nat_t ty_name), ctxt)\n | Prim (loc, T_string, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (String_t ty_name), ctxt)\n | Prim (loc, T_bytes, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Bytes_t ty_name), ctxt)\n | Prim (loc, T_mutez, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Mutez_t ty_name), ctxt)\n | Prim (loc, T_bool, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Bool_t ty_name), ctxt)\n | Prim (loc, T_key, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Key_t ty_name), ctxt)\n | Prim (loc, T_key_hash, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Key_hash_t ty_name), ctxt)\n | Prim (loc, T_timestamp, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Timestamp_t ty_name), ctxt)\n | Prim (loc, T_address, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Address_t ty_name), ctxt)\n | Prim (loc, T_signature, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Signature_t ty_name), ctxt)\n | Prim (loc, T_operation, [], annot) ->\n if allow_operation then\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Operation_t ty_name), ctxt)\n else error (Unexpected_operation loc)\n | Prim (loc, T_chain_id, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Chain_id_t ty_name), ctxt)\n | Prim (loc, T_never, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Never_t ty_name), ctxt)\n | Prim (loc, T_bls12_381_g1, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Bls12_381_g1_t ty_name), ctxt)\n | Prim (loc, T_bls12_381_g2, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Bls12_381_g2_t ty_name), ctxt)\n | Prim (loc, T_bls12_381_fr, [], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Bls12_381_fr_t ty_name), ctxt)\n | Prim (loc, T_contract, [utl], annot) ->\n if allow_contract then\n parse_parameter_ty ctxt ~legacy utl\n >>? fun (Ex_ty tl, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Contract_t (tl, ty_name)), ctxt)\n else error (Unexpected_contract loc)\n | Prim (loc, T_pair, utl :: utr, annot) ->\n extract_field_annot utl\n >>? fun (utl, left_field) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n utl\n >>? fun (Ex_ty tl, ctxt) ->\n ( match utr with\n | [utr] ->\n extract_field_annot utr\n | utr ->\n (* Unfold [pair t1 ... tn] as [pair t1 (... (pair tn-1 tn))] *)\n ok (Prim (loc, T_pair, utr, []), None) )\n >>? fun (utr, right_field) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n utr\n >>? fun (Ex_ty tr, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name ->\n ok\n ( Ex_ty\n (Pair_t ((tl, left_field, None), (tr, right_field, None), ty_name)),\n ctxt )\n | Prim (loc, T_or, [utl; utr], annot) ->\n extract_field_annot utl\n >>? fun (utl, left_constr) ->\n extract_field_annot utr\n >>? fun (utr, right_constr) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n utl\n >>? fun (Ex_ty tl, ctxt) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n utr\n >>? fun (Ex_ty tr, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name ->\n ok\n (Ex_ty (Union_t ((tl, left_constr), (tr, right_constr), ty_name)), ctxt)\n | Prim (loc, T_lambda, [uta; utr], annot) ->\n parse_any_ty ctxt ~legacy uta\n >>? fun (Ex_ty ta, ctxt) ->\n parse_any_ty ctxt ~legacy utr\n >>? fun (Ex_ty tr, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Lambda_t (ta, tr, ty_name)), ctxt)\n | Prim (loc, T_option, [ut], annot) ->\n ( if legacy then\n (* legacy semantics with (broken) field annotations *)\n extract_field_annot ut\n >>? fun (ut, _some_constr) ->\n parse_composed_type_annot loc annot\n >>? fun (ty_name, _none_constr, _) -> ok (ut, ty_name)\n else parse_type_annot loc annot >>? fun ty_name -> ok (ut, ty_name) )\n >>? fun (ut, ty_name) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n ut\n >>? fun (Ex_ty t, ctxt) -> ok (Ex_ty (Option_t (t, ty_name)), ctxt)\n | Prim (loc, T_list, [ut], annot) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n ut\n >>? fun (Ex_ty t, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (List_t (t, ty_name)), ctxt)\n | Prim (loc, T_ticket, [ut], annot) ->\n if allow_ticket then\n parse_comparable_ty ctxt ut\n >>? fun (Ex_comparable_ty t, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Ticket_t (t, ty_name)), ctxt)\n else error (Unexpected_ticket loc)\n | Prim (loc, T_set, [ut], annot) ->\n parse_comparable_ty ctxt ut\n >>? fun (Ex_comparable_ty t, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Set_t (t, ty_name)), ctxt)\n | Prim (loc, T_map, [uta; utr], annot) ->\n parse_comparable_ty ctxt uta\n >>? fun (Ex_comparable_ty ta, ctxt) ->\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage\n ~allow_operation\n ~allow_contract\n ~allow_ticket\n utr\n >>? fun (Ex_ty tr, ctxt) ->\n parse_type_annot loc annot\n >>? fun ty_name -> ok (Ex_ty (Map_t (ta, tr, ty_name)), ctxt)\n | Prim (loc, T_sapling_transaction, [memo_size], annot) ->\n parse_type_annot loc annot\n >>? fun ty_name ->\n parse_memo_size memo_size\n >|? fun memo_size ->\n (Ex_ty (Sapling_transaction_t (memo_size, ty_name)), ctxt)\n (*\n /!\\ When adding new lazy storage kinds, be careful to use\n [when allow_lazy_storage] /!\\\n Lazy storage should not be packable to avoid stealing a lazy storage\n from another contract with `PUSH t id` or `UNPACK`.\n *)\n | Prim (loc, T_big_map, args, annot) when allow_lazy_storage ->\n parse_big_map_ty ctxt ~legacy loc args annot\n >>? fun (big_map_ty, ctxt) -> ok (big_map_ty, ctxt)\n | Prim (loc, T_sapling_state, [memo_size], annot) when allow_lazy_storage ->\n parse_type_annot loc annot\n >>? fun ty_name ->\n parse_memo_size memo_size\n >|? fun memo_size -> (Ex_ty (Sapling_state_t (memo_size, ty_name)), ctxt)\n | Prim (loc, (T_big_map | T_sapling_state), _, _) ->\n error (Unexpected_lazy_storage loc)\n | Prim\n ( loc,\n ( ( T_unit\n | T_signature\n | T_int\n | T_nat\n | T_string\n | T_bytes\n | T_mutez\n | T_bool\n | T_key\n | T_key_hash\n | T_timestamp\n | T_address\n | T_chain_id\n | T_operation\n | T_never ) as prim ),\n l,\n _ ) ->\n error (Invalid_arity (loc, prim, 0, List.length l))\n | Prim\n (loc, ((T_set | T_list | T_option | T_contract | T_ticket) as prim), l, _)\n ->\n error (Invalid_arity (loc, prim, 1, List.length l))\n | Prim (loc, ((T_pair | T_or | T_map | T_lambda) as prim), l, _) ->\n error (Invalid_arity (loc, prim, 2, List.length l))\n | expr ->\n error\n @@ unexpected\n expr\n []\n Type_namespace\n [ T_pair;\n T_or;\n T_set;\n T_map;\n T_list;\n T_option;\n T_lambda;\n T_unit;\n T_signature;\n T_contract;\n T_int;\n T_nat;\n T_operation;\n T_string;\n T_bytes;\n T_mutez;\n T_bool;\n T_key;\n T_key_hash;\n T_timestamp;\n T_chain_id;\n T_never;\n T_bls12_381_g1;\n T_bls12_381_g2;\n T_bls12_381_fr;\n T_ticket ]\n\nand parse_big_map_ty ctxt ~legacy big_map_loc args map_annot =\n Gas.consume ctxt Typecheck_costs.parse_type_cycle\n >>? fun ctxt ->\n match args with\n | [key_ty; value_ty] ->\n parse_comparable_ty ctxt key_ty\n >>? fun (Ex_comparable_ty key_ty, ctxt) ->\n parse_big_map_value_ty ctxt ~legacy value_ty\n >>? fun (Ex_ty value_ty, ctxt) ->\n parse_type_annot big_map_loc map_annot\n >|? fun map_name ->\n let big_map_ty = Big_map_t (key_ty, value_ty, map_name) in\n (Ex_ty big_map_ty, ctxt)\n | args ->\n error @@ Invalid_arity (big_map_loc, T_big_map, 2, List.length args)\n\nand parse_big_map_value_ty ctxt ~legacy value_ty =\n parse_ty\n ctxt\n ~legacy\n ~allow_lazy_storage:false\n ~allow_operation:false\n ~allow_contract:legacy\n ~allow_ticket:true\n value_ty\n\nand parse_storage_ty :\n context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult =\n fun ctxt ~legacy node ->\n match node with\n | Prim\n ( loc,\n T_pair,\n [Prim (big_map_loc, T_big_map, args, map_annot); remaining_storage],\n storage_annot )\n when legacy -> (\n match storage_annot with\n | [] ->\n parse_normal_storage_ty ctxt ~legacy node\n | [single]\n when Compare.Int.(String.length single > 0)\n && Compare.Char.(single.[0] = '%') ->\n parse_normal_storage_ty ctxt ~legacy node\n | _ ->\n (* legacy semantics of big maps used the wrong annotation parser *)\n Gas.consume ctxt Typecheck_costs.parse_type_cycle\n >>? fun ctxt ->\n parse_big_map_ty ctxt ~legacy big_map_loc args map_annot\n >>? fun (Ex_ty big_map_ty, ctxt) ->\n parse_normal_storage_ty ctxt ~legacy remaining_storage\n >>? fun (Ex_ty remaining_storage, ctxt) ->\n parse_composed_type_annot loc storage_annot\n >>? fun (ty_name, map_field, storage_field) ->\n ok\n ( Ex_ty\n (Pair_t\n ( (big_map_ty, map_field, None),\n (remaining_storage, storage_field, None),\n ty_name )),\n ctxt ) )\n | _ ->\n parse_normal_storage_ty ctxt ~legacy node\n\nlet check_packable ~legacy loc root =\n let rec check : type t. t ty -> unit tzresult = function\n (* /!\\ When adding new lazy storage kinds, be sure to return an error. /!\\\n Lazy storage should not be packable. *)\n | Big_map_t _ ->\n error (Unexpected_lazy_storage loc)\n | Sapling_state_t _ ->\n error (Unexpected_lazy_storage loc)\n | Operation_t _ ->\n error (Unexpected_operation loc)\n | Unit_t _ ->\n ok_unit\n | Int_t _ ->\n ok_unit\n | Nat_t _ ->\n ok_unit\n | Signature_t _ ->\n ok_unit\n | String_t _ ->\n ok_unit\n | Bytes_t _ ->\n ok_unit\n | Mutez_t _ ->\n ok_unit\n | Key_hash_t _ ->\n ok_unit\n | Key_t _ ->\n ok_unit\n | Timestamp_t _ ->\n ok_unit\n | Address_t _ ->\n ok_unit\n | Bool_t _ ->\n ok_unit\n | Chain_id_t _ ->\n ok_unit\n | Never_t _ ->\n ok_unit\n | Set_t (_, _) ->\n ok_unit\n | Ticket_t _ ->\n error (Unexpected_ticket loc)\n | Lambda_t (_, _, _) ->\n ok_unit\n | Bls12_381_g1_t _ ->\n ok_unit\n | Bls12_381_g2_t _ ->\n ok_unit\n | Bls12_381_fr_t _ ->\n ok_unit\n | Pair_t ((l_ty, _, _), (r_ty, _, _), _) ->\n check l_ty >>? fun () -> check r_ty\n | Union_t ((l_ty, _), (r_ty, _), _) ->\n check l_ty >>? fun () -> check r_ty\n | Option_t (v_ty, _) ->\n check v_ty\n | List_t (elt_ty, _) ->\n check elt_ty\n | Map_t (_, elt_ty, _) ->\n check elt_ty\n | Contract_t (_, _) when legacy ->\n ok_unit\n | Contract_t (_, _) ->\n error (Unexpected_contract loc)\n | Sapling_transaction_t _ ->\n ok ()\n in\n check root\n\ntype ('arg, 'storage) code = {\n code : (('arg, 'storage) pair, (operation boxed_list, 'storage) pair) lambda;\n arg_type : 'arg ty;\n storage_type : 'storage ty;\n root_name : field_annot option;\n}\n\ntype ex_script = Ex_script : ('a, 'c) script -> ex_script\n\ntype ex_code = Ex_code : ('a, 'c) code -> ex_code\n\ntype _ dig_proof_argument =\n | Dig_proof_argument :\n ( ('x * 'rest, 'rest, 'bef, 'aft) stack_prefix_preservation_witness\n * ('x ty * var_annot option)\n * 'aft stack_ty )\n -> 'bef dig_proof_argument\n\ntype (_, _) dug_proof_argument =\n | Dug_proof_argument :\n ( ('rest, 'x * 'rest, 'bef, 'aft) stack_prefix_preservation_witness\n * unit\n * 'aft stack_ty )\n -> ('bef, 'x) dug_proof_argument\n\ntype _ dipn_proof_argument =\n | Dipn_proof_argument :\n ( ('fbef, 'faft, 'bef, 'aft) stack_prefix_preservation_witness\n * (context * ('fbef, 'faft) descr)\n * 'aft stack_ty )\n -> 'bef dipn_proof_argument\n\ntype _ dropn_proof_argument =\n | Dropn_proof_argument :\n ( ('rest, 'rest, 'bef, 'aft) stack_prefix_preservation_witness\n * 'rest stack_ty\n * 'aft stack_ty )\n -> 'bef dropn_proof_argument\n\ntype 'before comb_proof_argument =\n | Comb_proof_argument :\n ('before, 'after) comb_gadt_witness * 'after stack_ty\n -> 'before comb_proof_argument\n\ntype 'before uncomb_proof_argument =\n | Uncomb_proof_argument :\n ('before, 'after) uncomb_gadt_witness * 'after stack_ty\n -> 'before uncomb_proof_argument\n\ntype 'before comb_get_proof_argument =\n | Comb_get_proof_argument :\n ('before, 'after) comb_get_gadt_witness * 'after ty\n -> 'before comb_get_proof_argument\n\ntype ('rest, 'before) comb_set_proof_argument =\n | Comb_set_proof_argument :\n ('rest, 'before, 'after) comb_set_gadt_witness * 'after ty\n -> ('rest, 'before) comb_set_proof_argument\n\ntype 'before dup_n_proof_argument =\n | Dup_n_proof_argument :\n ('before, 'a) dup_n_gadt_witness * 'a ty\n -> 'before dup_n_proof_argument\n\nlet find_entrypoint (type full) (full : full ty) ~root_name entrypoint =\n let rec find_entrypoint :\n type t. t ty -> string -> (Script.node -> Script.node) * ex_ty =\n fun t entrypoint ->\n match t with\n | Union_t ((tl, al), (tr, ar), _) -> (\n if\n match al with\n | None ->\n false\n | Some (Field_annot l) ->\n Compare.String.(l = entrypoint)\n then ((fun e -> Prim (0, D_Left, [e], [])), Ex_ty tl)\n else if\n match ar with\n | None ->\n false\n | Some (Field_annot r) ->\n Compare.String.(r = entrypoint)\n then ((fun e -> Prim (0, D_Right, [e], [])), Ex_ty tr)\n else\n try\n let (f, t) = find_entrypoint tl entrypoint in\n ((fun e -> Prim (0, D_Left, [f e], [])), t)\n with Not_found ->\n let (f, t) = find_entrypoint tr entrypoint in\n ((fun e -> Prim (0, D_Right, [f e], [])), t) )\n | _ ->\n raise Not_found\n in\n let entrypoint =\n if Compare.String.(entrypoint = \"\") then \"default\" else entrypoint\n in\n if Compare.Int.(String.length entrypoint > 31) then\n error (Entrypoint_name_too_long entrypoint)\n else\n match root_name with\n | Some (Field_annot root_name) when Compare.String.(entrypoint = root_name)\n ->\n ok ((fun e -> e), Ex_ty full)\n | _ -> (\n try ok (find_entrypoint full entrypoint)\n with Not_found -> (\n match entrypoint with\n | \"default\" ->\n ok ((fun e -> e), Ex_ty full)\n | _ ->\n error (No_such_entrypoint entrypoint) ) )\n\nlet find_entrypoint_for_type (type full exp) ~legacy ~(full : full ty)\n ~(expected : exp ty) ~root_name entrypoint ctxt loc :\n (context * string * exp ty) tzresult =\n match (entrypoint, root_name) with\n | (\"default\", Some (Field_annot \"root\")) -> (\n match find_entrypoint full ~root_name entrypoint with\n | Error _ as err ->\n err\n | Ok (_, Ex_ty ty) -> (\n match merge_types ~legacy ctxt loc ty expected with\n | Ok (Eq, ty, ctxt) ->\n ok (ctxt, \"default\", ty)\n | Error _ ->\n merge_types ~legacy ctxt loc full expected\n >>? fun (Eq, full, ctxt) -> ok (ctxt, \"root\", (full : exp ty)) ) )\n | _ ->\n find_entrypoint full ~root_name entrypoint\n >>? fun (_, Ex_ty ty) ->\n merge_types ~legacy ctxt loc ty expected\n >>? fun (Eq, ty, ctxt) -> ok (ctxt, entrypoint, (ty : exp ty))\n\nmodule Entrypoints = Set.Make (String)\n\nexception Duplicate of string\n\nexception Too_long of string\n\nlet well_formed_entrypoints (type full) (full : full ty) ~root_name =\n let merge path annot (type t) (ty : t ty) reachable\n ((first_unreachable, all) as acc) =\n match annot with\n | None | Some (Field_annot \"\") -> (\n if reachable then acc\n else\n match ty with\n | Union_t _ ->\n acc\n | _ -> (\n match first_unreachable with\n | None ->\n (Some (List.rev path), all)\n | Some _ ->\n acc ) )\n | Some (Field_annot name) ->\n if Compare.Int.(String.length name > 31) then raise (Too_long name)\n else if Entrypoints.mem name all then raise (Duplicate name)\n else (first_unreachable, Entrypoints.add name all)\n in\n let rec check :\n type t.\n t ty ->\n prim list ->\n bool ->\n prim list option * Entrypoints.t ->\n prim list option * Entrypoints.t =\n fun t path reachable acc ->\n match t with\n | Union_t ((tl, al), (tr, ar), _) ->\n let acc = merge (D_Left :: path) al tl reachable acc in\n let acc = merge (D_Right :: path) ar tr reachable acc in\n let acc =\n check\n tl\n (D_Left :: path)\n (match al with Some _ -> true | None -> reachable)\n acc\n in\n check\n tr\n (D_Right :: path)\n (match ar with Some _ -> true | None -> reachable)\n acc\n | _ ->\n acc\n in\n try\n let (init, reachable) =\n match root_name with\n | None | Some (Field_annot \"\") ->\n (Entrypoints.empty, false)\n | Some (Field_annot name) ->\n (Entrypoints.singleton name, true)\n in\n let (first_unreachable, all) = check full [] reachable (None, init) in\n if not (Entrypoints.mem \"default\" all) then ok_unit\n else\n match first_unreachable with\n | None ->\n ok_unit\n | Some path ->\n error (Unreachable_entrypoint path)\n with\n | Duplicate name ->\n error (Duplicate_entrypoint name)\n | Too_long name ->\n error (Entrypoint_name_too_long name)\n\nlet parse_uint ~nb_bits =\n assert (Compare.Int.(nb_bits >= 0 && nb_bits <= 30)) ;\n let max_int = (1 lsl nb_bits) - 1 in\n let max_z = Z.of_int max_int in\n function\n | Micheline.Int (_, n) when Compare.Z.(Z.zero <= n) && Compare.Z.(n <= max_z)\n ->\n ok (Z.to_int n)\n | node ->\n error\n @@ Invalid_syntactic_constant\n ( location node,\n strip_locations node,\n \"a positive \" ^ string_of_int nb_bits\n ^ \"-bit integer (between 0 and \" ^ string_of_int max_int ^ \")\" )\n\nlet parse_uint10 = parse_uint ~nb_bits:10\n\nlet parse_uint11 = parse_uint ~nb_bits:11\n\n(* This type is used to:\n - serialize and deserialize tickets when they are stored or transferred,\n - type the READ_TICKET instruction. *)\nlet opened_ticket_type ty =\n Pair_key\n ( (Address_key None, None),\n (Pair_key ((ty, None), (Nat_key None, None), None), None),\n None )\n\n(* -- parse data of primitive types -- *)\n\nlet parse_unit ctxt ~legacy = function\n | Prim (loc, D_Unit, [], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>? fun () ->\n Gas.consume ctxt Typecheck_costs.unit >|? fun ctxt -> ((), ctxt)\n | Prim (loc, D_Unit, l, _) ->\n error @@ Invalid_arity (loc, D_Unit, 0, List.length l)\n | expr ->\n error @@ unexpected expr [] Constant_namespace [D_Unit]\n\nlet parse_bool ctxt ~legacy = function\n | Prim (loc, D_True, [], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>? fun () ->\n Gas.consume ctxt Typecheck_costs.bool >|? fun ctxt -> (true, ctxt)\n | Prim (loc, D_False, [], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>? fun () ->\n Gas.consume ctxt Typecheck_costs.bool >|? fun ctxt -> (false, ctxt)\n | Prim (loc, ((D_True | D_False) as c), l, _) ->\n error @@ Invalid_arity (loc, c, 0, List.length l)\n | expr ->\n error @@ unexpected expr [] Constant_namespace [D_True; D_False]\n\nlet parse_string ctxt = function\n | String (loc, v) as expr ->\n Gas.consume ctxt (Typecheck_costs.check_printable v)\n >>? fun ctxt ->\n let rec check_printable_ascii i =\n if Compare.Int.(i < 0) then true\n else\n match v.[i] with\n | '\\n' | '\\x20' .. '\\x7E' ->\n check_printable_ascii (i - 1)\n | _ ->\n false\n in\n if check_printable_ascii (String.length v - 1) then ok (v, ctxt)\n else\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a printable ascii string\")\n | expr ->\n error @@ Invalid_kind (location expr, [String_kind], kind expr)\n\nlet parse_bytes ctxt = function\n | Bytes (_, v) ->\n ok (v, ctxt)\n | expr ->\n error @@ Invalid_kind (location expr, [Bytes_kind], kind expr)\n\nlet parse_int ctxt = function\n | Int (_, v) ->\n ok (Script_int.of_zint v, ctxt)\n | expr ->\n error @@ Invalid_kind (location expr, [Int_kind], kind expr)\n\nlet parse_nat ctxt = function\n | Int (loc, v) as expr -> (\n let v = Script_int.of_zint v in\n match Script_int.is_nat v with\n | Some nat ->\n ok (nat, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a non-negative integer\") )\n | expr ->\n error @@ Invalid_kind (location expr, [Int_kind], kind expr)\n\nlet parse_mutez ctxt = function\n | Int (loc, v) as expr -> (\n try\n match Tez.of_mutez (Z.to_int64 v) with\n | None ->\n raise Exit\n | Some tez ->\n ok (tez, ctxt)\n with _ ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid mutez amount\") )\n | expr ->\n error @@ Invalid_kind (location expr, [Int_kind], kind expr)\n\nlet parse_timestamp ctxt = function\n | Int (_, v) (* As unparsed with [Optimized] or out of bounds [Readable]. *)\n ->\n ok (Script_timestamp.of_zint v, ctxt)\n | String (loc, s) as expr (* As unparsed with [Readable]. *) -> (\n Gas.consume ctxt Typecheck_costs.timestamp_readable\n >>? fun ctxt ->\n match Script_timestamp.of_string s with\n | Some v ->\n ok (v, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid timestamp\") )\n | expr ->\n error @@ Invalid_kind (location expr, [String_kind; Int_kind], kind expr)\n\nlet parse_key ctxt = function\n | Bytes (loc, bytes) as expr -> (\n (* As unparsed with [Optimized]. *)\n Gas.consume ctxt Typecheck_costs.public_key_optimized\n >>? fun ctxt ->\n match\n Data_encoding.Binary.of_bytes Signature.Public_key.encoding bytes\n with\n | Some k ->\n ok (k, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid public key\") )\n | String (loc, s) as expr -> (\n (* As unparsed with [Readable]. *)\n Gas.consume ctxt Typecheck_costs.public_key_readable\n >>? fun ctxt ->\n match Signature.Public_key.of_b58check_opt s with\n | Some k ->\n ok (k, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid public key\") )\n | expr ->\n error\n @@ Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)\n\nlet parse_key_hash ctxt = function\n | Bytes (loc, bytes) as expr -> (\n (* As unparsed with [Optimized]. *)\n Gas.consume ctxt Typecheck_costs.key_hash_optimized\n >>? fun ctxt ->\n match\n Data_encoding.Binary.of_bytes Signature.Public_key_hash.encoding bytes\n with\n | Some k ->\n ok (k, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid key hash\") )\n | String (loc, s) as expr (* As unparsed with [Readable]. *) -> (\n Gas.consume ctxt Typecheck_costs.key_hash_readable\n >>? fun ctxt ->\n match Signature.Public_key_hash.of_b58check_opt s with\n | Some k ->\n ok (k, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid key hash\") )\n | expr ->\n error\n @@ Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)\n\nlet parse_signature ctxt = function\n | Bytes (loc, bytes) as expr (* As unparsed with [Optimized]. *) -> (\n Gas.consume ctxt Typecheck_costs.signature_optimized\n >>? fun ctxt ->\n match Data_encoding.Binary.of_bytes Signature.encoding bytes with\n | Some k ->\n ok (k, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid signature\") )\n | String (loc, s) as expr (* As unparsed with [Readable]. *) -> (\n Gas.consume ctxt Typecheck_costs.signature_readable\n >>? fun ctxt ->\n match Signature.of_b58check_opt s with\n | Some s ->\n ok (s, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid signature\") )\n | expr ->\n error\n @@ Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)\n\nlet parse_chain_id ctxt = function\n | Bytes (loc, bytes) as expr -> (\n Gas.consume ctxt Typecheck_costs.chain_id_optimized\n >>? fun ctxt ->\n match Data_encoding.Binary.of_bytes Chain_id.encoding bytes with\n | Some k ->\n ok (k, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid chain id\") )\n | String (loc, s) as expr -> (\n Gas.consume ctxt Typecheck_costs.chain_id_readable\n >>? fun ctxt ->\n match Chain_id.of_b58check_opt s with\n | Some s ->\n ok (s, ctxt)\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid chain id\") )\n | expr ->\n error\n @@ Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)\n\nlet parse_address ctxt = function\n | Bytes (loc, bytes) as expr (* As unparsed with [Optimized]. *) -> (\n Gas.consume ctxt Typecheck_costs.contract\n >>? fun ctxt ->\n match\n Data_encoding.Binary.of_bytes\n Data_encoding.(tup2 Contract.encoding Variable.string)\n bytes\n with\n | Some (c, entrypoint) -> (\n if Compare.Int.(String.length entrypoint > 31) then\n error (Entrypoint_name_too_long entrypoint)\n else\n match entrypoint with\n | \"\" ->\n ok ((c, \"default\"), ctxt)\n | \"default\" ->\n error (Unexpected_annotation loc)\n | name ->\n ok ((c, name), ctxt) )\n | None ->\n error\n @@ Invalid_syntactic_constant\n (loc, strip_locations expr, \"a valid address\") )\n | String (loc, s) (* As unparsed with [Readable]. *) ->\n Gas.consume ctxt Typecheck_costs.contract\n >>? fun ctxt ->\n ( match String.index_opt s '%' with\n | None ->\n ok (s, \"default\")\n | Some pos -> (\n let len = String.length s - pos - 1 in\n let name = String.sub s (pos + 1) len in\n if Compare.Int.(len > 31) then error (Entrypoint_name_too_long name)\n else\n match (String.sub s 0 pos, name) with\n | (addr, \"\") ->\n ok (addr, \"default\")\n | (_, \"default\") ->\n error @@ Unexpected_annotation loc\n | addr_and_name ->\n ok addr_and_name ) )\n >>? fun (addr, entrypoint) ->\n Contract.of_b58check addr >|? fun c -> ((c, entrypoint), ctxt)\n | expr ->\n error\n @@ Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)\n\nlet parse_never expr = error @@ Invalid_never_expr (location expr)\n\n(* -- parse data of complex types -- *)\n\ntype ('ty, 'depth) comb_witness =\n | Comb_Pair : ('t, 'd) comb_witness -> (_ * 't, unit -> 'd) comb_witness\n | Comb_Any : (_, _) comb_witness\n\nlet parse_pair (type r) parse_l parse_r ctxt ~legacy\n (r_comb_witness : (r, unit -> _) comb_witness) expr =\n let parse_comb loc l rs =\n parse_l ctxt l\n >>=? fun (l, ctxt) ->\n ( match (rs, r_comb_witness) with\n | ([r], _) ->\n ok r\n | ([], _) ->\n error @@ Invalid_arity (loc, D_Pair, 2, 1)\n | (_ :: _, Comb_Pair _) ->\n (* Unfold [Pair x1 ... xn] as [Pair x1 (Pair x2 ... xn-1 xn))]\n for type [pair ta (pair tb1 tb2)] and n >= 3 only *)\n ok (Prim (loc, D_Pair, rs, []))\n | _ ->\n error @@ Invalid_arity (loc, D_Pair, 2, 1 + List.length rs) )\n >>?= fun r -> parse_r ctxt r >|=? fun (r, ctxt) -> ((l, r), ctxt)\n in\n match expr with\n | Prim (loc, D_Pair, l :: rs, annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>?= fun () -> parse_comb loc l rs\n | Prim (loc, D_Pair, l, _) ->\n fail @@ Invalid_arity (loc, D_Pair, 2, List.length l)\n (* Unfold [{x1; ...; xn}] as [Pair x1 x2 ... xn-1 xn] for n >= 2 *)\n | Seq (loc, l :: (_ :: _ as rs)) ->\n parse_comb loc l rs\n | Seq (loc, l) ->\n fail @@ Invalid_seq_arity (loc, 2, List.length l)\n | expr ->\n fail @@ unexpected expr [] Constant_namespace [D_Pair]\n\nlet parse_union parse_l parse_r ctxt ~legacy = function\n | Prim (loc, D_Left, [v], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>?= fun () -> parse_l ctxt v >|=? fun (v, ctxt) -> (L v, ctxt)\n | Prim (loc, D_Left, l, _) ->\n fail @@ Invalid_arity (loc, D_Left, 1, List.length l)\n | Prim (loc, D_Right, [v], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>?= fun () -> parse_r ctxt v >|=? fun (v, ctxt) -> (R v, ctxt)\n | Prim (loc, D_Right, l, _) ->\n fail @@ Invalid_arity (loc, D_Right, 1, List.length l)\n | expr ->\n fail @@ unexpected expr [] Constant_namespace [D_Left; D_Right]\n\nlet parse_option parse_v ctxt ~legacy = function\n | Prim (loc, D_Some, [v], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>?= fun () -> parse_v ctxt v >|=? fun (v, ctxt) -> (Some v, ctxt)\n | Prim (loc, D_Some, l, _) ->\n fail @@ Invalid_arity (loc, D_Some, 1, List.length l)\n | Prim (loc, D_None, [], annot) ->\n Lwt.return\n ( (if legacy then ok_unit else error_unexpected_annot loc annot)\n >|? fun () -> (None, ctxt) )\n | Prim (loc, D_None, l, _) ->\n fail @@ Invalid_arity (loc, D_None, 0, List.length l)\n | expr ->\n fail @@ unexpected expr [] Constant_namespace [D_Some; D_None]\n\n(* -- parse data of comparable types -- *)\n\nlet comparable_comb_witness1 :\n type t. t comparable_ty -> (t, unit -> unit) comb_witness = function\n | Pair_key _ ->\n Comb_Pair Comb_Any\n | _ ->\n Comb_Any\n\nlet rec parse_comparable_data :\n type a.\n ?type_logger:type_logger ->\n context ->\n a comparable_ty ->\n Script.node ->\n (a * context) tzresult Lwt.t =\n fun ?type_logger ctxt ty script_data ->\n (* No need for stack_depth here. Unlike [parse_data],\n [parse_comparable_data] doesn't call [parse_returning].\n The stack depth is bounded by the type depth, bounded by 1024. *)\n let parse_data_error () =\n serialize_ty_for_error ctxt (ty_of_comparable_ty ty)\n >|? fun (ty, _ctxt) ->\n Invalid_constant (location script_data, strip_locations script_data, ty)\n in\n let traced_no_lwt body = record_trace_eval parse_data_error body in\n let traced body =\n trace_eval (fun () -> Lwt.return @@ parse_data_error ()) body\n in\n Gas.consume ctxt Typecheck_costs.parse_data_cycle\n (* We could have a smaller cost but let's keep it consistent with\n [parse_data] for now. *)\n >>?= fun ctxt ->\n let legacy = false in\n match (ty, script_data) with\n | (Unit_key _, expr) ->\n Lwt.return @@ traced_no_lwt\n @@ (parse_unit ctxt ~legacy expr : (a * context) tzresult)\n | (Bool_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_bool ctxt ~legacy expr\n | (String_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_string ctxt expr\n | (Bytes_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_bytes ctxt expr\n | (Int_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_int ctxt expr\n | (Nat_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_nat ctxt expr\n | (Mutez_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_mutez ctxt expr\n | (Timestamp_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_timestamp ctxt expr\n | (Key_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_key ctxt expr\n | (Key_hash_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_key_hash ctxt expr\n | (Signature_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_signature ctxt expr\n | (Chain_id_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_chain_id ctxt expr\n | (Address_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_address ctxt expr\n | (Pair_key ((tl, _), (tr, _), _), expr) ->\n let r_witness = comparable_comb_witness1 tr in\n let parse_l ctxt v = parse_comparable_data ?type_logger ctxt tl v in\n let parse_r ctxt v = parse_comparable_data ?type_logger ctxt tr v in\n traced @@ parse_pair parse_l parse_r ctxt ~legacy r_witness expr\n | (Union_key ((tl, _), (tr, _), _), expr) ->\n let parse_l ctxt v = parse_comparable_data ?type_logger ctxt tl v in\n let parse_r ctxt v = parse_comparable_data ?type_logger ctxt tr v in\n traced @@ parse_union parse_l parse_r ctxt ~legacy expr\n | (Option_key (t, _), expr) ->\n let parse_v ctxt v = parse_comparable_data ?type_logger ctxt t v in\n traced @@ parse_option parse_v ctxt ~legacy expr\n | (Never_key _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_never expr\n\n(* -- parse data of any type -- *)\n\nlet comb_witness1 : type t. t ty -> (t, unit -> unit) comb_witness = function\n | Pair_t _ ->\n Comb_Pair Comb_Any\n | _ ->\n Comb_Any\n\n(*\n Some values, such as operations, tickets, or big map ids, are used only\n internally and are not allowed to be forged by users.\n In [parse_data], [allow_forged] should be [false] for:\n - PUSH\n - UNPACK\n - user-provided script parameters\n - storage on origination\n And [true] for:\n - internal calls parameters\n - storage after origination\n*)\n\nlet rec parse_data :\n type a.\n ?type_logger:type_logger ->\n stack_depth:int ->\n context ->\n legacy:bool ->\n allow_forged:bool ->\n a ty ->\n Script.node ->\n (a * context) tzresult Lwt.t =\n fun ?type_logger ~stack_depth ctxt ~legacy ~allow_forged ty script_data ->\n Gas.consume ctxt Typecheck_costs.parse_data_cycle\n >>?= fun ctxt ->\n let non_terminal_recursion ?type_logger ctxt ~legacy ty script_data =\n if Compare.Int.(stack_depth > 10_000) then\n fail Typechecking_too_many_recursive_calls\n else\n parse_data\n ?type_logger\n ~stack_depth:(stack_depth + 1)\n ctxt\n ~legacy\n ~allow_forged\n ty\n script_data\n in\n let parse_data_error () =\n serialize_ty_for_error ctxt ty\n >|? fun (ty, _ctxt) ->\n Invalid_constant (location script_data, strip_locations script_data, ty)\n in\n let fail_parse_data () = parse_data_error () >>?= fail in\n let traced_no_lwt body = record_trace_eval parse_data_error body in\n let traced body =\n trace_eval (fun () -> Lwt.return @@ parse_data_error ()) body\n in\n let traced_fail err = Lwt.return @@ traced_no_lwt (error err) in\n let parse_items ?type_logger ctxt expr key_type value_type items item_wrapper\n =\n fold_left_s\n (fun (last_value, map, ctxt) item ->\n match item with\n | Prim (loc, D_Elt, [k; v], annot) ->\n (if legacy then ok_unit else error_unexpected_annot loc annot)\n >>?= fun () ->\n parse_comparable_data ?type_logger ctxt key_type k\n >>=? fun (k, ctxt) ->\n non_terminal_recursion ?type_logger ctxt ~legacy value_type v\n >>=? fun (v, ctxt) ->\n Lwt.return\n ( ( match last_value with\n | Some value ->\n Gas.consume\n ctxt\n (Michelson_v1_gas.Cost_of.Interpreter.compare\n key_type\n value\n k)\n >>? fun ctxt ->\n let c = compare_comparable key_type value k in\n if Compare.Int.(0 <= c) then\n if Compare.Int.(0 = c) then\n error (Duplicate_map_keys (loc, strip_locations expr))\n else\n error (Unordered_map_keys (loc, strip_locations expr))\n else ok ctxt\n | None ->\n ok ctxt )\n >>? fun ctxt ->\n Gas.consume\n ctxt\n (Michelson_v1_gas.Cost_of.Interpreter.map_update k map)\n >|? fun ctxt ->\n (Some k, map_update k (Some (item_wrapper v)) map, ctxt) )\n | Prim (loc, D_Elt, l, _) ->\n fail @@ Invalid_arity (loc, D_Elt, 2, List.length l)\n | Prim (loc, name, _, _) ->\n fail @@ Invalid_primitive (loc, [D_Elt], name)\n | Int _ | String _ | Bytes _ | Seq _ ->\n fail_parse_data ())\n (None, empty_map key_type, ctxt)\n items\n |> traced\n >|=? fun (_, items, ctxt) -> (items, ctxt)\n in\n match (ty, script_data) with\n | (Unit_t _, expr) ->\n Lwt.return @@ traced_no_lwt\n @@ (parse_unit ctxt ~legacy expr : (a * context) tzresult)\n | (Bool_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_bool ctxt ~legacy expr\n | (String_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_string ctxt expr\n | (Bytes_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_bytes ctxt expr\n | (Int_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_int ctxt expr\n | (Nat_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_nat ctxt expr\n | (Mutez_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_mutez ctxt expr\n | (Timestamp_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_timestamp ctxt expr\n | (Key_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_key ctxt expr\n | (Key_hash_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_key_hash ctxt expr\n | (Signature_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_signature ctxt expr\n | (Operation_t _, _) ->\n (* operations cannot appear in parameters or storage,\n the protocol should never parse the bytes of an operation *)\n assert false\n | (Chain_id_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_chain_id ctxt expr\n | (Address_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_address ctxt expr\n | (Contract_t (ty, _), expr) ->\n traced\n ( parse_address ctxt expr\n >>?= fun ((c, entrypoint), ctxt) ->\n let loc = location expr in\n parse_contract ~legacy ctxt loc ty c ~entrypoint\n >|=? fun (ctxt, _) -> ((ty, (c, entrypoint)), ctxt) )\n (* Pairs *)\n | (Pair_t ((tl, _, _), (tr, _, _), _), expr) ->\n let r_witness = comb_witness1 tr in\n let parse_l ctxt v =\n non_terminal_recursion ?type_logger ctxt ~legacy tl v\n in\n let parse_r ctxt v =\n non_terminal_recursion ?type_logger ctxt ~legacy tr v\n in\n traced @@ parse_pair parse_l parse_r ctxt ~legacy r_witness expr\n (* Unions *)\n | (Union_t ((tl, _), (tr, _), _), expr) ->\n let parse_l ctxt v =\n non_terminal_recursion ?type_logger ctxt ~legacy tl v\n in\n let parse_r ctxt v =\n non_terminal_recursion ?type_logger ctxt ~legacy tr v\n in\n traced @@ parse_union parse_l parse_r ctxt ~legacy expr\n (* Lambdas *)\n | (Lambda_t (ta, tr, _ty_name), (Seq (_loc, _) as script_instr)) ->\n traced\n @@ parse_returning\n Lambda\n ?type_logger\n ~stack_depth\n ctxt\n ~legacy\n (ta, Some (Var_annot \"@arg\"))\n tr\n script_instr\n | (Lambda_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Seq_kind], kind expr))\n (* Options *)\n | (Option_t (t, _), expr) ->\n let parse_v ctxt v =\n non_terminal_recursion ?type_logger ctxt ~legacy t v\n in\n traced @@ parse_option parse_v ctxt ~legacy expr\n (* Lists *)\n | (List_t (t, _ty_name), Seq (_loc, items)) ->\n traced\n @@ fold_right_s\n (fun v (rest, ctxt) ->\n non_terminal_recursion ?type_logger ctxt ~legacy t v\n >|=? fun (v, ctxt) -> (list_cons v rest, ctxt))\n items\n (list_empty, ctxt)\n | (List_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Seq_kind], kind expr))\n (* Tickets *)\n | (Ticket_t (t, _ty_name), expr) ->\n if allow_forged then\n parse_comparable_data ?type_logger ctxt (opened_ticket_type t) expr\n >|=? fun ((ticketer, (contents, amount)), ctxt) ->\n ({ticketer; contents; amount}, ctxt)\n else traced_fail (Unexpected_forged_value (location expr))\n (* Sets *)\n | (Set_t (t, _ty_name), (Seq (loc, vs) as expr)) ->\n traced\n @@ fold_left_s\n (fun (last_value, set, ctxt) v ->\n parse_comparable_data ?type_logger ctxt t v\n >>=? fun (v, ctxt) ->\n Lwt.return\n ( ( match last_value with\n | Some value ->\n Gas.consume\n ctxt\n (Michelson_v1_gas.Cost_of.Interpreter.compare t value v)\n >>? fun ctxt ->\n let c = compare_comparable t value v in\n if Compare.Int.(0 <= c) then\n if Compare.Int.(0 = c) then\n error\n (Duplicate_set_values (loc, strip_locations expr))\n else\n error\n (Unordered_set_values (loc, strip_locations expr))\n else ok ctxt\n | None ->\n ok ctxt )\n >>? fun ctxt ->\n Gas.consume\n ctxt\n (Michelson_v1_gas.Cost_of.Interpreter.set_update v set)\n >|? fun ctxt -> (Some v, set_update v true set, ctxt) ))\n (None, empty_set t, ctxt)\n vs\n >|=? fun (_, set, ctxt) -> (set, ctxt)\n | (Set_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Seq_kind], kind expr))\n (* Maps *)\n | (Map_t (tk, tv, _ty_name), (Seq (_, vs) as expr)) ->\n parse_items ?type_logger ctxt expr tk tv vs (fun x -> x)\n | (Map_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Seq_kind], kind expr))\n | (Big_map_t (tk, tv, _ty_name), expr) ->\n ( match expr with\n | Int (loc, id) ->\n return (Some (id, loc), empty_map tk, ctxt)\n | Seq (_, vs) ->\n parse_items ?type_logger ctxt expr tk tv vs (fun x -> Some x)\n >|=? fun (diff, ctxt) -> (None, diff, ctxt)\n | Prim (loc, D_Pair, [Int (loc_id, id); Seq (_, vs)], annot) ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let tv_opt = Option_t (tv, None) in\n parse_items ?type_logger ctxt expr tk tv_opt vs (fun x -> x)\n >|=? fun (diff, ctxt) -> (Some (id, loc_id), diff, ctxt)\n | Prim (_, D_Pair, [Int _; expr], _) ->\n traced_fail (Invalid_kind (location expr, [Seq_kind], kind expr))\n | Prim (_, D_Pair, [expr; _], _) ->\n traced_fail (Invalid_kind (location expr, [Int_kind], kind expr))\n | Prim (loc, D_Pair, l, _) ->\n traced_fail @@ Invalid_arity (loc, D_Pair, 2, List.length l)\n | _ ->\n traced_fail\n (unexpected expr [Seq_kind; Int_kind] Constant_namespace [D_Pair])\n )\n >>=? fun (id_opt, diff, ctxt) ->\n ( match id_opt with\n | None ->\n return @@ (None, ctxt)\n | Some (id, loc) ->\n if allow_forged then\n let id = Big_map.Id.parse_z id in\n Big_map.exists ctxt id\n >>=? function\n | (_, None) ->\n traced_fail (Invalid_big_map (loc, id))\n | (ctxt, Some (btk, btv)) ->\n Lwt.return\n ( parse_comparable_ty ctxt (Micheline.root btk)\n >>? fun (Ex_comparable_ty btk, ctxt) ->\n parse_big_map_value_ty ctxt ~legacy (Micheline.root btv)\n >>? fun (Ex_ty btv, ctxt) ->\n comparable_ty_eq ctxt tk btk\n >>? fun (Eq, ctxt) ->\n ty_eq ctxt loc tv btv >>? fun (Eq, ctxt) -> ok (Some id, ctxt)\n )\n else traced_fail (Unexpected_forged_value loc) )\n >|=? fun (id, ctxt) -> ({id; diff; key_type = tk; value_type = tv}, ctxt)\n | (Never_t _, expr) ->\n Lwt.return @@ traced_no_lwt @@ parse_never expr\n (* Bls12_381 types *)\n | (Bls12_381_g1_t _, Bytes (_, bs)) -> (\n Gas.consume ctxt Typecheck_costs.bls12_381_g1\n >>?= fun ctxt ->\n match Bls12_381.G1.of_bytes_opt bs with\n | Some pt ->\n return (pt, ctxt)\n | None ->\n fail_parse_data () )\n | (Bls12_381_g1_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Bytes_kind], kind expr))\n | (Bls12_381_g2_t _, Bytes (_, bs)) -> (\n Gas.consume ctxt Typecheck_costs.bls12_381_g2\n >>?= fun ctxt ->\n match Bls12_381.G2.of_bytes_opt bs with\n | Some pt ->\n return (pt, ctxt)\n | None ->\n fail_parse_data () )\n | (Bls12_381_g2_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Bytes_kind], kind expr))\n | (Bls12_381_fr_t _, Bytes (_, bs)) -> (\n Gas.consume ctxt Typecheck_costs.bls12_381_fr\n >>?= fun ctxt ->\n match Bls12_381.Fr.of_bytes_opt bs with\n | Some pt ->\n return (pt, ctxt)\n | None ->\n fail_parse_data () )\n | (Bls12_381_fr_t _, Int (_, v)) ->\n Gas.consume ctxt Typecheck_costs.bls12_381_fr\n >>?= fun ctxt -> return (Bls12_381.Fr.of_z v, ctxt)\n | (Bls12_381_fr_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Bytes_kind], kind expr))\n (*\n /!\\ When adding new lazy storage kinds, you may want to guard the parsing\n of identifiers with [allow_forged].\n *)\n (* Sapling *)\n | (Sapling_transaction_t (memo_size, _), Bytes (_, bytes)) -> (\n match Data_encoding.Binary.of_bytes Sapling.transaction_encoding bytes with\n | Some transaction -> (\n match Sapling.transaction_get_memo_size transaction with\n | None ->\n return (transaction, ctxt)\n | Some transac_memo_size ->\n Lwt.return\n ( merge_memo_sizes memo_size transac_memo_size\n >|? fun _ms -> (transaction, ctxt) ) )\n | None ->\n fail_parse_data () )\n | (Sapling_transaction_t _, expr) ->\n traced_fail (Invalid_kind (location expr, [Bytes_kind], kind expr))\n | (Sapling_state_t (memo_size, _), Int (loc, id)) ->\n if allow_forged then\n let id = Sapling.Id.parse_z id in\n Sapling.state_from_id ctxt id\n >>=? fun (state, ctxt) ->\n Lwt.return\n ( traced_no_lwt @@ merge_memo_sizes memo_size state.Sapling.memo_size\n >|? fun _memo_size -> (state, ctxt) )\n else traced_fail (Unexpected_forged_value loc)\n | (Sapling_state_t (memo_size, _), Seq (_, [])) ->\n return (Sapling.empty_state ~memo_size (), ctxt)\n | (Sapling_state_t _, expr) ->\n (* Do not allow to input diffs as they are untrusted and may not be the\n result of a verify_update. *)\n traced_fail\n (Invalid_kind (location expr, [Int_kind; Seq_kind], kind expr))\n\nand parse_returning :\n type arg ret.\n ?type_logger:type_logger ->\n stack_depth:int ->\n tc_context ->\n context ->\n legacy:bool ->\n arg ty * var_annot option ->\n ret ty ->\n Script.node ->\n ((arg, ret) lambda * context) tzresult Lwt.t =\n fun ?type_logger\n ~stack_depth\n tc_context\n ctxt\n ~legacy\n (arg, arg_annot)\n ret\n script_instr ->\n parse_instr\n ?type_logger\n tc_context\n ctxt\n ~legacy\n ~stack_depth:(stack_depth + 1)\n script_instr\n (Item_t (arg, Empty_t, arg_annot))\n >>=? function\n | (Typed ({loc; aft = Item_t (ty, Empty_t, _) as stack_ty; _} as descr), ctxt)\n ->\n Lwt.return\n @@ record_trace_eval\n (fun () ->\n serialize_ty_for_error ctxt ret\n >>? fun (ret, ctxt) ->\n serialize_stack_for_error ctxt stack_ty\n >|? fun (stack_ty, _ctxt) -> Bad_return (loc, stack_ty, ret))\n ( merge_types ~legacy ctxt loc ty ret\n >|? fun (Eq, _ret, ctxt) ->\n ((Lam (descr, script_instr) : (arg, ret) lambda), ctxt) )\n | (Typed {loc; aft = stack_ty; _}, ctxt) ->\n Lwt.return\n ( serialize_ty_for_error ctxt ret\n >>? fun (ret, ctxt) ->\n serialize_stack_for_error ctxt stack_ty\n >>? fun (stack_ty, _ctxt) -> error (Bad_return (loc, stack_ty, ret)) )\n | (Failed {descr}, ctxt) ->\n return\n ( ( Lam (descr (Item_t (ret, Empty_t, None)), script_instr)\n : (arg, ret) lambda ),\n ctxt )\n\nand parse_instr :\n type bef.\n ?type_logger:type_logger ->\n stack_depth:int ->\n tc_context ->\n context ->\n legacy:bool ->\n Script.node ->\n bef stack_ty ->\n (bef judgement * context) tzresult Lwt.t =\n fun ?type_logger ~stack_depth tc_context ctxt ~legacy script_instr stack_ty ->\n let check_item_ty (type a b) ctxt (exp : a ty) (got : b ty) loc name n m :\n ((a, b) eq * a ty * context) tzresult =\n record_trace_eval (fun () ->\n serialize_stack_for_error ctxt stack_ty\n >|? fun (stack_ty, _ctxt) -> Bad_stack (loc, name, m, stack_ty))\n @@ record_trace\n (Bad_stack_item n)\n ( merge_types ~legacy ctxt loc exp got\n >>? fun (Eq, ty, ctxt) -> ok ((Eq : (a, b) eq), (ty : a ty), ctxt) )\n in\n let log_stack ctxt loc stack_ty aft =\n match (type_logger, script_instr) with\n | (None, _) | (Some _, (Seq (-1, _) | Int _ | String _ | Bytes _)) ->\n ok_unit\n | (Some log, (Prim _ | Seq _)) ->\n (* Unparsing for logging done in an unlimited context as this\n is used only by the client and not the protocol *)\n let ctxt = Gas.set_unlimited ctxt in\n unparse_stack ctxt stack_ty\n >>? fun (stack_ty, _) ->\n unparse_stack ctxt aft >|? fun (aft, _) -> log loc stack_ty aft ; ()\n in\n let return_no_lwt :\n type bef. context -> bef judgement -> (bef judgement * context) tzresult\n =\n fun ctxt judgement ->\n match judgement with\n | Typed {instr; loc; aft; _} ->\n let maximum_type_size = Constants.michelson_maximum_type_size ctxt in\n let type_size =\n type_size_of_stack_head\n aft\n ~up_to:(number_of_generated_growing_types instr)\n in\n if Compare.Int.(type_size > maximum_type_size) then\n error (Type_too_large (loc, type_size, maximum_type_size))\n else ok (judgement, ctxt)\n | Failed _ ->\n ok (judgement, ctxt)\n in\n let return :\n type bef.\n context -> bef judgement -> (bef judgement * context) tzresult Lwt.t =\n fun ctxt judgement -> Lwt.return @@ return_no_lwt ctxt judgement\n in\n let typed_no_lwt ctxt loc instr aft =\n log_stack ctxt loc stack_ty aft\n >>? fun () -> return_no_lwt ctxt (Typed {loc; instr; bef = stack_ty; aft})\n in\n let typed ctxt loc instr aft =\n Lwt.return @@ typed_no_lwt ctxt loc instr aft\n in\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>?= fun ctxt ->\n let non_terminal_recursion ?type_logger tc_context ctxt ~legacy script_instr\n stack_ty =\n if Compare.Int.(stack_depth > 10000) then\n fail Typechecking_too_many_recursive_calls\n else\n parse_instr\n ?type_logger\n tc_context\n ctxt\n ~stack_depth:(stack_depth + 1)\n ~legacy\n script_instr\n stack_ty\n in\n match (script_instr, stack_ty) with\n (* stack ops *)\n | (Prim (loc, I_DROP, [], annot), Item_t (_, rest, _)) ->\n ( error_unexpected_annot loc annot >>?= fun () -> typed ctxt loc Drop rest\n : (bef judgement * context) tzresult Lwt.t )\n | (Prim (loc, I_DROP, [n], result_annot), whole_stack) ->\n parse_uint10 n\n >>?= fun whole_n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument whole_n)\n >>?= fun ctxt ->\n let rec make_proof_argument :\n type tstk. int -> tstk stack_ty -> tstk dropn_proof_argument tzresult\n =\n fun n stk ->\n match (Compare.Int.(n = 0), stk) with\n | (true, rest) ->\n ok @@ Dropn_proof_argument (Rest, rest, rest)\n | (false, Item_t (v, rest, annot)) ->\n make_proof_argument (n - 1) rest\n >|? fun (Dropn_proof_argument (n', stack_after_drops, aft')) ->\n Dropn_proof_argument\n (Prefix n', stack_after_drops, Item_t (v, aft', annot))\n | (_, _) ->\n serialize_stack_for_error ctxt whole_stack\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_DROP, whole_n, whole_stack))\n in\n error_unexpected_annot loc result_annot\n >>?= fun () ->\n make_proof_argument whole_n whole_stack\n >>?= fun (Dropn_proof_argument (n', stack_after_drops, _aft)) ->\n typed ctxt loc (Dropn (whole_n, n')) stack_after_drops\n | (Prim (loc, I_DROP, (_ :: _ :: _ as l), _), _) ->\n (* Technically, the arities 0 and 1 are allowed but the error only mentions 1.\n However, DROP is equivalent to DROP 1 so hinting at an arity of 1 makes sense. *)\n fail (Invalid_arity (loc, I_DROP, 1, List.length l))\n | (Prim (loc, I_DUP, [], annot), Item_t (v, rest, stack_annot)) ->\n parse_var_annot loc annot ~default:stack_annot\n >>?= fun annot ->\n record_trace_eval\n (fun () ->\n serialize_ty_for_error ctxt v\n >|? fun (t, _ctxt) -> Non_dupable_type (loc, t))\n (check_dupable_ty ctxt loc v)\n >>?= fun ctxt ->\n typed ctxt loc Dup (Item_t (v, Item_t (v, rest, stack_annot), annot))\n | (Prim (loc, I_DUP, [n], v_annot), stack_ty) ->\n parse_var_annot loc v_annot\n >>?= fun annot ->\n let rec make_proof_argument :\n type before.\n int -> before stack_ty -> before dup_n_proof_argument tzresult =\n fun n (stack_ty : before stack_ty) ->\n match (n, stack_ty) with\n | (1, Item_t (hd_ty, _, _)) ->\n ok @@ Dup_n_proof_argument (Dup_n_zero, hd_ty)\n | (n, Item_t (_, tl_ty, _)) ->\n make_proof_argument (n - 1) tl_ty\n >|? fun (Dup_n_proof_argument (dup_n_witness, b_ty)) ->\n Dup_n_proof_argument (Dup_n_succ dup_n_witness, b_ty)\n | _ ->\n serialize_stack_for_error ctxt stack_ty\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_DUP, 1, whole_stack))\n in\n parse_uint10 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n error_unless (Compare.Int.( > ) n 0) (Dup_n_bad_argument loc)\n >>?= fun () ->\n record_trace (Dup_n_bad_stack loc) (make_proof_argument n stack_ty)\n >>?= fun (Dup_n_proof_argument (witness, after_ty)) ->\n record_trace_eval\n (fun () ->\n serialize_ty_for_error ctxt after_ty\n >|? fun (t, _ctxt) -> Non_dupable_type (loc, t))\n (check_dupable_ty ctxt loc after_ty)\n >>?= fun ctxt ->\n typed ctxt loc (Dup_n (n, witness)) (Item_t (after_ty, stack_ty, annot))\n | (Prim (loc, I_DIG, [n], result_annot), stack) ->\n let rec make_proof_argument :\n type tstk. int -> tstk stack_ty -> tstk dig_proof_argument tzresult =\n fun n stk ->\n match (Compare.Int.(n = 0), stk) with\n | (true, Item_t (v, rest, annot)) ->\n ok @@ Dig_proof_argument (Rest, (v, annot), rest)\n | (false, Item_t (v, rest, annot)) ->\n make_proof_argument (n - 1) rest\n >|? fun (Dig_proof_argument (n', (x, xv), aft')) ->\n Dig_proof_argument (Prefix n', (x, xv), Item_t (v, aft', annot))\n | (_, _) ->\n serialize_stack_for_error ctxt stack\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_DIG, 1, whole_stack))\n in\n parse_uint10 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n error_unexpected_annot loc result_annot\n >>?= fun () ->\n make_proof_argument n stack\n >>?= fun (Dig_proof_argument (n', (x, stack_annot), aft)) ->\n typed ctxt loc (Dig (n, n')) (Item_t (x, aft, stack_annot))\n | (Prim (loc, I_DIG, (([] | _ :: _ :: _) as l), _), _) ->\n fail (Invalid_arity (loc, I_DIG, 1, List.length l))\n | (Prim (loc, I_DUG, [n], result_annot), Item_t (x, whole_stack, stack_annot))\n ->\n parse_uint10 n\n >>?= fun whole_n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument whole_n)\n >>?= fun ctxt ->\n let rec make_proof_argument :\n type tstk x.\n int ->\n x ty ->\n var_annot option ->\n tstk stack_ty ->\n (tstk, x) dug_proof_argument tzresult =\n fun n x stack_annot stk ->\n match (Compare.Int.(n = 0), stk) with\n | (true, rest) ->\n ok @@ Dug_proof_argument (Rest, (), Item_t (x, rest, stack_annot))\n | (false, Item_t (v, rest, annot)) ->\n make_proof_argument (n - 1) x stack_annot rest\n >|? fun (Dug_proof_argument (n', (), aft')) ->\n Dug_proof_argument (Prefix n', (), Item_t (v, aft', annot))\n | (_, _) ->\n serialize_stack_for_error ctxt whole_stack\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_DUG, whole_n, whole_stack))\n in\n error_unexpected_annot loc result_annot\n >>?= fun () ->\n make_proof_argument whole_n x stack_annot whole_stack\n >>?= fun (Dug_proof_argument (n', (), aft)) ->\n typed ctxt loc (Dug (whole_n, n')) aft\n | (Prim (loc, I_DUG, [_], result_annot), (Empty_t as stack)) ->\n Lwt.return\n ( error_unexpected_annot loc result_annot\n >>? fun () ->\n serialize_stack_for_error ctxt stack\n >>? fun (stack, _ctxt) -> error (Bad_stack (loc, I_DUG, 1, stack)) )\n | (Prim (loc, I_DUG, (([] | _ :: _ :: _) as l), _), _) ->\n fail (Invalid_arity (loc, I_DUG, 1, List.length l))\n | ( Prim (loc, I_SWAP, [], annot),\n Item_t (v, Item_t (w, rest, stack_annot), cur_top_annot) ) ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n typed\n ctxt\n loc\n Swap\n (Item_t (w, Item_t (v, rest, cur_top_annot), stack_annot))\n | (Prim (loc, I_PUSH, [t; d], annot), stack) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n parse_packable_ty ctxt ~legacy t\n >>?= fun (Ex_ty t, ctxt) ->\n parse_data\n ?type_logger\n ~stack_depth:(stack_depth + 1)\n ctxt\n ~legacy\n ~allow_forged:false\n t\n d\n >>=? fun (v, ctxt) -> typed ctxt loc (Const v) (Item_t (t, stack, annot))\n | (Prim (loc, I_UNIT, [], annot), stack) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n typed ctxt loc (Const ()) (Item_t (Unit_t ty_name, stack, annot))\n (* options *)\n | (Prim (loc, I_SOME, [], annot), Item_t (t, rest, _)) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n typed ctxt loc Cons_some (Item_t (Option_t (t, ty_name), rest, annot))\n | (Prim (loc, I_NONE, [t], annot), stack) ->\n parse_any_ty ctxt ~legacy t\n >>?= fun (Ex_ty t, ctxt) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n typed\n ctxt\n loc\n (Cons_none t)\n (Item_t (Option_t (t, ty_name), stack, annot))\n | ( Prim (loc, I_IF_NONE, [bt; bf], annot),\n (Item_t (Option_t (t, _), rest, option_annot) as bef) ) ->\n check_kind [Seq_kind] bt\n >>?= fun () ->\n check_kind [Seq_kind] bf\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let annot = gen_access_annot option_annot default_some_annot in\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy bt rest\n >>=? fun (btr, ctxt) ->\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n bf\n (Item_t (t, rest, annot))\n >>=? fun (bfr, ctxt) ->\n let branch ibt ibf =\n {loc; instr = If_none (ibt, ibf); bef; aft = ibt.aft}\n in\n merge_branches ~legacy ctxt loc btr bfr {branch}\n >>?= fun (judgement, ctxt) -> return ctxt judgement\n (* pairs *)\n | ( Prim (loc, I_PAIR, [], annot),\n Item_t (a, Item_t (b, rest, snd_annot), fst_annot) ) ->\n parse_constr_annot\n loc\n annot\n ~if_special_first:(var_to_field_annot fst_annot)\n ~if_special_second:(var_to_field_annot snd_annot)\n >>?= fun (annot, ty_name, l_field, r_field) ->\n typed\n ctxt\n loc\n Cons_pair\n (Item_t\n ( Pair_t ((a, l_field, fst_annot), (b, r_field, snd_annot), ty_name),\n rest,\n annot ))\n | (Prim (loc, I_PAIR, [n], annot), stack_ty) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n let rec make_proof_argument :\n type before.\n int ->\n before stack_ty ->\n (before comb_proof_argument * var_annot option) tzresult =\n fun n stack_ty ->\n match (n, stack_ty) with\n | (1, Item_t (a_ty, tl_ty, a_annot_opt)) ->\n ok\n ( Comb_proof_argument (Comb_one, Item_t (a_ty, tl_ty, annot)),\n a_annot_opt )\n | (n, Item_t (a_ty, tl_ty, prop_annot_opt)) ->\n make_proof_argument (n - 1) tl_ty\n >|? fun ( Comb_proof_argument\n (comb_witness, Item_t (b_ty, tl_ty', annot)),\n b_annot_opt ) ->\n let prop_annot_opt' = var_to_field_annot prop_annot_opt in\n let b_prop_annot_opt = var_to_field_annot b_annot_opt in\n let pair_t =\n Pair_t\n ( (a_ty, prop_annot_opt', None),\n (b_ty, b_prop_annot_opt, None),\n None )\n in\n ( Comb_proof_argument\n (Comb_succ comb_witness, Item_t (pair_t, tl_ty', annot)),\n None )\n | _ ->\n serialize_stack_for_error ctxt stack_ty\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_PAIR, 1, whole_stack))\n in\n parse_uint10 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n error_unless (Compare.Int.( > ) n 1) (Pair_bad_argument loc)\n >>?= fun () ->\n make_proof_argument n stack_ty\n >>?= fun (Comb_proof_argument (witness, after_ty), _none) ->\n typed ctxt loc (Comb (n, witness)) after_ty\n | (Prim (loc, I_UNPAIR, [n], annot), stack_ty) ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let rec make_proof_argument :\n type before.\n int -> before stack_ty -> before uncomb_proof_argument tzresult =\n fun n stack_ty ->\n match (n, stack_ty) with\n | (1, Item_t (a_ty, tl_ty, annot)) ->\n ok\n @@ Uncomb_proof_argument (Uncomb_one, Item_t (a_ty, tl_ty, annot))\n | ( n,\n Item_t\n ( Pair_t ((a_ty, field_opt, _), (b_ty, b_field_opt, _), _),\n tl_ty,\n _ ) ) ->\n let b_annot = Script_ir_annot.field_to_var_annot b_field_opt in\n make_proof_argument (n - 1) (Item_t (b_ty, tl_ty, b_annot))\n >|? fun (Uncomb_proof_argument (uncomb_witness, after_ty)) ->\n Uncomb_proof_argument\n ( Uncomb_succ uncomb_witness,\n Item_t\n (a_ty, after_ty, Script_ir_annot.field_to_var_annot field_opt)\n )\n | _ ->\n serialize_stack_for_error ctxt stack_ty\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_UNPAIR, 1, whole_stack))\n in\n parse_uint10 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n error_unless (Compare.Int.( > ) n 1) (Unpair_bad_argument loc)\n >>?= fun () ->\n make_proof_argument n stack_ty\n >>?= fun (Uncomb_proof_argument (witness, after_ty)) ->\n typed ctxt loc (Uncomb (n, witness)) after_ty\n | (Prim (loc, I_GET, [n], annot), Item_t (comb_ty, rest_ty, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n let rec make_proof_argument :\n type before.\n int -> before ty -> before comb_get_proof_argument tzresult =\n fun n ty ->\n match (n, ty) with\n | (0, value_ty) ->\n ok @@ Comb_get_proof_argument (Comb_get_zero, value_ty)\n | (1, Pair_t ((hd_ty, _at1, _at2), _, _annot)) ->\n ok @@ Comb_get_proof_argument (Comb_get_one, hd_ty)\n | (n, Pair_t (_, (tl_ty, _bt1, _bt2), _annot)) ->\n make_proof_argument (n - 2) tl_ty\n >|? fun (Comb_get_proof_argument (comb_get_left_witness, ty')) ->\n Comb_get_proof_argument\n (Comb_get_plus_two comb_get_left_witness, ty')\n | _ ->\n serialize_stack_for_error ctxt stack_ty\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_GET, 1, whole_stack))\n in\n parse_uint11 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n make_proof_argument n comb_ty\n >>?= fun (Comb_get_proof_argument (witness, ty')) ->\n let after_stack_ty = Item_t (ty', rest_ty, annot) in\n typed ctxt loc (Comb_get (n, witness)) after_stack_ty\n | ( Prim (loc, I_UPDATE, [n], annot),\n Item_t (value_ty, Item_t (comb_ty, rest_ty, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n let rec make_proof_argument :\n type value before.\n int ->\n value ty ->\n before ty ->\n (value, before) comb_set_proof_argument tzresult =\n fun n value_ty ty ->\n match (n, ty) with\n | (0, _) ->\n ok @@ Comb_set_proof_argument (Comb_set_zero, value_ty)\n | (1, Pair_t ((_hd_ty, at1, at2), (tl_ty, bt1, bt2), annot)) ->\n let after_ty =\n Pair_t ((value_ty, at1, at2), (tl_ty, bt1, bt2), annot)\n in\n ok @@ Comb_set_proof_argument (Comb_set_one, after_ty)\n | (n, Pair_t ((hd_ty, at1, at2), (tl_ty, bt1, bt2), annot)) ->\n make_proof_argument (n - 2) value_ty tl_ty\n >|? fun (Comb_set_proof_argument (comb_set_left_witness, tl_ty')) ->\n let after_ty =\n Pair_t ((hd_ty, at1, at2), (tl_ty', bt1, bt2), annot)\n in\n Comb_set_proof_argument\n (Comb_set_plus_two comb_set_left_witness, after_ty)\n | _ ->\n serialize_stack_for_error ctxt stack_ty\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_UPDATE, 2, whole_stack))\n in\n parse_uint11 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n make_proof_argument n value_ty comb_ty\n >>?= fun (Comb_set_proof_argument (witness, after_ty)) ->\n let after_stack_ty = Item_t (after_ty, rest_ty, annot) in\n typed ctxt loc (Comb_set (n, witness)) after_stack_ty\n | ( Prim (loc, I_UNPAIR, [], annot),\n Item_t\n ( Pair_t\n ( (a, expected_field_annot_a, a_annot),\n (b, expected_field_annot_b, b_annot),\n _ ),\n rest,\n pair_annot ) ) ->\n parse_unpair_annot\n loc\n annot\n ~pair_annot\n ~value_annot_car:a_annot\n ~value_annot_cdr:b_annot\n ~field_name_car:expected_field_annot_a\n ~field_name_cdr:expected_field_annot_b\n >>?= fun (annot_a, annot_b, field_a, field_b) ->\n check_correct_field field_a expected_field_annot_a\n >>?= fun () ->\n check_correct_field field_b expected_field_annot_b\n >>?= fun () ->\n typed ctxt loc Unpair (Item_t (a, Item_t (b, rest, annot_b), annot_a))\n | ( Prim (loc, I_CAR, [], annot),\n Item_t\n (Pair_t ((a, expected_field_annot, a_annot), _, _), rest, pair_annot)\n ) ->\n parse_destr_annot\n loc\n annot\n ~pair_annot\n ~value_annot:a_annot\n ~field_name:expected_field_annot\n ~default_accessor:default_car_annot\n >>?= fun (annot, field_annot) ->\n check_correct_field field_annot expected_field_annot\n >>?= fun () -> typed ctxt loc Car (Item_t (a, rest, annot))\n | ( Prim (loc, I_CDR, [], annot),\n Item_t\n (Pair_t (_, (b, expected_field_annot, b_annot), _), rest, pair_annot)\n ) ->\n parse_destr_annot\n loc\n annot\n ~pair_annot\n ~value_annot:b_annot\n ~field_name:expected_field_annot\n ~default_accessor:default_cdr_annot\n >>?= fun (annot, field_annot) ->\n check_correct_field field_annot expected_field_annot\n >>?= fun () -> typed ctxt loc Cdr (Item_t (b, rest, annot))\n (* unions *)\n | (Prim (loc, I_LEFT, [tr], annot), Item_t (tl, rest, stack_annot)) ->\n parse_any_ty ctxt ~legacy tr\n >>?= fun (Ex_ty tr, ctxt) ->\n parse_constr_annot\n loc\n annot\n ~if_special_first:(var_to_field_annot stack_annot)\n >>?= fun (annot, tname, l_field, r_field) ->\n typed\n ctxt\n loc\n Cons_left\n (Item_t (Union_t ((tl, l_field), (tr, r_field), tname), rest, annot))\n | (Prim (loc, I_RIGHT, [tl], annot), Item_t (tr, rest, stack_annot)) ->\n parse_any_ty ctxt ~legacy tl\n >>?= fun (Ex_ty tl, ctxt) ->\n parse_constr_annot\n loc\n annot\n ~if_special_second:(var_to_field_annot stack_annot)\n >>?= fun (annot, tname, l_field, r_field) ->\n typed\n ctxt\n loc\n Cons_right\n (Item_t (Union_t ((tl, l_field), (tr, r_field), tname), rest, annot))\n | ( Prim (loc, I_IF_LEFT, [bt; bf], annot),\n ( Item_t (Union_t ((tl, l_field), (tr, r_field), _), rest, union_annot)\n as bef ) ) ->\n check_kind [Seq_kind] bt\n >>?= fun () ->\n check_kind [Seq_kind] bf\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let left_annot =\n gen_access_annot union_annot l_field ~default:default_left_annot\n in\n let right_annot =\n gen_access_annot union_annot r_field ~default:default_right_annot\n in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n bt\n (Item_t (tl, rest, left_annot))\n >>=? fun (btr, ctxt) ->\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n bf\n (Item_t (tr, rest, right_annot))\n >>=? fun (bfr, ctxt) ->\n let branch ibt ibf =\n {loc; instr = If_left (ibt, ibf); bef; aft = ibt.aft}\n in\n merge_branches ~legacy ctxt loc btr bfr {branch}\n >>?= fun (judgement, ctxt) -> return ctxt judgement\n (* lists *)\n | (Prim (loc, I_NIL, [t], annot), stack) ->\n parse_any_ty ctxt ~legacy t\n >>?= fun (Ex_ty t, ctxt) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n typed ctxt loc Nil (Item_t (List_t (t, ty_name), stack, annot))\n | ( Prim (loc, I_CONS, [], annot),\n Item_t (tv, Item_t (List_t (t, ty_name), rest, _), _) ) ->\n check_item_ty ctxt tv t loc I_CONS 1 2\n >>?= fun (Eq, t, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Cons_list (Item_t (List_t (t, ty_name), rest, annot))\n | ( Prim (loc, I_IF_CONS, [bt; bf], annot),\n (Item_t (List_t (t, ty_name), rest, list_annot) as bef) ) ->\n check_kind [Seq_kind] bt\n >>?= fun () ->\n check_kind [Seq_kind] bf\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let hd_annot = gen_access_annot list_annot default_hd_annot in\n let tl_annot = gen_access_annot list_annot default_tl_annot in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n bt\n (Item_t (t, Item_t (List_t (t, ty_name), rest, tl_annot), hd_annot))\n >>=? fun (btr, ctxt) ->\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy bf rest\n >>=? fun (bfr, ctxt) ->\n let branch ibt ibf =\n {loc; instr = If_cons (ibt, ibf); bef; aft = ibt.aft}\n in\n merge_branches ~legacy ctxt loc btr bfr {branch}\n >>?= fun (judgement, ctxt) -> return ctxt judgement\n | (Prim (loc, I_SIZE, [], annot), Item_t (List_t _, rest, _)) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, tname) ->\n typed ctxt loc List_size (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_MAP, [body], annot),\n Item_t (List_t (elt, _), starting_rest, list_annot) ) -> (\n check_kind [Seq_kind] body\n >>?= fun () ->\n parse_var_type_annot loc annot\n >>?= fun (ret_annot, list_ty_name) ->\n let elt_annot = gen_access_annot list_annot default_elt_annot in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n body\n (Item_t (elt, starting_rest, elt_annot))\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ({aft = Item_t (ret, rest, _); _} as ibody) ->\n let invalid_map_body () =\n serialize_stack_for_error ctxt ibody.aft\n >|? fun (aft, _ctxt) -> Invalid_map_body (loc, aft)\n in\n Lwt.return\n @@ record_trace_eval\n invalid_map_body\n ( merge_stacks ~legacy loc ctxt 1 rest starting_rest\n >>? fun (Eq, rest, ctxt) ->\n typed_no_lwt\n ctxt\n loc\n (List_map ibody)\n (Item_t (List_t (ret, list_ty_name), rest, ret_annot)) )\n | Typed {aft; _} ->\n Lwt.return\n ( serialize_stack_for_error ctxt aft\n >>? fun (aft, _ctxt) -> error (Invalid_map_body (loc, aft)) )\n | Failed _ ->\n fail (Invalid_map_block_fail loc) )\n | ( Prim (loc, I_ITER, [body], annot),\n Item_t (List_t (elt, _), rest, list_annot) ) -> (\n check_kind [Seq_kind] body\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let elt_annot = gen_access_annot list_annot default_elt_annot in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n body\n (Item_t (elt, rest, elt_annot))\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ({aft; _} as ibody) ->\n let invalid_iter_body () =\n serialize_stack_for_error ctxt ibody.aft\n >>? fun (aft, ctxt) ->\n serialize_stack_for_error ctxt rest\n >|? fun (rest, _ctxt) -> Invalid_iter_body (loc, rest, aft)\n in\n Lwt.return\n @@ record_trace_eval\n invalid_iter_body\n ( merge_stacks ~legacy loc ctxt 1 aft rest\n >>? fun (Eq, rest, ctxt) ->\n typed_no_lwt ctxt loc (List_iter ibody) rest )\n | Failed {descr} ->\n typed ctxt loc (List_iter (descr rest)) rest )\n (* sets *)\n | (Prim (loc, I_EMPTY_SET, [t], annot), rest) ->\n parse_comparable_ty ctxt t\n >>?= fun (Ex_comparable_ty t, ctxt) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, tname) ->\n typed ctxt loc (Empty_set t) (Item_t (Set_t (t, tname), rest, annot))\n | ( Prim (loc, I_ITER, [body], annot),\n Item_t (Set_t (comp_elt, _), rest, set_annot) ) -> (\n check_kind [Seq_kind] body\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let elt_annot = gen_access_annot set_annot default_elt_annot in\n let elt = ty_of_comparable_ty comp_elt in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n body\n (Item_t (elt, rest, elt_annot))\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ({aft; _} as ibody) ->\n let invalid_iter_body () =\n serialize_stack_for_error ctxt ibody.aft\n >>? fun (aft, ctxt) ->\n serialize_stack_for_error ctxt rest\n >|? fun (rest, _ctxt) -> Invalid_iter_body (loc, rest, aft)\n in\n Lwt.return\n @@ record_trace_eval\n invalid_iter_body\n ( merge_stacks ~legacy loc ctxt 1 aft rest\n >>? fun (Eq, rest, ctxt) ->\n typed_no_lwt ctxt loc (Set_iter ibody) rest )\n | Failed {descr} ->\n typed ctxt loc (Set_iter (descr rest)) rest )\n | ( Prim (loc, I_MEM, [], annot),\n Item_t (v, Item_t (Set_t (elt, _), rest, _), _) ) ->\n let elt = ty_of_comparable_ty elt in\n parse_var_type_annot loc annot\n >>?= fun (annot, tname) ->\n check_item_ty ctxt elt v loc I_MEM 1 2\n >>?= fun (Eq, _, ctxt) ->\n typed ctxt loc Set_mem (Item_t (Bool_t tname, rest, annot))\n | ( Prim (loc, I_UPDATE, [], annot),\n Item_t\n ( v,\n Item_t (Bool_t _, Item_t (Set_t (elt, tname), rest, set_annot), _),\n _ ) ) ->\n check_item_ty ctxt (ty_of_comparable_ty elt) v loc I_UPDATE 1 3\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot ~default:set_annot\n >>?= fun annot ->\n typed ctxt loc Set_update (Item_t (Set_t (elt, tname), rest, annot))\n | (Prim (loc, I_SIZE, [], annot), Item_t (Set_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Set_size (Item_t (Nat_t None, rest, annot))\n (* maps *)\n | (Prim (loc, I_EMPTY_MAP, [tk; tv], annot), stack) ->\n parse_comparable_ty ctxt tk\n >>?= fun (Ex_comparable_ty tk, ctxt) ->\n parse_any_ty ctxt ~legacy tv\n >>?= fun (Ex_ty tv, ctxt) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n typed\n ctxt\n loc\n (Empty_map (tk, tv))\n (Item_t (Map_t (tk, tv, ty_name), stack, annot))\n | ( Prim (loc, I_MAP, [body], annot),\n Item_t (Map_t (ck, elt, _), starting_rest, _map_annot) ) -> (\n let k = ty_of_comparable_ty ck in\n check_kind [Seq_kind] body\n >>?= fun () ->\n parse_var_type_annot loc annot\n >>?= fun (ret_annot, ty_name) ->\n let k_name = field_to_var_annot default_key_annot in\n let e_name = field_to_var_annot default_elt_annot in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n body\n (Item_t\n ( Pair_t ((k, None, k_name), (elt, None, e_name), None),\n starting_rest,\n None ))\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ({aft = Item_t (ret, rest, _); _} as ibody) ->\n let invalid_map_body () =\n serialize_stack_for_error ctxt ibody.aft\n >|? fun (aft, _ctxt) -> Invalid_map_body (loc, aft)\n in\n Lwt.return\n @@ record_trace_eval\n invalid_map_body\n ( merge_stacks ~legacy loc ctxt 1 rest starting_rest\n >>? fun (Eq, rest, ctxt) ->\n typed_no_lwt\n ctxt\n loc\n (Map_map ibody)\n (Item_t (Map_t (ck, ret, ty_name), rest, ret_annot)) )\n | Typed {aft; _} ->\n Lwt.return\n ( serialize_stack_for_error ctxt aft\n >>? fun (aft, _ctxt) -> error (Invalid_map_body (loc, aft)) )\n | Failed _ ->\n fail (Invalid_map_block_fail loc) )\n | ( Prim (loc, I_ITER, [body], annot),\n Item_t (Map_t (comp_elt, element_ty, _), rest, _map_annot) ) -> (\n check_kind [Seq_kind] body\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let k_name = field_to_var_annot default_key_annot in\n let e_name = field_to_var_annot default_elt_annot in\n let key = ty_of_comparable_ty comp_elt in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n body\n (Item_t\n ( Pair_t ((key, None, k_name), (element_ty, None, e_name), None),\n rest,\n None ))\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ({aft; _} as ibody) ->\n let invalid_iter_body () =\n serialize_stack_for_error ctxt ibody.aft\n >>? fun (aft, ctxt) ->\n serialize_stack_for_error ctxt rest\n >|? fun (rest, _ctxt) -> Invalid_iter_body (loc, rest, aft)\n in\n Lwt.return\n @@ record_trace_eval\n invalid_iter_body\n ( merge_stacks ~legacy loc ctxt 1 aft rest\n >>? fun (Eq, rest, ctxt) ->\n typed_no_lwt ctxt loc (Map_iter ibody) rest )\n | Failed {descr} ->\n typed ctxt loc (Map_iter (descr rest)) rest )\n | ( Prim (loc, I_MEM, [], annot),\n Item_t (vk, Item_t (Map_t (ck, _, _), rest, _), _) ) ->\n let k = ty_of_comparable_ty ck in\n check_item_ty ctxt vk k loc I_MEM 1 2\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Map_mem (Item_t (Bool_t None, rest, annot))\n | ( Prim (loc, I_GET, [], annot),\n Item_t (vk, Item_t (Map_t (ck, elt, _), rest, _), _) ) ->\n let k = ty_of_comparable_ty ck in\n check_item_ty ctxt vk k loc I_GET 1 2\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Map_get (Item_t (Option_t (elt, None), rest, annot))\n | ( Prim (loc, I_UPDATE, [], annot),\n Item_t\n ( vk,\n Item_t\n ( Option_t (vv, _),\n Item_t (Map_t (ck, v, map_name), rest, map_annot),\n _ ),\n _ ) ) ->\n let k = ty_of_comparable_ty ck in\n check_item_ty ctxt vk k loc I_UPDATE 1 3\n >>?= fun (Eq, _, ctxt) ->\n check_item_ty ctxt vv v loc I_UPDATE 2 3\n >>?= fun (Eq, v, ctxt) ->\n parse_var_annot loc annot ~default:map_annot\n >>?= fun annot ->\n typed ctxt loc Map_update (Item_t (Map_t (ck, v, map_name), rest, annot))\n | ( Prim (loc, I_GET_AND_UPDATE, [], annot),\n Item_t\n ( vk,\n Item_t\n ( Option_t (vv, vname),\n Item_t (Map_t (ck, v, map_name), rest, map_annot),\n v_annot ),\n _ ) ) ->\n let k = ty_of_comparable_ty ck in\n check_item_ty ctxt vk k loc I_GET_AND_UPDATE 1 3\n >>?= fun (Eq, _, ctxt) ->\n check_item_ty ctxt vv v loc I_GET_AND_UPDATE 2 3\n >>?= fun (Eq, v, ctxt) ->\n parse_var_annot loc annot ~default:map_annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Map_get_and_update\n (Item_t\n ( Option_t (vv, vname),\n Item_t (Map_t (ck, v, map_name), rest, annot),\n v_annot ))\n | (Prim (loc, I_SIZE, [], annot), Item_t (Map_t (_, _, _), rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Map_size (Item_t (Nat_t None, rest, annot))\n (* big_map *)\n | (Prim (loc, I_EMPTY_BIG_MAP, [tk; tv], annot), stack) ->\n parse_comparable_ty ctxt tk\n >>?= fun (Ex_comparable_ty tk, ctxt) ->\n parse_big_map_value_ty ctxt ~legacy tv\n >>?= fun (Ex_ty tv, ctxt) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n typed\n ctxt\n loc\n (Empty_big_map (tk, tv))\n (Item_t (Big_map_t (tk, tv, ty_name), stack, annot))\n | ( Prim (loc, I_MEM, [], annot),\n Item_t (set_key, Item_t (Big_map_t (map_key, _, _), rest, _), _) ) ->\n let k = ty_of_comparable_ty map_key in\n check_item_ty ctxt set_key k loc I_MEM 1 2\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Big_map_mem (Item_t (Bool_t None, rest, annot))\n | ( Prim (loc, I_GET, [], annot),\n Item_t (vk, Item_t (Big_map_t (ck, elt, _), rest, _), _) ) ->\n let k = ty_of_comparable_ty ck in\n check_item_ty ctxt vk k loc I_GET 1 2\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Big_map_get (Item_t (Option_t (elt, None), rest, annot))\n | ( Prim (loc, I_UPDATE, [], annot),\n Item_t\n ( set_key,\n Item_t\n ( Option_t (set_value, _),\n Item_t (Big_map_t (map_key, map_value, map_name), rest, map_annot),\n _ ),\n _ ) ) ->\n let k = ty_of_comparable_ty map_key in\n check_item_ty ctxt set_key k loc I_UPDATE 1 3\n >>?= fun (Eq, _, ctxt) ->\n check_item_ty ctxt set_value map_value loc I_UPDATE 2 3\n >>?= fun (Eq, map_value, ctxt) ->\n parse_var_annot loc annot ~default:map_annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Big_map_update\n (Item_t (Big_map_t (map_key, map_value, map_name), rest, annot))\n | ( Prim (loc, I_GET_AND_UPDATE, [], annot),\n Item_t\n ( vk,\n Item_t\n ( Option_t (vv, vname),\n Item_t (Big_map_t (ck, v, map_name), rest, map_annot),\n v_annot ),\n _ ) ) ->\n let k = ty_of_comparable_ty ck in\n check_item_ty ctxt vk k loc I_GET_AND_UPDATE 1 3\n >>?= fun (Eq, _, ctxt) ->\n check_item_ty ctxt vv v loc I_GET_AND_UPDATE 2 3\n >>?= fun (Eq, v, ctxt) ->\n parse_var_annot loc annot ~default:map_annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Big_map_get_and_update\n (Item_t\n ( Option_t (vv, vname),\n Item_t (Big_map_t (ck, v, map_name), rest, annot),\n v_annot ))\n (* Sapling *)\n | (Prim (loc, I_SAPLING_EMPTY_STATE, [memo_size], annot), rest) ->\n parse_memo_size memo_size\n >>?= fun memo_size ->\n parse_var_annot loc annot ~default:default_sapling_state_annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n (Sapling_empty_state {memo_size})\n (Item_t (Sapling_state_t (memo_size, None), rest, annot))\n | ( Prim (loc, I_SAPLING_VERIFY_UPDATE, [], _),\n Item_t\n ( Sapling_transaction_t (transaction_memo_size, _),\n Item_t\n ( (Sapling_state_t (state_memo_size, _) as state_ty),\n rest,\n stack_annot ),\n _ ) ) ->\n merge_memo_sizes state_memo_size transaction_memo_size\n >>?= fun _memo_size ->\n typed\n ctxt\n loc\n Sapling_verify_update\n (Item_t\n ( Option_t\n ( Pair_t\n ( (Int_t None, None, default_sapling_balance_annot),\n (state_ty, None, None),\n None ),\n None ),\n rest,\n stack_annot ))\n (* control *)\n | (Seq (loc, []), stack) ->\n typed ctxt loc Nop stack\n | (Seq (loc, [single]), stack) -> (\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy single stack\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ({aft; _} as instr) ->\n let nop = {bef = aft; loc; aft; instr = Nop} in\n typed ctxt loc (Seq (instr, nop)) aft\n | Failed {descr; _} ->\n let descr aft =\n let nop = {bef = aft; loc; aft; instr = Nop} in\n let descr = descr aft in\n {descr with instr = Seq (descr, nop)}\n in\n return ctxt (Failed {descr}) )\n | (Seq (loc, hd :: tl), stack) -> (\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy hd stack\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Failed _ ->\n fail (Fail_not_in_tail_position (Micheline.location hd))\n | Typed ({aft = middle; _} as ihd) -> (\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n (Seq (-1, tl))\n middle\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Failed {descr} ->\n let descr ret =\n {loc; instr = Seq (ihd, descr ret); bef = stack; aft = ret}\n in\n return ctxt (Failed {descr})\n | Typed itl ->\n typed ctxt loc (Seq (ihd, itl)) itl.aft ) )\n | (Prim (loc, I_IF, [bt; bf], annot), (Item_t (Bool_t _, rest, _) as bef)) ->\n check_kind [Seq_kind] bt\n >>?= fun () ->\n check_kind [Seq_kind] bf\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy bt rest\n >>=? fun (btr, ctxt) ->\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy bf rest\n >>=? fun (bfr, ctxt) ->\n let branch ibt ibf = {loc; instr = If (ibt, ibf); bef; aft = ibt.aft} in\n merge_branches ~legacy ctxt loc btr bfr {branch}\n >>?= fun (judgement, ctxt) -> return ctxt judgement\n | ( Prim (loc, I_LOOP, [body], annot),\n (Item_t (Bool_t _, rest, _stack_annot) as stack) ) -> (\n check_kind [Seq_kind] body\n >>?= fun () ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n non_terminal_recursion ?type_logger tc_context ctxt ~legacy body rest\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ibody ->\n let unmatched_branches () =\n serialize_stack_for_error ctxt ibody.aft\n >>? fun (aft, ctxt) ->\n serialize_stack_for_error ctxt stack\n >|? fun (stack, _ctxt) -> Unmatched_branches (loc, aft, stack)\n in\n Lwt.return\n @@ record_trace_eval\n unmatched_branches\n ( merge_stacks ~legacy loc ctxt 1 ibody.aft stack\n >>? fun (Eq, _stack, ctxt) ->\n typed_no_lwt ctxt loc (Loop ibody) rest )\n | Failed {descr} ->\n let ibody = descr stack in\n typed ctxt loc (Loop ibody) rest )\n | ( Prim (loc, I_LOOP_LEFT, [body], annot),\n (Item_t (Union_t ((tl, l_field), (tr, _), _), rest, union_annot) as stack)\n ) -> (\n check_kind [Seq_kind] body\n >>?= fun () ->\n parse_var_annot loc annot\n >>?= fun annot ->\n let l_annot =\n gen_access_annot union_annot l_field ~default:default_left_annot\n in\n non_terminal_recursion\n ?type_logger\n tc_context\n ctxt\n ~legacy\n body\n (Item_t (tl, rest, l_annot))\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed ibody ->\n let unmatched_branches () =\n serialize_stack_for_error ctxt ibody.aft\n >>? fun (aft, ctxt) ->\n serialize_stack_for_error ctxt stack\n >|? fun (stack, _ctxt) -> Unmatched_branches (loc, aft, stack)\n in\n Lwt.return\n @@ record_trace_eval\n unmatched_branches\n ( merge_stacks ~legacy loc ctxt 1 ibody.aft stack\n >>? fun (Eq, _stack, ctxt) ->\n typed_no_lwt\n ctxt\n loc\n (Loop_left ibody)\n (Item_t (tr, rest, annot)) )\n | Failed {descr} ->\n let ibody = descr stack in\n typed ctxt loc (Loop_left ibody) (Item_t (tr, rest, annot)) )\n | (Prim (loc, I_LAMBDA, [arg; ret; code], annot), stack) ->\n parse_any_ty ctxt ~legacy arg\n >>?= fun (Ex_ty arg, ctxt) ->\n parse_any_ty ctxt ~legacy ret\n >>?= fun (Ex_ty ret, ctxt) ->\n check_kind [Seq_kind] code\n >>?= fun () ->\n parse_var_annot loc annot\n >>?= fun annot ->\n parse_returning\n Lambda\n ?type_logger\n ~stack_depth\n ctxt\n ~legacy\n (arg, default_arg_annot)\n ret\n code\n >>=? fun (lambda, ctxt) ->\n typed\n ctxt\n loc\n (Lambda lambda)\n (Item_t (Lambda_t (arg, ret, None), stack, annot))\n | ( Prim (loc, I_EXEC, [], annot),\n Item_t (arg, Item_t (Lambda_t (param, ret, _), rest, _), _) ) ->\n check_item_ty ctxt arg param loc I_EXEC 1 2\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Exec (Item_t (ret, rest, annot))\n | ( Prim (loc, I_APPLY, [], annot),\n Item_t\n ( capture,\n Item_t\n ( Lambda_t\n (Pair_t ((capture_ty, _, _), (arg_ty, _, _), lam_annot), ret, _),\n rest,\n _ ),\n _ ) ) ->\n check_packable ~legacy:false loc capture_ty\n >>?= fun () ->\n check_item_ty ctxt capture capture_ty loc I_APPLY 1 2\n >>?= fun (Eq, capture_ty, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n (Apply capture_ty)\n (Item_t (Lambda_t (arg_ty, ret, lam_annot), rest, annot))\n | (Prim (loc, I_DIP, [code], annot), Item_t (v, rest, stack_annot)) -> (\n error_unexpected_annot loc annot\n >>?= fun () ->\n check_kind [Seq_kind] code\n >>?= fun () ->\n non_terminal_recursion\n ?type_logger\n (add_dip v stack_annot tc_context)\n ctxt\n ~legacy\n code\n rest\n >>=? fun (judgement, ctxt) ->\n match judgement with\n | Typed descr ->\n typed ctxt loc (Dip descr) (Item_t (v, descr.aft, stack_annot))\n | Failed _ ->\n fail (Fail_not_in_tail_position loc) )\n | (Prim (loc, I_DIP, [n; code], result_annot), stack) ->\n parse_uint10 n\n >>?= fun n ->\n Gas.consume ctxt (Typecheck_costs.proof_argument n)\n >>?= fun ctxt ->\n let rec make_proof_argument :\n type tstk.\n int\n (* -> (fbef stack_ty -> (fbef judgement * context) tzresult Lwt.t) *) ->\n tc_context ->\n tstk stack_ty ->\n tstk dipn_proof_argument tzresult Lwt.t =\n fun n inner_tc_context stk ->\n match (Compare.Int.(n = 0), stk) with\n | (true, rest) -> (\n non_terminal_recursion\n ?type_logger\n inner_tc_context\n ctxt\n ~legacy\n code\n rest\n >>=? fun (judgement, ctxt) ->\n Lwt.return\n @@\n match judgement with\n | Typed descr ->\n ok @@ Dipn_proof_argument (Rest, (ctxt, descr), descr.aft)\n | Failed _ ->\n error (Fail_not_in_tail_position loc) )\n | (false, Item_t (v, rest, annot)) ->\n make_proof_argument (n - 1) (add_dip v annot tc_context) rest\n >|=? fun (Dipn_proof_argument (n', descr, aft')) ->\n Dipn_proof_argument (Prefix n', descr, Item_t (v, aft', annot))\n | (_, _) ->\n Lwt.return\n ( serialize_stack_for_error ctxt stack\n >>? fun (whole_stack, _ctxt) ->\n error (Bad_stack (loc, I_DIP, 1, whole_stack)) )\n in\n error_unexpected_annot loc result_annot\n >>?= fun () ->\n make_proof_argument n tc_context stack\n >>=? fun (Dipn_proof_argument (n', (new_ctxt, descr), aft)) ->\n (* TODO: which context should be used in the next line? new_ctxt or the old ctxt? *)\n typed new_ctxt loc (Dipn (n, n', descr)) aft\n | (Prim (loc, I_DIP, (([] | _ :: _ :: _ :: _) as l), _), _) ->\n (* Technically, the arities 1 and 2 are allowed but the error only mentions 2.\n However, DIP {code} is equivalent to DIP 1 {code} so hinting at an arity of 2 makes sense. *)\n fail (Invalid_arity (loc, I_DIP, 2, List.length l))\n | (Prim (loc, I_FAILWITH, [], annot), Item_t (v, _rest, _)) ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n (if legacy then ok_unit else check_packable ~legacy:false loc v)\n >>?= fun () ->\n let descr aft = {loc; instr = Failwith v; bef = stack_ty; aft} in\n log_stack ctxt loc stack_ty Empty_t\n >>?= fun () -> return ctxt (Failed {descr})\n | (Prim (loc, I_NEVER, [], annot), Item_t (Never_t _, _rest, _)) ->\n error_unexpected_annot loc annot\n >>?= fun () ->\n let descr aft = {loc; instr = Never; bef = stack_ty; aft} in\n log_stack ctxt loc stack_ty Empty_t\n >>?= fun () -> return ctxt (Failed {descr})\n (* timestamp operations *)\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Timestamp_t tname, Item_t (Int_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Add_timestamp_to_seconds\n (Item_t (Timestamp_t tname, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Int_t _, Item_t (Timestamp_t tname, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Add_seconds_to_timestamp\n (Item_t (Timestamp_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Timestamp_t tname, Item_t (Int_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Sub_timestamp_seconds\n (Item_t (Timestamp_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Timestamp_t tn1, Item_t (Timestamp_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Diff_timestamps (Item_t (Int_t tname, rest, annot))\n (* string operations *)\n | ( Prim (loc, I_CONCAT, [], annot),\n Item_t (String_t tn1, Item_t (String_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Concat_string_pair (Item_t (String_t tname, rest, annot))\n | ( Prim (loc, I_CONCAT, [], annot),\n Item_t (List_t (String_t tname, _), rest, list_annot) ) ->\n parse_var_annot ~default:list_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Concat_string (Item_t (String_t tname, rest, annot))\n | ( Prim (loc, I_SLICE, [], annot),\n Item_t\n ( Nat_t _,\n Item_t (Nat_t _, Item_t (String_t tname, rest, string_annot), _),\n _ ) ) ->\n parse_var_annot\n ~default:(gen_access_annot string_annot default_slice_annot)\n loc\n annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Slice_string\n (Item_t (Option_t (String_t tname, None), rest, annot))\n | (Prim (loc, I_SIZE, [], annot), Item_t (String_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc String_size (Item_t (Nat_t None, rest, annot))\n (* bytes operations *)\n | ( Prim (loc, I_CONCAT, [], annot),\n Item_t (Bytes_t tn1, Item_t (Bytes_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Concat_bytes_pair (Item_t (Bytes_t tname, rest, annot))\n | ( Prim (loc, I_CONCAT, [], annot),\n Item_t (List_t (Bytes_t tname, _), rest, list_annot) ) ->\n parse_var_annot ~default:list_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Concat_bytes (Item_t (Bytes_t tname, rest, annot))\n | ( Prim (loc, I_SLICE, [], annot),\n Item_t\n ( Nat_t _,\n Item_t (Nat_t _, Item_t (Bytes_t tname, rest, bytes_annot), _),\n _ ) ) ->\n parse_var_annot\n ~default:(gen_access_annot bytes_annot default_slice_annot)\n loc\n annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Slice_bytes\n (Item_t (Option_t (Bytes_t tname, None), rest, annot))\n | (Prim (loc, I_SIZE, [], annot), Item_t (Bytes_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Bytes_size (Item_t (Nat_t None, rest, annot))\n (* currency operations *)\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Mutez_t tn1, Item_t (Mutez_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Add_tez (Item_t (Mutez_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Mutez_t tn1, Item_t (Mutez_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Sub_tez (Item_t (Mutez_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Mutez_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n (* no type name check *)\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Mul_teznat (Item_t (Mutez_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Nat_t _, Item_t (Mutez_t tname, rest, _), _) ) ->\n (* no type name check *)\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Mul_nattez (Item_t (Mutez_t tname, rest, annot))\n (* boolean operations *)\n | ( Prim (loc, I_OR, [], annot),\n Item_t (Bool_t tn1, Item_t (Bool_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname -> typed ctxt loc Or (Item_t (Bool_t tname, rest, annot))\n | ( Prim (loc, I_AND, [], annot),\n Item_t (Bool_t tn1, Item_t (Bool_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname -> typed ctxt loc And (Item_t (Bool_t tname, rest, annot))\n | ( Prim (loc, I_XOR, [], annot),\n Item_t (Bool_t tn1, Item_t (Bool_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname -> typed ctxt loc Xor (Item_t (Bool_t tname, rest, annot))\n | (Prim (loc, I_NOT, [], annot), Item_t (Bool_t tname, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Not (Item_t (Bool_t tname, rest, annot))\n (* integer operations *)\n | (Prim (loc, I_ABS, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Abs_int (Item_t (Nat_t None, rest, annot))\n | (Prim (loc, I_ISNAT, [], annot), Item_t (Int_t _, rest, int_annot)) ->\n parse_var_annot loc annot ~default:int_annot\n >>?= fun annot ->\n typed ctxt loc Is_nat (Item_t (Option_t (Nat_t None, None), rest, annot))\n | (Prim (loc, I_INT, [], annot), Item_t (Nat_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Int_nat (Item_t (Int_t None, rest, annot))\n | (Prim (loc, I_NEG, [], annot), Item_t (Int_t tname, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Neg_int (Item_t (Int_t tname, rest, annot))\n | (Prim (loc, I_NEG, [], annot), Item_t (Nat_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Neg_nat (Item_t (Int_t None, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Int_t tn1, Item_t (Int_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Add_intint (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Int_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Add_intnat (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Nat_t _, Item_t (Int_t tname, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Add_natint (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Add_natnat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Int_t tn1, Item_t (Int_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Sub_int (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Int_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Sub_int (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Nat_t _, Item_t (Int_t tname, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Sub_int (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_SUB, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun _tname ->\n typed ctxt loc Sub_int (Item_t (Int_t None, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Int_t tn1, Item_t (Int_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Mul_intint (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Int_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Mul_intnat (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Nat_t _, Item_t (Int_t tname, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Mul_natint (Item_t (Int_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Mul_natnat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_EDIV, [], annot),\n Item_t (Mutez_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Ediv_teznat\n (Item_t\n ( Option_t\n ( Pair_t\n ( (Mutez_t tname, None, None),\n (Mutez_t tname, None, None),\n None ),\n None ),\n rest,\n annot ))\n | ( Prim (loc, I_EDIV, [], annot),\n Item_t (Mutez_t tn1, Item_t (Mutez_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed\n ctxt\n loc\n Ediv_tez\n (Item_t\n ( Option_t\n ( Pair_t\n ((Nat_t None, None, None), (Mutez_t tname, None, None), None),\n None ),\n rest,\n annot ))\n | ( Prim (loc, I_EDIV, [], annot),\n Item_t (Int_t tn1, Item_t (Int_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed\n ctxt\n loc\n Ediv_intint\n (Item_t\n ( Option_t\n ( Pair_t\n ((Int_t tname, None, None), (Nat_t None, None, None), None),\n None ),\n rest,\n annot ))\n | ( Prim (loc, I_EDIV, [], annot),\n Item_t (Int_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Ediv_intnat\n (Item_t\n ( Option_t\n ( Pair_t\n ((Int_t tname, None, None), (Nat_t None, None, None), None),\n None ),\n rest,\n annot ))\n | ( Prim (loc, I_EDIV, [], annot),\n Item_t (Nat_t tname, Item_t (Int_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Ediv_natint\n (Item_t\n ( Option_t\n ( Pair_t\n ((Int_t None, None, None), (Nat_t tname, None, None), None),\n None ),\n rest,\n annot ))\n | ( Prim (loc, I_EDIV, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed\n ctxt\n loc\n Ediv_natnat\n (Item_t\n ( Option_t\n ( Pair_t\n ((Nat_t tname, None, None), (Nat_t tname, None, None), None),\n None ),\n rest,\n annot ))\n | ( Prim (loc, I_LSL, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Lsl_nat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_LSR, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Lsr_nat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_OR, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Or_nat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_AND, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc And_nat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_AND, [], annot),\n Item_t (Int_t _, Item_t (Nat_t tname, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc And_int_nat (Item_t (Nat_t tname, rest, annot))\n | ( Prim (loc, I_XOR, [], annot),\n Item_t (Nat_t tn1, Item_t (Nat_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed ctxt loc Xor_nat (Item_t (Nat_t tname, rest, annot))\n | (Prim (loc, I_NOT, [], annot), Item_t (Int_t tname, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Not_int (Item_t (Int_t tname, rest, annot))\n | (Prim (loc, I_NOT, [], annot), Item_t (Nat_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Not_nat (Item_t (Int_t None, rest, annot))\n (* comparison *)\n | (Prim (loc, I_COMPARE, [], annot), Item_t (t1, Item_t (t2, rest, _), _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n check_item_ty ctxt t1 t2 loc I_COMPARE 1 2\n >>?= fun (Eq, t, ctxt) ->\n comparable_ty_of_ty ctxt loc t\n >>?= fun (key, ctxt) ->\n typed ctxt loc (Compare key) (Item_t (Int_t None, rest, annot))\n (* comparators *)\n | (Prim (loc, I_EQ, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Eq (Item_t (Bool_t None, rest, annot))\n | (Prim (loc, I_NEQ, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Neq (Item_t (Bool_t None, rest, annot))\n | (Prim (loc, I_LT, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Lt (Item_t (Bool_t None, rest, annot))\n | (Prim (loc, I_GT, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Gt (Item_t (Bool_t None, rest, annot))\n | (Prim (loc, I_LE, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Le (Item_t (Bool_t None, rest, annot))\n | (Prim (loc, I_GE, [], annot), Item_t (Int_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot -> typed ctxt loc Ge (Item_t (Bool_t None, rest, annot))\n (* annotations *)\n | (Prim (loc, I_CAST, [cast_t], annot), Item_t (t, stack, item_annot)) ->\n parse_var_annot loc annot ~default:item_annot\n >>?= fun annot ->\n parse_any_ty ctxt ~legacy cast_t\n >>?= fun (Ex_ty cast_t, ctxt) ->\n merge_types ~legacy ctxt loc cast_t t\n >>?= fun (Eq, _, ctxt) ->\n typed ctxt loc Nop (Item_t (cast_t, stack, annot))\n | (Prim (loc, I_RENAME, [], annot), Item_t (t, stack, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n (* can erase annot *)\n typed ctxt loc Nop (Item_t (t, stack, annot))\n (* packing *)\n | (Prim (loc, I_PACK, [], annot), Item_t (t, rest, unpacked_annot)) ->\n check_packable\n ~legacy:true\n (* allow to pack contracts for hash/signature checks *) loc\n t\n >>?= fun () ->\n parse_var_annot\n loc\n annot\n ~default:(gen_access_annot unpacked_annot default_pack_annot)\n >>?= fun annot ->\n typed ctxt loc (Pack t) (Item_t (Bytes_t None, rest, annot))\n | (Prim (loc, I_UNPACK, [ty], annot), Item_t (Bytes_t _, rest, packed_annot))\n ->\n parse_packable_ty ctxt ~legacy ty\n >>?= fun (Ex_ty t, ctxt) ->\n parse_var_type_annot loc annot\n >>?= fun (annot, ty_name) ->\n let annot =\n default_annot\n annot\n ~default:(gen_access_annot packed_annot default_unpack_annot)\n in\n typed ctxt loc (Unpack t) (Item_t (Option_t (t, ty_name), rest, annot))\n (* protocol *)\n | ( Prim (loc, I_ADDRESS, [], annot),\n Item_t (Contract_t _, rest, contract_annot) ) ->\n parse_var_annot\n loc\n annot\n ~default:(gen_access_annot contract_annot default_addr_annot)\n >>?= fun annot ->\n typed ctxt loc Address (Item_t (Address_t None, rest, annot))\n | ( Prim (loc, I_CONTRACT, [ty], annot),\n Item_t (Address_t _, rest, addr_annot) ) ->\n parse_parameter_ty ctxt ~legacy ty\n >>?= fun (Ex_ty t, ctxt) ->\n parse_entrypoint_annot\n loc\n annot\n ~default:(gen_access_annot addr_annot default_contract_annot)\n >>?= fun (annot, entrypoint) ->\n ( match entrypoint with\n | None ->\n Ok \"default\"\n | Some (Field_annot \"default\") ->\n error (Unexpected_annotation loc)\n | Some (Field_annot entrypoint) ->\n if Compare.Int.(String.length entrypoint > 31) then\n error (Entrypoint_name_too_long entrypoint)\n else Ok entrypoint )\n >>?= fun entrypoint ->\n typed\n ctxt\n loc\n (Contract (t, entrypoint))\n (Item_t (Option_t (Contract_t (t, None), None), rest, annot))\n | ( Prim (loc, I_TRANSFER_TOKENS, [], annot),\n Item_t (p, Item_t (Mutez_t _, Item_t (Contract_t (cp, _), rest, _), _), _)\n ) ->\n check_item_ty ctxt p cp loc I_TRANSFER_TOKENS 1 4\n >>?= fun (Eq, _, ctxt) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Transfer_tokens (Item_t (Operation_t None, rest, annot))\n | ( Prim (loc, I_SET_DELEGATE, [], annot),\n Item_t (Option_t (Key_hash_t _, _), rest, _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Set_delegate (Item_t (Operation_t None, rest, annot))\n | (Prim (_, I_CREATE_ACCOUNT, _, _), _) ->\n fail (Deprecated_instruction I_CREATE_ACCOUNT)\n | (Prim (loc, I_IMPLICIT_ACCOUNT, [], annot), Item_t (Key_hash_t _, rest, _))\n ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Implicit_account\n (Item_t (Contract_t (Unit_t None, None), rest, annot))\n | ( Prim (loc, I_CREATE_CONTRACT, [(Seq _ as code)], annot),\n Item_t\n ( Option_t (Key_hash_t _, _),\n Item_t (Mutez_t _, Item_t (ginit, rest, _), _),\n _ ) ) ->\n parse_two_var_annot loc annot\n >>?= fun (op_annot, addr_annot) ->\n let canonical_code = fst @@ Micheline.extract_locations code in\n parse_toplevel ~legacy canonical_code\n >>?= fun (arg_type, storage_type, code_field, root_name) ->\n record_trace\n (Ill_formed_type (Some \"parameter\", canonical_code, location arg_type))\n (parse_parameter_ty ctxt ~legacy arg_type)\n >>?= fun (Ex_ty arg_type, ctxt) ->\n (if legacy then ok_unit else well_formed_entrypoints ~root_name arg_type)\n >>?= fun () ->\n record_trace\n (Ill_formed_type (Some \"storage\", canonical_code, location storage_type))\n (parse_storage_ty ctxt ~legacy storage_type)\n >>?= fun (Ex_ty storage_type, ctxt) ->\n let arg_annot =\n default_annot\n (type_to_var_annot (name_of_ty arg_type))\n ~default:default_param_annot\n in\n let storage_annot =\n default_annot\n (type_to_var_annot (name_of_ty storage_type))\n ~default:default_storage_annot\n in\n let arg_type_full =\n Pair_t\n ( (arg_type, None, arg_annot),\n (storage_type, None, storage_annot),\n None )\n in\n let ret_type_full =\n Pair_t\n ( (List_t (Operation_t None, None), None, None),\n (storage_type, None, None),\n None )\n in\n trace\n (Ill_typed_contract (canonical_code, []))\n (parse_returning\n (Toplevel\n {\n storage_type;\n param_type = arg_type;\n root_name;\n legacy_create_contract_literal = false;\n })\n ctxt\n ~legacy\n ?type_logger\n ~stack_depth\n (arg_type_full, None)\n ret_type_full\n code_field)\n >>=? fun ( ( Lam\n ( { bef = Item_t (arg, Empty_t, _);\n aft = Item_t (ret, Empty_t, _);\n _ },\n _ ) as lambda ),\n ctxt ) ->\n merge_types ~legacy ctxt loc arg arg_type_full\n >>?= fun (Eq, _, ctxt) ->\n merge_types ~legacy ctxt loc ret ret_type_full\n >>?= fun (Eq, _, ctxt) ->\n merge_types ~legacy ctxt loc storage_type ginit\n >>?= fun (Eq, _, ctxt) ->\n typed\n ctxt\n loc\n (Create_contract (storage_type, arg_type, lambda, root_name))\n (Item_t\n ( Operation_t None,\n Item_t (Address_t None, rest, addr_annot),\n op_annot ))\n | (Prim (loc, I_NOW, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_now_annot\n >>?= fun annot ->\n typed ctxt loc Now (Item_t (Timestamp_t None, stack, annot))\n | (Prim (loc, I_AMOUNT, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_amount_annot\n >>?= fun annot ->\n typed ctxt loc Amount (Item_t (Mutez_t None, stack, annot))\n | (Prim (loc, I_CHAIN_ID, [], annot), stack) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc ChainId (Item_t (Chain_id_t None, stack, annot))\n | (Prim (loc, I_BALANCE, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_balance_annot\n >>?= fun annot ->\n typed ctxt loc Balance (Item_t (Mutez_t None, stack, annot))\n | (Prim (loc, I_LEVEL, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_level_annot\n >>?= fun annot ->\n typed ctxt loc Level (Item_t (Nat_t None, stack, annot))\n | (Prim (loc, I_VOTING_POWER, [], annot), Item_t (Key_hash_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Voting_power (Item_t (Nat_t None, rest, annot))\n | (Prim (loc, I_TOTAL_VOTING_POWER, [], annot), stack) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Total_voting_power (Item_t (Nat_t None, stack, annot))\n | (Prim (_, I_STEPS_TO_QUOTA, _, _), _) ->\n fail (Deprecated_instruction I_STEPS_TO_QUOTA)\n | (Prim (loc, I_SOURCE, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_source_annot\n >>?= fun annot ->\n typed ctxt loc Source (Item_t (Address_t None, stack, annot))\n | (Prim (loc, I_SENDER, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_sender_annot\n >>?= fun annot ->\n typed ctxt loc Sender (Item_t (Address_t None, stack, annot))\n | (Prim (loc, I_SELF, [], annot), stack) ->\n Lwt.return\n ( parse_entrypoint_annot loc annot ~default:default_self_annot\n >>? fun (annot, entrypoint) ->\n let entrypoint =\n Option.fold\n ~some:(fun (Field_annot annot) -> annot)\n ~none:\"default\"\n entrypoint\n in\n let rec get_toplevel_type :\n tc_context -> (bef judgement * context) tzresult = function\n | Lambda ->\n error (Self_in_lambda loc)\n | Dip (_, prev) ->\n get_toplevel_type prev\n | Toplevel\n {param_type; root_name; legacy_create_contract_literal = false}\n ->\n find_entrypoint param_type ~root_name entrypoint\n >>? fun (_, Ex_ty param_type) ->\n typed_no_lwt\n ctxt\n loc\n (Self (param_type, entrypoint))\n (Item_t (Contract_t (param_type, None), stack, annot))\n | Toplevel\n {param_type; root_name = _; legacy_create_contract_literal = true}\n ->\n typed_no_lwt\n ctxt\n loc\n (Self (param_type, \"default\"))\n (Item_t (Contract_t (param_type, None), stack, annot))\n in\n get_toplevel_type tc_context )\n | (Prim (loc, I_SELF_ADDRESS, [], annot), stack) ->\n parse_var_annot loc annot ~default:default_self_annot\n >>?= fun annot ->\n typed ctxt loc Self_address (Item_t (Address_t None, stack, annot))\n (* cryptography *)\n | (Prim (loc, I_HASH_KEY, [], annot), Item_t (Key_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Hash_key (Item_t (Key_hash_t None, rest, annot))\n | ( Prim (loc, I_CHECK_SIGNATURE, [], annot),\n Item_t\n (Key_t _, Item_t (Signature_t _, Item_t (Bytes_t _, rest, _), _), _) )\n ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Check_signature (Item_t (Bool_t None, rest, annot))\n | (Prim (loc, I_BLAKE2B, [], annot), Item_t (Bytes_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Blake2b (Item_t (Bytes_t None, rest, annot))\n | (Prim (loc, I_SHA256, [], annot), Item_t (Bytes_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Sha256 (Item_t (Bytes_t None, rest, annot))\n | (Prim (loc, I_SHA512, [], annot), Item_t (Bytes_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Sha512 (Item_t (Bytes_t None, rest, annot))\n | (Prim (loc, I_KECCAK, [], annot), Item_t (Bytes_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Keccak (Item_t (Bytes_t None, rest, annot))\n | (Prim (loc, I_SHA3, [], annot), Item_t (Bytes_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Sha3 (Item_t (Bytes_t None, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Bls12_381_g1_t tn1, Item_t (Bls12_381_g1_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed\n ctxt\n loc\n Add_bls12_381_g1\n (Item_t (Bls12_381_g1_t tname, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Bls12_381_g2_t tn1, Item_t (Bls12_381_g2_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed\n ctxt\n loc\n Add_bls12_381_g2\n (Item_t (Bls12_381_g2_t tname, rest, annot))\n | ( Prim (loc, I_ADD, [], annot),\n Item_t (Bls12_381_fr_t tn1, Item_t (Bls12_381_fr_t tn2, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_type_annot ~legacy tn1 tn2\n >>?= fun tname ->\n typed\n ctxt\n loc\n Add_bls12_381_fr\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Bls12_381_g1_t tname, Item_t (Bls12_381_fr_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_g1\n (Item_t (Bls12_381_g1_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Bls12_381_g2_t tname, Item_t (Bls12_381_fr_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_g2\n (Item_t (Bls12_381_g2_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Bls12_381_fr_t tname, Item_t (Bls12_381_fr_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_fr\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Nat_t tname, Item_t (Bls12_381_fr_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_fr_z\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Int_t tname, Item_t (Bls12_381_fr_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_fr_z\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Bls12_381_fr_t tname, Item_t (Int_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_z_fr\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | ( Prim (loc, I_MUL, [], annot),\n Item_t (Bls12_381_fr_t tname, Item_t (Nat_t _, rest, _), _) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Mul_bls12_381_z_fr\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | (Prim (loc, I_INT, [], annot), Item_t (Bls12_381_fr_t _, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed ctxt loc Int_bls12_381_fr (Item_t (Int_t None, rest, annot))\n | (Prim (loc, I_NEG, [], annot), Item_t (Bls12_381_g1_t tname, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Neg_bls12_381_g1\n (Item_t (Bls12_381_g1_t tname, rest, annot))\n | (Prim (loc, I_NEG, [], annot), Item_t (Bls12_381_g2_t tname, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Neg_bls12_381_g2\n (Item_t (Bls12_381_g2_t tname, rest, annot))\n | (Prim (loc, I_NEG, [], annot), Item_t (Bls12_381_fr_t tname, rest, _)) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Neg_bls12_381_fr\n (Item_t (Bls12_381_fr_t tname, rest, annot))\n | ( Prim (loc, I_PAIRING_CHECK, [], annot),\n Item_t\n ( List_t\n (Pair_t ((Bls12_381_g1_t _, _, _), (Bls12_381_g2_t _, _, _), _), _),\n rest,\n _ ) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n typed\n ctxt\n loc\n Pairing_check_bls12_381\n (Item_t (Bool_t None, rest, annot))\n (* Tickets *)\n | (Prim (loc, I_TICKET, [], annot), Item_t (t, Item_t (Nat_t _, rest, _), _))\n ->\n parse_var_annot loc annot\n >>?= fun annot ->\n comparable_ty_of_ty ctxt loc t\n >>?= fun (ty, ctxt) ->\n typed ctxt loc Ticket (Item_t (Ticket_t (ty, None), rest, annot))\n | ( Prim (loc, I_READ_TICKET, [], annot),\n (Item_t (Ticket_t (t, _), _, _) as full_stack) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n let () = check_dupable_comparable_ty t in\n let result = ty_of_comparable_ty @@ opened_ticket_type t in\n typed ctxt loc Read_ticket (Item_t (result, full_stack, annot))\n | ( Prim (loc, I_SPLIT_TICKET, [], annot),\n Item_t\n ( (Ticket_t (t, _) as ticket_t),\n Item_t\n (Pair_t ((Nat_t _, fa_a, a_a), (Nat_t _, fa_b, a_b), _), rest, _),\n _ ) ) ->\n parse_var_annot loc annot\n >>?= fun annot ->\n let () = check_dupable_comparable_ty t in\n let result =\n Option_t\n (Pair_t ((ticket_t, fa_a, a_a), (ticket_t, fa_b, a_b), None), None)\n in\n typed ctxt loc Split_ticket (Item_t (result, rest, annot))\n | ( Prim (loc, I_JOIN_TICKETS, [], annot),\n Item_t\n ( Pair_t (((Ticket_t _ as ty_a), _, _), ((Ticket_t _ as ty_b), _, _), _),\n rest,\n _ ) ) -> (\n parse_var_annot loc annot\n >>?= fun annot ->\n merge_types ~legacy ctxt loc ty_a ty_b\n >>?= fun (Eq, ty, ctxt) ->\n match ty with\n | Ticket_t (contents_ty, _) ->\n typed\n ctxt\n loc\n (Join_tickets contents_ty)\n (Item_t (Option_t (ty, None), rest, annot))\n | _ ->\n (* TODO: fix injectivity of types *) assert false )\n (* Primitive parsing errors *)\n | ( Prim\n ( loc,\n ( ( I_DUP\n | I_SWAP\n | I_SOME\n | I_UNIT\n | I_PAIR\n | I_UNPAIR\n | I_CAR\n | I_CDR\n | I_CONS\n | I_CONCAT\n | I_SLICE\n | I_MEM\n | I_UPDATE\n | I_GET\n | I_EXEC\n | I_FAILWITH\n | I_SIZE\n | I_ADD\n | I_SUB\n | I_MUL\n | I_EDIV\n | I_OR\n | I_AND\n | I_XOR\n | I_NOT\n | I_ABS\n | I_NEG\n | I_LSL\n | I_LSR\n | I_COMPARE\n | I_EQ\n | I_NEQ\n | I_LT\n | I_GT\n | I_LE\n | I_GE\n | I_TRANSFER_TOKENS\n | I_SET_DELEGATE\n | I_NOW\n | I_IMPLICIT_ACCOUNT\n | I_AMOUNT\n | I_BALANCE\n | I_LEVEL\n | I_CHECK_SIGNATURE\n | I_HASH_KEY\n | I_SOURCE\n | I_SENDER\n | I_BLAKE2B\n | I_SHA256\n | I_SHA512\n | I_ADDRESS\n | I_RENAME\n | I_PACK\n | I_ISNAT\n | I_INT\n | I_SELF\n | I_CHAIN_ID\n | I_NEVER\n | I_VOTING_POWER\n | I_TOTAL_VOTING_POWER\n | I_KECCAK\n | I_SHA3\n | I_PAIRING_CHECK\n | I_TICKET\n | I_READ_TICKET\n | I_SPLIT_TICKET\n | I_JOIN_TICKETS ) as name ),\n (_ :: _ as l),\n _ ),\n _ ) ->\n fail (Invalid_arity (loc, name, 0, List.length l))\n | ( Prim\n ( loc,\n ( ( I_NONE\n | I_LEFT\n | I_RIGHT\n | I_NIL\n | I_MAP\n | I_ITER\n | I_EMPTY_SET\n | I_LOOP\n | I_LOOP_LEFT\n | I_CONTRACT\n | I_CAST\n | I_UNPACK\n | I_CREATE_CONTRACT ) as name ),\n (([] | _ :: _ :: _) as l),\n _ ),\n _ ) ->\n fail (Invalid_arity (loc, name, 1, List.length l))\n | ( Prim\n ( loc,\n ( ( I_PUSH\n | I_IF_NONE\n | I_IF_LEFT\n | I_IF_CONS\n | I_EMPTY_MAP\n | I_EMPTY_BIG_MAP\n | I_IF ) as name ),\n (([] | [_] | _ :: _ :: _ :: _) as l),\n _ ),\n _ ) ->\n fail (Invalid_arity (loc, name, 2, List.length l))\n | ( Prim\n (loc, I_LAMBDA, (([] | [_] | [_; _] | _ :: _ :: _ :: _ :: _) as l), _),\n _ ) ->\n fail (Invalid_arity (loc, I_LAMBDA, 3, List.length l))\n (* Stack errors *)\n | ( Prim\n ( loc,\n ( ( I_ADD\n | I_SUB\n | I_MUL\n | I_EDIV\n | I_AND\n | I_OR\n | I_XOR\n | I_LSL\n | I_LSR\n | I_CONCAT\n | I_PAIRING_CHECK ) as name ),\n [],\n _ ),\n Item_t (ta, Item_t (tb, _, _), _) ) ->\n serialize_ty_for_error ctxt ta\n >>?= fun (ta, ctxt) ->\n serialize_ty_for_error ctxt tb\n >>?= fun (tb, _ctxt) -> fail (Undefined_binop (loc, name, ta, tb))\n | ( Prim\n ( loc,\n ( ( I_NEG\n | I_ABS\n | I_NOT\n | I_SIZE\n | I_EQ\n | I_NEQ\n | I_LT\n | I_GT\n | I_LE\n | I_GE\n (* CONCAT is both unary and binary; this case can only be triggered\n on a singleton stack *)\n | I_CONCAT ) as name ),\n [],\n _ ),\n Item_t (t, _, _) ) ->\n serialize_ty_for_error ctxt t\n >>?= fun (t, _ctxt) -> fail (Undefined_unop (loc, name, t))\n | (Prim (loc, ((I_UPDATE | I_SLICE) as name), [], _), stack) ->\n Lwt.return\n ( serialize_stack_for_error ctxt stack\n >>? fun (stack, _ctxt) -> error (Bad_stack (loc, name, 3, stack)) )\n | (Prim (loc, I_CREATE_CONTRACT, _, _), stack) ->\n serialize_stack_for_error ctxt stack\n >>?= fun (stack, _ctxt) ->\n fail (Bad_stack (loc, I_CREATE_CONTRACT, 7, stack))\n | (Prim (loc, I_TRANSFER_TOKENS, [], _), stack) ->\n Lwt.return\n ( serialize_stack_for_error ctxt stack\n >>? fun (stack, _ctxt) ->\n error (Bad_stack (loc, I_TRANSFER_TOKENS, 4, stack)) )\n | ( Prim\n ( loc,\n ( ( I_DROP\n | I_DUP\n | I_CAR\n | I_CDR\n | I_UNPAIR\n | I_SOME\n | I_BLAKE2B\n | I_SHA256\n | I_SHA512\n | I_DIP\n | I_IF_NONE\n | I_LEFT\n | I_RIGHT\n | I_IF_LEFT\n | I_IF\n | I_LOOP\n | I_IF_CONS\n | I_IMPLICIT_ACCOUNT\n | I_NEG\n | I_ABS\n | I_INT\n | I_NOT\n | I_HASH_KEY\n | I_EQ\n | I_NEQ\n | I_LT\n | I_GT\n | I_LE\n | I_GE\n | I_SIZE\n | I_FAILWITH\n | I_RENAME\n | I_PACK\n | I_ISNAT\n | I_ADDRESS\n | I_SET_DELEGATE\n | I_CAST\n | I_MAP\n | I_ITER\n | I_LOOP_LEFT\n | I_UNPACK\n | I_CONTRACT\n | I_NEVER\n | I_KECCAK\n | I_SHA3\n | I_READ_TICKET\n | I_JOIN_TICKETS ) as name ),\n _,\n _ ),\n stack ) ->\n Lwt.return\n ( serialize_stack_for_error ctxt stack\n >>? fun (stack, _ctxt) -> error (Bad_stack (loc, name, 1, stack)) )\n | ( Prim\n ( loc,\n ( ( I_SWAP\n | I_PAIR\n | I_CONS\n | I_GET\n | I_MEM\n | I_EXEC\n | I_CHECK_SIGNATURE\n | I_ADD\n | I_SUB\n | I_MUL\n | I_EDIV\n | I_AND\n | I_OR\n | I_XOR\n | I_LSL\n | I_LSR\n | I_COMPARE\n | I_PAIRING_CHECK\n | I_TICKET\n | I_SPLIT_TICKET ) as name ),\n _,\n _ ),\n stack ) ->\n Lwt.return\n ( serialize_stack_for_error ctxt stack\n >>? fun (stack, _ctxt) -> error (Bad_stack (loc, name, 2, stack)) )\n (* Generic parsing errors *)\n | (expr, _) ->\n fail\n @@ unexpected\n expr\n [Seq_kind]\n Instr_namespace\n [ I_DROP;\n I_DUP;\n I_DIG;\n I_DUG;\n I_SWAP;\n I_SOME;\n I_UNIT;\n I_PAIR;\n I_UNPAIR;\n I_CAR;\n I_CDR;\n I_CONS;\n I_MEM;\n I_UPDATE;\n I_MAP;\n I_ITER;\n I_GET;\n I_GET_AND_UPDATE;\n I_EXEC;\n I_FAILWITH;\n I_SIZE;\n I_CONCAT;\n I_ADD;\n I_SUB;\n I_MUL;\n I_EDIV;\n I_OR;\n I_AND;\n I_XOR;\n I_NOT;\n I_ABS;\n I_INT;\n I_NEG;\n I_LSL;\n I_LSR;\n I_COMPARE;\n I_EQ;\n I_NEQ;\n I_LT;\n I_GT;\n I_LE;\n I_GE;\n I_TRANSFER_TOKENS;\n I_CREATE_CONTRACT;\n I_NOW;\n I_AMOUNT;\n I_BALANCE;\n I_LEVEL;\n I_IMPLICIT_ACCOUNT;\n I_CHECK_SIGNATURE;\n I_BLAKE2B;\n I_SHA256;\n I_SHA512;\n I_HASH_KEY;\n I_PUSH;\n I_NONE;\n I_LEFT;\n I_RIGHT;\n I_NIL;\n I_EMPTY_SET;\n I_DIP;\n I_LOOP;\n I_IF_NONE;\n I_IF_LEFT;\n I_IF_CONS;\n I_EMPTY_MAP;\n I_EMPTY_BIG_MAP;\n I_IF;\n I_SOURCE;\n I_SENDER;\n I_SELF;\n I_SELF_ADDRESS;\n I_LAMBDA;\n I_NEVER;\n I_VOTING_POWER;\n I_TOTAL_VOTING_POWER;\n I_KECCAK;\n I_SHA3;\n I_PAIRING_CHECK;\n I_SAPLING_EMPTY_STATE;\n I_SAPLING_VERIFY_UPDATE;\n I_TICKET;\n I_READ_TICKET;\n I_SPLIT_TICKET;\n I_JOIN_TICKETS ]\n\nand parse_contract :\n type arg.\n legacy:bool ->\n context ->\n Script.location ->\n arg ty ->\n Contract.t ->\n entrypoint:string ->\n (context * arg typed_contract) tzresult Lwt.t =\n fun ~legacy ctxt loc arg contract ~entrypoint ->\n Gas.consume ctxt Typecheck_costs.contract_exists\n >>?= fun ctxt ->\n Contract.exists ctxt contract\n >>=? function\n | false ->\n fail (Invalid_contract (loc, contract))\n | true -> (\n trace (Invalid_contract (loc, contract))\n @@ Contract.get_script_code ctxt contract\n >>=? fun (ctxt, code) ->\n Lwt.return\n @@\n match code with\n | None -> (\n ty_eq ctxt loc arg (Unit_t None)\n >>? fun (Eq, ctxt) ->\n match entrypoint with\n | \"default\" ->\n let contract : arg typed_contract =\n (arg, (contract, entrypoint))\n in\n ok (ctxt, contract)\n | entrypoint ->\n error (No_such_entrypoint entrypoint) )\n | Some code ->\n Script.force_decode_in_context ctxt code\n >>? fun (code, ctxt) ->\n parse_toplevel ~legacy:true code\n >>? fun (arg_type, _, _, root_name) ->\n parse_parameter_ty ctxt ~legacy:true arg_type\n >>? fun (Ex_ty targ, ctxt) ->\n find_entrypoint_for_type\n ~legacy\n ~full:targ\n ~expected:arg\n ~root_name\n entrypoint\n ctxt\n loc\n >|? fun (ctxt, entrypoint, arg) ->\n let contract : arg typed_contract = (arg, (contract, entrypoint)) in\n (ctxt, contract) )\n\n(* Same as the one above, but does not fail when the contact is missing or\n if the expected type doesn't match the actual one. In that case None is\n returned and some overapproximation of the typechecking gas is consumed.\n This can still fail on gas exhaustion. *)\nand parse_contract_for_script :\n type arg.\n legacy:bool ->\n context ->\n Script.location ->\n arg ty ->\n Contract.t ->\n entrypoint:string ->\n (context * arg typed_contract option) tzresult Lwt.t =\n fun ~legacy ctxt loc arg contract ~entrypoint ->\n Gas.consume ctxt Typecheck_costs.contract_exists\n >>?= fun ctxt ->\n match (Contract.is_implicit contract, entrypoint) with\n | (Some _, \"default\") ->\n (* An implicit account on the \"default\" entrypoint always exists and has type unit. *)\n Lwt.return\n ( match ty_eq ctxt loc arg (Unit_t None) with\n | Ok (Eq, ctxt) ->\n let contract : arg typed_contract =\n (arg, (contract, entrypoint))\n in\n ok (ctxt, Some contract)\n | Error _ ->\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>? fun ctxt -> ok (ctxt, None) )\n | (Some _, _) ->\n Lwt.return\n ( Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >|? fun ctxt ->\n (* An implicit account on any other entrypoint is not a valid contract. *)\n (ctxt, None) )\n | (None, _) -> (\n (* Originated account *)\n Contract.exists ctxt contract\n >>=? function\n | false ->\n return (ctxt, None)\n | true -> (\n trace (Invalid_contract (loc, contract))\n @@ Contract.get_script_code ctxt contract\n >>=? fun (ctxt, code) ->\n match code with\n | None ->\n (* Since protocol 005, we have the invariant that all originated accounts have code *)\n assert false\n | Some code ->\n Lwt.return\n ( Script.force_decode_in_context ctxt code\n >>? fun (code, ctxt) ->\n (* can only fail because of gas *)\n match parse_toplevel ~legacy:true code with\n | Error _ ->\n error (Invalid_contract (loc, contract))\n | Ok (arg_type, _, _, root_name) -> (\n match parse_parameter_ty ctxt ~legacy:true arg_type with\n | Error _ ->\n error (Invalid_contract (loc, contract))\n | Ok (Ex_ty targ, ctxt) -> (\n match\n find_entrypoint_for_type\n ~legacy\n ~full:targ\n ~expected:arg\n ~root_name\n entrypoint\n ctxt\n loc\n >|? fun (ctxt, entrypoint, arg) ->\n let contract : arg typed_contract =\n (arg, (contract, entrypoint))\n in\n (ctxt, Some contract)\n with\n | Ok res ->\n ok res\n | Error _ ->\n (* overapproximation by checking if targ = targ,\n can only fail because of gas *)\n merge_types ~legacy ctxt loc targ targ\n >|? fun (Eq, _, ctxt) -> (ctxt, None) ) ) ) ) )\n\nand parse_toplevel :\n legacy:bool ->\n Script.expr ->\n (Script.node * Script.node * Script.node * field_annot option) tzresult =\n fun ~legacy toplevel ->\n record_trace (Ill_typed_contract (toplevel, []))\n @@\n match root toplevel with\n | Int (loc, _) ->\n error (Invalid_kind (loc, [Seq_kind], Int_kind))\n | String (loc, _) ->\n error (Invalid_kind (loc, [Seq_kind], String_kind))\n | Bytes (loc, _) ->\n error (Invalid_kind (loc, [Seq_kind], Bytes_kind))\n | Prim (loc, _, _, _) ->\n error (Invalid_kind (loc, [Seq_kind], Prim_kind))\n | Seq (_, fields) -> (\n let rec find_fields p s c fields =\n match fields with\n | [] ->\n ok (p, s, c)\n | Int (loc, _) :: _ ->\n error (Invalid_kind (loc, [Prim_kind], Int_kind))\n | String (loc, _) :: _ ->\n error (Invalid_kind (loc, [Prim_kind], String_kind))\n | Bytes (loc, _) :: _ ->\n error (Invalid_kind (loc, [Prim_kind], Bytes_kind))\n | Seq (loc, _) :: _ ->\n error (Invalid_kind (loc, [Prim_kind], Seq_kind))\n | Prim (loc, K_parameter, [arg], annot) :: rest -> (\n match p with\n | None ->\n find_fields (Some (arg, loc, annot)) s c rest\n | Some _ ->\n error (Duplicate_field (loc, K_parameter)) )\n | Prim (loc, K_storage, [arg], annot) :: rest -> (\n match s with\n | None ->\n find_fields p (Some (arg, loc, annot)) c rest\n | Some _ ->\n error (Duplicate_field (loc, K_storage)) )\n | Prim (loc, K_code, [arg], annot) :: rest -> (\n match c with\n | None ->\n find_fields p s (Some (arg, loc, annot)) rest\n | Some _ ->\n error (Duplicate_field (loc, K_code)) )\n | Prim (loc, ((K_parameter | K_storage | K_code) as name), args, _)\n :: _ ->\n error (Invalid_arity (loc, name, 1, List.length args))\n | Prim (loc, name, _, _) :: _ ->\n let allowed = [K_parameter; K_storage; K_code] in\n error (Invalid_primitive (loc, allowed, name))\n in\n find_fields None None None fields\n >>? function\n | (None, _, _) ->\n error (Missing_field K_parameter)\n | (Some _, None, _) ->\n error (Missing_field K_storage)\n | (Some _, Some _, None) ->\n error (Missing_field K_code)\n | (Some (p, ploc, pannot), Some (s, sloc, sannot), Some (c, cloc, carrot))\n ->\n let maybe_root_name =\n (* root name can be attached to either the parameter\n primitive or the toplevel constructor *)\n Script_ir_annot.extract_field_annot p\n >>? fun (p, root_name) ->\n match root_name with\n | Some _ ->\n ok (p, pannot, root_name)\n | None -> (\n match pannot with\n | [single]\n when Compare.Int.(String.length single > 0)\n && Compare.Char.(single.[0] = '%') ->\n parse_field_annot ploc [single]\n >>? fun pannot -> ok (p, [], pannot)\n | _ ->\n ok (p, pannot, None) )\n in\n if legacy then\n (* legacy semantics ignores spurious annotations *)\n let (p, root_name) =\n match maybe_root_name with\n | Ok (p, _, root_name) ->\n (p, root_name)\n | Error _ ->\n (p, None)\n in\n ok (p, s, c, root_name)\n else\n (* only one field annot is allowed to set the root entrypoint name *)\n maybe_root_name\n >>? fun (p, pannot, root_name) ->\n Script_ir_annot.error_unexpected_annot ploc pannot\n >>? fun () ->\n Script_ir_annot.error_unexpected_annot cloc carrot\n >>? fun () ->\n Script_ir_annot.error_unexpected_annot sloc sannot\n >>? fun () -> ok (p, s, c, root_name) )\n\nlet parse_code :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n code:lazy_expr ->\n (ex_code * context) tzresult Lwt.t =\n fun ?type_logger ctxt ~legacy ~code ->\n Script.force_decode_in_context ctxt code\n >>?= fun (code, ctxt) ->\n parse_toplevel ~legacy code\n >>?= fun (arg_type, storage_type, code_field, root_name) ->\n record_trace\n (Ill_formed_type (Some \"parameter\", code, location arg_type))\n (parse_parameter_ty ctxt ~legacy arg_type)\n >>?= fun (Ex_ty arg_type, ctxt) ->\n (if legacy then ok_unit else well_formed_entrypoints ~root_name arg_type)\n >>?= fun () ->\n record_trace\n (Ill_formed_type (Some \"storage\", code, location storage_type))\n (parse_storage_ty ctxt ~legacy storage_type)\n >>?= fun (Ex_ty storage_type, ctxt) ->\n let arg_annot =\n default_annot\n (type_to_var_annot (name_of_ty arg_type))\n ~default:default_param_annot\n in\n let storage_annot =\n default_annot\n (type_to_var_annot (name_of_ty storage_type))\n ~default:default_storage_annot\n in\n let arg_type_full =\n Pair_t\n ((arg_type, None, arg_annot), (storage_type, None, storage_annot), None)\n in\n let ret_type_full =\n Pair_t\n ( (List_t (Operation_t None, None), None, None),\n (storage_type, None, None),\n None )\n in\n trace\n (Ill_typed_contract (code, []))\n (parse_returning\n (Toplevel\n {\n storage_type;\n param_type = arg_type;\n root_name;\n legacy_create_contract_literal = false;\n })\n ctxt\n ~legacy\n ~stack_depth:0\n ?type_logger\n (arg_type_full, None)\n ret_type_full\n code_field)\n >|=? fun (code, ctxt) ->\n (Ex_code {code; arg_type; storage_type; root_name}, ctxt)\n\nlet parse_storage :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n allow_forged:bool ->\n 'storage ty ->\n storage:lazy_expr ->\n ('storage * context) tzresult Lwt.t =\n fun ?type_logger ctxt ~legacy ~allow_forged storage_type ~storage ->\n Script.force_decode_in_context ctxt storage\n >>?= fun (storage, ctxt) ->\n trace_eval\n (fun () ->\n Lwt.return\n ( serialize_ty_for_error ctxt storage_type\n >|? fun (storage_type, _ctxt) ->\n Ill_typed_data (None, storage, storage_type) ))\n (parse_data\n ?type_logger\n ~stack_depth:0\n ctxt\n ~legacy\n ~allow_forged\n storage_type\n (root storage))\n\nlet parse_script :\n ?type_logger:type_logger ->\n context ->\n legacy:bool ->\n allow_forged_in_storage:bool ->\n Script.t ->\n (ex_script * context) tzresult Lwt.t =\n fun ?type_logger ctxt ~legacy ~allow_forged_in_storage {code; storage} ->\n parse_code ~legacy ctxt ?type_logger ~code\n >>=? fun (Ex_code {code; arg_type; storage_type; root_name}, ctxt) ->\n parse_storage\n ?type_logger\n ctxt\n ~legacy\n ~allow_forged:allow_forged_in_storage\n storage_type\n ~storage\n >|=? fun (storage, ctxt) ->\n (Ex_script {code; arg_type; storage; storage_type; root_name}, ctxt)\n\nlet typecheck_code :\n legacy:bool ->\n context ->\n Script.expr ->\n (type_map * context) tzresult Lwt.t =\n fun ~legacy ctxt code ->\n parse_toplevel ~legacy code\n >>?= fun (arg_type, storage_type, code_field, root_name) ->\n let type_map = ref [] in\n record_trace\n (Ill_formed_type (Some \"parameter\", code, location arg_type))\n (parse_parameter_ty ctxt ~legacy arg_type)\n >>?= fun (Ex_ty arg_type, ctxt) ->\n (if legacy then ok_unit else well_formed_entrypoints ~root_name arg_type)\n >>?= fun () ->\n record_trace\n (Ill_formed_type (Some \"storage\", code, location storage_type))\n (parse_storage_ty ctxt ~legacy storage_type)\n >>?= fun (Ex_ty storage_type, ctxt) ->\n let arg_annot =\n default_annot\n (type_to_var_annot (name_of_ty arg_type))\n ~default:default_param_annot\n in\n let storage_annot =\n default_annot\n (type_to_var_annot (name_of_ty storage_type))\n ~default:default_storage_annot\n in\n let arg_type_full =\n Pair_t\n ((arg_type, None, arg_annot), (storage_type, None, storage_annot), None)\n in\n let ret_type_full =\n Pair_t\n ( (List_t (Operation_t None, None), None, None),\n (storage_type, None, None),\n None )\n in\n let result =\n parse_returning\n (Toplevel\n {\n storage_type;\n param_type = arg_type;\n root_name;\n legacy_create_contract_literal = false;\n })\n ctxt\n ~legacy\n ~stack_depth:0\n ~type_logger:(fun loc bef aft ->\n type_map := (loc, (bef, aft)) :: !type_map)\n (arg_type_full, None)\n ret_type_full\n code_field\n in\n trace (Ill_typed_contract (code, !type_map)) result\n >|=? fun (Lam _, ctxt) -> (!type_map, ctxt)\n\nmodule Entrypoints_map = Map.Make (String)\n\nlet list_entrypoints (type full) (full : full ty) ctxt ~root_name =\n let merge path annot (type t) (ty : t ty) reachable\n ((unreachables, all) as acc) =\n match annot with\n | None | Some (Field_annot \"\") -> (\n ok\n @@\n if reachable then acc\n else\n match ty with\n | Union_t _ ->\n acc\n | _ ->\n (List.rev path :: unreachables, all) )\n | Some (Field_annot name) ->\n if Compare.Int.(String.length name > 31) then\n ok (List.rev path :: unreachables, all)\n else if Entrypoints_map.mem name all then\n ok (List.rev path :: unreachables, all)\n else\n unparse_ty ctxt ty\n >>? fun (unparsed_ty, _) ->\n ok\n ( unreachables,\n Entrypoints_map.add name (List.rev path, unparsed_ty) all )\n in\n let rec fold_tree :\n type t.\n t ty ->\n prim list ->\n bool ->\n prim list list * (prim list * Script.node) Entrypoints_map.t ->\n (prim list list * (prim list * Script.node) Entrypoints_map.t) tzresult =\n fun t path reachable acc ->\n match t with\n | Union_t ((tl, al), (tr, ar), _) ->\n merge (D_Left :: path) al tl reachable acc\n >>? fun acc ->\n merge (D_Right :: path) ar tr reachable acc\n >>? fun acc ->\n fold_tree\n tl\n (D_Left :: path)\n (match al with Some _ -> true | None -> reachable)\n acc\n >>? fun acc ->\n fold_tree\n tr\n (D_Right :: path)\n (match ar with Some _ -> true | None -> reachable)\n acc\n | _ ->\n ok acc\n in\n unparse_ty ctxt full\n >>? fun (unparsed_full, _) ->\n let (init, reachable) =\n match root_name with\n | None | Some (Field_annot \"\") ->\n (Entrypoints_map.empty, false)\n | Some (Field_annot name) ->\n (Entrypoints_map.singleton name ([], unparsed_full), true)\n in\n fold_tree full [] reachable ([], init)\n\n(* ---- Unparsing (Typed IR -> Untyped expressions) --------------------------*)\n\n(* -- Unparsing data of primitive types -- *)\n\nlet unparse_unit ctxt () = ok (Prim (-1, D_Unit, [], []), ctxt)\n\nlet unparse_int ctxt v = ok (Int (-1, Script_int.to_zint v), ctxt)\n\nlet unparse_nat ctxt v = ok (Int (-1, Script_int.to_zint v), ctxt)\n\nlet unparse_string ctxt s = ok (String (-1, s), ctxt)\n\nlet unparse_bytes ctxt s = ok (Bytes (-1, s), ctxt)\n\nlet unparse_bool ctxt b =\n ok (Prim (-1, (if b then D_True else D_False), [], []), ctxt)\n\nlet unparse_timestamp ctxt mode t =\n match mode with\n | Optimized | Optimized_legacy ->\n ok (Int (-1, Script_timestamp.to_zint t), ctxt)\n | Readable -> (\n Gas.consume ctxt Unparse_costs.timestamp_readable\n >>? fun ctxt ->\n match Script_timestamp.to_notation t with\n | None ->\n ok (Int (-1, Script_timestamp.to_zint t), ctxt)\n | Some s ->\n ok (String (-1, s), ctxt) )\n\nlet unparse_address ctxt mode (c, entrypoint) =\n Gas.consume ctxt Unparse_costs.contract\n >>? fun ctxt ->\n ( match entrypoint with\n (* given parse_address, this should not happen *)\n | \"\" ->\n error Unparsing_invariant_violated\n | _ ->\n ok () )\n >|? fun () ->\n match mode with\n | Optimized | Optimized_legacy ->\n let entrypoint =\n match entrypoint with \"default\" -> \"\" | name -> name\n in\n let bytes =\n Data_encoding.Binary.to_bytes_exn\n Data_encoding.(tup2 Contract.encoding Variable.string)\n (c, entrypoint)\n in\n (Bytes (-1, bytes), ctxt)\n | Readable ->\n let notation =\n match entrypoint with\n | \"default\" ->\n Contract.to_b58check c\n | entrypoint ->\n Contract.to_b58check c ^ \"%\" ^ entrypoint\n in\n (String (-1, notation), ctxt)\n\nlet unparse_contract ctxt mode (_, address) = unparse_address ctxt mode address\n\nlet unparse_signature ctxt mode s =\n match mode with\n | Optimized | Optimized_legacy ->\n Gas.consume ctxt Unparse_costs.signature_optimized\n >|? fun ctxt ->\n let bytes = Data_encoding.Binary.to_bytes_exn Signature.encoding s in\n (Bytes (-1, bytes), ctxt)\n | Readable ->\n Gas.consume ctxt Unparse_costs.signature_readable\n >|? fun ctxt -> (String (-1, Signature.to_b58check s), ctxt)\n\nlet unparse_mutez ctxt v = ok (Int (-1, Z.of_int64 (Tez.to_mutez v)), ctxt)\n\nlet unparse_key ctxt mode k =\n match mode with\n | Optimized | Optimized_legacy ->\n Gas.consume ctxt Unparse_costs.public_key_optimized\n >|? fun ctxt ->\n let bytes =\n Data_encoding.Binary.to_bytes_exn Signature.Public_key.encoding k\n in\n (Bytes (-1, bytes), ctxt)\n | Readable ->\n Gas.consume ctxt Unparse_costs.public_key_readable\n >|? fun ctxt -> (String (-1, Signature.Public_key.to_b58check k), ctxt)\n\nlet unparse_key_hash ctxt mode k =\n match mode with\n | Optimized | Optimized_legacy ->\n Gas.consume ctxt Unparse_costs.key_hash_optimized\n >|? fun ctxt ->\n let bytes =\n Data_encoding.Binary.to_bytes_exn Signature.Public_key_hash.encoding k\n in\n (Bytes (-1, bytes), ctxt)\n | Readable ->\n Gas.consume ctxt Unparse_costs.key_hash_readable\n >|? fun ctxt ->\n (String (-1, Signature.Public_key_hash.to_b58check k), ctxt)\n\nlet unparse_operation ctxt (op, _big_map_diff) =\n let bytes =\n Data_encoding.Binary.to_bytes_exn Operation.internal_operation_encoding op\n in\n Gas.consume ctxt (Unparse_costs.operation bytes)\n >|? fun ctxt -> (Bytes (-1, bytes), ctxt)\n\nlet unparse_chain_id ctxt mode chain_id =\n match mode with\n | Optimized | Optimized_legacy ->\n Gas.consume ctxt Unparse_costs.chain_id_optimized\n >|? fun ctxt ->\n let bytes =\n Data_encoding.Binary.to_bytes_exn Chain_id.encoding chain_id\n in\n (Bytes (-1, bytes), ctxt)\n | Readable ->\n Gas.consume ctxt Unparse_costs.chain_id_readable\n >|? fun ctxt -> (String (-1, Chain_id.to_b58check chain_id), ctxt)\n\nlet unparse_bls12_381_g1 ctxt x =\n Gas.consume ctxt Unparse_costs.bls12_381_g1\n >|? fun ctxt ->\n let bytes = Bls12_381.G1.to_bytes x in\n (Bytes (-1, bytes), ctxt)\n\nlet unparse_bls12_381_g2 ctxt x =\n Gas.consume ctxt Unparse_costs.bls12_381_g2\n >|? fun ctxt ->\n let bytes = Bls12_381.G2.to_bytes x in\n (Bytes (-1, bytes), ctxt)\n\nlet unparse_bls12_381_fr ctxt x =\n Gas.consume ctxt Unparse_costs.bls12_381_fr\n >|? fun ctxt ->\n let bytes = Bls12_381.Fr.to_bytes x in\n (Bytes (-1, bytes), ctxt)\n\n(* -- Unparsing data of complex types -- *)\n\nlet unparse_pair (type r) unparse_l unparse_r ctxt mode\n (r_comb_witness : (r, unit -> unit -> _) comb_witness) (l, (r : r)) =\n unparse_l ctxt l\n >>=? fun (l, ctxt) ->\n unparse_r ctxt r\n >|=? fun (r, ctxt) ->\n (* Fold combs.\n For combs, three notations are supported:\n - a) [Pair x1 (Pair x2 ... (Pair xn-1 xn) ...)],\n - b) [Pair x1 x2 ... xn-1 xn], and\n - c) [{x1; x2; ...; xn-1; xn}].\n In readable mode, we always use b),\n in optimized mode we use the shortest to serialize:\n - for n=2, [Pair x1 x2],\n - for n=3, [Pair x1 (Pair x2 x3)],\n - for n>=4, [{x1; x2; ...; xn}].\n *)\n let res =\n match (mode, r_comb_witness, r) with\n | (Optimized, Comb_Pair _, Micheline.Seq (_, r)) ->\n (* Optimized case n > 4 *)\n Micheline.Seq (-1, l :: r)\n | ( Optimized,\n Comb_Pair (Comb_Pair _),\n Prim (_, D_Pair, [x2; Prim (_, D_Pair, [x3; x4], [])], []) ) ->\n (* Optimized case n = 4 *)\n Micheline.Seq (-1, [l; x2; x3; x4])\n | (Readable, Comb_Pair _, Prim (_, D_Pair, xs, [])) ->\n (* Readable case n > 2 *)\n Prim (-1, D_Pair, l :: xs, [])\n | _ ->\n (* The remaining cases are:\n - Optimized n = 2,\n - Optimized n = 3, and\n - Readable n = 2,\n - Optimized_legacy, any n *)\n Prim (-1, D_Pair, [l; r], [])\n in\n (res, ctxt)\n\nlet unparse_union unparse_l unparse_r ctxt = function\n | L l ->\n unparse_l ctxt l >|=? fun (l, ctxt) -> (Prim (-1, D_Left, [l], []), ctxt)\n | R r ->\n unparse_r ctxt r >|=? fun (r, ctxt) -> (Prim (-1, D_Right, [r], []), ctxt)\n\nlet unparse_option unparse_v ctxt = function\n | Some v ->\n unparse_v ctxt v >|=? fun (v, ctxt) -> (Prim (-1, D_Some, [v], []), ctxt)\n | None ->\n return (Prim (-1, D_None, [], []), ctxt)\n\n(* -- Unparsing data of comparable types -- *)\n\nlet comparable_comb_witness2 :\n type t. t comparable_ty -> (t, unit -> unit -> unit) comb_witness =\n function\n | Pair_key (_, (Pair_key _, _), _) ->\n Comb_Pair (Comb_Pair Comb_Any)\n | Pair_key _ ->\n Comb_Pair Comb_Any\n | _ ->\n Comb_Any\n\nlet rec unparse_comparable_data :\n type a.\n context ->\n unparsing_mode ->\n a comparable_ty ->\n a ->\n (Script.node * context) tzresult Lwt.t =\n fun ctxt mode ty a ->\n (* No need for stack_depth here. Unlike [unparse_data],\n [unparse_comparable_data] doesn't call [unparse_code].\n The stack depth is bounded by the type depth, currently bounded\n by 1000 (michelson_maximum_type_size). *)\n Gas.consume ctxt Unparse_costs.unparse_data_cycle\n (* We could have a smaller cost but let's keep it consistent with\n [unparse_data] for now. *)\n >>?= fun ctxt ->\n match (ty, a) with\n | (Unit_key _, v) ->\n Lwt.return @@ unparse_unit ctxt v\n | (Int_key _, v) ->\n Lwt.return @@ unparse_int ctxt v\n | (Nat_key _, v) ->\n Lwt.return @@ unparse_nat ctxt v\n | (String_key _, s) ->\n Lwt.return @@ unparse_string ctxt s\n | (Bytes_key _, s) ->\n Lwt.return @@ unparse_bytes ctxt s\n | (Bool_key _, b) ->\n Lwt.return @@ unparse_bool ctxt b\n | (Timestamp_key _, t) ->\n Lwt.return @@ unparse_timestamp ctxt mode t\n | (Address_key _, address) ->\n Lwt.return @@ unparse_address ctxt mode address\n | (Signature_key _, s) ->\n Lwt.return @@ unparse_signature ctxt mode s\n | (Mutez_key _, v) ->\n Lwt.return @@ unparse_mutez ctxt v\n | (Key_key _, k) ->\n Lwt.return @@ unparse_key ctxt mode k\n | (Key_hash_key _, k) ->\n Lwt.return @@ unparse_key_hash ctxt mode k\n | (Chain_id_key _, chain_id) ->\n Lwt.return @@ unparse_chain_id ctxt mode chain_id\n | (Pair_key ((tl, _), (tr, _), _), pair) ->\n let r_witness = comparable_comb_witness2 tr in\n let unparse_l ctxt v = unparse_comparable_data ctxt mode tl v in\n let unparse_r ctxt v = unparse_comparable_data ctxt mode tr v in\n unparse_pair unparse_l unparse_r ctxt mode r_witness pair\n | (Union_key ((tl, _), (tr, _), _), v) ->\n let unparse_l ctxt v = unparse_comparable_data ctxt mode tl v in\n let unparse_r ctxt v = unparse_comparable_data ctxt mode tr v in\n unparse_union unparse_l unparse_r ctxt v\n | (Option_key (t, _), v) ->\n let unparse_v ctxt v = unparse_comparable_data ctxt mode t v in\n unparse_option unparse_v ctxt v\n | (Never_key _, _) ->\n .\n\n(* -- Unparsing data of any type -- *)\n\nlet comb_witness2 : type t. t ty -> (t, unit -> unit -> unit) comb_witness =\n function\n | Pair_t (_, (Pair_t _, _, _), _) ->\n Comb_Pair (Comb_Pair Comb_Any)\n | Pair_t _ ->\n Comb_Pair Comb_Any\n | _ ->\n Comb_Any\n\nlet rec unparse_data :\n type a.\n context ->\n stack_depth:int ->\n unparsing_mode ->\n a ty ->\n a ->\n (Script.node * context) tzresult Lwt.t =\n fun ctxt ~stack_depth mode ty a ->\n Gas.consume ctxt Unparse_costs.unparse_data_cycle\n >>?= fun ctxt ->\n let non_terminal_recursion ctxt mode ty a =\n if Compare.Int.(stack_depth > 10_000) then\n fail Unparsing_too_many_recursive_calls\n else unparse_data ctxt ~stack_depth:(stack_depth + 1) mode ty a\n in\n match (ty, a) with\n | (Unit_t _, v) ->\n Lwt.return @@ unparse_unit ctxt v\n | (Int_t _, v) ->\n Lwt.return @@ unparse_int ctxt v\n | (Nat_t _, v) ->\n Lwt.return @@ unparse_nat ctxt v\n | (String_t _, s) ->\n Lwt.return @@ unparse_string ctxt s\n | (Bytes_t _, s) ->\n Lwt.return @@ unparse_bytes ctxt s\n | (Bool_t _, b) ->\n Lwt.return @@ unparse_bool ctxt b\n | (Timestamp_t _, t) ->\n Lwt.return @@ unparse_timestamp ctxt mode t\n | (Address_t _, address) ->\n Lwt.return @@ unparse_address ctxt mode address\n | (Contract_t _, contract) ->\n Lwt.return @@ unparse_contract ctxt mode contract\n | (Signature_t _, s) ->\n Lwt.return @@ unparse_signature ctxt mode s\n | (Mutez_t _, v) ->\n Lwt.return @@ unparse_mutez ctxt v\n | (Key_t _, k) ->\n Lwt.return @@ unparse_key ctxt mode k\n | (Key_hash_t _, k) ->\n Lwt.return @@ unparse_key_hash ctxt mode k\n | (Operation_t _, operation) ->\n Lwt.return @@ unparse_operation ctxt operation\n | (Chain_id_t _, chain_id) ->\n Lwt.return @@ unparse_chain_id ctxt mode chain_id\n | (Bls12_381_g1_t _, x) ->\n Lwt.return @@ unparse_bls12_381_g1 ctxt x\n | (Bls12_381_g2_t _, x) ->\n Lwt.return @@ unparse_bls12_381_g2 ctxt x\n | (Bls12_381_fr_t _, x) ->\n Lwt.return @@ unparse_bls12_381_fr ctxt x\n | (Pair_t ((tl, _, _), (tr, _, _), _), pair) ->\n let r_witness = comb_witness2 tr in\n let unparse_l ctxt v = non_terminal_recursion ctxt mode tl v in\n let unparse_r ctxt v = non_terminal_recursion ctxt mode tr v in\n unparse_pair unparse_l unparse_r ctxt mode r_witness pair\n | (Union_t ((tl, _), (tr, _), _), v) ->\n let unparse_l ctxt v = non_terminal_recursion ctxt mode tl v in\n let unparse_r ctxt v = non_terminal_recursion ctxt mode tr v in\n unparse_union unparse_l unparse_r ctxt v\n | (Option_t (t, _), v) ->\n let unparse_v ctxt v = non_terminal_recursion ctxt mode t v in\n unparse_option unparse_v ctxt v\n | (List_t (t, _), items) ->\n fold_left_s\n (fun (l, ctxt) element ->\n non_terminal_recursion ctxt mode t element\n >|=? fun (unparsed, ctxt) -> (unparsed :: l, ctxt))\n ([], ctxt)\n items.elements\n >|=? fun (items, ctxt) -> (Micheline.Seq (-1, List.rev items), ctxt)\n | (Ticket_t (t, _), {ticketer; contents; amount}) ->\n let t = ty_of_comparable_ty @@ opened_ticket_type t in\n unparse_data ctxt ~stack_depth mode t (ticketer, (contents, amount))\n | (Set_t (t, _), set) ->\n fold_left_s\n (fun (l, ctxt) item ->\n unparse_comparable_data ctxt mode t item\n >|=? fun (item, ctxt) -> (item :: l, ctxt))\n ([], ctxt)\n (set_fold (fun e acc -> e :: acc) set [])\n >|=? fun (items, ctxt) -> (Micheline.Seq (-1, items), ctxt)\n | (Map_t (kt, vt, _), map) ->\n let items = map_fold (fun k v acc -> (k, v) :: acc) map [] in\n unparse_items ctxt ~stack_depth:(stack_depth + 1) mode kt vt items\n >|=? fun (items, ctxt) -> (Micheline.Seq (-1, items), ctxt)\n | (Big_map_t (_kt, _vt, _), {id = Some id; diff = (module Diff); _})\n when Diff.OPS.is_empty (fst Diff.boxed) ->\n return (Micheline.Int (-1, Big_map.Id.unparse_to_z id), ctxt)\n | (Big_map_t (kt, vt, _), {id = Some id; diff = (module Diff); _}) ->\n let items =\n Diff.OPS.fold (fun k v acc -> (k, v) :: acc) (fst Diff.boxed) []\n in\n let vt = Option_t (vt, None) in\n unparse_items ctxt ~stack_depth:(stack_depth + 1) mode kt vt items\n >|=? fun (items, ctxt) ->\n ( Micheline.Prim\n ( -1,\n D_Pair,\n [Int (-1, Big_map.Id.unparse_to_z id); Seq (-1, items)],\n [] ),\n ctxt )\n | (Big_map_t (kt, vt, _), {id = None; diff = (module Diff); _}) ->\n let items =\n Diff.OPS.fold\n (fun k v acc -> match v with None -> acc | Some v -> (k, v) :: acc)\n (fst Diff.boxed)\n []\n in\n unparse_items ctxt ~stack_depth:(stack_depth + 1) mode kt vt items\n >|=? fun (items, ctxt) -> (Micheline.Seq (-1, items), ctxt)\n | (Lambda_t _, Lam (_, original_code)) ->\n unparse_code ctxt ~stack_depth:(stack_depth + 1) mode original_code\n | (Never_t _, _) ->\n .\n | (Sapling_transaction_t _, s) ->\n Lwt.return\n ( Gas.consume ctxt (Unparse_costs.sapling_transaction s)\n >|? fun ctxt ->\n let bytes =\n Data_encoding.Binary.to_bytes_exn Sapling.transaction_encoding s\n in\n (Bytes (-1, bytes), ctxt) )\n | (Sapling_state_t _, {id; diff; _}) ->\n Lwt.return\n ( Gas.consume ctxt (Unparse_costs.sapling_diff diff)\n >|? fun ctxt ->\n ( ( match diff with\n | {commitments_and_ciphertexts = []; nullifiers = []} -> (\n match id with\n | None ->\n Micheline.Seq (-1, [])\n | Some id ->\n let id = Sapling.Id.unparse_to_z id in\n Micheline.Int (-1, id) )\n | diff -> (\n let diff_bytes =\n Data_encoding.Binary.to_bytes_exn Sapling.diff_encoding diff\n in\n let unparsed_diff = Bytes (-1, diff_bytes) in\n match id with\n | None ->\n unparsed_diff\n | Some id ->\n let id = Sapling.Id.unparse_to_z id in\n Micheline.Prim (-1, D_Pair, [Int (-1, id); unparsed_diff], [])\n ) ),\n ctxt ) )\n\nand unparse_items :\n type k v.\n context ->\n stack_depth:int ->\n unparsing_mode ->\n k comparable_ty ->\n v ty ->\n (k * v) list ->\n (Script.node list * context) tzresult Lwt.t =\n fun ctxt ~stack_depth mode kt vt items ->\n fold_left_s\n (fun (l, ctxt) (k, v) ->\n unparse_comparable_data ctxt mode kt k\n >>=? fun (key, ctxt) ->\n unparse_data ctxt ~stack_depth:(stack_depth + 1) mode vt v\n >|=? fun (value, ctxt) -> (Prim (-1, D_Elt, [key; value], []) :: l, ctxt))\n ([], ctxt)\n items\n\nand unparse_code ctxt ~stack_depth mode code =\n let legacy = true in\n Gas.consume ctxt Unparse_costs.unparse_instr_cycle\n >>?= fun ctxt ->\n let non_terminal_recursion ctxt mode code =\n if Compare.Int.(stack_depth > 10_000) then\n fail Unparsing_too_many_recursive_calls\n else unparse_code ctxt ~stack_depth:(stack_depth + 1) mode code\n in\n match code with\n | Prim (loc, I_PUSH, [ty; data], annot) ->\n parse_packable_ty ctxt ~legacy ty\n >>?= fun (Ex_ty t, ctxt) ->\n let allow_forged =\n false\n (* Forgeable in PUSH data are already forbidden at parsing,\n the only case for which this matters is storing a lambda resulting\n from APPLYing a non-forgeable but this cannot happen either as long\n as all packable values are also forgeable. *)\n in\n parse_data\n ctxt\n ~stack_depth:(stack_depth + 1)\n ~legacy\n ~allow_forged\n t\n data\n >>=? fun (data, ctxt) ->\n unparse_data ctxt ~stack_depth:(stack_depth + 1) mode t data\n >>=? fun (data, ctxt) ->\n return (Prim (loc, I_PUSH, [ty; data], annot), ctxt)\n | Seq (loc, items) ->\n fold_left_s\n (fun (l, ctxt) item ->\n non_terminal_recursion ctxt mode item\n >|=? fun (item, ctxt) -> (item :: l, ctxt))\n ([], ctxt)\n items\n >>=? fun (items, ctxt) ->\n return (Micheline.Seq (loc, List.rev items), ctxt)\n | Prim (loc, prim, items, annot) ->\n fold_left_s\n (fun (l, ctxt) item ->\n non_terminal_recursion ctxt mode item\n >|=? fun (item, ctxt) -> (item :: l, ctxt))\n ([], ctxt)\n items\n >>=? fun (items, ctxt) ->\n return (Prim (loc, prim, List.rev items, annot), ctxt)\n | (Int _ | String _ | Bytes _) as atom ->\n return (atom, ctxt)\n\n(* Gas accounting may not be perfect in this function, as it is only called by RPCs. *)\nlet unparse_script ctxt mode {code; arg_type; storage; storage_type; root_name}\n =\n let (Lam (_, original_code)) = code in\n unparse_code ctxt ~stack_depth:0 mode original_code\n >>=? fun (code, ctxt) ->\n unparse_data ctxt ~stack_depth:0 mode storage_type storage\n >>=? fun (storage, ctxt) ->\n Lwt.return\n ( unparse_ty ctxt arg_type\n >>? fun (arg_type, ctxt) ->\n unparse_ty ctxt storage_type\n >>? fun (storage_type, ctxt) ->\n let arg_type = add_field_annot root_name None arg_type in\n let open Micheline in\n let code =\n Seq\n ( -1,\n [ Prim (-1, K_parameter, [arg_type], []);\n Prim (-1, K_storage, [storage_type], []);\n Prim (-1, K_code, [code], []) ] )\n in\n Gas.consume ctxt Unparse_costs.unparse_instr_cycle\n >>? fun ctxt ->\n Gas.consume ctxt Unparse_costs.unparse_instr_cycle\n >>? fun ctxt ->\n Gas.consume ctxt Unparse_costs.unparse_instr_cycle\n >>? fun ctxt ->\n Gas.consume ctxt Unparse_costs.unparse_instr_cycle\n >>? fun ctxt ->\n Gas.consume ctxt (Script.strip_locations_cost code)\n >>? fun ctxt ->\n Gas.consume ctxt (Script.strip_locations_cost storage)\n >|? fun ctxt ->\n ( {\n code = lazy_expr (strip_locations code);\n storage = lazy_expr (strip_locations storage);\n },\n ctxt ) )\n\nlet pack_node unparsed ctxt =\n Gas.consume ctxt (Script.strip_locations_cost unparsed)\n >>? fun ctxt ->\n let bytes =\n Data_encoding.Binary.to_bytes_exn\n expr_encoding\n (Micheline.strip_locations unparsed)\n in\n Gas.consume ctxt (Script.serialized_cost bytes)\n >>? fun ctxt ->\n let bytes = Bytes.cat (Bytes.of_string \"\\005\") bytes in\n Gas.consume ctxt (Script.serialized_cost bytes) >|? fun ctxt -> (bytes, ctxt)\n\nlet pack_data ctxt typ data ~mode =\n unparse_data ~stack_depth:0 ctxt mode typ data\n >>=? fun (unparsed, ctxt) -> Lwt.return @@ pack_node unparsed ctxt\n\nlet pack_comparable_data ctxt typ data ~mode =\n unparse_comparable_data ctxt mode typ data\n >>=? fun (unparsed, ctxt) -> Lwt.return @@ pack_node unparsed ctxt\n\nlet hash_bytes ctxt bytes =\n Gas.consume ctxt (Michelson_v1_gas.Cost_of.Interpreter.blake2b bytes)\n >|? fun ctxt -> (Script_expr_hash.(hash_bytes [bytes]), ctxt)\n\nlet hash_data ctxt typ data =\n pack_data ctxt typ data ~mode:Optimized_legacy\n >>=? fun (bytes, ctxt) -> Lwt.return @@ hash_bytes ctxt bytes\n\nlet hash_comparable_data ctxt typ data =\n pack_comparable_data ctxt typ data ~mode:Optimized_legacy\n >>=? fun (bytes, ctxt) -> Lwt.return @@ hash_bytes ctxt bytes\n\nlet pack_data ctxt typ data = pack_data ctxt typ data ~mode:Optimized_legacy\n\n(* ---------------- Big map -------------------------------------------------*)\n\nlet empty_big_map key_type value_type =\n {id = None; diff = empty_map key_type; key_type; value_type}\n\nlet big_map_mem ctxt key {id; diff; key_type; _} =\n match (map_get key diff, id) with\n | (None, None) ->\n return (false, ctxt)\n | (None, Some id) ->\n hash_comparable_data ctxt key_type key\n >>=? fun (hash, ctxt) ->\n Alpha_context.Big_map.mem ctxt id hash >|=? fun (ctxt, res) -> (res, ctxt)\n | (Some None, _) ->\n return (false, ctxt)\n | (Some (Some _), _) ->\n return (true, ctxt)\n\nlet big_map_get ctxt key {id; diff; key_type; value_type} =\n match (map_get key diff, id) with\n | (Some x, _) ->\n return (x, ctxt)\n | (None, None) ->\n return (None, ctxt)\n | (None, Some id) -> (\n hash_comparable_data ctxt key_type key\n >>=? fun (hash, ctxt) ->\n Alpha_context.Big_map.get_opt ctxt id hash\n >>=? function\n | (ctxt, None) ->\n return (None, ctxt)\n | (ctxt, Some value) ->\n parse_data\n ~stack_depth:0\n ctxt\n ~legacy:true\n ~allow_forged:true\n value_type\n (Micheline.root value)\n >|=? fun (x, ctxt) -> (Some x, ctxt) )\n\nlet big_map_update key value ({diff; _} as map) =\n {map with diff = map_set key value diff}\n\n(* ---------------- Lazy storage---------------------------------------------*)\n\ntype lazy_storage_ids = Lazy_storage.IdSet.t\n\nlet no_lazy_storage_id = Lazy_storage.IdSet.empty\n\nlet diff_of_big_map ctxt mode ~temporary ~ids_to_copy\n {id; key_type; value_type; diff} =\n ( match id with\n | Some id ->\n if Lazy_storage.IdSet.mem Big_map id ids_to_copy then\n Big_map.fresh ~temporary ctxt\n >|=? fun (ctxt, duplicate) ->\n (ctxt, Lazy_storage.Copy {src = id}, duplicate)\n else\n (* The first occurrence encountered of a big_map reuses the\n ID. This way, the payer is only charged for the diff.\n For this to work, this diff has to be put at the end of\n the global diff, otherwise the duplicates will use the\n updated version as a base. This is true because we add\n this diff first in the accumulator of\n `extract_lazy_storage_updates`, and this accumulator is not\n reversed. *)\n return (ctxt, Lazy_storage.Existing, id)\n | None ->\n Big_map.fresh ~temporary ctxt\n >>=? fun (ctxt, id) ->\n Lwt.return\n (let kt = unparse_comparable_ty key_type in\n Gas.consume ctxt (Script.strip_locations_cost kt)\n >>? fun ctxt ->\n unparse_ty ctxt value_type\n >>? fun (kv, ctxt) ->\n Gas.consume ctxt (Script.strip_locations_cost kv)\n >|? fun ctxt ->\n let key_type = Micheline.strip_locations kt in\n let value_type = Micheline.strip_locations kv in\n (ctxt, Lazy_storage.(Alloc Big_map.{key_type; value_type}), id)) )\n >>=? fun (ctxt, init, id) ->\n let pairs = map_fold (fun key value acc -> (key, value) :: acc) diff [] in\n fold_left_s\n (fun (acc, ctxt) (key, value) ->\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>?= fun ctxt ->\n hash_comparable_data ctxt key_type key\n >>=? fun (key_hash, ctxt) ->\n unparse_comparable_data ctxt mode key_type key\n >>=? fun (key_node, ctxt) ->\n Gas.consume ctxt (Script.strip_locations_cost key_node)\n >>?= fun ctxt ->\n let key = Micheline.strip_locations key_node in\n ( match value with\n | None ->\n return (None, ctxt)\n | Some x ->\n unparse_data ~stack_depth:0 ctxt mode value_type x\n >>=? fun (node, ctxt) ->\n Lwt.return\n ( Gas.consume ctxt (Script.strip_locations_cost node)\n >|? fun ctxt -> (Some (Micheline.strip_locations node), ctxt) ) )\n >|=? fun (value, ctxt) ->\n let diff_item = Big_map.{key; key_hash; value} in\n (diff_item :: acc, ctxt))\n ([], ctxt)\n (List.rev pairs)\n >|=? fun (updates, ctxt) -> (Lazy_storage.Update {init; updates}, id, ctxt)\n\nlet diff_of_sapling_state ctxt ~temporary ~ids_to_copy\n ({id; diff; memo_size} : Sapling.state) =\n ( match id with\n | Some id ->\n if Lazy_storage.IdSet.mem Sapling_state id ids_to_copy then\n Sapling.fresh ~temporary ctxt\n >|=? fun (ctxt, duplicate) ->\n (ctxt, Lazy_storage.Copy {src = id}, duplicate)\n else return (ctxt, Lazy_storage.Existing, id)\n | None ->\n Sapling.fresh ~temporary ctxt\n >|=? fun (ctxt, id) -> (ctxt, Lazy_storage.Alloc Sapling.{memo_size}, id)\n )\n >|=? fun (ctxt, init, id) ->\n (Lazy_storage.Update {init; updates = diff}, id, ctxt)\n\n(**\n Witness flag for whether a type can be populated by a value containing a\n lazy storage.\n [False_f] must be used only when a value of the type cannot contain a lazy\n storage.\n\n This flag is built in [has_lazy_storage] and used only in\n [extract_lazy_storage_updates] and [collect_lazy_storage].\n\n This flag is necessary to avoid these two functions to have a quadratic\n complexity in the size of the type.\n\n Add new lazy storage kinds here.\n\n Please keep the usage of this GADT local.\n*)\ntype 'ty has_lazy_storage =\n | True_f : _ has_lazy_storage\n | False_f : _ has_lazy_storage\n | Pair_f :\n 'a has_lazy_storage * 'b has_lazy_storage\n -> ('a, 'b) pair has_lazy_storage\n | Union_f :\n 'a has_lazy_storage * 'b has_lazy_storage\n -> ('a, 'b) union has_lazy_storage\n | Option_f : 'a has_lazy_storage -> 'a option has_lazy_storage\n | List_f : 'a has_lazy_storage -> 'a boxed_list has_lazy_storage\n | Map_f : 'v has_lazy_storage -> (_, 'v) map has_lazy_storage\n\n(**\n This function is called only on storage and parameter types of contracts,\n once per typechecked contract. It has a complexity linear in the size of\n the types, which happen to be literally written types, so the gas for them\n has already been paid.\n*)\nlet rec has_lazy_storage : type t. t ty -> t has_lazy_storage =\n let aux1 cons t =\n match has_lazy_storage t with False_f -> False_f | h -> cons h\n in\n let aux2 cons t1 t2 =\n match (has_lazy_storage t1, has_lazy_storage t2) with\n | (False_f, False_f) ->\n False_f\n | (h1, h2) ->\n cons h1 h2\n in\n function\n | Big_map_t (_, _, _) ->\n True_f\n | Sapling_state_t _ ->\n True_f\n | Unit_t _ ->\n False_f\n | Int_t _ ->\n False_f\n | Nat_t _ ->\n False_f\n | Signature_t _ ->\n False_f\n | String_t _ ->\n False_f\n | Bytes_t _ ->\n False_f\n | Mutez_t _ ->\n False_f\n | Key_hash_t _ ->\n False_f\n | Key_t _ ->\n False_f\n | Timestamp_t _ ->\n False_f\n | Address_t _ ->\n False_f\n | Bool_t _ ->\n False_f\n | Lambda_t (_, _, _) ->\n False_f\n | Set_t (_, _) ->\n False_f\n | Contract_t (_, _) ->\n False_f\n | Operation_t _ ->\n False_f\n | Chain_id_t _ ->\n False_f\n | Never_t _ ->\n False_f\n | Bls12_381_g1_t _ ->\n False_f\n | Bls12_381_g2_t _ ->\n False_f\n | Bls12_381_fr_t _ ->\n False_f\n | Sapling_transaction_t _ ->\n False_f\n | Ticket_t _ ->\n False_f\n | Pair_t ((l, _, _), (r, _, _), _) ->\n aux2 (fun l r -> Pair_f (l, r)) l r\n | Union_t ((l, _), (r, _), _) ->\n aux2 (fun l r -> Union_f (l, r)) l r\n | Option_t (t, _) ->\n aux1 (fun h -> Option_f h) t\n | List_t (t, _) ->\n aux1 (fun h -> List_f h) t\n | Map_t (_, t, _) ->\n aux1 (fun h -> Map_f h) t\n\n(**\n Transforms a value potentially containing lazy storage in an intermediary\n state to a value containing lazy storage only represented by identifiers.\n\n Returns the updated value, the updated set of ids to copy, and the lazy\n storage diff to show on the receipt and apply on the storage.\n*)\nlet extract_lazy_storage_updates ctxt mode ~temporary ids_to_copy acc ty x =\n let rec aux :\n type a.\n context ->\n unparsing_mode ->\n temporary:bool ->\n Lazy_storage.IdSet.t ->\n Lazy_storage.diffs ->\n a ty ->\n a ->\n has_lazy_storage:a has_lazy_storage ->\n (context * a * Lazy_storage.IdSet.t * Lazy_storage.diffs) tzresult Lwt.t\n =\n fun ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage ->\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>?= fun ctxt ->\n match (has_lazy_storage, ty, x) with\n | (False_f, _, _) ->\n return (ctxt, x, ids_to_copy, acc)\n | (_, Big_map_t (_, _, _), map) ->\n diff_of_big_map ctxt mode ~temporary ~ids_to_copy map\n >|=? fun (diff, id, ctxt) ->\n let (module Map) = map.diff in\n let map = {map with diff = empty_map Map.key_ty; id = Some id} in\n let diff = Lazy_storage.make Big_map id diff in\n let ids_to_copy = Lazy_storage.IdSet.add Big_map id ids_to_copy in\n (ctxt, map, ids_to_copy, diff :: acc)\n | (_, Sapling_state_t _, sapling_state) ->\n diff_of_sapling_state ctxt ~temporary ~ids_to_copy sapling_state\n >|=? fun (diff, id, ctxt) ->\n let sapling_state =\n Sapling.empty_state ~id ~memo_size:sapling_state.memo_size ()\n in\n let diff = Lazy_storage.make Sapling_state id diff in\n let ids_to_copy =\n Lazy_storage.IdSet.add Sapling_state id ids_to_copy\n in\n (ctxt, sapling_state, ids_to_copy, diff :: acc)\n | (Pair_f (hl, hr), Pair_t ((tyl, _, _), (tyr, _, _), _), (xl, xr)) ->\n aux ctxt mode ~temporary ids_to_copy acc tyl xl ~has_lazy_storage:hl\n >>=? fun (ctxt, xl, ids_to_copy, acc) ->\n aux ctxt mode ~temporary ids_to_copy acc tyr xr ~has_lazy_storage:hr\n >|=? fun (ctxt, xr, ids_to_copy, acc) ->\n (ctxt, (xl, xr), ids_to_copy, acc)\n | (Union_f (has_lazy_storage, _), Union_t ((ty, _), (_, _), _), L x) ->\n aux ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage\n >|=? fun (ctxt, x, ids_to_copy, acc) -> (ctxt, L x, ids_to_copy, acc)\n | (Union_f (_, has_lazy_storage), Union_t ((_, _), (ty, _), _), R x) ->\n aux ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage\n >|=? fun (ctxt, x, ids_to_copy, acc) -> (ctxt, R x, ids_to_copy, acc)\n | (Option_f has_lazy_storage, Option_t (ty, _), Some x) ->\n aux ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage\n >|=? fun (ctxt, x, ids_to_copy, acc) -> (ctxt, Some x, ids_to_copy, acc)\n | (List_f has_lazy_storage, List_t (ty, _), l) ->\n fold_left_s\n (fun (ctxt, l, ids_to_copy, acc) x ->\n aux ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage\n >|=? fun (ctxt, x, ids_to_copy, acc) ->\n (ctxt, list_cons x l, ids_to_copy, acc))\n (ctxt, list_empty, ids_to_copy, acc)\n l.elements\n >|=? fun (ctxt, l, ids_to_copy, acc) ->\n let reversed = {length = l.length; elements = List.rev l.elements} in\n (ctxt, reversed, ids_to_copy, acc)\n | (Map_f has_lazy_storage, Map_t (_, ty, _), (module M)) ->\n fold_left_s\n (fun (ctxt, m, ids_to_copy, acc) (k, x) ->\n aux ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage\n >|=? fun (ctxt, x, ids_to_copy, acc) ->\n (ctxt, M.OPS.add k x m, ids_to_copy, acc))\n (ctxt, M.OPS.empty, ids_to_copy, acc)\n (M.OPS.bindings (fst M.boxed))\n >|=? fun (ctxt, m, ids_to_copy, acc) ->\n let module M = struct\n module OPS = M.OPS\n\n type key = M.key\n\n type value = M.value\n\n let key_ty = M.key_ty\n\n let boxed = (m, snd M.boxed)\n end in\n ( ctxt,\n (module M : Boxed_map with type key = M.key and type value = M.value),\n ids_to_copy,\n acc )\n | (_, Option_t (_, _), None) ->\n return (ctxt, None, ids_to_copy, acc)\n | _ ->\n assert false\n (* TODO: fix injectivity of types *)\n in\n let has_lazy_storage = has_lazy_storage ty in\n aux ctxt mode ~temporary ids_to_copy acc ty x ~has_lazy_storage\n\nlet rec fold_lazy_storage :\n type a.\n f:'acc Lazy_storage.IdSet.fold_f ->\n init:'acc ->\n context ->\n a ty ->\n a ->\n has_lazy_storage:a has_lazy_storage ->\n ('acc * context) tzresult =\n fun ~f ~init ctxt ty x ~has_lazy_storage ->\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>? fun ctxt ->\n match (has_lazy_storage, ty, x) with\n | (_, Big_map_t (_, _, _), {id = Some id}) ->\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>? fun ctxt -> ok (f.f Big_map id init, ctxt)\n | (_, Sapling_state_t _, {id = Some id}) ->\n Gas.consume ctxt Typecheck_costs.parse_instr_cycle\n >>? fun ctxt -> ok (f.f Sapling_state id init, ctxt)\n | (False_f, _, _) ->\n ok (init, ctxt)\n | (_, Big_map_t (_, _, _), {id = None}) ->\n ok (init, ctxt)\n | (_, Sapling_state_t _, {id = None}) ->\n ok (init, ctxt)\n | (Pair_f (hl, hr), Pair_t ((tyl, _, _), (tyr, _, _), _), (xl, xr)) ->\n fold_lazy_storage ~f ~init ctxt tyl xl ~has_lazy_storage:hl\n >>? fun (init, ctxt) ->\n fold_lazy_storage ~f ~init ctxt tyr xr ~has_lazy_storage:hr\n | (Union_f (has_lazy_storage, _), Union_t ((ty, _), (_, _), _), L x) ->\n fold_lazy_storage ~f ~init ctxt ty x ~has_lazy_storage\n | (Union_f (_, has_lazy_storage), Union_t ((_, _), (ty, _), _), R x) ->\n fold_lazy_storage ~f ~init ctxt ty x ~has_lazy_storage\n | (_, Option_t (_, _), None) ->\n ok (init, ctxt)\n | (Option_f has_lazy_storage, Option_t (ty, _), Some x) ->\n fold_lazy_storage ~f ~init ctxt ty x ~has_lazy_storage\n | (List_f has_lazy_storage, List_t (ty, _), l) ->\n List.fold_left\n (fun acc x ->\n acc\n >>? fun (init, ctxt) ->\n fold_lazy_storage ~f ~init ctxt ty x ~has_lazy_storage)\n (ok (init, ctxt))\n l.elements\n | (Map_f has_lazy_storage, Map_t (_, ty, _), m) ->\n map_fold\n (fun _ v acc ->\n acc\n >>? fun (init, ctxt) ->\n fold_lazy_storage ~f ~init ctxt ty v ~has_lazy_storage)\n m\n (ok (init, ctxt))\n | _ ->\n (* TODO: fix injectivity of types *) assert false\n\nlet collect_lazy_storage ctxt ty x =\n let has_lazy_storage = has_lazy_storage ty in\n fold_lazy_storage\n ~f:{f = (fun kind id acc -> Lazy_storage.IdSet.add kind id acc)}\n ~init:no_lazy_storage_id\n ctxt\n ty\n x\n ~has_lazy_storage\n\nlet extract_lazy_storage_diff ctxt mode ~temporary ~to_duplicate ~to_update ty\n v =\n (*\n Basically [to_duplicate] are ids from the argument and [to_update] are ids\n from the storage before execution (i.e. it is safe to reuse them since they\n will be owned by the same contract).\n *)\n let to_duplicate = Lazy_storage.IdSet.diff to_duplicate to_update in\n extract_lazy_storage_updates ctxt mode ~temporary to_duplicate [] ty v\n >|=? fun (ctxt, v, alive, diffs) ->\n let diffs =\n if temporary then diffs\n else\n let dead = Lazy_storage.IdSet.diff to_update alive in\n Lazy_storage.IdSet.fold_all\n {f = (fun kind id acc -> Lazy_storage.make kind id Remove :: acc)}\n dead\n diffs\n in\n match diffs with\n | [] ->\n (v, None, ctxt)\n | diffs ->\n (v, Some diffs (* do not reverse *), ctxt)\n\nlet list_of_big_map_ids ids =\n Lazy_storage.IdSet.fold Big_map (fun id acc -> id :: acc) ids []\n\nlet parse_data = parse_data ~stack_depth:0\n\nlet parse_instr = parse_instr ~stack_depth:0\n\nlet unparse_data = unparse_data ~stack_depth:0\n\nlet unparse_code = unparse_code ~stack_depth:0\n\nlet get_single_sapling_state ctxt ty x =\n let has_lazy_storage = has_lazy_storage ty in\n let f (type i a u) (kind : (i, a, u) Lazy_storage.Kind.t) (id : i)\n single_id_opt : Sapling.Id.t option =\n match kind with\n | Lazy_storage.Kind.Sapling_state -> (\n match single_id_opt with None -> Some id | Some _ -> raise Not_found\n (* more than one *) )\n | _ ->\n single_id_opt\n in\n fold_lazy_storage ~f:{f} ~init:None ctxt ty x ~has_lazy_storage\n >>? function (None, _) -> raise Not_found | (Some id, ctxt) -> ok (id, ctxt)\n" ;
} ;
{ name = "Script_tc_errors_registration" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Script\nopen Script_tc_errors\n\n(* Helpers for encoding *)\nlet type_map_enc =\n let open Data_encoding in\n let stack_enc = list (tup2 Script.expr_encoding (list string)) in\n list\n (conv\n (fun (loc, (bef, aft)) -> (loc, bef, aft))\n (fun (loc, bef, aft) -> (loc, (bef, aft)))\n (obj3\n (req \"location\" Script.location_encoding)\n (req \"stack_before\" stack_enc)\n (req \"stack_after\" stack_enc)))\n\nlet stack_ty_enc =\n let open Data_encoding in\n list (obj2 (req \"type\" Script.expr_encoding) (dft \"annots\" (list string) []))\n\n(* main registration *)\nlet () =\n let open Data_encoding in\n let located enc =\n merge_objs (obj1 (req \"location\" Script.location_encoding)) enc\n in\n let arity_enc = int8 in\n let namespace_enc =\n def\n \"primitiveNamespace\"\n ~title:\"Primitive namespace\"\n ~description:\n \"One of the four possible namespaces of primitive (data constructor, \\\n type name, instruction or keyword).\"\n @@ string_enum\n [ (\"type\", Michelson_v1_primitives.Type_namespace);\n (\"constant\", Constant_namespace);\n (\"instruction\", Instr_namespace);\n (\"keyword\", Keyword_namespace) ]\n in\n let kind_enc =\n def\n \"expressionKind\"\n ~title:\"Expression kind\"\n ~description:\n \"One of the four possible kinds of expression (integer, string, \\\n primitive application or sequence).\"\n @@ string_enum\n [ (\"integer\", Int_kind);\n (\"string\", String_kind);\n (\"bytes\", Bytes_kind);\n (\"primitiveApplication\", Prim_kind);\n (\"sequence\", Seq_kind) ]\n in\n (* -- Structure errors ---------------------- *)\n (* Invalid arity *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_arity\"\n ~title:\"Invalid arity\"\n ~description:\n \"In a script or data expression, a primitive was applied to an \\\n unsupported number of arguments.\"\n (located\n (obj3\n (req \"primitive_name\" Script.prim_encoding)\n (req \"expected_arity\" arity_enc)\n (req \"wrong_arity\" arity_enc)))\n (function\n | Invalid_arity (loc, name, exp, got) ->\n Some (loc, (name, exp, got))\n | _ ->\n None)\n (fun (loc, (name, exp, got)) -> Invalid_arity (loc, name, exp, got)) ;\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_seq_arity\"\n ~title:\"Invalid sequence arity\"\n ~description:\n \"In a script or data expression, a sequence was used with a number of \\\n elements too small.\"\n (located\n (obj2\n (req \"minimal_expected_arity\" arity_enc)\n (req \"wrong_arity\" arity_enc)))\n (function\n | Invalid_seq_arity (loc, exp, got) -> Some (loc, (exp, got)) | _ -> None)\n (fun (loc, (exp, got)) -> Invalid_seq_arity (loc, exp, got)) ;\n (* Missing field *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.missing_script_field\"\n ~title:\"Script is missing a field (parse error)\"\n ~description:\"When parsing script, a field was expected, but not provided\"\n (obj1 (req \"prim\" prim_encoding))\n (function Missing_field prim -> Some prim | _ -> None)\n (fun prim -> Missing_field prim) ;\n (* Invalid primitive *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_primitive\"\n ~title:\"Invalid primitive\"\n ~description:\"In a script or data expression, a primitive was unknown.\"\n (located\n (obj2\n (dft \"expected_primitive_names\" (list prim_encoding) [])\n (req \"wrong_primitive_name\" prim_encoding)))\n (function\n | Invalid_primitive (loc, exp, got) -> Some (loc, (exp, got)) | _ -> None)\n (fun (loc, (exp, got)) -> Invalid_primitive (loc, exp, got)) ;\n (* Invalid kind *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_expression_kind\"\n ~title:\"Invalid expression kind\"\n ~description:\n \"In a script or data expression, an expression was of the wrong kind \\\n (for instance a string where only a primitive applications can appear).\"\n (located\n (obj2 (req \"expected_kinds\" (list kind_enc)) (req \"wrong_kind\" kind_enc)))\n (function\n | Invalid_kind (loc, exp, got) -> Some (loc, (exp, got)) | _ -> None)\n (fun (loc, (exp, got)) -> Invalid_kind (loc, exp, got)) ;\n (* Invalid namespace *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_primitive_namespace\"\n ~title:\"Invalid primitive namespace\"\n ~description:\n \"In a script or data expression, a primitive was of the wrong namespace.\"\n (located\n (obj3\n (req \"primitive_name\" prim_encoding)\n (req \"expected_namespace\" namespace_enc)\n (req \"wrong_namespace\" namespace_enc)))\n (function\n | Invalid_namespace (loc, name, exp, got) ->\n Some (loc, (name, exp, got))\n | _ ->\n None)\n (fun (loc, (name, exp, got)) -> Invalid_namespace (loc, name, exp, got)) ;\n (* Invalid literal for type never *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_never_expr\"\n ~title:\"Invalid expression for type never\"\n ~description:\n \"In a script or data expression, an expression was provided but a value \\\n of type never was expected. No expression can have type never.\"\n (located unit)\n (function Invalid_never_expr loc -> Some (loc, ()) | _ -> None)\n (fun (loc, ()) -> Invalid_never_expr loc) ;\n (* Duplicate field *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.duplicate_script_field\"\n ~title:\"Script has a duplicated field (parse error)\"\n ~description:\"When parsing script, a field was found more than once\"\n (obj2 (req \"loc\" location_encoding) (req \"prim\" prim_encoding))\n (function Duplicate_field (loc, prim) -> Some (loc, prim) | _ -> None)\n (fun (loc, prim) -> Duplicate_field (loc, prim)) ;\n (* Unexpected big_map *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unexpected_lazy_storage\"\n ~title:\"Lazy storage in unauthorized position (type error)\"\n ~description:\n \"When parsing script, a big_map or sapling_state type was found in a \\\n position where it could end up stored inside a big_map, which is \\\n forbidden for now.\"\n (obj1 (req \"loc\" location_encoding))\n (function Unexpected_lazy_storage loc -> Some loc | _ -> None)\n (fun loc -> Unexpected_lazy_storage loc) ;\n (* Unexpected operation *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unexpected_operation\"\n ~title:\"Operation in unauthorized position (type error)\"\n ~description:\n \"When parsing script, an operation type was found in the storage or \\\n parameter field.\"\n (obj1 (req \"loc\" location_encoding))\n (function Unexpected_operation loc -> Some loc | _ -> None)\n (fun loc -> Unexpected_operation loc) ;\n (* No such entrypoint *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.no_such_entrypoint\"\n ~title:\"No such entrypoint (type error)\"\n ~description:\"An entrypoint was not found when calling a contract.\"\n (obj1 (req \"entrypoint\" string))\n (function No_such_entrypoint entrypoint -> Some entrypoint | _ -> None)\n (fun entrypoint -> No_such_entrypoint entrypoint) ;\n (* Unreachable entrypoint *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unreachable_entrypoint\"\n ~title:\"Unreachable entrypoint (type error)\"\n ~description:\"An entrypoint in the contract is not reachable.\"\n (obj1 (req \"path\" (list prim_encoding)))\n (function Unreachable_entrypoint path -> Some path | _ -> None)\n (fun path -> Unreachable_entrypoint path) ;\n (* Duplicate entrypoint *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.duplicate_entrypoint\"\n ~title:\"Duplicate entrypoint (type error)\"\n ~description:\"Two entrypoints have the same name.\"\n (obj1 (req \"path\" string))\n (function Duplicate_entrypoint entrypoint -> Some entrypoint | _ -> None)\n (fun entrypoint -> Duplicate_entrypoint entrypoint) ;\n (* Entrypoint name too long *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.entrypoint_name_too_long\"\n ~title:\"Entrypoint name too long (type error)\"\n ~description:\n \"An entrypoint name exceeds the maximum length of 31 characters.\"\n (obj1 (req \"name\" string))\n (function\n | Entrypoint_name_too_long entrypoint -> Some entrypoint | _ -> None)\n (fun entrypoint -> Entrypoint_name_too_long entrypoint) ;\n (* Unexpected contract *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unexpected_contract\"\n ~title:\"Contract in unauthorized position (type error)\"\n ~description:\n \"When parsing script, a contract type was found in the storage or \\\n parameter field.\"\n (obj1 (req \"loc\" location_encoding))\n (function Unexpected_contract loc -> Some loc | _ -> None)\n (fun loc -> Unexpected_contract loc) ;\n (* -- Value typing errors ---------------------- *)\n (* Unordered map keys *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unordered_map_literal\"\n ~title:\"Invalid map key order\"\n ~description:\"Map keys must be in strictly increasing order\"\n (obj2\n (req \"location\" Script.location_encoding)\n (req \"item\" Script.expr_encoding))\n (function Unordered_map_keys (loc, expr) -> Some (loc, expr) | _ -> None)\n (fun (loc, expr) -> Unordered_map_keys (loc, expr)) ;\n (* Duplicate map keys *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.duplicate_map_keys\"\n ~title:\"Duplicate map keys\"\n ~description:\"Map literals cannot contain duplicated keys\"\n (obj2\n (req \"location\" Script.location_encoding)\n (req \"item\" Script.expr_encoding))\n (function Duplicate_map_keys (loc, expr) -> Some (loc, expr) | _ -> None)\n (fun (loc, expr) -> Duplicate_map_keys (loc, expr)) ;\n (* Unordered set values *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unordered_set_literal\"\n ~title:\"Invalid set value order\"\n ~description:\"Set values must be in strictly increasing order\"\n (obj2\n (req \"location\" Script.location_encoding)\n (req \"value\" Script.expr_encoding))\n (function\n | Unordered_set_values (loc, expr) -> Some (loc, expr) | _ -> None)\n (fun (loc, expr) -> Unordered_set_values (loc, expr)) ;\n (* Duplicate set values *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.duplicate_set_values_in_literal\"\n ~title:\"Sets literals cannot contain duplicate elements\"\n ~description:\n \"Set literals cannot contain duplicate elements, but a duplicate was \\\n found while parsing.\"\n (obj2\n (req \"location\" Script.location_encoding)\n (req \"value\" Script.expr_encoding))\n (function\n | Duplicate_set_values (loc, expr) -> Some (loc, expr) | _ -> None)\n (fun (loc, expr) -> Duplicate_set_values (loc, expr)) ;\n (* -- Instruction typing errors ------------- *)\n (* Fail not in tail position *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.fail_not_in_tail_position\"\n ~title:\"FAIL not in tail position\"\n ~description:\"There is non trivial garbage code after a FAIL instruction.\"\n (located empty)\n (function Fail_not_in_tail_position loc -> Some (loc, ()) | _ -> None)\n (fun (loc, ()) -> Fail_not_in_tail_position loc) ;\n (* Undefined binary operation *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.undefined_binop\"\n ~title:\"Undefined binop\"\n ~description:\n \"A binary operation is called on operands of types over which it is not \\\n defined.\"\n (located\n (obj3\n (req \"operator_name\" prim_encoding)\n (req \"wrong_left_operand_type\" Script.expr_encoding)\n (req \"wrong_right_operand_type\" Script.expr_encoding)))\n (function\n | Undefined_binop (loc, n, tyl, tyr) ->\n Some (loc, (n, tyl, tyr))\n | _ ->\n None)\n (fun (loc, (n, tyl, tyr)) -> Undefined_binop (loc, n, tyl, tyr)) ;\n (* Undefined unary operation *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.undefined_unop\"\n ~title:\"Undefined unop\"\n ~description:\n \"A unary operation is called on an operand of type over which it is not \\\n defined.\"\n (located\n (obj2\n (req \"operator_name\" prim_encoding)\n (req \"wrong_operand_type\" Script.expr_encoding)))\n (function Undefined_unop (loc, n, ty) -> Some (loc, (n, ty)) | _ -> None)\n (fun (loc, (n, ty)) -> Undefined_unop (loc, n, ty)) ;\n (* Bad return *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_return\"\n ~title:\"Bad return\"\n ~description:\"Unexpected stack at the end of a lambda or script.\"\n (located\n (obj2\n (req \"expected_return_type\" Script.expr_encoding)\n (req \"wrong_stack_type\" stack_ty_enc)))\n (function Bad_return (loc, sty, ty) -> Some (loc, (ty, sty)) | _ -> None)\n (fun (loc, (ty, sty)) -> Bad_return (loc, sty, ty)) ;\n (* Bad stack *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_stack\"\n ~title:\"Bad stack\"\n ~description:\"The stack has an unexpected length or contents.\"\n (located\n (obj3\n (req \"primitive_name\" prim_encoding)\n (req \"relevant_stack_portion\" int16)\n (req \"wrong_stack_type\" stack_ty_enc)))\n (function\n | Bad_stack (loc, name, s, sty) -> Some (loc, (name, s, sty)) | _ -> None)\n (fun (loc, (name, s, sty)) -> Bad_stack (loc, name, s, sty)) ;\n (* Inconsistent annotations *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.inconsistent_annotations\"\n ~title:\"Annotations inconsistent between branches\"\n ~description:\"The annotations on two types could not be merged\"\n (obj2 (req \"annot1\" string) (req \"annot2\" string))\n (function\n | Inconsistent_annotations (annot1, annot2) ->\n Some (annot1, annot2)\n | _ ->\n None)\n (fun (annot1, annot2) -> Inconsistent_annotations (annot1, annot2)) ;\n (* Inconsistent field annotations *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.inconsistent_field_annotations\"\n ~title:\"Annotations for field accesses is inconsistent\"\n ~description:\n \"The specified field does not match the field annotation in the type\"\n (obj2 (req \"annot1\" string) (req \"annot2\" string))\n (function\n | Inconsistent_field_annotations (annot1, annot2) ->\n Some (annot1, annot2)\n | _ ->\n None)\n (fun (annot1, annot2) -> Inconsistent_field_annotations (annot1, annot2)) ;\n (* Inconsistent type annotations *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.inconsistent_type_annotations\"\n ~title:\"Types contain inconsistent annotations\"\n ~description:\"The two types contain annotations that do not match\"\n (located\n (obj2\n (req \"type1\" Script.expr_encoding)\n (req \"type2\" Script.expr_encoding)))\n (function\n | Inconsistent_type_annotations (loc, ty1, ty2) ->\n Some (loc, (ty1, ty2))\n | _ ->\n None)\n (fun (loc, (ty1, ty2)) -> Inconsistent_type_annotations (loc, ty1, ty2)) ;\n (* Unexpected annotation *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unexpected_annotation\"\n ~title:\"An annotation was encountered where no annotation is expected\"\n ~description:\"A node in the syntax tree was improperly annotated\"\n (located empty)\n (function Unexpected_annotation loc -> Some (loc, ()) | _ -> None)\n (fun (loc, ()) -> Unexpected_annotation loc) ;\n (* Ungrouped annotations *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.ungrouped_annotations\"\n ~title:\"Annotations of the same kind were found spread apart\"\n ~description:\"Annotations of the same kind must be grouped\"\n (located empty)\n (function Ungrouped_annotations loc -> Some (loc, ()) | _ -> None)\n (fun (loc, ()) -> Ungrouped_annotations loc) ;\n (* Unmatched branches *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unmatched_branches\"\n ~title:\"Unmatched branches\"\n ~description:\n \"At the join point at the end of two code branches the stacks have \\\n inconsistent lengths or contents.\"\n (located\n (obj2\n (req \"first_stack_type\" stack_ty_enc)\n (req \"other_stack_type\" stack_ty_enc)))\n (function\n | Unmatched_branches (loc, stya, styb) ->\n Some (loc, (stya, styb))\n | _ ->\n None)\n (fun (loc, (stya, styb)) -> Unmatched_branches (loc, stya, styb)) ;\n (* Bad stack item *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_stack_item\"\n ~title:\"Bad stack item\"\n ~description:\n \"The type of a stack item is unexpected (this error is always \\\n accompanied by a more precise one).\"\n (obj1 (req \"item_level\" int16))\n (function Bad_stack_item n -> Some n | _ -> None)\n (fun n -> Bad_stack_item n) ;\n (* SELF in lambda *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.self_in_lambda\"\n ~title:\"SELF instruction in lambda\"\n ~description:\"A SELF instruction was encountered in a lambda expression.\"\n (located empty)\n (function Self_in_lambda loc -> Some (loc, ()) | _ -> None)\n (fun (loc, ()) -> Self_in_lambda loc) ;\n (* Bad stack length *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.inconsistent_stack_lengths\"\n ~title:\"Inconsistent stack lengths\"\n ~description:\n \"A stack was of an unexpected length (this error is always in the \\\n context of a located error).\"\n empty\n (function Bad_stack_length -> Some () | _ -> None)\n (fun () -> Bad_stack_length) ;\n (* -- Value typing errors ------------------- *)\n (* Invalid constant *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_constant\"\n ~title:\"Invalid constant\"\n ~description:\"A data expression was invalid for its expected type.\"\n (located\n (obj2\n (req \"expected_type\" Script.expr_encoding)\n (req \"wrong_expression\" Script.expr_encoding)))\n (function\n | Invalid_constant (loc, expr, ty) -> Some (loc, (ty, expr)) | _ -> None)\n (fun (loc, (ty, expr)) -> Invalid_constant (loc, expr, ty)) ;\n (* Invalid syntactic constant *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_syntactic_constant\"\n ~title:\"Invalid constant (parse error)\"\n ~description:\"A compile-time constant was invalid for its expected form.\"\n (located\n (obj2\n (req \"expected_form\" string)\n (req \"wrong_expression\" Script.expr_encoding)))\n (function\n | Invalid_syntactic_constant (loc, expr, expected) ->\n Some (loc, (expected, expr))\n | _ ->\n None)\n (fun (loc, (expected, expr)) ->\n Invalid_syntactic_constant (loc, expr, expected)) ;\n (* Invalid contract *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_contract\"\n ~title:\"Invalid contract\"\n ~description:\n \"A script or data expression references a contract that does not exist \\\n or assumes a wrong type for an existing contract.\"\n (located (obj1 (req \"contract\" Contract.encoding)))\n (function Invalid_contract (loc, c) -> Some (loc, c) | _ -> None)\n (fun (loc, c) -> Invalid_contract (loc, c)) ;\n (* Invalid big_map *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_big_map\"\n ~title:\"Invalid big_map\"\n ~description:\n \"A script or data expression references a big_map that does not exist \\\n or assumes a wrong type for an existing big_map.\"\n (located (obj1 (req \"big_map\" Big_map.Id.encoding)))\n (function Invalid_big_map (loc, c) -> Some (loc, c) | _ -> None)\n (fun (loc, c) -> Invalid_big_map (loc, c)) ;\n (* Comparable type expected *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.comparable_type_expected\"\n ~title:\"Comparable type expected\"\n ~description:\n \"A non comparable type was used in a place where only comparable types \\\n are accepted.\"\n (located (obj1 (req \"wrong_type\" Script.expr_encoding)))\n (function\n | Comparable_type_expected (loc, ty) -> Some (loc, ty) | _ -> None)\n (fun (loc, ty) -> Comparable_type_expected (loc, ty)) ;\n (* Inconsistent types *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.inconsistent_types\"\n ~title:\"Inconsistent types\"\n ~description:\n \"This is the basic type clash error, that appears in several places \\\n where the equality of two types have to be proven, it is always \\\n accompanied with another error that provides more context.\"\n (obj2\n (req \"first_type\" Script.expr_encoding)\n (req \"other_type\" Script.expr_encoding))\n (function Inconsistent_types (tya, tyb) -> Some (tya, tyb) | _ -> None)\n (fun (tya, tyb) -> Inconsistent_types (tya, tyb)) ;\n (* Inconsistent memo_sizes *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.inconsistent_memo_sizes\"\n ~title:\"Inconsistent memo sizes\"\n ~description:\n \"Memo sizes of two sapling states or transactions do not match\"\n (obj2\n (req \"first_memo_size\" Sapling.Memo_size.encoding)\n (req \"other_memo_size\" Sapling.Memo_size.encoding))\n (function\n | Inconsistent_memo_sizes (msa, msb) -> Some (msa, msb) | _ -> None)\n (fun (msa, msb) -> Inconsistent_memo_sizes (msa, msb)) ;\n (* -- Instruction typing errors ------------------- *)\n (* Invalid map body *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_map_body\"\n ~title:\"Invalid map body\"\n ~description:\"The body of a map block did not match the expected type\"\n (obj2 (req \"loc\" Script.location_encoding) (req \"body_type\" stack_ty_enc))\n (function Invalid_map_body (loc, stack) -> Some (loc, stack) | _ -> None)\n (fun (loc, stack) -> Invalid_map_body (loc, stack)) ;\n (* Invalid map block FAIL *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_map_block_fail\"\n ~title:\"FAIL instruction occurred as body of map block\"\n ~description:\n \"FAIL cannot be the only instruction in the body. The proper type of \\\n the return list cannot be inferred.\"\n (obj1 (req \"loc\" Script.location_encoding))\n (function Invalid_map_block_fail loc -> Some loc | _ -> None)\n (fun loc -> Invalid_map_block_fail loc) ;\n (* Invalid ITER body *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.invalid_iter_body\"\n ~title:\"ITER body returned wrong stack type\"\n ~description:\n \"The body of an ITER instruction must result in the same stack type as \\\n before the ITER.\"\n (obj3\n (req \"loc\" Script.location_encoding)\n (req \"bef_stack\" stack_ty_enc)\n (req \"aft_stack\" stack_ty_enc))\n (function\n | Invalid_iter_body (loc, bef, aft) -> Some (loc, bef, aft) | _ -> None)\n (fun (loc, bef, aft) -> Invalid_iter_body (loc, bef, aft)) ;\n (* Type too large *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.type_too_large\"\n ~title:\"Stack item type too large\"\n ~description:\"An instruction generated a type larger than the limit.\"\n (obj3\n (req \"loc\" Script.location_encoding)\n (req \"type_size\" uint16)\n (req \"maximum_type_size\" uint16))\n (function\n | Type_too_large (loc, ts, maxts) -> Some (loc, ts, maxts) | _ -> None)\n (fun (loc, ts, maxts) -> Type_too_large (loc, ts, maxts)) ;\n (* Bad PAIR argument *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_pair_argument\"\n ~title:\"0 or 1 passed to PAIR\"\n ~description:\"PAIR expects an argument of at least 2\"\n (obj1 (req \"loc\" Script.location_encoding))\n (function Pair_bad_argument loc -> Some loc | _ -> None)\n (fun loc -> Pair_bad_argument loc) ;\n (* Bad UNPAIR argument *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_unpair_argument\"\n ~title:\"0 or 1 passed to UNPAIR\"\n ~description:\"UNPAIR expects an argument of at least 2\"\n (obj1 (req \"loc\" Script.location_encoding))\n (function Unpair_bad_argument loc -> Some loc | _ -> None)\n (fun loc -> Unpair_bad_argument loc) ;\n (* Bad dup_n argument *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_dupn_argument\"\n ~title:\"0 passed to DUP n\"\n ~description:\"DUP expects an argument of at least 1 (passed 0)\"\n (obj1 (req \"loc\" Script.location_encoding))\n (function Dup_n_bad_argument loc -> Some loc | _ -> None)\n (fun loc -> Dup_n_bad_argument loc) ;\n (* Bad dup_n stack *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_dupn_stack\"\n ~title:\"Stack too short when typing DUP n\"\n ~description:\"Stack present when typing DUP n was too short\"\n (obj1 (req \"loc\" Script.location_encoding))\n (function Dup_n_bad_stack x -> Some x | _ -> None)\n (fun x -> Dup_n_bad_stack x) ;\n (* -- Toplevel errors ------------------- *)\n (* Ill typed data *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.ill_typed_data\"\n ~title:\"Ill typed data\"\n ~description:\n \"The toplevel error thrown when trying to typecheck a data expression \\\n against a given type (always followed by more precise errors).\"\n (obj3\n (opt \"identifier\" string)\n (req \"expected_type\" Script.expr_encoding)\n (req \"ill_typed_expression\" Script.expr_encoding))\n (function\n | Ill_typed_data (name, expr, ty) -> Some (name, ty, expr) | _ -> None)\n (fun (name, ty, expr) -> Ill_typed_data (name, expr, ty)) ;\n (* Ill formed type *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.ill_formed_type\"\n ~title:\"Ill formed type\"\n ~description:\n \"The toplevel error thrown when trying to parse a type expression \\\n (always followed by more precise errors).\"\n (obj3\n (opt \"identifier\" string)\n (req \"ill_formed_expression\" Script.expr_encoding)\n (req \"location\" Script.location_encoding))\n (function\n | Ill_formed_type (name, expr, loc) -> Some (name, expr, loc) | _ -> None)\n (fun (name, expr, loc) -> Ill_formed_type (name, expr, loc)) ;\n (* Ill typed contract *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.ill_typed_contract\"\n ~title:\"Ill typed contract\"\n ~description:\n \"The toplevel error thrown when trying to typecheck a contract code \\\n against given input, output and storage types (always followed by more \\\n precise errors).\"\n (obj2\n (req \"ill_typed_code\" Script.expr_encoding)\n (req \"type_map\" type_map_enc))\n (function\n | Ill_typed_contract (expr, type_map) ->\n Some (expr, type_map)\n | _ ->\n None)\n (fun (expr, type_map) -> Ill_typed_contract (expr, type_map)) ;\n (* Cannot serialize error *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.cannot_serialize_error\"\n ~title:\"Not enough gas to serialize error\"\n ~description:\"The error was too big to be serialized with the provided gas\"\n Data_encoding.empty\n (function Cannot_serialize_error -> Some () | _ -> None)\n (fun () -> Cannot_serialize_error) ;\n (* Deprecated instruction *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.deprecated_instruction\"\n ~title:\"Script is using a deprecated instruction\"\n ~description:\n \"A deprecated instruction usage is disallowed in newly created contracts\"\n (obj1 (req \"prim\" prim_encoding))\n (function Deprecated_instruction prim -> Some prim | _ -> None)\n (fun prim -> Deprecated_instruction prim) ;\n (* Typechecking stack overflow *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.typechecking_too_many_recursive_calls\"\n ~title:\"Too many recursive calls during typechecking\"\n ~description:\"Too many recursive calls were needed for typechecking\"\n Data_encoding.empty\n (function Typechecking_too_many_recursive_calls -> Some () | _ -> None)\n (fun () -> Typechecking_too_many_recursive_calls) ;\n (* Unparsing stack overflow *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.unparsing_stack_overflow\"\n ~title:\"Too many recursive calls during unparsing\"\n ~description:\"Too many recursive calls were needed for unparsing\"\n Data_encoding.empty\n (function Unparsing_too_many_recursive_calls -> Some () | _ -> None)\n (fun () -> Unparsing_too_many_recursive_calls) ;\n (* Unexpected forged value *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unexpected_forged_value\"\n ~title:\"Unexpected forged value\"\n ~description:\n \"A forged value was encountered but disallowed for that position.\"\n (obj1 (req \"location\" Script.location_encoding))\n (function Unexpected_forged_value loc -> Some loc | _ -> None)\n (fun loc -> Unexpected_forged_value loc) ;\n (* Unexpected ticket *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.unexpected_ticket\"\n ~title:\"Ticket in unauthorized position (type error)\"\n ~description:\"A ticket type has been found\"\n (obj1 (req \"loc\" location_encoding))\n (function Unexpected_ticket loc -> Some loc | _ -> None)\n (fun loc -> Unexpected_ticket loc) ;\n (* Attempt to duplicate a non-dupable type *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.non_dupable_type\"\n ~title:\"Non-dupable type duplication attempt\"\n ~description:\"DUP was used on a non-dupable type (e.g. tickets).\"\n (obj2 (req \"loc\" location_encoding) (req \"type\" Script.expr_encoding))\n (function Non_dupable_type (loc, ty) -> Some (loc, ty) | _ -> None)\n (fun (loc, ty) -> Non_dupable_type (loc, ty))\n" ;
} ;
{ name = "Script_interpreter" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\ntype execution_trace =\n (Script.location * Gas.t * (Script.expr * string option) list) list\n\ntype error +=\n | Reject of Script.location * Script.expr * execution_trace option\n\ntype error += Overflow of Script.location * execution_trace option\n\ntype error += Runtime_contract_error : Contract.t * Script.expr -> error\n\ntype error += Bad_contract_parameter of Contract.t (* `Permanent *)\n\ntype error += Cannot_serialize_failure\n\ntype error += Cannot_serialize_storage\n\ntype error += Michelson_too_many_recursive_calls\n\ntype execution_result = {\n ctxt : context;\n storage : Script.expr;\n lazy_storage_diff : Lazy_storage.diffs option;\n operations : packed_internal_operation list;\n}\n\ntype step_constants = {\n source : Contract.t;\n payer : Contract.t;\n self : Contract.t;\n amount : Tez.t;\n chain_id : Chain_id.t;\n}\n\n(** [STEP_LOGGER] is the module type of logging\n modules as passed to the Michelson interpreter.\n Note that logging must be performed by side-effects\n on an underlying log structure. *)\nmodule type STEP_LOGGER = sig\n (** [log_interp] is called at each call of the internal\n function [interp]. [interp] is called when starting\n the interpretation of a script and subsequently\n at each [Exec] instruction. *)\n val log_interp :\n context -> ('bef, 'aft) Script_typed_ir.descr -> 'bef -> unit\n\n (** [log_entry] is called {i before} executing\n each instruction but {i after} gas for\n this instruction has been successfully consumed. *)\n val log_entry : context -> ('bef, 'aft) Script_typed_ir.descr -> 'bef -> unit\n\n (** [log_exit] is called {i after} executing each\n instruction. *)\n val log_exit : context -> ('bef, 'aft) Script_typed_ir.descr -> 'aft -> unit\n\n (** [get_log] allows to obtain an execution trace, if\n any was produced. *)\n val get_log : unit -> execution_trace option tzresult Lwt.t\nend\n\ntype logger = (module STEP_LOGGER)\n\nval step :\n logger ->\n context ->\n step_constants ->\n ('bef, 'aft) Script_typed_ir.descr ->\n 'bef ->\n ('aft * context) tzresult Lwt.t\n\nval execute :\n ?logger:logger ->\n Alpha_context.t ->\n Script_ir_translator.unparsing_mode ->\n step_constants ->\n script:Script.t ->\n entrypoint:string ->\n parameter:Script.expr ->\n internal:bool ->\n execution_result tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Script\nopen Script_typed_ir\nopen Script_ir_translator\n\n(* ---- Run-time errors -----------------------------------------------------*)\n\ntype execution_trace =\n (Script.location * Gas.t * (Script.expr * string option) list) list\n\ntype error +=\n | Reject of Script.location * Script.expr * execution_trace option\n\ntype error += Overflow of Script.location * execution_trace option\n\ntype error += Runtime_contract_error : Contract.t * Script.expr -> error\n\ntype error += Bad_contract_parameter of Contract.t (* `Permanent *)\n\ntype error += Cannot_serialize_failure\n\ntype error += Cannot_serialize_storage\n\ntype error += Michelson_too_many_recursive_calls\n\nlet () =\n let open Data_encoding in\n let trace_encoding =\n list\n @@ obj3\n (req \"location\" Script.location_encoding)\n (req \"gas\" Gas.encoding)\n (req\n \"stack\"\n (list (obj2 (req \"item\" Script.expr_encoding) (opt \"annot\" string))))\n in\n (* Reject *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.script_rejected\"\n ~title:\"Script failed\"\n ~description:\"A FAILWITH instruction was reached\"\n (obj3\n (req \"location\" Script.location_encoding)\n (req \"with\" Script.expr_encoding)\n (opt \"trace\" trace_encoding))\n (function Reject (loc, v, trace) -> Some (loc, v, trace) | _ -> None)\n (fun (loc, v, trace) -> Reject (loc, v, trace)) ;\n (* Overflow *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.script_overflow\"\n ~title:\"Script failed (overflow error)\"\n ~description:\n \"A FAIL instruction was reached due to the detection of an overflow\"\n (obj2\n (req \"location\" Script.location_encoding)\n (opt \"trace\" trace_encoding))\n (function Overflow (loc, trace) -> Some (loc, trace) | _ -> None)\n (fun (loc, trace) -> Overflow (loc, trace)) ;\n (* Runtime contract error *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.runtime_error\"\n ~title:\"Script runtime error\"\n ~description:\"Toplevel error for all runtime script errors\"\n (obj2\n (req \"contract_handle\" Contract.encoding)\n (req \"contract_code\" Script.expr_encoding))\n (function\n | Runtime_contract_error (contract, expr) ->\n Some (contract, expr)\n | _ ->\n None)\n (fun (contract, expr) -> Runtime_contract_error (contract, expr)) ;\n (* Bad contract parameter *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.bad_contract_parameter\"\n ~title:\"Contract supplied an invalid parameter\"\n ~description:\n \"Either no parameter was supplied to a contract with a non-unit \\\n parameter type, a non-unit parameter was passed to an account, or a \\\n parameter was supplied of the wrong type\"\n Data_encoding.(obj1 (req \"contract\" Contract.encoding))\n (function Bad_contract_parameter c -> Some c | _ -> None)\n (fun c -> Bad_contract_parameter c) ;\n (* Cannot serialize failure *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.cannot_serialize_failure\"\n ~title:\"Not enough gas to serialize argument of FAILWITH\"\n ~description:\n \"Argument of FAILWITH was too big to be serialized with the provided gas\"\n Data_encoding.empty\n (function Cannot_serialize_failure -> Some () | _ -> None)\n (fun () -> Cannot_serialize_failure) ;\n (* Cannot serialize storage *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.cannot_serialize_storage\"\n ~title:\"Not enough gas to serialize execution storage\"\n ~description:\n \"The returned storage was too big to be serialized with the provided gas\"\n Data_encoding.empty\n (function Cannot_serialize_storage -> Some () | _ -> None)\n (fun () -> Cannot_serialize_storage) ;\n (* Michelson Stack Overflow *)\n register_error_kind\n `Permanent\n ~id:\"michelson_v1.interp_too_many_recursive_calls\"\n ~title:\"Too many recursive calls during interpretation\"\n ~description:\n \"Too many recursive calls were needed for interpretation of a Michelson \\\n script\"\n Data_encoding.empty\n (function Michelson_too_many_recursive_calls -> Some () | _ -> None)\n (fun () -> Michelson_too_many_recursive_calls)\n\n(* ---- interpreter ---------------------------------------------------------*)\n\nmodule Interp_costs = Michelson_v1_gas.Cost_of.Interpreter\n\nlet rec interp_stack_prefix_preserving_operation :\n type fbef bef faft aft result.\n (fbef -> (faft * result) tzresult Lwt.t) ->\n (fbef, faft, bef, aft) stack_prefix_preservation_witness ->\n bef ->\n (aft * result) tzresult Lwt.t =\n fun f n stk ->\n match (n, stk) with\n | ( Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix\n (Prefix (Prefix (Prefix (Prefix (Prefix n))))))))))))))),\n ( v0,\n ( v1,\n ( v2,\n ( v3,\n ( v4,\n ( v5,\n ( v6,\n (v7, (v8, (v9, (va, (vb, (vc, (vd, (ve, (vf, rest)))))))))\n ) ) ) ) ) ) ) ) ->\n interp_stack_prefix_preserving_operation f n rest\n >|=? fun (rest', result) ->\n ( ( v0,\n ( v1,\n ( v2,\n ( v3,\n ( v4,\n ( v5,\n ( v6,\n ( v7,\n (v8, (v9, (va, (vb, (vc, (vd, (ve, (vf, rest'))))))))\n ) ) ) ) ) ) ) ),\n result )\n | (Prefix (Prefix (Prefix (Prefix n))), (v0, (v1, (v2, (v3, rest))))) ->\n interp_stack_prefix_preserving_operation f n rest\n >|=? fun (rest', result) -> ((v0, (v1, (v2, (v3, rest')))), result)\n | (Prefix n, (v, rest)) ->\n interp_stack_prefix_preserving_operation f n rest\n >|=? fun (rest', result) -> ((v, rest'), result)\n | (Rest, v) ->\n f v\n\ntype step_constants = {\n source : Contract.t;\n payer : Contract.t;\n self : Contract.t;\n amount : Tez.t;\n chain_id : Chain_id.t;\n}\n\nmodule type STEP_LOGGER = sig\n val log_interp :\n context -> ('bef, 'aft) Script_typed_ir.descr -> 'bef -> unit\n\n val log_entry : context -> ('bef, 'aft) Script_typed_ir.descr -> 'bef -> unit\n\n val log_exit : context -> ('bef, 'aft) Script_typed_ir.descr -> 'aft -> unit\n\n val get_log : unit -> execution_trace option tzresult Lwt.t\nend\n\ntype logger = (module STEP_LOGGER)\n\nmodule No_trace : STEP_LOGGER = struct\n let log_interp _ctxt _descr _stack = ()\n\n let log_entry _ctxt _descr _stack = ()\n\n let log_exit _ctxt _descr _stack = ()\n\n let get_log () = return_none\nend\n\nlet cost_of_instr : type b a. (b, a) descr -> b -> Gas.cost =\n fun descr stack ->\n match (descr.instr, stack) with\n | (Drop, _) ->\n Interp_costs.drop\n | (Dup, _) ->\n Interp_costs.dup\n | (Swap, _) ->\n Interp_costs.swap\n | (Const _, _) ->\n Interp_costs.push\n | (Cons_some, _) ->\n Interp_costs.cons_some\n | (Cons_none _, _) ->\n Interp_costs.cons_none\n | (If_none _, _) ->\n Interp_costs.if_none\n | (Cons_pair, _) ->\n Interp_costs.cons_pair\n | (Unpair, _) ->\n Interp_costs.unpair\n | (Car, _) ->\n Interp_costs.car\n | (Cdr, _) ->\n Interp_costs.cdr\n | (Cons_left, _) ->\n Interp_costs.cons_left\n | (Cons_right, _) ->\n Interp_costs.cons_right\n | (If_left _, _) ->\n Interp_costs.if_left\n | (Cons_list, _) ->\n Interp_costs.cons_list\n | (Nil, _) ->\n Interp_costs.nil\n | (If_cons _, _) ->\n Interp_costs.if_cons\n | (List_map _, (list, _)) ->\n Interp_costs.list_map list\n | (List_size, _) ->\n Interp_costs.list_size\n | (List_iter _, (l, _)) ->\n Interp_costs.list_iter l\n | (Empty_set _, _) ->\n Interp_costs.empty_set\n | (Set_iter _, (set, _)) ->\n Interp_costs.set_iter set\n | (Set_mem, (v, (set, _))) ->\n Interp_costs.set_mem v set\n | (Set_update, (v, (_, (set, _)))) ->\n Interp_costs.set_update v set\n | (Set_size, _) ->\n Interp_costs.set_size\n | (Empty_map _, _) ->\n Interp_costs.empty_map\n | (Map_map _, (map, _)) ->\n Interp_costs.map_map map\n | (Map_iter _, (map, _)) ->\n Interp_costs.map_iter map\n | (Map_mem, (v, (map, _rest))) ->\n Interp_costs.map_mem v map\n | (Map_get, (v, (map, _rest))) ->\n Interp_costs.map_get v map\n | (Map_update, (k, (_, (map, _)))) ->\n Interp_costs.map_update k map\n | (Map_get_and_update, (k, (_, (map, _)))) ->\n Interp_costs.map_get_and_update k map\n | (Map_size, _) ->\n Interp_costs.map_size\n | (Empty_big_map _, _) ->\n Interp_costs.empty_map\n | (Big_map_mem, (key, (map, _))) ->\n Interp_costs.map_mem key map.diff\n | (Big_map_get, (key, (map, _))) ->\n Interp_costs.map_get key map.diff\n | (Big_map_update, (key, (_, (map, _)))) ->\n Interp_costs.map_update key map.diff\n | (Big_map_get_and_update, (key, (_, (map, _)))) ->\n Interp_costs.map_get_and_update key map.diff\n | (Add_seconds_to_timestamp, (n, (t, _))) ->\n Interp_costs.add_seconds_timestamp n t\n | (Add_timestamp_to_seconds, (t, (n, _))) ->\n Interp_costs.add_seconds_timestamp n t\n | (Sub_timestamp_seconds, (t, (n, _))) ->\n Interp_costs.sub_seconds_timestamp n t\n | (Diff_timestamps, (t1, (t2, _))) ->\n Interp_costs.diff_timestamps t1 t2\n | (Concat_string_pair, (x, (y, _))) ->\n Interp_costs.concat_string_pair x y\n | (Concat_string, (ss, _)) ->\n Interp_costs.concat_string_precheck ss\n | (Slice_string, (_offset, (_length, (s, _)))) ->\n Interp_costs.slice_string s\n | (String_size, _) ->\n Interp_costs.string_size\n | (Concat_bytes_pair, (x, (y, _))) ->\n Interp_costs.concat_bytes_pair x y\n | (Concat_bytes, (ss, _)) ->\n Interp_costs.concat_string_precheck ss\n | (Slice_bytes, (_offset, (_length, (s, _)))) ->\n Interp_costs.slice_bytes s\n | (Bytes_size, _) ->\n Interp_costs.bytes_size\n | (Add_tez, _) ->\n Interp_costs.add_tez\n | (Sub_tez, _) ->\n Interp_costs.sub_tez\n | (Mul_teznat, (_, (n, _))) ->\n Interp_costs.mul_teznat n\n | (Mul_nattez, (n, (_, _))) ->\n Interp_costs.mul_teznat n\n | (Or, _) ->\n Interp_costs.bool_or\n | (And, _) ->\n Interp_costs.bool_and\n | (Xor, _) ->\n Interp_costs.bool_xor\n | (Not, _) ->\n Interp_costs.bool_not\n | (Is_nat, _) ->\n Interp_costs.is_nat\n | (Abs_int, (x, _)) ->\n Interp_costs.abs_int x\n | (Int_nat, _) ->\n Interp_costs.int_nat\n | (Neg_int, (x, _)) ->\n Interp_costs.neg_int x\n | (Neg_nat, (x, _)) ->\n Interp_costs.neg_nat x\n | (Add_intint, (x, (y, _))) ->\n Interp_costs.add_bigint x y\n | (Add_intnat, (x, (y, _))) ->\n Interp_costs.add_bigint x y\n | (Add_natint, (x, (y, _))) ->\n Interp_costs.add_bigint x y\n | (Add_natnat, (x, (y, _))) ->\n Interp_costs.add_bigint x y\n | (Sub_int, (x, (y, _))) ->\n Interp_costs.sub_bigint x y\n | (Mul_intint, (x, (y, _))) ->\n Interp_costs.mul_bigint x y\n | (Mul_intnat, (x, (y, _))) ->\n Interp_costs.mul_bigint x y\n | (Mul_natint, (x, (y, _))) ->\n Interp_costs.mul_bigint x y\n | (Mul_natnat, (x, (y, _))) ->\n Interp_costs.mul_bigint x y\n | (Ediv_teznat, (x, (y, _))) ->\n Interp_costs.ediv_teznat x y\n | (Ediv_tez, _) ->\n Interp_costs.ediv_tez\n | (Ediv_intint, (x, (y, _))) ->\n Interp_costs.ediv_bigint x y\n | (Ediv_intnat, (x, (y, _))) ->\n Interp_costs.ediv_bigint x y\n | (Ediv_natint, (x, (y, _))) ->\n Interp_costs.ediv_bigint x y\n | (Ediv_natnat, (x, (y, _))) ->\n Interp_costs.ediv_bigint x y\n | (Lsl_nat, (x, _)) ->\n Interp_costs.lsl_nat x\n | (Lsr_nat, (x, _)) ->\n Interp_costs.lsr_nat x\n | (Or_nat, (x, (y, _))) ->\n Interp_costs.or_nat x y\n | (And_nat, (x, (y, _))) ->\n Interp_costs.and_nat x y\n | (And_int_nat, (x, (y, _))) ->\n Interp_costs.and_nat x y\n | (Xor_nat, (x, (y, _))) ->\n Interp_costs.xor_nat x y\n | (Not_int, (x, _)) ->\n Interp_costs.not_nat x\n | (Not_nat, (x, _)) ->\n Interp_costs.not_nat x\n | (Seq _, _) ->\n Interp_costs.seq\n | (If _, _) ->\n Interp_costs.if_\n | (Loop _, _) ->\n Interp_costs.loop\n | (Loop_left _, _) ->\n Interp_costs.loop_left\n | (Dip _, _) ->\n Interp_costs.dip\n | (Exec, _) ->\n Interp_costs.exec\n | (Apply _, _) ->\n Interp_costs.apply\n | (Lambda _, _) ->\n Interp_costs.push\n | (Failwith _, _) ->\n Gas.free\n | (Nop, _) ->\n Interp_costs.nop\n | (Compare ty, (a, (b, _))) ->\n Interp_costs.compare ty a b\n | (Eq, _) ->\n Interp_costs.neq\n | (Neq, _) ->\n Interp_costs.neq\n | (Lt, _) ->\n Interp_costs.neq\n | (Le, _) ->\n Interp_costs.neq\n | (Gt, _) ->\n Interp_costs.neq\n | (Ge, _) ->\n Interp_costs.neq\n | (Pack _, _) ->\n Gas.free\n | (Unpack _, _) ->\n Gas.free\n | (Address, _) ->\n Interp_costs.address\n | (Contract _, _) ->\n Interp_costs.contract\n | (Transfer_tokens, _) ->\n Interp_costs.transfer_tokens\n | (Implicit_account, _) ->\n Interp_costs.implicit_account\n | (Set_delegate, _) ->\n Interp_costs.set_delegate\n | (Balance, _) ->\n Interp_costs.balance\n | (Level, _) ->\n Interp_costs.level\n | (Now, _) ->\n Interp_costs.now\n | (Check_signature, (key, (_, (message, _)))) ->\n Interp_costs.check_signature key message\n | (Hash_key, (pk, _)) ->\n Interp_costs.hash_key pk\n | (Blake2b, (bytes, _)) ->\n Interp_costs.blake2b bytes\n | (Sha256, (bytes, _)) ->\n Interp_costs.sha256 bytes\n | (Sha512, (bytes, _)) ->\n Interp_costs.sha512 bytes\n | (Source, _) ->\n Interp_costs.source\n | (Sender, _) ->\n Interp_costs.source\n | (Self _, _) ->\n Interp_costs.self\n | (Self_address, _) ->\n Interp_costs.self\n | (Amount, _) ->\n Interp_costs.amount\n | (Dig (n, _), _) ->\n Interp_costs.dign n\n | (Dug (n, _), _) ->\n Interp_costs.dugn n\n | (Dipn (n, _, _), _) ->\n Interp_costs.dipn n\n | (Dropn (n, _), _) ->\n Interp_costs.dropn n\n | (ChainId, _) ->\n Interp_costs.chain_id\n | (Create_contract _, _) ->\n Interp_costs.create_contract\n | (Never, (_, _)) ->\n .\n | (Voting_power, _) ->\n Interp_costs.voting_power\n | (Total_voting_power, _) ->\n Interp_costs.total_voting_power\n | (Keccak, (bytes, _)) ->\n Interp_costs.keccak bytes\n | (Sha3, (bytes, _)) ->\n Interp_costs.sha3 bytes\n | (Add_bls12_381_g1, _) ->\n Interp_costs.add_bls12_381_g1\n | (Add_bls12_381_g2, _) ->\n Interp_costs.add_bls12_381_g2\n | (Add_bls12_381_fr, _) ->\n Interp_costs.add_bls12_381_fr\n | (Mul_bls12_381_g1, _) ->\n Interp_costs.mul_bls12_381_g1\n | (Mul_bls12_381_g2, _) ->\n Interp_costs.mul_bls12_381_g2\n | (Mul_bls12_381_fr, _) ->\n Interp_costs.mul_bls12_381_fr\n | (Mul_bls12_381_fr_z, _) ->\n Interp_costs.mul_bls12_381_fr_z\n | (Mul_bls12_381_z_fr, _) ->\n Interp_costs.mul_bls12_381_fr_z\n | (Int_bls12_381_fr, _) ->\n Interp_costs.int_bls12_381_fr\n | (Neg_bls12_381_g1, _) ->\n Interp_costs.neg_bls12_381_g1\n | (Neg_bls12_381_g2, _) ->\n Interp_costs.neg_bls12_381_g2\n | (Neg_bls12_381_fr, _) ->\n Interp_costs.neg_bls12_381_fr\n | (Pairing_check_bls12_381, (pairs, _)) ->\n Interp_costs.pairing_check_bls12_381 pairs\n | (Comb (n, _), _) ->\n Interp_costs.comb n\n | (Uncomb (n, _), _) ->\n Interp_costs.uncomb n\n | (Comb_get (n, _), _) ->\n Interp_costs.comb_get n\n | (Comb_set (n, _), _) ->\n Interp_costs.comb_set n\n | (Dup_n (n, _), _) ->\n Interp_costs.dupn n\n | (Sapling_empty_state _, _) ->\n Interp_costs.sapling_empty_state\n | (Sapling_verify_update, (tx, _)) ->\n let inputs = List.length tx.inputs in\n let outputs = List.length tx.outputs in\n Interp_costs.sapling_verify_update ~inputs ~outputs\n | (Ticket, _) ->\n Interp_costs.ticket\n | (Read_ticket, _) ->\n Interp_costs.read_ticket\n | (Split_ticket, (ticket, ((amount_a, amount_b), _))) ->\n Interp_costs.split_ticket ticket.amount amount_a amount_b\n | (Join_tickets ty, ((ticket_a, ticket_b), _)) ->\n Interp_costs.join_tickets ty ticket_a ticket_b\n\nlet unpack ctxt ~ty ~bytes =\n Gas.check_enough ctxt (Script.serialized_cost bytes)\n >>?= fun () ->\n if\n Compare.Int.(Bytes.length bytes >= 1)\n && Compare.Int.(TzEndian.get_uint8 bytes 0 = 0x05)\n then\n let bytes = Bytes.sub bytes 1 (Bytes.length bytes - 1) in\n match Data_encoding.Binary.of_bytes Script.expr_encoding bytes with\n | None ->\n Lwt.return\n ( Gas.consume ctxt (Interp_costs.unpack_failed bytes)\n >|? fun ctxt -> (None, ctxt) )\n | Some expr -> (\n Gas.consume ctxt (Script.deserialized_cost expr)\n >>?= fun ctxt ->\n parse_data\n ctxt\n ~legacy:false\n ~allow_forged:false\n ty\n (Micheline.root expr)\n >|= function\n | Ok (value, ctxt) ->\n ok (Some value, ctxt)\n | Error _ignored ->\n Gas.consume ctxt (Interp_costs.unpack_failed bytes)\n >|? fun ctxt -> (None, ctxt) )\n else return (None, ctxt)\n\nlet rec step_bounded :\n type b a.\n logger ->\n stack_depth:int ->\n context ->\n step_constants ->\n (b, a) descr ->\n b ->\n (a * context) tzresult Lwt.t =\n fun logger ~stack_depth ctxt step_constants ({instr; loc; _} as descr) stack ->\n let gas = cost_of_instr descr stack in\n Gas.consume ctxt gas\n >>?= fun ctxt ->\n let module Log = (val logger) in\n Log.log_entry ctxt descr stack ;\n let logged_return : a * context -> (a * context) tzresult Lwt.t =\n fun (ret, ctxt) ->\n Log.log_exit ctxt descr ret ;\n return (ret, ctxt)\n in\n let non_terminal_recursion ~ctxt ?(stack_depth = stack_depth + 1) descr stack\n =\n if Compare.Int.(stack_depth >= 10_000) then\n fail Michelson_too_many_recursive_calls\n else step_bounded logger ~stack_depth ctxt step_constants descr stack\n in\n match (instr, stack) with\n (* stack ops *)\n | (Drop, (_, rest)) ->\n logged_return (rest, ctxt)\n | (Dup, (v, rest)) ->\n logged_return ((v, (v, rest)), ctxt)\n | (Swap, (vi, (vo, rest))) ->\n logged_return ((vo, (vi, rest)), ctxt)\n | (Const v, rest) ->\n logged_return ((v, rest), ctxt)\n (* options *)\n | (Cons_some, (v, rest)) ->\n logged_return ((Some v, rest), ctxt)\n | (Cons_none _, rest) ->\n logged_return ((None, rest), ctxt)\n | (If_none (bt, _), (None, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bt rest\n | (If_none (_, bf), (Some v, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bf (v, rest)\n (* pairs *)\n | (Cons_pair, (a, (b, rest))) ->\n logged_return (((a, b), rest), ctxt)\n | (Unpair, ((a, b), rest)) ->\n logged_return ((a, (b, rest)), ctxt)\n | (Car, ((a, _), rest)) ->\n logged_return ((a, rest), ctxt)\n | (Cdr, ((_, b), rest)) ->\n logged_return ((b, rest), ctxt)\n (* unions *)\n | (Cons_left, (v, rest)) ->\n logged_return ((L v, rest), ctxt)\n | (Cons_right, (v, rest)) ->\n logged_return ((R v, rest), ctxt)\n | (If_left (bt, _), (L v, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bt (v, rest)\n | (If_left (_, bf), (R v, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bf (v, rest)\n (* lists *)\n | (Cons_list, (hd, (tl, rest))) ->\n logged_return ((list_cons hd tl, rest), ctxt)\n | (Nil, rest) ->\n logged_return ((list_empty, rest), ctxt)\n | (If_cons (_, bf), ({elements = []; _}, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bf rest\n | (If_cons (bt, _), ({elements = hd :: tl; length}, rest)) ->\n let tl = {elements = tl; length = length - 1} in\n step_bounded logger ~stack_depth ctxt step_constants bt (hd, (tl, rest))\n | (List_map body, (list, rest)) ->\n let rec loop rest ctxt l acc =\n match l with\n | [] ->\n let result = {elements = List.rev acc; length = list.length} in\n return ((result, rest), ctxt)\n | hd :: tl ->\n non_terminal_recursion ~ctxt body (hd, rest)\n >>=? fun ((hd, rest), ctxt) -> loop rest ctxt tl (hd :: acc)\n in\n loop rest ctxt list.elements []\n >>=? fun (res, ctxt) -> logged_return (res, ctxt)\n | (List_size, (list, rest)) ->\n logged_return ((Script_int.(abs (of_int list.length)), rest), ctxt)\n | (List_iter body, (l, init)) ->\n let rec loop ctxt l stack =\n match l with\n | [] ->\n return (stack, ctxt)\n | hd :: tl ->\n non_terminal_recursion ~ctxt body (hd, stack)\n >>=? fun (stack, ctxt) -> loop ctxt tl stack\n in\n loop ctxt l.elements init\n >>=? fun (res, ctxt) -> logged_return (res, ctxt)\n (* sets *)\n | (Empty_set t, rest) ->\n logged_return ((empty_set t, rest), ctxt)\n | (Set_iter body, (set, init)) ->\n let l = List.rev (set_fold (fun e acc -> e :: acc) set []) in\n let rec loop ctxt l stack =\n match l with\n | [] ->\n return (stack, ctxt)\n | hd :: tl ->\n non_terminal_recursion ~ctxt body (hd, stack)\n >>=? fun (stack, ctxt) -> loop ctxt tl stack\n in\n loop ctxt l init >>=? fun (res, ctxt) -> logged_return (res, ctxt)\n | (Set_mem, (v, (set, rest))) ->\n logged_return ((set_mem v set, rest), ctxt)\n | (Set_update, (v, (presence, (set, rest)))) ->\n logged_return ((set_update v presence set, rest), ctxt)\n | (Set_size, (set, rest)) ->\n logged_return ((set_size set, rest), ctxt)\n (* maps *)\n | (Empty_map (t, _), rest) ->\n logged_return ((empty_map t, rest), ctxt)\n | (Map_map body, (map, rest)) ->\n let l = List.rev (map_fold (fun k v acc -> (k, v) :: acc) map []) in\n let rec loop rest ctxt l acc =\n match l with\n | [] ->\n return ((acc, rest), ctxt)\n | ((k, _) as hd) :: tl ->\n non_terminal_recursion ~ctxt body (hd, rest)\n >>=? fun ((hd, rest), ctxt) ->\n loop rest ctxt tl (map_update k (Some hd) acc)\n in\n loop rest ctxt l (empty_map (map_key_ty map))\n >>=? fun (res, ctxt) -> logged_return (res, ctxt)\n | (Map_iter body, (map, init)) ->\n let l = List.rev (map_fold (fun k v acc -> (k, v) :: acc) map []) in\n let rec loop ctxt l stack =\n match l with\n | [] ->\n return (stack, ctxt)\n | hd :: tl ->\n non_terminal_recursion ~ctxt body (hd, stack)\n >>=? fun (stack, ctxt) -> loop ctxt tl stack\n in\n loop ctxt l init >>=? fun (res, ctxt) -> logged_return (res, ctxt)\n | (Map_mem, (v, (map, rest))) ->\n logged_return ((map_mem v map, rest), ctxt)\n | (Map_get, (v, (map, rest))) ->\n logged_return ((map_get v map, rest), ctxt)\n | (Map_update, (k, (v, (map, rest)))) ->\n logged_return ((map_update k v map, rest), ctxt)\n | (Map_get_and_update, (k, (v, (map, rest)))) ->\n let map' = map_update k v map in\n let v' = map_get k map in\n logged_return ((v', (map', rest)), ctxt)\n | (Map_size, (map, rest)) ->\n logged_return ((map_size map, rest), ctxt)\n (* Big map operations *)\n | (Empty_big_map (tk, tv), rest) ->\n logged_return ((Script_ir_translator.empty_big_map tk tv, rest), ctxt)\n | (Big_map_mem, (key, (map, rest))) ->\n Script_ir_translator.big_map_mem ctxt key map\n >>=? fun (res, ctxt) -> logged_return ((res, rest), ctxt)\n | (Big_map_get, (key, (map, rest))) ->\n Script_ir_translator.big_map_get ctxt key map\n >>=? fun (res, ctxt) -> logged_return ((res, rest), ctxt)\n | (Big_map_update, (key, (maybe_value, (map, rest)))) ->\n let big_map = Script_ir_translator.big_map_update key maybe_value map in\n logged_return ((big_map, rest), ctxt)\n | (Big_map_get_and_update, (k, (v, (map, rest)))) ->\n let map' = Script_ir_translator.big_map_update k v map in\n Script_ir_translator.big_map_get ctxt k map\n >>=? fun (v', ctxt) -> logged_return ((v', (map', rest)), ctxt)\n (* timestamp operations *)\n | (Add_seconds_to_timestamp, (n, (t, rest))) ->\n let result = Script_timestamp.add_delta t n in\n logged_return ((result, rest), ctxt)\n | (Add_timestamp_to_seconds, (t, (n, rest))) ->\n let result = Script_timestamp.add_delta t n in\n logged_return ((result, rest), ctxt)\n | (Sub_timestamp_seconds, (t, (s, rest))) ->\n let result = Script_timestamp.sub_delta t s in\n logged_return ((result, rest), ctxt)\n | (Diff_timestamps, (t1, (t2, rest))) ->\n let result = Script_timestamp.diff t1 t2 in\n logged_return ((result, rest), ctxt)\n (* string operations *)\n | (Concat_string_pair, (x, (y, rest))) ->\n let s = String.concat \"\" [x; y] in\n logged_return ((s, rest), ctxt)\n | (Concat_string, (ss, rest)) ->\n (* The cost for this fold_left has been paid upfront *)\n let total_length =\n List.fold_left\n (fun acc s -> Z.add acc (Z.of_int (String.length s)))\n Z.zero\n ss.elements\n in\n Gas.consume ctxt (Interp_costs.concat_string total_length)\n >>?= fun ctxt ->\n let s = String.concat \"\" ss.elements in\n logged_return ((s, rest), ctxt)\n | (Slice_string, (offset, (length, (s, rest)))) ->\n let s_length = Z.of_int (String.length s) in\n let offset = Script_int.to_zint offset in\n let length = Script_int.to_zint length in\n if Compare.Z.(offset < s_length && Z.add offset length <= s_length) then\n logged_return\n ( (Some (String.sub s (Z.to_int offset) (Z.to_int length)), rest),\n ctxt )\n else logged_return ((None, rest), ctxt)\n | (String_size, (s, rest)) ->\n logged_return ((Script_int.(abs (of_int (String.length s))), rest), ctxt)\n (* bytes operations *)\n | (Concat_bytes_pair, (x, (y, rest))) ->\n let s = Bytes.cat x y in\n logged_return ((s, rest), ctxt)\n | (Concat_bytes, (ss, rest)) ->\n (* The cost for this fold_left has been paid upfront *)\n let total_length =\n List.fold_left\n (fun acc s -> Z.add acc (Z.of_int (Bytes.length s)))\n Z.zero\n ss.elements\n in\n Gas.consume ctxt (Interp_costs.concat_string total_length)\n >>?= fun ctxt ->\n let s = Bytes.concat Bytes.empty ss.elements in\n logged_return ((s, rest), ctxt)\n | (Slice_bytes, (offset, (length, (s, rest)))) ->\n let s_length = Z.of_int (Bytes.length s) in\n let offset = Script_int.to_zint offset in\n let length = Script_int.to_zint length in\n if Compare.Z.(offset < s_length && Z.add offset length <= s_length) then\n logged_return\n ((Some (Bytes.sub s (Z.to_int offset) (Z.to_int length)), rest), ctxt)\n else logged_return ((None, rest), ctxt)\n | (Bytes_size, (s, rest)) ->\n logged_return ((Script_int.(abs (of_int (Bytes.length s))), rest), ctxt)\n (* currency operations *)\n | (Add_tez, (x, (y, rest))) ->\n Tez.(x +? y) >>?= fun res -> logged_return ((res, rest), ctxt)\n | (Sub_tez, (x, (y, rest))) ->\n Tez.(x -? y) >>?= fun res -> logged_return ((res, rest), ctxt)\n | (Mul_teznat, (x, (y, rest))) -> (\n match Script_int.to_int64 y with\n | None ->\n Log.get_log () >>=? fun log -> fail (Overflow (loc, log))\n | Some y ->\n Tez.(x *? y) >>?= fun res -> logged_return ((res, rest), ctxt) )\n | (Mul_nattez, (y, (x, rest))) -> (\n match Script_int.to_int64 y with\n | None ->\n Log.get_log () >>=? fun log -> fail (Overflow (loc, log))\n | Some y ->\n Tez.(x *? y) >>?= fun res -> logged_return ((res, rest), ctxt) )\n (* boolean operations *)\n | (Or, (x, (y, rest))) ->\n logged_return ((x || y, rest), ctxt)\n | (And, (x, (y, rest))) ->\n logged_return ((x && y, rest), ctxt)\n | (Xor, (x, (y, rest))) ->\n logged_return ((Compare.Bool.(x <> y), rest), ctxt)\n | (Not, (x, rest)) ->\n logged_return ((not x, rest), ctxt)\n (* integer operations *)\n | (Is_nat, (x, rest)) ->\n logged_return ((Script_int.is_nat x, rest), ctxt)\n | (Abs_int, (x, rest)) ->\n logged_return ((Script_int.abs x, rest), ctxt)\n | (Int_nat, (x, rest)) ->\n logged_return ((Script_int.int x, rest), ctxt)\n | (Neg_int, (x, rest)) ->\n logged_return ((Script_int.neg x, rest), ctxt)\n | (Neg_nat, (x, rest)) ->\n logged_return ((Script_int.neg x, rest), ctxt)\n | (Add_intint, (x, (y, rest))) ->\n logged_return ((Script_int.add x y, rest), ctxt)\n | (Add_intnat, (x, (y, rest))) ->\n logged_return ((Script_int.add x y, rest), ctxt)\n | (Add_natint, (x, (y, rest))) ->\n logged_return ((Script_int.add x y, rest), ctxt)\n | (Add_natnat, (x, (y, rest))) ->\n logged_return ((Script_int.add_n x y, rest), ctxt)\n | (Sub_int, (x, (y, rest))) ->\n logged_return ((Script_int.sub x y, rest), ctxt)\n | (Mul_intint, (x, (y, rest))) ->\n logged_return ((Script_int.mul x y, rest), ctxt)\n | (Mul_intnat, (x, (y, rest))) ->\n logged_return ((Script_int.mul x y, rest), ctxt)\n | (Mul_natint, (x, (y, rest))) ->\n logged_return ((Script_int.mul x y, rest), ctxt)\n | (Mul_natnat, (x, (y, rest))) ->\n logged_return ((Script_int.mul_n x y, rest), ctxt)\n | (Ediv_teznat, (x, (y, rest))) ->\n let x = Script_int.of_int64 (Tez.to_mutez x) in\n let result =\n match Script_int.ediv x y with\n | None ->\n None\n | Some (q, r) -> (\n match (Script_int.to_int64 q, Script_int.to_int64 r) with\n | (Some q, Some r) -> (\n match (Tez.of_mutez q, Tez.of_mutez r) with\n | (Some q, Some r) ->\n Some (q, r)\n (* Cannot overflow *)\n | _ ->\n assert false )\n (* Cannot overflow *)\n | _ ->\n assert false )\n in\n logged_return ((result, rest), ctxt)\n | (Ediv_tez, (x, (y, rest))) ->\n let x = Script_int.abs (Script_int.of_int64 (Tez.to_mutez x)) in\n let y = Script_int.abs (Script_int.of_int64 (Tez.to_mutez y)) in\n let result =\n match Script_int.ediv_n x y with\n | None ->\n None\n | Some (q, r) -> (\n match Script_int.to_int64 r with\n | None ->\n assert false (* Cannot overflow *)\n | Some r -> (\n match Tez.of_mutez r with\n | None ->\n assert false (* Cannot overflow *)\n | Some r ->\n Some (q, r) ) )\n in\n logged_return ((result, rest), ctxt)\n | (Ediv_intint, (x, (y, rest))) ->\n logged_return ((Script_int.ediv x y, rest), ctxt)\n | (Ediv_intnat, (x, (y, rest))) ->\n logged_return ((Script_int.ediv x y, rest), ctxt)\n | (Ediv_natint, (x, (y, rest))) ->\n logged_return ((Script_int.ediv x y, rest), ctxt)\n | (Ediv_natnat, (x, (y, rest))) ->\n logged_return ((Script_int.ediv_n x y, rest), ctxt)\n | (Lsl_nat, (x, (y, rest))) -> (\n match Script_int.shift_left_n x y with\n | None ->\n Log.get_log () >>=? fun log -> fail (Overflow (loc, log))\n | Some x ->\n logged_return ((x, rest), ctxt) )\n | (Lsr_nat, (x, (y, rest))) -> (\n match Script_int.shift_right_n x y with\n | None ->\n Log.get_log () >>=? fun log -> fail (Overflow (loc, log))\n | Some r ->\n logged_return ((r, rest), ctxt) )\n | (Or_nat, (x, (y, rest))) ->\n logged_return ((Script_int.logor x y, rest), ctxt)\n | (And_nat, (x, (y, rest))) ->\n logged_return ((Script_int.logand x y, rest), ctxt)\n | (And_int_nat, (x, (y, rest))) ->\n logged_return ((Script_int.logand x y, rest), ctxt)\n | (Xor_nat, (x, (y, rest))) ->\n logged_return ((Script_int.logxor x y, rest), ctxt)\n | (Not_int, (x, rest)) ->\n logged_return ((Script_int.lognot x, rest), ctxt)\n | (Not_nat, (x, rest)) ->\n logged_return ((Script_int.lognot x, rest), ctxt)\n (* control *)\n | (Seq (hd, tl), stack) ->\n non_terminal_recursion ~ctxt hd stack\n >>=? fun (trans, ctxt) ->\n step_bounded logger ~stack_depth ctxt step_constants tl trans\n | (If (bt, _), (true, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bt rest\n | (If (_, bf), (false, rest)) ->\n step_bounded logger ~stack_depth ctxt step_constants bf rest\n | (Loop body, (true, rest)) ->\n non_terminal_recursion ~ctxt body rest\n >>=? fun (trans, ctxt) ->\n step_bounded logger ~stack_depth ctxt step_constants descr trans\n | (Loop _, (false, rest)) ->\n logged_return (rest, ctxt)\n | (Loop_left body, (L v, rest)) ->\n non_terminal_recursion ~ctxt body (v, rest)\n >>=? fun (trans, ctxt) ->\n step_bounded logger ~stack_depth ctxt step_constants descr trans\n | (Loop_left _, (R v, rest)) ->\n logged_return ((v, rest), ctxt)\n | (Dip b, (ign, rest)) ->\n non_terminal_recursion ~ctxt b rest\n >>=? fun (res, ctxt) -> logged_return ((ign, res), ctxt)\n | (Exec, (arg, (Lam (code, _), rest))) ->\n Log.log_interp ctxt code (arg, ()) ;\n non_terminal_recursion ~ctxt code (arg, ())\n >>=? fun ((res, ()), ctxt) -> logged_return ((res, rest), ctxt)\n | (Apply capture_ty, (capture, (lam, rest))) -> (\n let (Lam (descr, expr)) = lam in\n let (Item_t (full_arg_ty, _, _)) = descr.bef in\n unparse_data ctxt Optimized capture_ty capture\n >>=? fun (const_expr, ctxt) ->\n unparse_ty ctxt capture_ty\n >>?= fun (ty_expr, ctxt) ->\n match full_arg_ty with\n | Pair_t ((capture_ty, _, _), (arg_ty, _, _), _) ->\n let arg_stack_ty = Item_t (arg_ty, Empty_t, None) in\n let const_descr =\n ( {\n loc = descr.loc;\n bef = arg_stack_ty;\n aft = Item_t (capture_ty, arg_stack_ty, None);\n instr = Const capture;\n }\n : (_, _) descr )\n in\n let pair_descr =\n ( {\n loc = descr.loc;\n bef = Item_t (capture_ty, arg_stack_ty, None);\n aft = Item_t (full_arg_ty, Empty_t, None);\n instr = Cons_pair;\n }\n : (_, _) descr )\n in\n let seq_descr =\n ( {\n loc = descr.loc;\n bef = arg_stack_ty;\n aft = Item_t (full_arg_ty, Empty_t, None);\n instr = Seq (const_descr, pair_descr);\n }\n : (_, _) descr )\n in\n let full_descr =\n ( {\n loc = descr.loc;\n bef = arg_stack_ty;\n aft = descr.aft;\n instr = Seq (seq_descr, descr);\n }\n : (_, _) descr )\n in\n let full_expr =\n Micheline.Seq\n ( 0,\n [ Prim (0, I_PUSH, [ty_expr; const_expr], []);\n Prim (0, I_PAIR, [], []);\n expr ] )\n in\n let lam' = Lam (full_descr, full_expr) in\n logged_return ((lam', rest), ctxt)\n | _ ->\n assert false )\n | (Lambda lam, rest) ->\n logged_return ((lam, rest), ctxt)\n | (Failwith tv, (v, _)) ->\n trace Cannot_serialize_failure (unparse_data ctxt Optimized tv v)\n >>=? fun (v, _ctxt) ->\n let v = Micheline.strip_locations v in\n Log.get_log () >>=? fun log -> fail (Reject (loc, v, log))\n | (Nop, stack) ->\n logged_return (stack, ctxt)\n (* comparison *)\n | (Compare ty, (a, (b, rest))) ->\n logged_return\n ( ( Script_int.of_int @@ Script_ir_translator.compare_comparable ty a b,\n rest ),\n ctxt )\n (* comparators *)\n | (Eq, (cmpres, rest)) ->\n let cmpres = Script_int.compare cmpres Script_int.zero in\n let cmpres = Compare.Int.(cmpres = 0) in\n logged_return ((cmpres, rest), ctxt)\n | (Neq, (cmpres, rest)) ->\n let cmpres = Script_int.compare cmpres Script_int.zero in\n let cmpres = Compare.Int.(cmpres <> 0) in\n logged_return ((cmpres, rest), ctxt)\n | (Lt, (cmpres, rest)) ->\n let cmpres = Script_int.compare cmpres Script_int.zero in\n let cmpres = Compare.Int.(cmpres < 0) in\n logged_return ((cmpres, rest), ctxt)\n | (Le, (cmpres, rest)) ->\n let cmpres = Script_int.compare cmpres Script_int.zero in\n let cmpres = Compare.Int.(cmpres <= 0) in\n logged_return ((cmpres, rest), ctxt)\n | (Gt, (cmpres, rest)) ->\n let cmpres = Script_int.compare cmpres Script_int.zero in\n let cmpres = Compare.Int.(cmpres > 0) in\n logged_return ((cmpres, rest), ctxt)\n | (Ge, (cmpres, rest)) ->\n let cmpres = Script_int.compare cmpres Script_int.zero in\n let cmpres = Compare.Int.(cmpres >= 0) in\n logged_return ((cmpres, rest), ctxt)\n (* packing *)\n | (Pack t, (value, rest)) ->\n Script_ir_translator.pack_data ctxt t value\n >>=? fun (bytes, ctxt) -> logged_return ((bytes, rest), ctxt)\n | (Unpack ty, (bytes, rest)) ->\n unpack ctxt ~ty ~bytes\n >>=? fun (opt, ctxt) -> logged_return ((opt, rest), ctxt)\n (* protocol *)\n | (Address, ((_, address), rest)) ->\n logged_return ((address, rest), ctxt)\n | (Contract (t, entrypoint), (contract, rest)) -> (\n match (contract, entrypoint) with\n | ((contract, \"default\"), entrypoint) | ((contract, entrypoint), \"default\")\n ->\n Script_ir_translator.parse_contract_for_script\n ~legacy:false\n ctxt\n loc\n t\n contract\n ~entrypoint\n >>=? fun (ctxt, maybe_contract) ->\n logged_return ((maybe_contract, rest), ctxt)\n | _ ->\n logged_return ((None, rest), ctxt) )\n | (Transfer_tokens, (p, (amount, ((tp, (destination, entrypoint)), rest))))\n ->\n collect_lazy_storage ctxt tp p\n >>?= fun (to_duplicate, ctxt) ->\n let to_update = no_lazy_storage_id in\n extract_lazy_storage_diff\n ctxt\n Optimized\n tp\n p\n ~to_duplicate\n ~to_update\n ~temporary:true\n >>=? fun (p, lazy_storage_diff, ctxt) ->\n unparse_data ctxt Optimized tp p\n >>=? fun (p, ctxt) ->\n Gas.consume ctxt (Script.strip_locations_cost p)\n >>?= fun ctxt ->\n let operation =\n Transaction\n {\n amount;\n destination;\n entrypoint;\n parameters = Script.lazy_expr (Micheline.strip_locations p);\n }\n in\n fresh_internal_nonce ctxt\n >>?= fun (ctxt, nonce) ->\n logged_return\n ( ( ( Internal_operation\n {source = step_constants.self; operation; nonce},\n lazy_storage_diff ),\n rest ),\n ctxt )\n | (Implicit_account, (key, rest)) ->\n let contract = Contract.implicit_contract key in\n logged_return (((Unit_t None, (contract, \"default\")), rest), ctxt)\n | ( Create_contract (storage_type, param_type, Lam (_, code), root_name),\n (* Removed the instruction's arguments manager, spendable and delegatable *)\n (delegate, (credit, (init, rest))) ) ->\n unparse_ty ctxt param_type\n >>?= fun (unparsed_param_type, ctxt) ->\n let unparsed_param_type =\n Script_ir_translator.add_field_annot root_name None unparsed_param_type\n in\n unparse_ty ctxt storage_type\n >>?= fun (unparsed_storage_type, ctxt) ->\n let code =\n Micheline.strip_locations\n (Seq\n ( 0,\n [ Prim (0, K_parameter, [unparsed_param_type], []);\n Prim (0, K_storage, [unparsed_storage_type], []);\n Prim (0, K_code, [code], []) ] ))\n in\n collect_lazy_storage ctxt storage_type init\n >>?= fun (to_duplicate, ctxt) ->\n let to_update = no_lazy_storage_id in\n extract_lazy_storage_diff\n ctxt\n Optimized\n storage_type\n init\n ~to_duplicate\n ~to_update\n ~temporary:true\n >>=? fun (init, lazy_storage_diff, ctxt) ->\n unparse_data ctxt Optimized storage_type init\n >>=? fun (storage, ctxt) ->\n Gas.consume ctxt (Script.strip_locations_cost storage)\n >>?= fun ctxt ->\n let storage = Micheline.strip_locations storage in\n Contract.fresh_contract_from_current_nonce ctxt\n >>?= fun (ctxt, contract) ->\n let operation =\n Origination\n {\n credit;\n delegate;\n preorigination = Some contract;\n script =\n {\n code = Script.lazy_expr code;\n storage = Script.lazy_expr storage;\n };\n }\n in\n fresh_internal_nonce ctxt\n >>?= fun (ctxt, nonce) ->\n logged_return\n ( ( ( Internal_operation\n {source = step_constants.self; operation; nonce},\n lazy_storage_diff ),\n ((contract, \"default\"), rest) ),\n ctxt )\n | (Set_delegate, (delegate, rest)) ->\n let operation = Delegation delegate in\n fresh_internal_nonce ctxt\n >>?= fun (ctxt, nonce) ->\n logged_return\n ( ( ( Internal_operation\n {source = step_constants.self; operation; nonce},\n None ),\n rest ),\n ctxt )\n | (Balance, rest) ->\n Contract.get_balance_carbonated ctxt step_constants.self\n >>=? fun (ctxt, balance) -> logged_return ((balance, rest), ctxt)\n | (Level, rest) ->\n let level =\n (Level.current ctxt).level |> Raw_level.to_int32 |> Script_int.of_int32\n |> Script_int.abs\n in\n logged_return ((level, rest), ctxt)\n | (Now, rest) ->\n let now = Script_timestamp.now ctxt in\n logged_return ((now, rest), ctxt)\n | (Check_signature, (key, (signature, (message, rest)))) ->\n let res = Signature.check key signature message in\n logged_return ((res, rest), ctxt)\n | (Hash_key, (key, rest)) ->\n logged_return ((Signature.Public_key.hash key, rest), ctxt)\n | (Blake2b, (bytes, rest)) ->\n let hash = Raw_hashes.blake2b bytes in\n logged_return ((hash, rest), ctxt)\n | (Sha256, (bytes, rest)) ->\n let hash = Raw_hashes.sha256 bytes in\n logged_return ((hash, rest), ctxt)\n | (Sha512, (bytes, rest)) ->\n let hash = Raw_hashes.sha512 bytes in\n logged_return ((hash, rest), ctxt)\n | (Source, rest) ->\n logged_return (((step_constants.payer, \"default\"), rest), ctxt)\n | (Sender, rest) ->\n logged_return (((step_constants.source, \"default\"), rest), ctxt)\n | (Self (t, entrypoint), rest) ->\n logged_return (((t, (step_constants.self, entrypoint)), rest), ctxt)\n | (Self_address, rest) ->\n logged_return (((step_constants.self, \"default\"), rest), ctxt)\n | (Amount, rest) ->\n logged_return ((step_constants.amount, rest), ctxt)\n | (Dig (_n, n'), stack) ->\n interp_stack_prefix_preserving_operation\n (fun (v, rest) -> return (rest, v))\n n'\n stack\n >>=? fun (aft, x) -> logged_return ((x, aft), ctxt)\n | (Dug (_n, n'), (v, rest)) ->\n interp_stack_prefix_preserving_operation\n (fun stk -> return ((v, stk), ()))\n n'\n rest\n >>=? fun (aft, ()) -> logged_return (aft, ctxt)\n | (Dipn (n, n', b), stack) ->\n interp_stack_prefix_preserving_operation\n (fun stk ->\n non_terminal_recursion\n ~ctxt\n b\n stk\n (* This is a cheap upper bound of the number recursive calls to\n `interp_stack_prefix_preserving_operation`, which does\n ((n / 16) + log2 (n % 16)) iterations *)\n ~stack_depth:(stack_depth + 4 + (n / 16)))\n n'\n stack\n >>=? fun (aft, ctxt') -> logged_return (aft, ctxt')\n | (Dropn (_n, n'), stack) ->\n interp_stack_prefix_preserving_operation\n (fun stk -> return (stk, stk))\n n'\n stack\n >>=? fun (_, rest) -> logged_return (rest, ctxt)\n | (Sapling_empty_state {memo_size}, stack) ->\n logged_return ((Sapling.empty_state ~memo_size (), stack), ctxt)\n | (Sapling_verify_update, (transaction, (state, rest))) -> (\n let address = Contract.to_b58check step_constants.self in\n let chain_id = Chain_id.to_b58check step_constants.chain_id in\n let anti_replay = address ^ chain_id in\n Sapling.verify_update ctxt state transaction anti_replay\n >>=? fun (ctxt, balance_state_opt) ->\n match balance_state_opt with\n | Some (balance, state) ->\n logged_return\n ((Some (Script_int.of_int64 balance, state), rest), ctxt)\n | None ->\n logged_return ((None, rest), ctxt) )\n | (ChainId, rest) ->\n logged_return ((step_constants.chain_id, rest), ctxt)\n | (Never, (_, _)) ->\n .\n | (Voting_power, (key_hash, rest)) ->\n Vote.get_voting_power ctxt key_hash\n >>=? fun (ctxt, rolls) ->\n logged_return ((Script_int.(abs (of_int32 rolls)), rest), ctxt)\n | (Total_voting_power, rest) ->\n Vote.get_total_voting_power ctxt\n >>=? fun (ctxt, rolls) ->\n logged_return ((Script_int.(abs (of_int32 rolls)), rest), ctxt)\n | (Keccak, (bytes, rest)) ->\n let hash = Raw_hashes.keccak256 bytes in\n logged_return ((hash, rest), ctxt)\n | (Sha3, (bytes, rest)) ->\n let hash = Raw_hashes.sha3_256 bytes in\n logged_return ((hash, rest), ctxt)\n | (Add_bls12_381_g1, (x, (y, rest))) ->\n logged_return ((Bls12_381.G1.add x y, rest), ctxt)\n | (Add_bls12_381_g2, (x, (y, rest))) ->\n logged_return ((Bls12_381.G2.add x y, rest), ctxt)\n | (Add_bls12_381_fr, (x, (y, rest))) ->\n logged_return ((Bls12_381.Fr.add x y, rest), ctxt)\n | (Mul_bls12_381_g1, (x, (y, rest))) ->\n logged_return ((Bls12_381.G1.mul x y, rest), ctxt)\n | (Mul_bls12_381_g2, (x, (y, rest))) ->\n logged_return ((Bls12_381.G2.mul x y, rest), ctxt)\n | (Mul_bls12_381_fr, (x, (y, rest))) ->\n logged_return ((Bls12_381.Fr.mul x y, rest), ctxt)\n | (Mul_bls12_381_fr_z, (x, (y, rest))) ->\n let x = Bls12_381.Fr.of_z (Script_int.to_zint x) in\n let res = (Bls12_381.Fr.mul x y, rest) in\n logged_return (res, ctxt)\n | (Mul_bls12_381_z_fr, (y, (x, rest))) ->\n let x = Bls12_381.Fr.of_z (Script_int.to_zint x) in\n let res = (Bls12_381.Fr.mul x y, rest) in\n logged_return (res, ctxt)\n | (Int_bls12_381_fr, (x, rest)) ->\n logged_return ((Script_int.of_zint (Bls12_381.Fr.to_z x), rest), ctxt)\n | (Neg_bls12_381_g1, (x, rest)) ->\n logged_return ((Bls12_381.G1.negate x, rest), ctxt)\n | (Neg_bls12_381_g2, (x, rest)) ->\n logged_return ((Bls12_381.G2.negate x, rest), ctxt)\n | (Neg_bls12_381_fr, (x, rest)) ->\n logged_return ((Bls12_381.Fr.negate x, rest), ctxt)\n | (Pairing_check_bls12_381, (pairs, rest)) ->\n let check =\n match pairs.elements with\n | [] ->\n true\n | pairs ->\n Bls12_381.(\n miller_loop pairs |> final_exponentiation_opt\n |> Option.map Gt.(eq one))\n |> Option.value ~default:false\n in\n logged_return ((check, rest), ctxt)\n | (Comb (_, witness), stack) ->\n let rec aux :\n type before after.\n (before, after) comb_gadt_witness -> before -> after =\n fun witness stack ->\n match (witness, stack) with\n | (Comb_one, stack) ->\n stack\n | (Comb_succ witness', (a, tl)) ->\n let (b, tl') = aux witness' tl in\n ((a, b), tl')\n in\n logged_return (aux witness stack, ctxt)\n | (Uncomb (_, witness), stack) ->\n let rec aux :\n type before after.\n (before, after) uncomb_gadt_witness -> before -> after =\n fun witness stack ->\n match (witness, stack) with\n | (Uncomb_one, stack) ->\n stack\n | (Uncomb_succ witness', ((a, b), tl)) ->\n (a, aux witness' (b, tl))\n in\n logged_return (aux witness stack, ctxt)\n | (Comb_get (_, witness), (comb, stack)) ->\n let rec aux :\n type before after.\n (before, after) comb_get_gadt_witness -> before -> after =\n fun witness comb ->\n match (witness, comb) with\n | (Comb_get_zero, v) ->\n v\n | (Comb_get_one, (a, _)) ->\n a\n | (Comb_get_plus_two witness', (_, b)) ->\n aux witness' b\n in\n logged_return ((aux witness comb, stack), ctxt)\n | (Comb_set (_, witness), (value, (comb, stack))) ->\n let rec aux :\n type value before after.\n (value, before, after) comb_set_gadt_witness ->\n value ->\n before ->\n after =\n fun witness value item ->\n match (witness, item) with\n | (Comb_set_zero, _) ->\n value\n | (Comb_set_one, (_hd, tl)) ->\n (value, tl)\n | (Comb_set_plus_two witness', (hd, tl)) ->\n (hd, aux witness' value tl)\n in\n logged_return ((aux witness value comb, stack), ctxt)\n | (Dup_n (_, witness), stack) ->\n let rec aux :\n type before after.\n (before, after) dup_n_gadt_witness -> before -> after =\n fun witness stack ->\n match (witness, stack) with\n | (Dup_n_zero, (a, _)) ->\n a\n | (Dup_n_succ witness', (_, tl)) ->\n aux witness' tl\n in\n logged_return ((aux witness stack, stack), ctxt)\n (* Tickets *)\n | (Ticket, (contents, (amount, rest))) ->\n let ticketer = (step_constants.self, \"default\") in\n logged_return (({ticketer; contents; amount}, rest), ctxt)\n | (Read_ticket, (({ticketer; contents; amount}, _) as stack)) ->\n logged_return (((ticketer, (contents, amount)), stack), ctxt)\n | (Split_ticket, (ticket, ((amount_a, amount_b), rest))) ->\n let result =\n if\n Compare.Int.(\n Script_int.(compare (add_n amount_a amount_b) ticket.amount) = 0)\n then\n Some\n ({ticket with amount = amount_a}, {ticket with amount = amount_b})\n else None\n in\n logged_return ((result, rest), ctxt)\n | (Join_tickets contents_ty, ((ticket_a, ticket_b), rest)) ->\n let result =\n if\n Compare.Int.(\n compare_address ticket_a.ticketer ticket_b.ticketer = 0\n && compare_comparable\n contents_ty\n ticket_a.contents\n ticket_b.contents\n = 0)\n then\n Some\n {\n ticketer = ticket_a.ticketer;\n contents = ticket_a.contents;\n amount = Script_int.add_n ticket_a.amount ticket_b.amount;\n }\n else None\n in\n logged_return ((result, rest), ctxt)\n\nlet step :\n type b a.\n logger ->\n context ->\n step_constants ->\n (b, a) descr ->\n b ->\n (a * context) tzresult Lwt.t =\n step_bounded ~stack_depth:0\n\nlet interp :\n type p r.\n logger ->\n context ->\n step_constants ->\n (p, r) lambda ->\n p ->\n (r * context) tzresult Lwt.t =\n fun logger ctxt step_constants (Lam (code, _)) arg ->\n let stack = (arg, ()) in\n let module Log = (val logger) in\n Log.log_interp ctxt code stack ;\n step logger ctxt step_constants code stack\n >|=? fun ((ret, ()), ctxt) -> (ret, ctxt)\n\n(* ---- contract handling ---------------------------------------------------*)\nlet execute logger ctxt mode step_constants ~entrypoint ~internal\n unparsed_script arg :\n ( Script.expr\n * packed_internal_operation list\n * context\n * Lazy_storage.diffs option )\n tzresult\n Lwt.t =\n parse_script ctxt unparsed_script ~legacy:true ~allow_forged_in_storage:true\n >>=? fun (Ex_script {code; arg_type; storage; storage_type; root_name}, ctxt) ->\n record_trace\n (Bad_contract_parameter step_constants.self)\n (find_entrypoint arg_type ~root_name entrypoint)\n >>?= fun (box, _) ->\n trace\n (Bad_contract_parameter step_constants.self)\n (parse_data ctxt ~legacy:false ~allow_forged:internal arg_type (box arg))\n >>=? fun (arg, ctxt) ->\n Script.force_decode_in_context ctxt unparsed_script.code\n >>?= fun (script_code, ctxt) ->\n Script_ir_translator.collect_lazy_storage ctxt arg_type arg\n >>?= fun (to_duplicate, ctxt) ->\n Script_ir_translator.collect_lazy_storage ctxt storage_type storage\n >>?= fun (to_update, ctxt) ->\n trace\n (Runtime_contract_error (step_constants.self, script_code))\n (interp logger ctxt step_constants code (arg, storage))\n >>=? fun ((ops, storage), ctxt) ->\n Script_ir_translator.extract_lazy_storage_diff\n ctxt\n mode\n ~temporary:false\n ~to_duplicate\n ~to_update\n storage_type\n storage\n >>=? fun (storage, lazy_storage_diff, ctxt) ->\n trace\n Cannot_serialize_storage\n ( unparse_data ctxt mode storage_type storage\n >>=? fun (storage, ctxt) ->\n Lwt.return\n ( Gas.consume ctxt (Script.strip_locations_cost storage)\n >>? fun ctxt -> ok (Micheline.strip_locations storage, ctxt) ) )\n >|=? fun (storage, ctxt) ->\n let (ops, op_diffs) = List.split ops.elements in\n let lazy_storage_diff =\n match\n List.flatten\n (List.map (Option.value ~default:[]) (op_diffs @ [lazy_storage_diff]))\n with\n | [] ->\n None\n | diff ->\n Some diff\n in\n (storage, ops, ctxt, lazy_storage_diff)\n\ntype execution_result = {\n ctxt : context;\n storage : Script.expr;\n lazy_storage_diff : Lazy_storage.diffs option;\n operations : packed_internal_operation list;\n}\n\nlet execute ?(logger = (module No_trace : STEP_LOGGER)) ctxt mode\n step_constants ~script ~entrypoint ~parameter ~internal =\n execute\n logger\n ctxt\n mode\n step_constants\n ~entrypoint\n ~internal\n script\n (Micheline.root parameter)\n >|=? fun (storage, operations, ctxt, lazy_storage_diff) ->\n {ctxt; storage; lazy_storage_diff; operations}\n" ;
} ;
{ name = "Baking" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Misc\n\ntype error += Invalid_fitness_gap of int64 * int64 (* `Permanent *)\n\ntype error += Timestamp_too_early of Timestamp.t * Timestamp.t\n\n(* `Permanent *)\n\ntype error +=\n | Invalid_block_signature of Block_hash.t * Signature.Public_key_hash.t\n\n(* `Permanent *)\n\ntype error += Unexpected_endorsement\n\ntype error += Invalid_signature (* `Permanent *)\n\ntype error += Invalid_stamp (* `Permanent *)\n\n(** [minimal_time ctxt priority pred_block_time] returns the minimal\n time, given the predecessor block timestamp [pred_block_time],\n after which a baker with priority [priority] is allowed to\n bake. Fail with [Invalid_time_between_blocks_constant] if the minimal\n time cannot be computed. *)\nval minimal_time : context -> int -> Time.t -> Time.t tzresult\n\n(** [check_baking_rights ctxt block pred_timestamp] verifies that:\n * the contract that owned the roll at cycle start has the block signer as delegate.\n * the timestamp is coherent with the announced slot.\n*)\nval check_baking_rights :\n context ->\n Block_header.contents ->\n Time.t ->\n (public_key * Period.t) tzresult Lwt.t\n\n(** For a given level computes who has the right to\n include an endorsement in the next block.\n The result can be stored in Alpha_context.allowed_endorsements *)\nval endorsement_rights :\n context ->\n Level.t ->\n (public_key * int list * bool) Signature.Public_key_hash.Map.t tzresult Lwt.t\n\n(** Check that the operation was signed by a delegate allowed\n to endorse at the level specified by the endorsement. *)\nval check_endorsement_rights :\n context ->\n Chain_id.t ->\n Kind.endorsement Operation.t ->\n (public_key_hash * int list * bool) tzresult Lwt.t\n\n(** Returns the baking reward calculated w.r.t a given priority [p] and a\n number [e] of included endorsements *)\nval baking_reward :\n context -> block_priority:int -> included_endorsements:int -> Tez.t tzresult\n\n(** Returns the endorsing reward calculated w.r.t a given priority. *)\nval endorsing_reward : context -> block_priority:int -> int -> Tez.t tzresult\n\n(** [baking_priorities ctxt level] is the lazy list of contract's\n public key hashes that are allowed to bake for [level]. *)\nval baking_priorities : context -> Level.t -> public_key lazy_list\n\n(** [first_baking_priorities ctxt ?max_priority contract_hash level]\n is a list of priorities of max [?max_priority] elements, where the\n delegate of [contract_hash] is allowed to bake for [level]. If\n [?max_priority] is [None], a sensible number of priorities is\n returned. *)\nval first_baking_priorities :\n context ->\n ?max_priority:int ->\n public_key_hash ->\n Level.t ->\n int list tzresult Lwt.t\n\n(** [check_signature ctxt chain_id block id] check if the block is\n signed with the given key, and belongs to the given [chain_id] *)\nval check_signature :\n Block_header.t -> Chain_id.t -> public_key -> unit tzresult Lwt.t\n\n(** Checks if the header that would be built from the given components\n is valid for the given difficulty. The signature is not passed as it\n is does not impact the proof-of-work stamp. The stamp is checked on\n the hash of a block header whose signature has been zeroed-out. *)\nval check_header_proof_of_work_stamp :\n Block_header.shell_header -> Block_header.contents -> int64 -> bool\n\n(** verify if the proof of work stamp is valid *)\nval check_proof_of_work_stamp : context -> Block_header.t -> unit tzresult\n\n(** check if the gap between the fitness of the current context\n and the given block is within the protocol parameters *)\nval check_fitness_gap : context -> Block_header.t -> unit tzresult\n\nval dawn_of_a_new_cycle : context -> Cycle.t option\n\nval earlier_predecessor_timestamp : context -> Level.t -> Timestamp.t tzresult\n\n(** Since Emmy+\n\n A block is valid only if its timestamp has a minimal delay with\n respect to the previous block's timestamp, and this minimal delay\n depends not only on the block's priority but also on the number of\n endorsement operations included in the block.\n\n In Emmy+, blocks' fitness increases by one unit with each level.\n\n In this way, Emmy+ simplifies the optimal baking strategy: The\n bakers used to have to choose whether to wait for more endorsements\n to include in their block, or to publish the block immediately,\n without waiting. The incentive for including more endorsements was\n to increase the fitness and win against unknown blocks. However,\n when a block was produced too late in the priority period, there\n was the risk that the block did not reach endorsers before the\n block of next priority. In Emmy+, the baker does not need to take\n such a decision, because the baker cannot publish a block too\n early. *)\n\n(** Given a delay of a block's timestamp with respect to the minimum\n time to bake at the block's priority (as returned by\n `minimum_time`), it returns the minimum number of endorsements that\n the block has to contain *)\nval minimum_allowed_endorsements : context -> block_delay:Period.t -> int\n\n(** This is the somehow the dual of the previous function. Given a\n block priority and a number of endorsement slots (given by the\n `endorsing_power` argument), it returns the minimum time at which\n the next block can be baked. *)\nval minimal_valid_time :\n context -> priority:int -> endorsing_power:int -> Time.t tzresult\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Misc\n\ntype error += Invalid_fitness_gap of int64 * int64 (* `Permanent *)\n\ntype error += Timestamp_too_early of Timestamp.t * Timestamp.t\n\n(* `Permanent *)\n\ntype error += Unexpected_endorsement (* `Permanent *)\n\ntype error +=\n | Invalid_block_signature of Block_hash.t * Signature.Public_key_hash.t\n\n(* `Permanent *)\n\ntype error += Invalid_signature (* `Permanent *)\n\ntype error += Invalid_stamp (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"baking.timestamp_too_early\"\n ~title:\"Block forged too early\"\n ~description:\n \"The block timestamp is before the first slot for this baker at this \\\n level\"\n ~pp:(fun ppf (r, p) ->\n Format.fprintf\n ppf\n \"Block forged too early (%a is before %a)\"\n Time.pp_hum\n p\n Time.pp_hum\n r)\n Data_encoding.(\n obj2 (req \"minimum\" Time.encoding) (req \"provided\" Time.encoding))\n (function Timestamp_too_early (r, p) -> Some (r, p) | _ -> None)\n (fun (r, p) -> Timestamp_too_early (r, p)) ;\n register_error_kind\n `Permanent\n ~id:\"baking.invalid_fitness_gap\"\n ~title:\"Invalid fitness gap\"\n ~description:\"The gap of fitness is out of bounds\"\n ~pp:(fun ppf (m, g) ->\n Format.fprintf ppf \"The gap of fitness %Ld is not between 0 and %Ld\" g m)\n Data_encoding.(obj2 (req \"maximum\" int64) (req \"provided\" int64))\n (function Invalid_fitness_gap (m, g) -> Some (m, g) | _ -> None)\n (fun (m, g) -> Invalid_fitness_gap (m, g)) ;\n register_error_kind\n `Permanent\n ~id:\"baking.invalid_block_signature\"\n ~title:\"Invalid block signature\"\n ~description:\"A block was not signed with the expected private key.\"\n ~pp:(fun ppf (block, pkh) ->\n Format.fprintf\n ppf\n \"Invalid signature for block %a. Expected: %a.\"\n Block_hash.pp_short\n block\n Signature.Public_key_hash.pp_short\n pkh)\n Data_encoding.(\n obj2\n (req \"block\" Block_hash.encoding)\n (req \"expected\" Signature.Public_key_hash.encoding))\n (function\n | Invalid_block_signature (block, pkh) -> Some (block, pkh) | _ -> None)\n (fun (block, pkh) -> Invalid_block_signature (block, pkh)) ;\n register_error_kind\n `Permanent\n ~id:\"baking.invalid_signature\"\n ~title:\"Invalid block signature\"\n ~description:\"The block's signature is invalid\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Invalid block signature\")\n Data_encoding.empty\n (function Invalid_signature -> Some () | _ -> None)\n (fun () -> Invalid_signature) ;\n register_error_kind\n `Permanent\n ~id:\"baking.insufficient_proof_of_work\"\n ~title:\"Insufficient block proof-of-work stamp\"\n ~description:\"The block's proof-of-work stamp is insufficient\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Insufficient proof-of-work stamp\")\n Data_encoding.empty\n (function Invalid_stamp -> Some () | _ -> None)\n (fun () -> Invalid_stamp) ;\n register_error_kind\n `Permanent\n ~id:\"baking.unexpected_endorsement\"\n ~title:\"Endorsement from unexpected delegate\"\n ~description:\n \"The operation is signed by a delegate without endorsement rights.\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"The endorsement is signed by a delegate without endorsement rights.\")\n Data_encoding.unit\n (function Unexpected_endorsement -> Some () | _ -> None)\n (fun () -> Unexpected_endorsement)\n\nlet minimal_time c priority pred_timestamp =\n let priority = Int32.of_int priority in\n let rec cumsum_time_between_blocks acc durations p =\n if Compare.Int32.( <= ) p 0l then ok acc\n else\n match durations with\n | [] ->\n cumsum_time_between_blocks acc [Period.one_minute] p\n | [last] ->\n Period.mult p last >>? fun period -> Timestamp.(acc +? period)\n | first :: durations ->\n Timestamp.(acc +? first)\n >>? fun acc ->\n let p = Int32.pred p in\n cumsum_time_between_blocks acc durations p\n in\n cumsum_time_between_blocks\n pred_timestamp\n (Constants.time_between_blocks c)\n (Int32.succ priority)\n\nlet earlier_predecessor_timestamp ctxt level =\n let current = Level.current ctxt in\n let current_timestamp = Timestamp.current ctxt in\n let gap = Level.diff level current in\n let step = List.hd (Constants.time_between_blocks ctxt) in\n if Compare.Int32.(gap < 1l) then\n failwith \"Baking.earlier_block_timestamp: past block.\"\n else\n Period.mult (Int32.pred gap) step\n >>? fun delay -> Timestamp.(current_timestamp +? delay)\n\nlet check_timestamp c priority pred_timestamp =\n minimal_time c priority pred_timestamp\n >>? fun minimal_time ->\n let timestamp = Alpha_context.Timestamp.current c in\n record_trace\n (Timestamp_too_early (minimal_time, timestamp))\n Timestamp.(timestamp -? minimal_time)\n\nlet check_baking_rights c {Block_header.priority; _} pred_timestamp =\n let level = Level.current c in\n Roll.baking_rights_owner c level ~priority\n >>=? fun delegate ->\n Lwt.return\n ( check_timestamp c priority pred_timestamp\n >|? fun block_delay -> (delegate, block_delay) )\n\ntype error += Incorrect_priority (* `Permanent *)\n\ntype error += Incorrect_number_of_endorsements (* `Permanent *)\n\nlet () =\n register_error_kind\n `Permanent\n ~id:\"incorrect_priority\"\n ~title:\"Incorrect priority\"\n ~description:\"Block priority must be non-negative.\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"The block priority must be non-negative.\")\n Data_encoding.unit\n (function Incorrect_priority -> Some () | _ -> None)\n (fun () -> Incorrect_priority)\n\nlet () =\n let description =\n \"The number of endorsements must be non-negative and at most the \\\n endorsers_per_block constant.\"\n in\n register_error_kind\n `Permanent\n ~id:\"incorrect_number_of_endorsements\"\n ~title:\"Incorrect number of endorsements\"\n ~description\n ~pp:(fun ppf () -> Format.fprintf ppf \"%s\" description)\n Data_encoding.unit\n (function Incorrect_number_of_endorsements -> Some () | _ -> None)\n (fun () -> Incorrect_number_of_endorsements)\n\nlet rec reward_for_priority reward_per_prio prio =\n match reward_per_prio with\n | [] ->\n (* Empty reward list in parameters means no rewards *)\n Tez.zero\n | [last] ->\n last\n | first :: rest ->\n if Compare.Int.(prio <= 0) then first\n else reward_for_priority rest (pred prio)\n\nlet baking_reward ctxt ~block_priority ~included_endorsements =\n error_unless Compare.Int.(block_priority >= 0) Incorrect_priority\n >>? fun () ->\n error_unless\n Compare.Int.(\n included_endorsements >= 0\n && included_endorsements <= Constants.endorsers_per_block ctxt)\n Incorrect_number_of_endorsements\n >>? fun () ->\n let reward_per_endorsement =\n reward_for_priority\n (Constants.baking_reward_per_endorsement ctxt)\n block_priority\n in\n Tez.(reward_per_endorsement *? Int64.of_int included_endorsements)\n\nlet endorsing_reward ctxt ~block_priority num_slots =\n error_unless Compare.Int.(block_priority >= 0) Incorrect_priority\n >>? fun () ->\n let reward_per_endorsement =\n reward_for_priority (Constants.endorsement_reward ctxt) block_priority\n in\n Tez.(reward_per_endorsement *? Int64.of_int num_slots)\n\nlet baking_priorities c level =\n let rec f priority =\n Roll.baking_rights_owner c level ~priority\n >|=? fun delegate -> LCons (delegate, fun () -> f (succ priority))\n in\n f 0\n\nlet endorsement_rights ctxt level =\n fold_left_s\n (fun acc slot ->\n Roll.endorsement_rights_owner ctxt level ~slot\n >|=? fun pk ->\n let pkh = Signature.Public_key.hash pk in\n let right =\n match Signature.Public_key_hash.Map.find_opt pkh acc with\n | None ->\n (pk, [slot], false)\n | Some (pk, slots, used) ->\n (pk, slot :: slots, used)\n in\n Signature.Public_key_hash.Map.add pkh right acc)\n Signature.Public_key_hash.Map.empty\n (0 --> (Constants.endorsers_per_block ctxt - 1))\n\nlet check_endorsement_rights ctxt chain_id (op : Kind.endorsement Operation.t)\n =\n let current_level = Level.current ctxt in\n let (Single (Endorsement {level; _})) = op.protocol_data.contents in\n ( if Raw_level.(succ level = current_level.level) then\n return (Alpha_context.allowed_endorsements ctxt)\n else endorsement_rights ctxt (Level.from_raw ctxt level) )\n >>=? fun endorsements ->\n match\n Signature.Public_key_hash.Map.fold (* no find_first *)\n (fun pkh (pk, slots, used) acc ->\n match Operation.check_signature pk chain_id op with\n | Error _ ->\n acc\n | Ok () ->\n Some (pkh, slots, used))\n endorsements\n None\n with\n | None ->\n fail Unexpected_endorsement\n | Some v ->\n return v\n\nlet select_delegate delegate delegate_list max_priority =\n let rec loop acc l n =\n if Compare.Int.(n >= max_priority) then return (List.rev acc)\n else\n let (LCons (pk, t)) = l in\n let acc =\n if\n Signature.Public_key_hash.equal\n delegate\n (Signature.Public_key.hash pk)\n then n :: acc\n else acc\n in\n t () >>=? fun t -> loop acc t (succ n)\n in\n loop [] delegate_list 0\n\nlet first_baking_priorities ctxt ?(max_priority = 32) delegate level =\n baking_priorities ctxt level\n >>=? fun delegate_list -> select_delegate delegate delegate_list max_priority\n\nlet check_hash hash stamp_threshold =\n let bytes = Block_hash.to_bytes hash in\n let word = TzEndian.get_int64 bytes 0 in\n Compare.Uint64.(word <= stamp_threshold)\n\nlet check_header_proof_of_work_stamp shell contents stamp_threshold =\n let hash =\n Block_header.hash\n {shell; protocol_data = {contents; signature = Signature.zero}}\n in\n check_hash hash stamp_threshold\n\nlet check_proof_of_work_stamp ctxt block =\n let proof_of_work_threshold = Constants.proof_of_work_threshold ctxt in\n if\n check_header_proof_of_work_stamp\n block.Block_header.shell\n block.protocol_data.contents\n proof_of_work_threshold\n then ok_unit\n else error Invalid_stamp\n\nlet check_signature block chain_id key =\n let check_signature key\n {Block_header.shell; protocol_data = {contents; signature}} =\n let unsigned_header =\n Data_encoding.Binary.to_bytes_exn\n Block_header.unsigned_encoding\n (shell, contents)\n in\n Signature.check\n ~watermark:(Block_header chain_id)\n key\n signature\n unsigned_header\n in\n if check_signature key block then return_unit\n else\n fail\n (Invalid_block_signature\n (Block_header.hash block, Signature.Public_key.hash key))\n\nlet max_fitness_gap _ctxt = 1L\n\nlet check_fitness_gap ctxt (block : Block_header.t) =\n let current_fitness = Fitness.current ctxt in\n Fitness.to_int64 block.shell.fitness\n >>? fun announced_fitness ->\n let gap = Int64.sub announced_fitness current_fitness in\n if Compare.Int64.(gap <= 0L || max_fitness_gap ctxt < gap) then\n error (Invalid_fitness_gap (max_fitness_gap ctxt, gap))\n else ok_unit\n\nlet last_of_a_cycle ctxt (l : Level.t) =\n Compare.Int32.(\n Int32.succ l.Level.cycle_position = Constants.blocks_per_cycle ctxt)\n\nlet dawn_of_a_new_cycle ctxt =\n let level = Level.current ctxt in\n if last_of_a_cycle ctxt level then Some level.cycle else None\n\nlet minimum_allowed_endorsements ctxt ~block_delay =\n let minimum = Constants.initial_endorsers ctxt in\n let delay_per_missing_endorsement =\n Period.to_seconds (Constants.delay_per_missing_endorsement ctxt)\n in\n let reduced_time_constraint =\n let delay = Period.to_seconds block_delay in\n if Compare.Int64.(delay_per_missing_endorsement = 0L) then delay\n else Int64.div delay delay_per_missing_endorsement\n in\n if Compare.Int64.(Int64.of_int minimum < reduced_time_constraint) then 0\n else minimum - Int64.to_int reduced_time_constraint\n\nlet minimal_valid_time ctxt ~priority ~endorsing_power =\n let predecessor_timestamp = Timestamp.current ctxt in\n minimal_time ctxt priority predecessor_timestamp\n >>? fun minimal_time ->\n let minimal_required_endorsements = Constants.initial_endorsers ctxt in\n let delay_per_missing_endorsement =\n Constants.delay_per_missing_endorsement ctxt\n in\n let missing_endorsements =\n Compare.Int.max 0 (minimal_required_endorsements - endorsing_power)\n in\n Period.mult (Int32.of_int missing_endorsements) delay_per_missing_endorsement\n >|? fun delay -> Time.add minimal_time (Period.to_seconds delay)\n" ;
} ;
{ name = "Amendment" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(**\n Only delegates with at least one roll take part in the amendment procedure.\n It works as follows:\n - Proposal period: delegates can submit protocol amendment proposals using\n the proposal operation. At the end of a proposal period, the proposal with\n most supporters is selected and we move to a testing_vote period.\n If there are no proposals, or a tie between proposals, a new proposal\n period starts.\n - Testing_vote period: delegates can cast votes to test or not the winning\n proposal using the ballot operation.\n At the end of a testing_vote period if participation reaches the quorum\n and the proposal has a supermajority in favor, we proceed to a testing\n period. Otherwise we go back to a proposal period.\n In any case, if there is enough participation the quorum is updated.\n - Testing period: a test chain is forked for the length of the period.\n At the end of a testing period we move to a promotion_vote period.\n - Promotion_vote period: delegates can cast votes to promote or not the\n tested proposal using the ballot operation.\n At the end of a promotion_vote period if participation reaches the quorum\n and the tested proposal has a supermajority in favor, we move to\n an adoption period. Otherwise we go back to a proposal period.\n In any case, if there is enough participation the quorum is updated.\n - Adoption period: At the end of an adoption period, the proposal is activated\n as the new protocol.\n*)\n\nopen Alpha_context\n\n(** If at the end of a voting period, moves to the next one following\n the state machine of the amendment procedure. *)\nval may_start_new_voting_period : context -> context tzresult Lwt.t\n\ntype error +=\n | Unexpected_proposal\n | Unauthorized_proposal\n | Too_many_proposals\n | Empty_proposal\n\n(** Records a list of proposals for a delegate.\n @raise Unexpected_proposal if [ctxt] is not in a proposal period.\n @raise Unauthorized_proposal if [delegate] is not in the listing. *)\nval record_proposals :\n context -> public_key_hash -> Protocol_hash.t list -> context tzresult Lwt.t\n\ntype error += Invalid_proposal | Unexpected_ballot | Unauthorized_ballot\n\nval record_ballot :\n context ->\n public_key_hash ->\n Protocol_hash.t ->\n Vote.ballot ->\n context tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\n(** Returns the proposal submitted by the most delegates.\n Returns None in case of a tie, if proposal quorum is below required\n minimum or if there are no proposals. *)\nlet select_winning_proposal ctxt =\n Vote.get_proposals ctxt\n >>=? fun proposals ->\n let merge proposal vote winners =\n match winners with\n | None ->\n Some ([proposal], vote)\n | Some (winners, winners_vote) as previous ->\n if Compare.Int32.(vote = winners_vote) then\n Some (proposal :: winners, winners_vote)\n else if Compare.Int32.(vote > winners_vote) then Some ([proposal], vote)\n else previous\n in\n match Protocol_hash.Map.fold merge proposals None with\n | Some ([proposal], vote) ->\n Vote.listing_size ctxt\n >>=? fun max_vote ->\n let min_proposal_quorum = Constants.min_proposal_quorum ctxt in\n let min_vote_to_pass =\n Int32.div (Int32.mul min_proposal_quorum max_vote) 100_00l\n in\n if Compare.Int32.(vote >= min_vote_to_pass) then return_some proposal\n else return_none\n | _ ->\n return_none\n\n(* in case of a tie, let's do nothing. *)\n\n(** A proposal is approved if it has supermajority and the participation reaches\n the current quorum.\n Supermajority means the yays are more 8/10 of casted votes.\n The participation is the ratio of all received votes, including passes, with\n respect to the number of possible votes.\n The participation EMA (exponential moving average) uses the last\n participation EMA and the current participation./\n The expected quorum is calculated using the last participation EMA, capped\n by the min/max quorum protocol constants. *)\nlet approval_and_participation_ema (ballots : Vote.ballots) ~maximum_vote\n ~participation_ema ~expected_quorum =\n (* Note overflows: considering a maximum of 8e8 tokens, with roll size as\n small as 1e3, there is a maximum of 8e5 rolls and thus votes.\n In 'participation' an Int64 is used because in the worst case 'all_votes is\n 8e5 and after the multiplication is 8e9, making it potentially overflow a\n signed Int32 which is 2e9. *)\n let casted_votes = Int32.add ballots.yay ballots.nay in\n let all_votes = Int32.add casted_votes ballots.pass in\n let supermajority = Int32.div (Int32.mul 8l casted_votes) 10l in\n let participation =\n (* in centile of percentage *)\n Int64.(\n to_int32 (div (mul (of_int32 all_votes) 100_00L) (of_int32 maximum_vote)))\n in\n let approval =\n Compare.Int32.(\n participation >= expected_quorum && ballots.yay >= supermajority)\n in\n let new_participation_ema =\n Int32.(div (add (mul 8l participation_ema) (mul 2l participation)) 10l)\n in\n (approval, new_participation_ema)\n\nlet get_approval_and_update_participation_ema ctxt =\n Vote.get_ballots ctxt\n >>=? fun ballots ->\n Vote.listing_size ctxt\n >>=? fun maximum_vote ->\n Vote.get_participation_ema ctxt\n >>=? fun participation_ema ->\n Vote.get_current_quorum ctxt\n >>=? fun expected_quorum ->\n Vote.clear_ballots ctxt\n >>= fun ctxt ->\n let (approval, new_participation_ema) =\n approval_and_participation_ema\n ballots\n ~maximum_vote\n ~participation_ema\n ~expected_quorum\n in\n Vote.set_participation_ema ctxt new_participation_ema\n >|=? fun ctxt -> (ctxt, approval)\n\n(** Implements the state machine of the amendment procedure. Note that\n [update_listings], that computes the vote weight of each delegate, is run at\n the end of each voting period. This state-machine prepare the voting_period\n for the next block. *)\nlet start_new_voting_period ctxt =\n Voting_period.get_current_kind ctxt\n >>=? fun kind ->\n ( match kind with\n | Proposal -> (\n select_winning_proposal ctxt\n >>=? fun proposal ->\n Vote.clear_proposals ctxt\n >>= fun ctxt ->\n match proposal with\n | None ->\n Voting_period.reset ctxt\n | Some proposal ->\n Vote.init_current_proposal ctxt proposal >>=? Voting_period.succ )\n | Testing_vote ->\n get_approval_and_update_participation_ema ctxt\n >>=? fun (ctxt, approved) ->\n if approved then\n let expiration =\n Time.add\n (Timestamp.current ctxt)\n (Constants.test_chain_duration ctxt)\n in\n Vote.get_current_proposal ctxt\n >>=? fun proposal ->\n fork_test_chain ctxt proposal expiration >>= Voting_period.succ\n else\n Vote.clear_current_proposal ctxt\n >>=? fun ctxt -> Voting_period.reset ctxt\n | Testing ->\n Voting_period.succ ctxt\n | Promotion_vote ->\n get_approval_and_update_participation_ema ctxt\n >>=? fun (ctxt, approved) ->\n if approved then Voting_period.succ ctxt\n else Vote.clear_current_proposal ctxt >>=? Voting_period.reset\n | Adoption ->\n Vote.get_current_proposal ctxt\n >>=? fun proposal ->\n activate ctxt proposal\n >>= fun ctxt -> Vote.clear_current_proposal ctxt >>=? Voting_period.reset\n )\n >>=? fun ctxt -> Vote.update_listings ctxt\n\ntype error +=\n | (* `Branch *)\n Invalid_proposal\n | Unexpected_proposal\n | Unauthorized_proposal\n | Too_many_proposals\n | Empty_proposal\n | Unexpected_ballot\n | Unauthorized_ballot\n\nlet () =\n let open Data_encoding in\n (* Invalid proposal *)\n register_error_kind\n `Branch\n ~id:\"invalid_proposal\"\n ~title:\"Invalid proposal\"\n ~description:\"Ballot provided for a proposal that is not the current one.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Invalid proposal\")\n empty\n (function Invalid_proposal -> Some () | _ -> None)\n (fun () -> Invalid_proposal) ;\n (* Unexpected proposal *)\n register_error_kind\n `Branch\n ~id:\"unexpected_proposal\"\n ~title:\"Unexpected proposal\"\n ~description:\"Proposal recorded outside of a proposal period.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Unexpected proposal\")\n empty\n (function Unexpected_proposal -> Some () | _ -> None)\n (fun () -> Unexpected_proposal) ;\n (* Unauthorized proposal *)\n register_error_kind\n `Branch\n ~id:\"unauthorized_proposal\"\n ~title:\"Unauthorized proposal\"\n ~description:\n \"The delegate provided for the proposal is not in the voting listings.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Unauthorized proposal\")\n empty\n (function Unauthorized_proposal -> Some () | _ -> None)\n (fun () -> Unauthorized_proposal) ;\n (* Unexpected ballot *)\n register_error_kind\n `Branch\n ~id:\"unexpected_ballot\"\n ~title:\"Unexpected ballot\"\n ~description:\"Ballot recorded outside of a voting period.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Unexpected ballot\")\n empty\n (function Unexpected_ballot -> Some () | _ -> None)\n (fun () -> Unexpected_ballot) ;\n (* Unauthorized ballot *)\n register_error_kind\n `Branch\n ~id:\"unauthorized_ballot\"\n ~title:\"Unauthorized ballot\"\n ~description:\n \"The delegate provided for the ballot is not in the voting listings.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Unauthorized ballot\")\n empty\n (function Unauthorized_ballot -> Some () | _ -> None)\n (fun () -> Unauthorized_ballot) ;\n (* Too many proposals *)\n register_error_kind\n `Branch\n ~id:\"too_many_proposals\"\n ~title:\"Too many proposals\"\n ~description:\n \"The delegate reached the maximum number of allowed proposals.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Too many proposals\")\n empty\n (function Too_many_proposals -> Some () | _ -> None)\n (fun () -> Too_many_proposals) ;\n (* Empty proposal *)\n register_error_kind\n `Branch\n ~id:\"empty_proposal\"\n ~title:\"Empty proposal\"\n ~description:\"Proposal lists cannot be empty.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Empty proposal\")\n empty\n (function Empty_proposal -> Some () | _ -> None)\n (fun () -> Empty_proposal)\n\n(* @return [true] if [List.length l] > [n] w/o computing length *)\nlet rec longer_than l n =\n if Compare.Int.(n < 0) then assert false\n else\n match l with\n | [] ->\n false\n | _ :: rest ->\n if Compare.Int.(n = 0) then true\n else (* n > 0 *)\n longer_than rest (n - 1)\n\nlet record_proposals ctxt delegate proposals =\n (match proposals with [] -> error Empty_proposal | _ :: _ -> ok_unit)\n >>?= fun () ->\n Voting_period.get_current_kind ctxt\n >>=? function\n | Proposal ->\n Vote.in_listings ctxt delegate\n >>= fun in_listings ->\n if in_listings then\n Vote.recorded_proposal_count_for_delegate ctxt delegate\n >>=? fun count ->\n error_when\n (longer_than proposals (Constants.max_proposals_per_delegate - count))\n Too_many_proposals\n >>?= fun () ->\n fold_left_s\n (fun ctxt proposal -> Vote.record_proposal ctxt proposal delegate)\n ctxt\n proposals\n else fail Unauthorized_proposal\n | Testing_vote | Testing | Promotion_vote | Adoption ->\n fail Unexpected_proposal\n\nlet record_ballot ctxt delegate proposal ballot =\n Voting_period.get_current_kind ctxt\n >>=? function\n | Testing_vote | Promotion_vote ->\n Vote.get_current_proposal ctxt\n >>=? fun current_proposal ->\n error_unless\n (Protocol_hash.equal proposal current_proposal)\n Invalid_proposal\n >>?= fun () ->\n Vote.has_recorded_ballot ctxt delegate\n >>= fun has_ballot ->\n error_when has_ballot Unauthorized_ballot\n >>?= fun () ->\n Vote.in_listings ctxt delegate\n >>= fun in_listings ->\n if in_listings then Vote.record_ballot ctxt delegate ballot\n else fail Unauthorized_ballot\n | Testing | Proposal | Adoption ->\n fail Unexpected_ballot\n\nlet may_start_new_voting_period ctxt =\n Voting_period.is_last_block ctxt\n >>=? fun is_last ->\n if is_last then start_new_voting_period ctxt else return ctxt\n" ;
} ;
{ name = "Apply_results" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Result of applying an operation, can be used for experimenting\n with protocol updates, by clients to print out a summary of the\n operation at pre-injection simulation and at confirmation time,\n and by block explorers. *)\n\nopen Alpha_context\n\n(** Result of applying a {!Operation.t}. Follows the same structure. *)\ntype 'kind operation_metadata = {contents : 'kind contents_result_list}\n\nand packed_operation_metadata =\n | Operation_metadata : 'kind operation_metadata -> packed_operation_metadata\n | No_operation_metadata : packed_operation_metadata\n\n(** Result of applying a {!Operation.contents_list}. Follows the same structure. *)\nand 'kind contents_result_list =\n | Single_result : 'kind contents_result -> 'kind contents_result_list\n | Cons_result :\n 'kind Kind.manager contents_result\n * 'rest Kind.manager contents_result_list\n -> ('kind * 'rest) Kind.manager contents_result_list\n\nand packed_contents_result_list =\n | Contents_result_list :\n 'kind contents_result_list\n -> packed_contents_result_list\n\n(** Result of applying an {!Operation.contents}. Follows the same structure. *)\nand 'kind contents_result =\n | Endorsement_result : {\n balance_updates : Delegate.balance_updates;\n delegate : Signature.Public_key_hash.t;\n slots : int list;\n }\n -> Kind.endorsement contents_result\n | Seed_nonce_revelation_result :\n Delegate.balance_updates\n -> Kind.seed_nonce_revelation contents_result\n | Double_endorsement_evidence_result :\n Delegate.balance_updates\n -> Kind.double_endorsement_evidence contents_result\n | Double_baking_evidence_result :\n Delegate.balance_updates\n -> Kind.double_baking_evidence contents_result\n | Activate_account_result :\n Delegate.balance_updates\n -> Kind.activate_account contents_result\n | Proposals_result : Kind.proposals contents_result\n | Ballot_result : Kind.ballot contents_result\n | Manager_operation_result : {\n balance_updates : Delegate.balance_updates;\n operation_result : 'kind manager_operation_result;\n internal_operation_results : packed_internal_operation_result list;\n }\n -> 'kind Kind.manager contents_result\n\nand packed_contents_result =\n | Contents_result : 'kind contents_result -> packed_contents_result\n\n(** The result of an operation in the queue. [Skipped] ones should\n always be at the tail, and after a single [Failed]. *)\nand 'kind manager_operation_result =\n | Applied of 'kind successful_manager_operation_result\n | Backtracked of\n 'kind successful_manager_operation_result * error list option\n | Failed : 'kind Kind.manager * error list -> 'kind manager_operation_result\n | Skipped : 'kind Kind.manager -> 'kind manager_operation_result\n\n(** Result of applying a {!manager_operation_content}, either internal\n or external. *)\nand _ successful_manager_operation_result =\n | Reveal_result : {\n consumed_gas : Gas.Arith.fp;\n }\n -> Kind.reveal successful_manager_operation_result\n | Transaction_result : {\n storage : Script.expr option;\n lazy_storage_diff : Lazy_storage.diffs option;\n balance_updates : Delegate.balance_updates;\n originated_contracts : Contract.t list;\n consumed_gas : Gas.Arith.fp;\n storage_size : Z.t;\n paid_storage_size_diff : Z.t;\n allocated_destination_contract : bool;\n }\n -> Kind.transaction successful_manager_operation_result\n | Origination_result : {\n lazy_storage_diff : Lazy_storage.diffs option;\n balance_updates : Delegate.balance_updates;\n originated_contracts : Contract.t list;\n consumed_gas : Gas.Arith.fp;\n storage_size : Z.t;\n paid_storage_size_diff : Z.t;\n }\n -> Kind.origination successful_manager_operation_result\n | Delegation_result : {\n consumed_gas : Gas.Arith.fp;\n }\n -> Kind.delegation successful_manager_operation_result\n\nand packed_successful_manager_operation_result =\n | Successful_manager_result :\n 'kind successful_manager_operation_result\n -> packed_successful_manager_operation_result\n\nand packed_internal_operation_result =\n | Internal_operation_result :\n 'kind internal_operation * 'kind manager_operation_result\n -> packed_internal_operation_result\n\n(** Serializer for {!packed_operation_result}. *)\nval operation_metadata_encoding : packed_operation_metadata Data_encoding.t\n\nval operation_data_and_metadata_encoding :\n (Operation.packed_protocol_data * packed_operation_metadata) Data_encoding.t\n\ntype 'kind contents_and_result_list =\n | Single_and_result :\n 'kind Alpha_context.contents * 'kind contents_result\n -> 'kind contents_and_result_list\n | Cons_and_result :\n 'kind Kind.manager Alpha_context.contents\n * 'kind Kind.manager contents_result\n * 'rest Kind.manager contents_and_result_list\n -> ('kind * 'rest) Kind.manager contents_and_result_list\n\ntype packed_contents_and_result_list =\n | Contents_and_result_list :\n 'kind contents_and_result_list\n -> packed_contents_and_result_list\n\nval contents_and_result_list_encoding :\n packed_contents_and_result_list Data_encoding.t\n\nval pack_contents_list :\n 'kind contents_list ->\n 'kind contents_result_list ->\n 'kind contents_and_result_list\n\nval unpack_contents_list :\n 'kind contents_and_result_list ->\n 'kind contents_list * 'kind contents_result_list\n\nval to_list : packed_contents_result_list -> packed_contents_result list\n\nval of_list : packed_contents_result list -> packed_contents_result_list\n\ntype ('a, 'b) eq = Eq : ('a, 'a) eq\n\nval kind_equal_list :\n 'kind contents_list ->\n 'kind2 contents_result_list ->\n ('kind, 'kind2) eq option\n\ntype block_metadata = {\n baker : Signature.Public_key_hash.t;\n level : Level.compat_t;\n level_info : Level.t;\n voting_period_kind : Voting_period.kind;\n voting_period_info : Voting_period.info;\n nonce_hash : Nonce_hash.t option;\n consumed_gas : Gas.Arith.fp;\n deactivated : Signature.Public_key_hash.t list;\n balance_updates : Delegate.balance_updates;\n}\n\nval block_metadata_encoding : block_metadata Data_encoding.encoding\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\nopen Data_encoding\n\nlet error_encoding =\n def\n \"error\"\n ~description:\n \"The full list of RPC errors would be too long to include.\\n\\\n It is available at RPC `/errors` (GET).\\n\\\n Errors specific to protocol Alpha have an id that starts with \\\n `proto.alpha`.\"\n @@ splitted\n ~json:\n (conv\n (fun err ->\n Data_encoding.Json.construct Error_monad.error_encoding err)\n (fun json ->\n Data_encoding.Json.destruct Error_monad.error_encoding json)\n json)\n ~binary:Error_monad.error_encoding\n\ntype _ successful_manager_operation_result =\n | Reveal_result : {\n consumed_gas : Gas.Arith.fp;\n }\n -> Kind.reveal successful_manager_operation_result\n | Transaction_result : {\n storage : Script.expr option;\n lazy_storage_diff : Lazy_storage.diffs option;\n balance_updates : Delegate.balance_updates;\n originated_contracts : Contract.t list;\n consumed_gas : Gas.Arith.fp;\n storage_size : Z.t;\n paid_storage_size_diff : Z.t;\n allocated_destination_contract : bool;\n }\n -> Kind.transaction successful_manager_operation_result\n | Origination_result : {\n lazy_storage_diff : Lazy_storage.diffs option;\n balance_updates : Delegate.balance_updates;\n originated_contracts : Contract.t list;\n consumed_gas : Gas.Arith.fp;\n storage_size : Z.t;\n paid_storage_size_diff : Z.t;\n }\n -> Kind.origination successful_manager_operation_result\n | Delegation_result : {\n consumed_gas : Gas.Arith.fp;\n }\n -> Kind.delegation successful_manager_operation_result\n\ntype packed_successful_manager_operation_result =\n | Successful_manager_result :\n 'kind successful_manager_operation_result\n -> packed_successful_manager_operation_result\n\ntype 'kind manager_operation_result =\n | Applied of 'kind successful_manager_operation_result\n | Backtracked of\n 'kind successful_manager_operation_result * error list option\n | Failed : 'kind Kind.manager * error list -> 'kind manager_operation_result\n | Skipped : 'kind Kind.manager -> 'kind manager_operation_result\n\ntype packed_internal_operation_result =\n | Internal_operation_result :\n 'kind internal_operation * 'kind manager_operation_result\n -> packed_internal_operation_result\n\nmodule Manager_result = struct\n type 'kind case =\n | MCase : {\n op_case : 'kind Operation.Encoding.Manager_operations.case;\n encoding : 'a Data_encoding.t;\n kind : 'kind Kind.manager;\n iselect :\n packed_internal_operation_result ->\n ('kind internal_operation * 'kind manager_operation_result) option;\n select :\n packed_successful_manager_operation_result ->\n 'kind successful_manager_operation_result option;\n proj : 'kind successful_manager_operation_result -> 'a;\n inj : 'a -> 'kind successful_manager_operation_result;\n t : 'kind manager_operation_result Data_encoding.t;\n }\n -> 'kind case\n\n let make ~op_case ~encoding ~kind ~iselect ~select ~proj ~inj =\n let (Operation.Encoding.Manager_operations.MCase {name; _}) = op_case in\n let t =\n def (Format.asprintf \"operation.alpha.operation_result.%s\" name)\n @@ union\n ~tag_size:`Uint8\n [ case\n (Tag 0)\n ~title:\"Applied\"\n (merge_objs (obj1 (req \"status\" (constant \"applied\"))) encoding)\n (fun o ->\n match o with\n | Skipped _ | Failed _ | Backtracked _ ->\n None\n | Applied o -> (\n match select (Successful_manager_result o) with\n | None ->\n None\n | Some o ->\n Some ((), proj o) ))\n (fun ((), x) -> Applied (inj x));\n case\n (Tag 1)\n ~title:\"Failed\"\n (obj2\n (req \"status\" (constant \"failed\"))\n (req \"errors\" (list error_encoding)))\n (function Failed (_, errs) -> Some ((), errs) | _ -> None)\n (fun ((), errs) -> Failed (kind, errs));\n case\n (Tag 2)\n ~title:\"Skipped\"\n (obj1 (req \"status\" (constant \"skipped\")))\n (function Skipped _ -> Some () | _ -> None)\n (fun () -> Skipped kind);\n case\n (Tag 3)\n ~title:\"Backtracked\"\n (merge_objs\n (obj2\n (req \"status\" (constant \"backtracked\"))\n (opt \"errors\" (list error_encoding)))\n encoding)\n (fun o ->\n match o with\n | Skipped _ | Failed _ | Applied _ ->\n None\n | Backtracked (o, errs) -> (\n match select (Successful_manager_result o) with\n | None ->\n None\n | Some o ->\n Some (((), errs), proj o) ))\n (fun (((), errs), x) -> Backtracked (inj x, errs)) ]\n in\n MCase {op_case; encoding; kind; iselect; select; proj; inj; t}\n\n let reveal_case =\n make\n ~op_case:Operation.Encoding.Manager_operations.reveal_case\n ~encoding:\n Data_encoding.(\n obj2\n (dft \"consumed_gas\" Gas.Arith.n_integral_encoding Gas.Arith.zero)\n (dft \"consumed_milligas\" Gas.Arith.n_fp_encoding Gas.Arith.zero))\n ~iselect:(function\n | Internal_operation_result (({operation = Reveal _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\n ~select:(function\n | Successful_manager_result (Reveal_result _ as op) ->\n Some op\n | _ ->\n None)\n ~kind:Kind.Reveal_manager_kind\n ~proj:(function\n | Reveal_result {consumed_gas} ->\n (Gas.Arith.ceil consumed_gas, consumed_gas))\n ~inj:(fun (consumed_gas, consumed_milligas) ->\n assert (Gas.Arith.(equal (ceil consumed_milligas) consumed_gas)) ;\n Reveal_result {consumed_gas = consumed_milligas})\n\n let transaction_case =\n make\n ~op_case:Operation.Encoding.Manager_operations.transaction_case\n ~encoding:\n (obj10\n (opt \"storage\" Script.expr_encoding)\n (opt\n (* The field [big_map_diff] is deprecated since 008, use [lazy_storage_diff] instead.\n Is it kept here for a transition period, for tool like indexers to update.\n TODO(009): remove it. *)\n \"big_map_diff\"\n Lazy_storage.legacy_big_map_diff_encoding)\n (dft \"balance_updates\" Delegate.balance_updates_encoding [])\n (dft \"originated_contracts\" (list Contract.encoding) [])\n (dft \"consumed_gas\" Gas.Arith.n_integral_encoding Gas.Arith.zero)\n (dft \"consumed_milligas\" Gas.Arith.n_fp_encoding Gas.Arith.zero)\n (dft \"storage_size\" z Z.zero)\n (dft \"paid_storage_size_diff\" z Z.zero)\n (dft \"allocated_destination_contract\" bool false)\n (opt \"lazy_storage_diff\" Lazy_storage.encoding))\n ~iselect:(function\n | Internal_operation_result\n (({operation = Transaction _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\n ~select:(function\n | Successful_manager_result (Transaction_result _ as op) ->\n Some op\n | _ ->\n None)\n ~kind:Kind.Transaction_manager_kind\n ~proj:(function\n | Transaction_result\n { storage;\n lazy_storage_diff;\n balance_updates;\n originated_contracts;\n consumed_gas;\n storage_size;\n paid_storage_size_diff;\n allocated_destination_contract } ->\n ( storage,\n lazy_storage_diff,\n balance_updates,\n originated_contracts,\n Gas.Arith.ceil consumed_gas,\n consumed_gas,\n storage_size,\n paid_storage_size_diff,\n allocated_destination_contract,\n lazy_storage_diff ))\n ~inj:\n (fun ( storage,\n legacy_lazy_storage_diff,\n balance_updates,\n originated_contracts,\n consumed_gas,\n consumed_milligas,\n storage_size,\n paid_storage_size_diff,\n allocated_destination_contract,\n lazy_storage_diff ) ->\n assert (Gas.Arith.(equal (ceil consumed_milligas) consumed_gas)) ;\n let lazy_storage_diff =\n Option.first_some lazy_storage_diff legacy_lazy_storage_diff\n in\n Transaction_result\n {\n storage;\n lazy_storage_diff;\n balance_updates;\n originated_contracts;\n consumed_gas = consumed_milligas;\n storage_size;\n paid_storage_size_diff;\n allocated_destination_contract;\n })\n\n let origination_case =\n make\n ~op_case:Operation.Encoding.Manager_operations.origination_case\n ~encoding:\n (obj8\n (opt\n (* The field [big_map_diff] is deprecated since 008, use [lazy_storage_diff] instead.\n Is it kept here for a transition period, for tool like indexers to update.\n TODO(009): remove it. *)\n \"big_map_diff\"\n Lazy_storage.legacy_big_map_diff_encoding)\n (dft \"balance_updates\" Delegate.balance_updates_encoding [])\n (dft \"originated_contracts\" (list Contract.encoding) [])\n (dft \"consumed_gas\" Gas.Arith.n_integral_encoding Gas.Arith.zero)\n (dft \"consumed_milligas\" Gas.Arith.n_fp_encoding Gas.Arith.zero)\n (dft \"storage_size\" z Z.zero)\n (dft \"paid_storage_size_diff\" z Z.zero)\n (opt \"lazy_storage_diff\" Lazy_storage.encoding))\n ~iselect:(function\n | Internal_operation_result\n (({operation = Origination _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\n ~select:(function\n | Successful_manager_result (Origination_result _ as op) ->\n Some op\n | _ ->\n None)\n ~proj:(function\n | Origination_result\n { lazy_storage_diff;\n balance_updates;\n originated_contracts;\n consumed_gas;\n storage_size;\n paid_storage_size_diff } ->\n ( lazy_storage_diff,\n balance_updates,\n originated_contracts,\n Gas.Arith.ceil consumed_gas,\n consumed_gas,\n storage_size,\n paid_storage_size_diff,\n lazy_storage_diff ))\n ~kind:Kind.Origination_manager_kind\n ~inj:\n (fun ( legacy_lazy_storage_diff,\n balance_updates,\n originated_contracts,\n consumed_gas,\n consumed_milligas,\n storage_size,\n paid_storage_size_diff,\n lazy_storage_diff ) ->\n assert (Gas.Arith.(equal (ceil consumed_milligas) consumed_gas)) ;\n let lazy_storage_diff =\n Option.first_some lazy_storage_diff legacy_lazy_storage_diff\n in\n Origination_result\n {\n lazy_storage_diff;\n balance_updates;\n originated_contracts;\n consumed_gas = consumed_milligas;\n storage_size;\n paid_storage_size_diff;\n })\n\n let delegation_case =\n make\n ~op_case:Operation.Encoding.Manager_operations.delegation_case\n ~encoding:\n Data_encoding.(\n obj2\n (dft \"consumed_gas\" Gas.Arith.n_integral_encoding Gas.Arith.zero)\n (dft \"consumed_milligas\" Gas.Arith.n_fp_encoding Gas.Arith.zero))\n ~iselect:(function\n | Internal_operation_result (({operation = Delegation _; _} as op), res)\n ->\n Some (op, res)\n | _ ->\n None)\n ~select:(function\n | Successful_manager_result (Delegation_result _ as op) ->\n Some op\n | _ ->\n None)\n ~kind:Kind.Delegation_manager_kind\n ~proj:(function\n | Delegation_result {consumed_gas} ->\n (Gas.Arith.ceil consumed_gas, consumed_gas))\n ~inj:(fun (consumed_gas, consumed_milligas) ->\n assert (Gas.Arith.(equal (ceil consumed_milligas) consumed_gas)) ;\n Delegation_result {consumed_gas = consumed_milligas})\nend\n\nlet internal_operation_result_encoding :\n packed_internal_operation_result Data_encoding.t =\n let make (type kind)\n (Manager_result.MCase res_case : kind Manager_result.case) =\n let (Operation.Encoding.Manager_operations.MCase op_case) =\n res_case.op_case\n in\n case\n (Tag op_case.tag)\n ~title:op_case.name\n (merge_objs\n (obj3\n (req \"kind\" (constant op_case.name))\n (req \"source\" Contract.encoding)\n (req \"nonce\" uint16))\n (merge_objs op_case.encoding (obj1 (req \"result\" res_case.t))))\n (fun op ->\n match res_case.iselect op with\n | Some (op, res) ->\n Some (((), op.source, op.nonce), (op_case.proj op.operation, res))\n | None ->\n None)\n (fun (((), source, nonce), (op, res)) ->\n let op = {source; operation = op_case.inj op; nonce} in\n Internal_operation_result (op, res))\n in\n def \"operation.alpha.internal_operation_result\"\n @@ union\n [ make Manager_result.reveal_case;\n make Manager_result.transaction_case;\n make Manager_result.origination_case;\n make Manager_result.delegation_case ]\n\ntype 'kind contents_result =\n | Endorsement_result : {\n balance_updates : Delegate.balance_updates;\n delegate : Signature.Public_key_hash.t;\n slots : int list;\n }\n -> Kind.endorsement contents_result\n | Seed_nonce_revelation_result :\n Delegate.balance_updates\n -> Kind.seed_nonce_revelation contents_result\n | Double_endorsement_evidence_result :\n Delegate.balance_updates\n -> Kind.double_endorsement_evidence contents_result\n | Double_baking_evidence_result :\n Delegate.balance_updates\n -> Kind.double_baking_evidence contents_result\n | Activate_account_result :\n Delegate.balance_updates\n -> Kind.activate_account contents_result\n | Proposals_result : Kind.proposals contents_result\n | Ballot_result : Kind.ballot contents_result\n | Manager_operation_result : {\n balance_updates : Delegate.balance_updates;\n operation_result : 'kind manager_operation_result;\n internal_operation_results : packed_internal_operation_result list;\n }\n -> 'kind Kind.manager contents_result\n\ntype packed_contents_result =\n | Contents_result : 'kind contents_result -> packed_contents_result\n\ntype packed_contents_and_result =\n | Contents_and_result :\n 'kind Operation.contents * 'kind contents_result\n -> packed_contents_and_result\n\ntype ('a, 'b) eq = Eq : ('a, 'a) eq\n\nlet equal_manager_kind :\n type a b. a Kind.manager -> b Kind.manager -> (a, b) eq option =\n fun ka kb ->\n match (ka, kb) with\n | (Kind.Reveal_manager_kind, Kind.Reveal_manager_kind) ->\n Some Eq\n | (Kind.Reveal_manager_kind, _) ->\n None\n | (Kind.Transaction_manager_kind, Kind.Transaction_manager_kind) ->\n Some Eq\n | (Kind.Transaction_manager_kind, _) ->\n None\n | (Kind.Origination_manager_kind, Kind.Origination_manager_kind) ->\n Some Eq\n | (Kind.Origination_manager_kind, _) ->\n None\n | (Kind.Delegation_manager_kind, Kind.Delegation_manager_kind) ->\n Some Eq\n | (Kind.Delegation_manager_kind, _) ->\n None\n\nmodule Encoding = struct\n type 'kind case =\n | Case : {\n op_case : 'kind Operation.Encoding.case;\n encoding : 'a Data_encoding.t;\n select : packed_contents_result -> 'kind contents_result option;\n mselect :\n packed_contents_and_result ->\n ('kind contents * 'kind contents_result) option;\n proj : 'kind contents_result -> 'a;\n inj : 'a -> 'kind contents_result;\n }\n -> 'kind case\n\n let tagged_case tag name args proj inj =\n let open Data_encoding in\n case\n tag\n ~title:(String.capitalize_ascii name)\n (merge_objs (obj1 (req \"kind\" (constant name))) args)\n (fun x -> match proj x with None -> None | Some x -> Some ((), x))\n (fun ((), x) -> inj x)\n\n let endorsement_case =\n Case\n {\n op_case = Operation.Encoding.endorsement_case;\n encoding =\n obj3\n (req \"balance_updates\" Delegate.balance_updates_encoding)\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"slots\" (list uint8));\n select =\n (function\n | Contents_result (Endorsement_result _ as op) -> Some op | _ -> None);\n mselect =\n (function\n | Contents_and_result ((Endorsement _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj =\n (function\n | Endorsement_result {balance_updates; delegate; slots} ->\n (balance_updates, delegate, slots));\n inj =\n (fun (balance_updates, delegate, slots) ->\n Endorsement_result {balance_updates; delegate; slots});\n }\n\n let seed_nonce_revelation_case =\n Case\n {\n op_case = Operation.Encoding.seed_nonce_revelation_case;\n encoding =\n obj1 (req \"balance_updates\" Delegate.balance_updates_encoding);\n select =\n (function\n | Contents_result (Seed_nonce_revelation_result _ as op) ->\n Some op\n | _ ->\n None);\n mselect =\n (function\n | Contents_and_result ((Seed_nonce_revelation _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj = (fun (Seed_nonce_revelation_result bus) -> bus);\n inj = (fun bus -> Seed_nonce_revelation_result bus);\n }\n\n let double_endorsement_evidence_case =\n Case\n {\n op_case = Operation.Encoding.double_endorsement_evidence_case;\n encoding =\n obj1 (req \"balance_updates\" Delegate.balance_updates_encoding);\n select =\n (function\n | Contents_result (Double_endorsement_evidence_result _ as op) ->\n Some op\n | _ ->\n None);\n mselect =\n (function\n | Contents_and_result ((Double_endorsement_evidence _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj = (fun (Double_endorsement_evidence_result bus) -> bus);\n inj = (fun bus -> Double_endorsement_evidence_result bus);\n }\n\n let double_baking_evidence_case =\n Case\n {\n op_case = Operation.Encoding.double_baking_evidence_case;\n encoding =\n obj1 (req \"balance_updates\" Delegate.balance_updates_encoding);\n select =\n (function\n | Contents_result (Double_baking_evidence_result _ as op) ->\n Some op\n | _ ->\n None);\n mselect =\n (function\n | Contents_and_result ((Double_baking_evidence _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj = (fun (Double_baking_evidence_result bus) -> bus);\n inj = (fun bus -> Double_baking_evidence_result bus);\n }\n\n let activate_account_case =\n Case\n {\n op_case = Operation.Encoding.activate_account_case;\n encoding =\n obj1 (req \"balance_updates\" Delegate.balance_updates_encoding);\n select =\n (function\n | Contents_result (Activate_account_result _ as op) ->\n Some op\n | _ ->\n None);\n mselect =\n (function\n | Contents_and_result ((Activate_account _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj = (fun (Activate_account_result bus) -> bus);\n inj = (fun bus -> Activate_account_result bus);\n }\n\n let proposals_case =\n Case\n {\n op_case = Operation.Encoding.proposals_case;\n encoding = Data_encoding.empty;\n select =\n (function\n | Contents_result (Proposals_result as op) -> Some op | _ -> None);\n mselect =\n (function\n | Contents_and_result ((Proposals _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj = (fun Proposals_result -> ());\n inj = (fun () -> Proposals_result);\n }\n\n let ballot_case =\n Case\n {\n op_case = Operation.Encoding.ballot_case;\n encoding = Data_encoding.empty;\n select =\n (function\n | Contents_result (Ballot_result as op) -> Some op | _ -> None);\n mselect =\n (function\n | Contents_and_result ((Ballot _ as op), res) ->\n Some (op, res)\n | _ ->\n None);\n proj = (fun Ballot_result -> ());\n inj = (fun () -> Ballot_result);\n }\n\n let make_manager_case (type kind)\n (Operation.Encoding.Case op_case :\n kind Kind.manager Operation.Encoding.case)\n (Manager_result.MCase res_case : kind Manager_result.case) mselect =\n Case\n {\n op_case = Operation.Encoding.Case op_case;\n encoding =\n obj3\n (req \"balance_updates\" Delegate.balance_updates_encoding)\n (req \"operation_result\" res_case.t)\n (dft\n \"internal_operation_results\"\n (list internal_operation_result_encoding)\n []);\n select =\n (function\n | Contents_result\n (Manager_operation_result\n ({operation_result = Applied res; _} as op)) -> (\n match res_case.select (Successful_manager_result res) with\n | Some res ->\n Some\n (Manager_operation_result\n {op with operation_result = Applied res})\n | None ->\n None )\n | Contents_result\n (Manager_operation_result\n ({operation_result = Backtracked (res, errs); _} as op)) -> (\n match res_case.select (Successful_manager_result res) with\n | Some res ->\n Some\n (Manager_operation_result\n {op with operation_result = Backtracked (res, errs)})\n | None ->\n None )\n | Contents_result\n (Manager_operation_result\n ({operation_result = Skipped kind; _} as op)) -> (\n match equal_manager_kind kind res_case.kind with\n | None ->\n None\n | Some Eq ->\n Some\n (Manager_operation_result\n {op with operation_result = Skipped kind}) )\n | Contents_result\n (Manager_operation_result\n ({operation_result = Failed (kind, errs); _} as op)) -> (\n match equal_manager_kind kind res_case.kind with\n | None ->\n None\n | Some Eq ->\n Some\n (Manager_operation_result\n {op with operation_result = Failed (kind, errs)}) )\n | Contents_result Ballot_result ->\n None\n | Contents_result (Endorsement_result _) ->\n None\n | Contents_result (Seed_nonce_revelation_result _) ->\n None\n | Contents_result (Double_endorsement_evidence_result _) ->\n None\n | Contents_result (Double_baking_evidence_result _) ->\n None\n | Contents_result (Activate_account_result _) ->\n None\n | Contents_result Proposals_result ->\n None);\n mselect;\n proj =\n (fun (Manager_operation_result\n { balance_updates = bus;\n operation_result = r;\n internal_operation_results = rs }) ->\n (bus, r, rs));\n inj =\n (fun (bus, r, rs) ->\n Manager_operation_result\n {\n balance_updates = bus;\n operation_result = r;\n internal_operation_results = rs;\n });\n }\n\n let reveal_case =\n make_manager_case\n Operation.Encoding.reveal_case\n Manager_result.reveal_case\n (function\n | Contents_and_result\n ((Manager_operation {operation = Reveal _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\n\n let transaction_case =\n make_manager_case\n Operation.Encoding.transaction_case\n Manager_result.transaction_case\n (function\n | Contents_and_result\n ((Manager_operation {operation = Transaction _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\n\n let origination_case =\n make_manager_case\n Operation.Encoding.origination_case\n Manager_result.origination_case\n (function\n | Contents_and_result\n ((Manager_operation {operation = Origination _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\n\n let delegation_case =\n make_manager_case\n Operation.Encoding.delegation_case\n Manager_result.delegation_case\n (function\n | Contents_and_result\n ((Manager_operation {operation = Delegation _; _} as op), res) ->\n Some (op, res)\n | _ ->\n None)\nend\n\nlet contents_result_encoding =\n let open Encoding in\n let make\n (Case\n { op_case = Operation.Encoding.Case {tag; name; _};\n encoding;\n mselect = _;\n select;\n proj;\n inj }) =\n let proj x =\n match select x with None -> None | Some x -> Some (proj x)\n in\n let inj x = Contents_result (inj x) in\n tagged_case (Tag tag) name encoding proj inj\n in\n def \"operation.alpha.contents_result\"\n @@ union\n [ make endorsement_case;\n make seed_nonce_revelation_case;\n make double_endorsement_evidence_case;\n make double_baking_evidence_case;\n make activate_account_case;\n make proposals_case;\n make ballot_case;\n make reveal_case;\n make transaction_case;\n make origination_case;\n make delegation_case ]\n\nlet contents_and_result_encoding =\n let open Encoding in\n let make\n (Case\n { op_case = Operation.Encoding.Case {tag; name; encoding; proj; inj; _};\n mselect;\n encoding = meta_encoding;\n proj = meta_proj;\n inj = meta_inj;\n _ }) =\n let proj c =\n match mselect c with\n | Some (op, res) ->\n Some (proj op, meta_proj res)\n | _ ->\n None\n in\n let inj (op, res) = Contents_and_result (inj op, meta_inj res) in\n let encoding = merge_objs encoding (obj1 (req \"metadata\" meta_encoding)) in\n tagged_case (Tag tag) name encoding proj inj\n in\n def \"operation.alpha.operation_contents_and_result\"\n @@ union\n [ make endorsement_case;\n make seed_nonce_revelation_case;\n make double_endorsement_evidence_case;\n make double_baking_evidence_case;\n make activate_account_case;\n make proposals_case;\n make ballot_case;\n make reveal_case;\n make transaction_case;\n make origination_case;\n make delegation_case ]\n\ntype 'kind contents_result_list =\n | Single_result : 'kind contents_result -> 'kind contents_result_list\n | Cons_result :\n 'kind Kind.manager contents_result\n * 'rest Kind.manager contents_result_list\n -> ('kind * 'rest) Kind.manager contents_result_list\n\ntype packed_contents_result_list =\n | Contents_result_list :\n 'kind contents_result_list\n -> packed_contents_result_list\n\nlet contents_result_list_encoding =\n let rec to_list = function\n | Contents_result_list (Single_result o) ->\n [Contents_result o]\n | Contents_result_list (Cons_result (o, os)) ->\n Contents_result o :: to_list (Contents_result_list os)\n in\n let rec of_list = function\n | [] ->\n Pervasives.failwith \"cannot decode empty operation result\"\n | [Contents_result o] ->\n Contents_result_list (Single_result o)\n | Contents_result o :: os -> (\n let (Contents_result_list os) = of_list os in\n match (o, os) with\n | ( Manager_operation_result _,\n Single_result (Manager_operation_result _) ) ->\n Contents_result_list (Cons_result (o, os))\n | (Manager_operation_result _, Cons_result _) ->\n Contents_result_list (Cons_result (o, os))\n | _ ->\n Pervasives.failwith \"cannot decode ill-formed operation result\" )\n in\n def \"operation.alpha.contents_list_result\"\n @@ conv to_list of_list (list contents_result_encoding)\n\ntype 'kind contents_and_result_list =\n | Single_and_result :\n 'kind Alpha_context.contents * 'kind contents_result\n -> 'kind contents_and_result_list\n | Cons_and_result :\n 'kind Kind.manager Alpha_context.contents\n * 'kind Kind.manager contents_result\n * 'rest Kind.manager contents_and_result_list\n -> ('kind * 'rest) Kind.manager contents_and_result_list\n\ntype packed_contents_and_result_list =\n | Contents_and_result_list :\n 'kind contents_and_result_list\n -> packed_contents_and_result_list\n\nlet contents_and_result_list_encoding =\n let rec to_list = function\n | Contents_and_result_list (Single_and_result (op, res)) ->\n [Contents_and_result (op, res)]\n | Contents_and_result_list (Cons_and_result (op, res, rest)) ->\n Contents_and_result (op, res)\n :: to_list (Contents_and_result_list rest)\n in\n let rec of_list = function\n | [] ->\n Pervasives.failwith \"cannot decode empty combined operation result\"\n | [Contents_and_result (op, res)] ->\n Contents_and_result_list (Single_and_result (op, res))\n | Contents_and_result (op, res) :: rest -> (\n let (Contents_and_result_list rest) = of_list rest in\n match (op, rest) with\n | (Manager_operation _, Single_and_result (Manager_operation _, _)) ->\n Contents_and_result_list (Cons_and_result (op, res, rest))\n | (Manager_operation _, Cons_and_result (_, _, _)) ->\n Contents_and_result_list (Cons_and_result (op, res, rest))\n | _ ->\n Pervasives.failwith\n \"cannot decode ill-formed combined operation result\" )\n in\n conv to_list of_list (Variable.list contents_and_result_encoding)\n\ntype 'kind operation_metadata = {contents : 'kind contents_result_list}\n\ntype packed_operation_metadata =\n | Operation_metadata : 'kind operation_metadata -> packed_operation_metadata\n | No_operation_metadata : packed_operation_metadata\n\nlet operation_metadata_encoding =\n def \"operation.alpha.result\"\n @@ union\n [ case\n (Tag 0)\n ~title:\"Operation_metadata\"\n contents_result_list_encoding\n (function\n | Operation_metadata {contents} ->\n Some (Contents_result_list contents)\n | _ ->\n None)\n (fun (Contents_result_list contents) ->\n Operation_metadata {contents});\n case\n (Tag 1)\n ~title:\"No_operation_metadata\"\n empty\n (function No_operation_metadata -> Some () | _ -> None)\n (fun () -> No_operation_metadata) ]\n\nlet kind_equal :\n type kind kind2.\n kind contents -> kind2 contents_result -> (kind, kind2) eq option =\n fun op res ->\n match (op, res) with\n | (Endorsement _, Endorsement_result _) ->\n Some Eq\n | (Endorsement _, _) ->\n None\n | (Seed_nonce_revelation _, Seed_nonce_revelation_result _) ->\n Some Eq\n | (Seed_nonce_revelation _, _) ->\n None\n | (Double_endorsement_evidence _, Double_endorsement_evidence_result _) ->\n Some Eq\n | (Double_endorsement_evidence _, _) ->\n None\n | (Double_baking_evidence _, Double_baking_evidence_result _) ->\n Some Eq\n | (Double_baking_evidence _, _) ->\n None\n | (Activate_account _, Activate_account_result _) ->\n Some Eq\n | (Activate_account _, _) ->\n None\n | (Proposals _, Proposals_result) ->\n Some Eq\n | (Proposals _, _) ->\n None\n | (Ballot _, Ballot_result) ->\n Some Eq\n | (Ballot _, _) ->\n None\n | ( Manager_operation {operation = Reveal _; _},\n Manager_operation_result {operation_result = Applied (Reveal_result _); _}\n ) ->\n Some Eq\n | ( Manager_operation {operation = Reveal _; _},\n Manager_operation_result\n {operation_result = Backtracked (Reveal_result _, _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Reveal _; _},\n Manager_operation_result\n { operation_result = Failed (Alpha_context.Kind.Reveal_manager_kind, _);\n _ } ) ->\n Some Eq\n | ( Manager_operation {operation = Reveal _; _},\n Manager_operation_result\n {operation_result = Skipped Alpha_context.Kind.Reveal_manager_kind; _}\n ) ->\n Some Eq\n | (Manager_operation {operation = Reveal _; _}, _) ->\n None\n | ( Manager_operation {operation = Transaction _; _},\n Manager_operation_result\n {operation_result = Applied (Transaction_result _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Transaction _; _},\n Manager_operation_result\n {operation_result = Backtracked (Transaction_result _, _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Transaction _; _},\n Manager_operation_result\n { operation_result =\n Failed (Alpha_context.Kind.Transaction_manager_kind, _);\n _ } ) ->\n Some Eq\n | ( Manager_operation {operation = Transaction _; _},\n Manager_operation_result\n { operation_result = Skipped Alpha_context.Kind.Transaction_manager_kind;\n _ } ) ->\n Some Eq\n | (Manager_operation {operation = Transaction _; _}, _) ->\n None\n | ( Manager_operation {operation = Origination _; _},\n Manager_operation_result\n {operation_result = Applied (Origination_result _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Origination _; _},\n Manager_operation_result\n {operation_result = Backtracked (Origination_result _, _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Origination _; _},\n Manager_operation_result\n { operation_result =\n Failed (Alpha_context.Kind.Origination_manager_kind, _);\n _ } ) ->\n Some Eq\n | ( Manager_operation {operation = Origination _; _},\n Manager_operation_result\n { operation_result = Skipped Alpha_context.Kind.Origination_manager_kind;\n _ } ) ->\n Some Eq\n | (Manager_operation {operation = Origination _; _}, _) ->\n None\n | ( Manager_operation {operation = Delegation _; _},\n Manager_operation_result\n {operation_result = Applied (Delegation_result _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Delegation _; _},\n Manager_operation_result\n {operation_result = Backtracked (Delegation_result _, _); _} ) ->\n Some Eq\n | ( Manager_operation {operation = Delegation _; _},\n Manager_operation_result\n { operation_result =\n Failed (Alpha_context.Kind.Delegation_manager_kind, _);\n _ } ) ->\n Some Eq\n | ( Manager_operation {operation = Delegation _; _},\n Manager_operation_result\n { operation_result = Skipped Alpha_context.Kind.Delegation_manager_kind;\n _ } ) ->\n Some Eq\n | (Manager_operation {operation = Delegation _; _}, _) ->\n None\n\nlet rec kind_equal_list :\n type kind kind2.\n kind contents_list -> kind2 contents_result_list -> (kind, kind2) eq option\n =\n fun contents res ->\n match (contents, res) with\n | (Single op, Single_result res) -> (\n match kind_equal op res with None -> None | Some Eq -> Some Eq )\n | (Cons (op, ops), Cons_result (res, ress)) -> (\n match kind_equal op res with\n | None ->\n None\n | Some Eq -> (\n match kind_equal_list ops ress with None -> None | Some Eq -> Some Eq ) )\n | _ ->\n None\n\nlet rec pack_contents_list :\n type kind.\n kind contents_list ->\n kind contents_result_list ->\n kind contents_and_result_list =\n fun contents res ->\n match (contents, res) with\n | (Single op, Single_result res) ->\n Single_and_result (op, res)\n | (Cons (op, ops), Cons_result (res, ress)) ->\n Cons_and_result (op, res, pack_contents_list ops ress)\n | ( Single (Manager_operation _),\n Cons_result (Manager_operation_result _, Single_result _) ) ->\n .\n | ( Cons (_, _),\n Single_result (Manager_operation_result {operation_result = Failed _; _})\n ) ->\n .\n | ( Cons (_, _),\n Single_result\n (Manager_operation_result {operation_result = Skipped _; _}) ) ->\n .\n | ( Cons (_, _),\n Single_result\n (Manager_operation_result {operation_result = Applied _; _}) ) ->\n .\n | ( Cons (_, _),\n Single_result\n (Manager_operation_result {operation_result = Backtracked _; _}) ) ->\n .\n | (Single _, Cons_result _) ->\n .\n\nlet rec unpack_contents_list :\n type kind.\n kind contents_and_result_list ->\n kind contents_list * kind contents_result_list = function\n | Single_and_result (op, res) ->\n (Single op, Single_result res)\n | Cons_and_result (op, res, rest) ->\n let (ops, ress) = unpack_contents_list rest in\n (Cons (op, ops), Cons_result (res, ress))\n\nlet rec to_list = function\n | Contents_result_list (Single_result o) ->\n [Contents_result o]\n | Contents_result_list (Cons_result (o, os)) ->\n Contents_result o :: to_list (Contents_result_list os)\n\nlet rec of_list = function\n | [] ->\n assert false\n | [Contents_result o] ->\n Contents_result_list (Single_result o)\n | Contents_result o :: os -> (\n let (Contents_result_list os) = of_list os in\n match (o, os) with\n | (Manager_operation_result _, Single_result (Manager_operation_result _))\n ->\n Contents_result_list (Cons_result (o, os))\n | (Manager_operation_result _, Cons_result _) ->\n Contents_result_list (Cons_result (o, os))\n | _ ->\n Pervasives.failwith\n \"Operation result list of length > 1 should only contains manager \\\n operations result.\" )\n\nlet operation_data_and_metadata_encoding =\n def \"operation.alpha.operation_with_metadata\"\n @@ union\n [ case\n (Tag 0)\n ~title:\"Operation_with_metadata\"\n (obj2\n (req \"contents\" (dynamic_size contents_and_result_list_encoding))\n (opt \"signature\" Signature.encoding))\n (function\n | (Operation_data _, No_operation_metadata) ->\n None\n | (Operation_data op, Operation_metadata res) -> (\n match kind_equal_list op.contents res.contents with\n | None ->\n Pervasives.failwith\n \"cannot decode inconsistent combined operation result\"\n | Some Eq ->\n Some\n ( Contents_and_result_list\n (pack_contents_list op.contents res.contents),\n op.signature ) ))\n (fun (Contents_and_result_list contents, signature) ->\n let (op_contents, res_contents) = unpack_contents_list contents in\n ( Operation_data {contents = op_contents; signature},\n Operation_metadata {contents = res_contents} ));\n case\n (Tag 1)\n ~title:\"Operation_without_metadata\"\n (obj2\n (req \"contents\" (dynamic_size Operation.contents_list_encoding))\n (opt \"signature\" Signature.encoding))\n (function\n | (Operation_data op, No_operation_metadata) ->\n Some (Contents_list op.contents, op.signature)\n | (Operation_data _, Operation_metadata _) ->\n None)\n (fun (Contents_list contents, signature) ->\n (Operation_data {contents; signature}, No_operation_metadata)) ]\n\ntype block_metadata = {\n baker : Signature.Public_key_hash.t;\n level : Level.compat_t;\n level_info : Level.t;\n voting_period_kind : Voting_period.kind;\n voting_period_info : Voting_period.info;\n nonce_hash : Nonce_hash.t option;\n consumed_gas : Gas.Arith.fp;\n deactivated : Signature.Public_key_hash.t list;\n balance_updates : Delegate.balance_updates;\n}\n\nlet block_metadata_encoding =\n let open Data_encoding in\n def \"block_header.alpha.metadata\"\n @@ conv\n (fun { baker;\n level;\n level_info;\n voting_period_kind;\n voting_period_info;\n nonce_hash;\n consumed_gas;\n deactivated;\n balance_updates } ->\n ( baker,\n level,\n level_info,\n voting_period_kind,\n voting_period_info,\n nonce_hash,\n consumed_gas,\n deactivated,\n balance_updates ))\n (fun ( baker,\n level,\n level_info,\n voting_period_kind,\n voting_period_info,\n nonce_hash,\n consumed_gas,\n deactivated,\n balance_updates ) ->\n {\n baker;\n level;\n level_info;\n voting_period_kind;\n voting_period_info;\n nonce_hash;\n consumed_gas;\n deactivated;\n balance_updates;\n })\n (obj9\n (req \"baker\" Signature.Public_key_hash.encoding)\n (req\n ~description:\"This field is DEPRECATED: use level_info instead\"\n \"level\"\n Level.compat_encoding)\n (req \"level_info\" Level.encoding)\n (req\n ~description:\n \"This field is DEPRECATED: use voting_period_info instead\"\n \"voting_period_kind\"\n Voting_period.kind_encoding)\n (req \"voting_period_info\" Voting_period.info_encoding)\n (req \"nonce_hash\" (option Nonce_hash.encoding))\n (req \"consumed_gas\" Gas.Arith.n_fp_encoding)\n (req \"deactivated\" (list Signature.Public_key_hash.encoding))\n (req \"balance_updates\" Delegate.balance_updates_encoding))\n" ;
} ;
{ name = "Apply" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Tezos Protocol Implementation - Main Entry Points *)\n\nopen Alpha_context\n\ntype error += Wrong_voting_period of int32 * int32\n\n(* `Temporary *)\n\ntype error += Wrong_endorsement_predecessor of Block_hash.t * Block_hash.t\n\n(* `Temporary *)\n\ntype error += Duplicate_endorsement of Signature.Public_key_hash.t\n\n(* `Branch *)\n\ntype error += Invalid_endorsement_level\n\ntype error += Invalid_commitment of {expected : bool}\n\ntype error += Internal_operation_replay of packed_internal_operation\n\ntype error += Invalid_double_endorsement_evidence (* `Permanent *)\n\ntype error +=\n | Inconsistent_double_endorsement_evidence of {\n delegate1 : Signature.Public_key_hash.t;\n delegate2 : Signature.Public_key_hash.t;\n }\n\n(* `Permanent *)\n\ntype error += Unrequired_double_endorsement_evidence (* `Branch*)\n\ntype error +=\n | Too_early_double_endorsement_evidence of {\n level : Raw_level.t;\n current : Raw_level.t;\n }\n\n(* `Temporary *)\n\ntype error +=\n | Outdated_double_endorsement_evidence of {\n level : Raw_level.t;\n last : Raw_level.t;\n }\n\n(* `Permanent *)\n\ntype error +=\n | Invalid_double_baking_evidence of {\n hash1 : Block_hash.t;\n level1 : Int32.t;\n hash2 : Block_hash.t;\n level2 : Int32.t;\n }\n\n(* `Permanent *)\n\ntype error +=\n | Inconsistent_double_baking_evidence of {\n delegate1 : Signature.Public_key_hash.t;\n delegate2 : Signature.Public_key_hash.t;\n }\n\n(* `Permanent *)\n\ntype error += Unrequired_double_baking_evidence (* `Branch*)\n\ntype error +=\n | Too_early_double_baking_evidence of {\n level : Raw_level.t;\n current : Raw_level.t;\n }\n\n(* `Temporary *)\n\ntype error +=\n | Outdated_double_baking_evidence of {\n level : Raw_level.t;\n last : Raw_level.t;\n }\n\n(* `Permanent *)\n\ntype error += Invalid_activation of {pkh : Ed25519.Public_key_hash.t}\n\ntype error += Multiple_revelation\n\ntype error += Gas_quota_exceeded_init_deserialize (* Permanent *)\n\ntype error += (* `Permanent *) Inconsistent_sources\n\ntype error +=\n | Not_enough_endorsements_for_priority of {\n required : int;\n priority : int;\n endorsements : int;\n timestamp : Time.t;\n }\n\nlet () =\n register_error_kind\n `Temporary\n ~id:\"operation.wrong_endorsement_predecessor\"\n ~title:\"Wrong endorsement predecessor\"\n ~description:\n \"Trying to include an endorsement in a block that is not the successor \\\n of the endorsed one\"\n ~pp:(fun ppf (e, p) ->\n Format.fprintf\n ppf\n \"Wrong predecessor %a, expected %a\"\n Block_hash.pp\n p\n Block_hash.pp\n e)\n Data_encoding.(\n obj2\n (req \"expected\" Block_hash.encoding)\n (req \"provided\" Block_hash.encoding))\n (function\n | Wrong_endorsement_predecessor (e, p) -> Some (e, p) | _ -> None)\n (fun (e, p) -> Wrong_endorsement_predecessor (e, p)) ;\n register_error_kind\n `Temporary\n ~id:\"operation.wrong_voting_period\"\n ~title:\"Wrong voting period\"\n ~description:\n \"Trying to include a proposal or ballot meant for another voting period\"\n ~pp:(fun ppf (e, p) ->\n Format.fprintf ppf \"Wrong voting period %ld, current is %ld\" p e)\n Data_encoding.(\n obj2 (req \"current_index\" int32) (req \"provided_index\" int32))\n (function Wrong_voting_period (e, p) -> Some (e, p) | _ -> None)\n (fun (e, p) -> Wrong_voting_period (e, p)) ;\n register_error_kind\n `Branch\n ~id:\"operation.duplicate_endorsement\"\n ~title:\"Duplicate endorsement\"\n ~description:\"Two endorsements received from same delegate\"\n ~pp:(fun ppf k ->\n Format.fprintf\n ppf\n \"Duplicate endorsement from delegate %a (possible replay attack).\"\n Signature.Public_key_hash.pp_short\n k)\n Data_encoding.(obj1 (req \"delegate\" Signature.Public_key_hash.encoding))\n (function Duplicate_endorsement k -> Some k | _ -> None)\n (fun k -> Duplicate_endorsement k) ;\n register_error_kind\n `Temporary\n ~id:\"operation.invalid_endorsement_level\"\n ~title:\"Unexpected level in endorsement\"\n ~description:\n \"The level of an endorsement is inconsistent with the provided block \\\n hash.\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"Unexpected level in endorsement.\")\n Data_encoding.unit\n (function Invalid_endorsement_level -> Some () | _ -> None)\n (fun () -> Invalid_endorsement_level) ;\n register_error_kind\n `Permanent\n ~id:\"block.invalid_commitment\"\n ~title:\"Invalid commitment in block header\"\n ~description:\"The block header has invalid commitment.\"\n ~pp:(fun ppf expected ->\n if expected then\n Format.fprintf ppf \"Missing seed's nonce commitment in block header.\"\n else\n Format.fprintf\n ppf\n \"Unexpected seed's nonce commitment in block header.\")\n Data_encoding.(obj1 (req \"expected\" bool))\n (function Invalid_commitment {expected} -> Some expected | _ -> None)\n (fun expected -> Invalid_commitment {expected}) ;\n register_error_kind\n `Permanent\n ~id:\"internal_operation_replay\"\n ~title:\"Internal operation replay\"\n ~description:\"An internal operation was emitted twice by a script\"\n ~pp:(fun ppf (Internal_operation {nonce; _}) ->\n Format.fprintf\n ppf\n \"Internal operation %d was emitted twice by a script\"\n nonce)\n Operation.internal_operation_encoding\n (function Internal_operation_replay op -> Some op | _ -> None)\n (fun op -> Internal_operation_replay op) ;\n register_error_kind\n `Permanent\n ~id:\"block.invalid_double_endorsement_evidence\"\n ~title:\"Invalid double endorsement evidence\"\n ~description:\"A double-endorsement evidence is malformed\"\n ~pp:(fun ppf () ->\n Format.fprintf ppf \"Malformed double-endorsement evidence\")\n Data_encoding.empty\n (function Invalid_double_endorsement_evidence -> Some () | _ -> None)\n (fun () -> Invalid_double_endorsement_evidence) ;\n register_error_kind\n `Permanent\n ~id:\"block.inconsistent_double_endorsement_evidence\"\n ~title:\"Inconsistent double endorsement evidence\"\n ~description:\n \"A double-endorsement evidence is inconsistent (two distinct delegates)\"\n ~pp:(fun ppf (delegate1, delegate2) ->\n Format.fprintf\n ppf\n \"Inconsistent double-endorsement evidence (distinct delegate: %a and \\\n %a)\"\n Signature.Public_key_hash.pp_short\n delegate1\n Signature.Public_key_hash.pp_short\n delegate2)\n Data_encoding.(\n obj2\n (req \"delegate1\" Signature.Public_key_hash.encoding)\n (req \"delegate2\" Signature.Public_key_hash.encoding))\n (function\n | Inconsistent_double_endorsement_evidence {delegate1; delegate2} ->\n Some (delegate1, delegate2)\n | _ ->\n None)\n (fun (delegate1, delegate2) ->\n Inconsistent_double_endorsement_evidence {delegate1; delegate2}) ;\n register_error_kind\n `Branch\n ~id:\"block.unrequired_double_endorsement_evidence\"\n ~title:\"Unrequired double endorsement evidence\"\n ~description:\"A double-endorsement evidence is unrequired\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"A valid double-endorsement operation cannot be applied: the \\\n associated delegate has previously been denounced in this cycle.\")\n Data_encoding.empty\n (function Unrequired_double_endorsement_evidence -> Some () | _ -> None)\n (fun () -> Unrequired_double_endorsement_evidence) ;\n register_error_kind\n `Temporary\n ~id:\"block.too_early_double_endorsement_evidence\"\n ~title:\"Too early double endorsement evidence\"\n ~description:\"A double-endorsement evidence is in the future\"\n ~pp:(fun ppf (level, current) ->\n Format.fprintf\n ppf\n \"A double-endorsement evidence is in the future (current level: %a, \\\n endorsement level: %a)\"\n Raw_level.pp\n current\n Raw_level.pp\n level)\n Data_encoding.(\n obj2 (req \"level\" Raw_level.encoding) (req \"current\" Raw_level.encoding))\n (function\n | Too_early_double_endorsement_evidence {level; current} ->\n Some (level, current)\n | _ ->\n None)\n (fun (level, current) ->\n Too_early_double_endorsement_evidence {level; current}) ;\n register_error_kind\n `Permanent\n ~id:\"block.outdated_double_endorsement_evidence\"\n ~title:\"Outdated double endorsement evidence\"\n ~description:\"A double-endorsement evidence is outdated.\"\n ~pp:(fun ppf (level, last) ->\n Format.fprintf\n ppf\n \"A double-endorsement evidence is outdated (last acceptable level: \\\n %a, endorsement level: %a)\"\n Raw_level.pp\n last\n Raw_level.pp\n level)\n Data_encoding.(\n obj2 (req \"level\" Raw_level.encoding) (req \"last\" Raw_level.encoding))\n (function\n | Outdated_double_endorsement_evidence {level; last} ->\n Some (level, last)\n | _ ->\n None)\n (fun (level, last) -> Outdated_double_endorsement_evidence {level; last}) ;\n register_error_kind\n `Permanent\n ~id:\"block.invalid_double_baking_evidence\"\n ~title:\"Invalid double baking evidence\"\n ~description:\n \"A double-baking evidence is inconsistent (two distinct level)\"\n ~pp:(fun ppf (hash1, level1, hash2, level2) ->\n Format.fprintf\n ppf\n \"Invalid double-baking evidence (hash: %a and %a, levels: %ld and %ld)\"\n Block_hash.pp\n hash1\n Block_hash.pp\n hash2\n level1\n level2)\n Data_encoding.(\n obj4\n (req \"hash1\" Block_hash.encoding)\n (req \"level1\" int32)\n (req \"hash2\" Block_hash.encoding)\n (req \"level2\" int32))\n (function\n | Invalid_double_baking_evidence {hash1; level1; hash2; level2} ->\n Some (hash1, level1, hash2, level2)\n | _ ->\n None)\n (fun (hash1, level1, hash2, level2) ->\n Invalid_double_baking_evidence {hash1; level1; hash2; level2}) ;\n register_error_kind\n `Permanent\n ~id:\"block.inconsistent_double_baking_evidence\"\n ~title:\"Inconsistent double baking evidence\"\n ~description:\n \"A double-baking evidence is inconsistent (two distinct delegates)\"\n ~pp:(fun ppf (delegate1, delegate2) ->\n Format.fprintf\n ppf\n \"Inconsistent double-baking evidence (distinct delegate: %a and %a)\"\n Signature.Public_key_hash.pp_short\n delegate1\n Signature.Public_key_hash.pp_short\n delegate2)\n Data_encoding.(\n obj2\n (req \"delegate1\" Signature.Public_key_hash.encoding)\n (req \"delegate2\" Signature.Public_key_hash.encoding))\n (function\n | Inconsistent_double_baking_evidence {delegate1; delegate2} ->\n Some (delegate1, delegate2)\n | _ ->\n None)\n (fun (delegate1, delegate2) ->\n Inconsistent_double_baking_evidence {delegate1; delegate2}) ;\n register_error_kind\n `Branch\n ~id:\"block.unrequired_double_baking_evidence\"\n ~title:\"Unrequired double baking evidence\"\n ~description:\"A double-baking evidence is unrequired\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"A valid double-baking operation cannot be applied: the associated \\\n delegate has previously been denounced in this cycle.\")\n Data_encoding.empty\n (function Unrequired_double_baking_evidence -> Some () | _ -> None)\n (fun () -> Unrequired_double_baking_evidence) ;\n register_error_kind\n `Temporary\n ~id:\"block.too_early_double_baking_evidence\"\n ~title:\"Too early double baking evidence\"\n ~description:\"A double-baking evidence is in the future\"\n ~pp:(fun ppf (level, current) ->\n Format.fprintf\n ppf\n \"A double-baking evidence is in the future (current level: %a, \\\n baking level: %a)\"\n Raw_level.pp\n current\n Raw_level.pp\n level)\n Data_encoding.(\n obj2 (req \"level\" Raw_level.encoding) (req \"current\" Raw_level.encoding))\n (function\n | Too_early_double_baking_evidence {level; current} ->\n Some (level, current)\n | _ ->\n None)\n (fun (level, current) -> Too_early_double_baking_evidence {level; current}) ;\n register_error_kind\n `Permanent\n ~id:\"block.outdated_double_baking_evidence\"\n ~title:\"Outdated double baking evidence\"\n ~description:\"A double-baking evidence is outdated.\"\n ~pp:(fun ppf (level, last) ->\n Format.fprintf\n ppf\n \"A double-baking evidence is outdated (last acceptable level: %a, \\\n baking level: %a)\"\n Raw_level.pp\n last\n Raw_level.pp\n level)\n Data_encoding.(\n obj2 (req \"level\" Raw_level.encoding) (req \"last\" Raw_level.encoding))\n (function\n | Outdated_double_baking_evidence {level; last} ->\n Some (level, last)\n | _ ->\n None)\n (fun (level, last) -> Outdated_double_baking_evidence {level; last}) ;\n register_error_kind\n `Permanent\n ~id:\"operation.invalid_activation\"\n ~title:\"Invalid activation\"\n ~description:\n \"The given key and secret do not correspond to any existing \\\n preallocated contract\"\n ~pp:(fun ppf pkh ->\n Format.fprintf\n ppf\n \"Invalid activation. The public key %a does not match any commitment.\"\n Ed25519.Public_key_hash.pp\n pkh)\n Data_encoding.(obj1 (req \"pkh\" Ed25519.Public_key_hash.encoding))\n (function Invalid_activation {pkh} -> Some pkh | _ -> None)\n (fun pkh -> Invalid_activation {pkh}) ;\n register_error_kind\n `Permanent\n ~id:\"block.multiple_revelation\"\n ~title:\"Multiple revelations were included in a manager operation\"\n ~description:\n \"A manager operation should not contain more than one revelation\"\n ~pp:(fun ppf () ->\n Format.fprintf\n ppf\n \"Multiple revelations were included in a manager operation\")\n Data_encoding.empty\n (function Multiple_revelation -> Some () | _ -> None)\n (fun () -> Multiple_revelation) ;\n register_error_kind\n `Permanent\n ~id:\"gas_exhausted.init_deserialize\"\n ~title:\"Not enough gas for initial deserialization of script expressions\"\n ~description:\n \"Gas limit was not high enough to deserialize the transaction \\\n parameters or origination script code or initial storage, making the \\\n operation impossible to parse within the provided gas bounds.\"\n Data_encoding.empty\n (function Gas_quota_exceeded_init_deserialize -> Some () | _ -> None)\n (fun () -> Gas_quota_exceeded_init_deserialize) ;\n register_error_kind\n `Permanent\n ~id:\"operation.inconsistent_sources\"\n ~title:\"Inconsistent sources in operation pack\"\n ~description:\n \"The operation pack includes operations from different sources.\"\n ~pp:(fun ppf () ->\n Format.pp_print_string\n ppf\n \"The operation pack includes operations from different sources.\")\n Data_encoding.empty\n (function Inconsistent_sources -> Some () | _ -> None)\n (fun () -> Inconsistent_sources) ;\n register_error_kind\n `Permanent\n ~id:\"operation.not_enough_endorsements_for_priority\"\n ~title:\"Not enough endorsements for priority\"\n ~description:\n \"The block being validated does not include the required minimum number \\\n of endorsements for this priority.\"\n ~pp:(fun ppf (required, endorsements, priority, timestamp) ->\n Format.fprintf\n ppf\n \"Wrong number of endorsements (%i) for priority (%i), %i are expected \\\n at %a\"\n endorsements\n priority\n required\n Time.pp_hum\n timestamp)\n Data_encoding.(\n obj4\n (req \"required\" int31)\n (req \"endorsements\" int31)\n (req \"priority\" int31)\n (req \"timestamp\" Time.encoding))\n (function\n | Not_enough_endorsements_for_priority\n {required; endorsements; priority; timestamp} ->\n Some (required, endorsements, priority, timestamp)\n | _ ->\n None)\n (fun (required, endorsements, priority, timestamp) ->\n Not_enough_endorsements_for_priority\n {required; endorsements; priority; timestamp})\n\nopen Apply_results\n\nlet apply_manager_operation_content :\n type kind.\n Alpha_context.t ->\n Script_ir_translator.unparsing_mode ->\n payer:Contract.t ->\n source:Contract.t ->\n chain_id:Chain_id.t ->\n internal:bool ->\n kind manager_operation ->\n ( context\n * kind successful_manager_operation_result\n * packed_internal_operation list )\n tzresult\n Lwt.t =\n fun ctxt mode ~payer ~source ~chain_id ~internal operation ->\n let before_operation =\n (* This context is not used for backtracking. Only to compute\n gas consumption and originations for the operation result. *)\n ctxt\n in\n Contract.must_exist ctxt source\n >>=? fun () ->\n Gas.consume ctxt Michelson_v1_gas.Cost_of.manager_operation\n >>?= fun ctxt ->\n match operation with\n | Reveal _ ->\n return\n (* No-op: action already performed by `precheck_manager_contents`. *)\n ( ctxt,\n ( Reveal_result\n {consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt}\n : kind successful_manager_operation_result ),\n [] )\n | Transaction {amount; parameters; destination; entrypoint} -> (\n Contract.spend ctxt source amount\n >>=? fun ctxt ->\n ( match Contract.is_implicit destination with\n | None ->\n return (ctxt, [], false)\n | Some _ -> (\n Contract.allocated ctxt destination\n >>=? function\n | true ->\n return (ctxt, [], false)\n | false ->\n Lwt.return\n ( Fees.origination_burn ctxt\n >|? fun (ctxt, origination_burn) ->\n ( ctxt,\n [(Delegate.Contract payer, Delegate.Debited origination_burn)],\n true ) ) ) )\n >>=? fun (ctxt, maybe_burn_balance_update, allocated_destination_contract)\n ->\n Contract.credit ctxt destination amount\n >>=? fun ctxt ->\n Contract.get_script ctxt destination\n >>=? fun (ctxt, script) ->\n match script with\n | None ->\n Lwt.return\n ( ( match entrypoint with\n | \"default\" ->\n ok_unit\n | entrypoint ->\n error (Script_tc_errors.No_such_entrypoint entrypoint) )\n >>? (fun () ->\n Script.force_decode_in_context ctxt parameters\n >>? fun (arg, ctxt) ->\n (* see [note] *)\n (* [note]: for toplevel ops, cost is nil since the\n lazy value has already been forced at precheck, so\n we compute and consume the full cost again *)\n let cost_arg = Script.deserialized_cost arg in\n Gas.consume ctxt cost_arg\n >>? fun ctxt ->\n match Micheline.root arg with\n | Prim (_, D_Unit, [], _) ->\n (* Allow [Unit] parameter to non-scripted contracts. *)\n ok ctxt\n | _ ->\n error\n (Script_interpreter.Bad_contract_parameter destination))\n >|? fun ctxt ->\n let result =\n Transaction_result\n {\n storage = None;\n lazy_storage_diff = None;\n balance_updates =\n Delegate.cleanup_balance_updates\n ( [ (Delegate.Contract source, Delegate.Debited amount);\n (Contract destination, Credited amount) ]\n @ maybe_burn_balance_update );\n originated_contracts = [];\n consumed_gas =\n Gas.consumed ~since:before_operation ~until:ctxt;\n storage_size = Z.zero;\n paid_storage_size_diff = Z.zero;\n allocated_destination_contract;\n }\n in\n (ctxt, result, []) )\n | Some script ->\n Script.force_decode_in_context ctxt parameters\n >>?= fun (parameter, ctxt) ->\n (* see [note] *)\n let cost_parameter = Script.deserialized_cost parameter in\n Gas.consume ctxt cost_parameter\n >>?= fun ctxt ->\n let step_constants =\n let open Script_interpreter in\n {source; payer; self = destination; amount; chain_id}\n in\n Script_interpreter.execute\n ctxt\n mode\n step_constants\n ~script\n ~parameter\n ~entrypoint\n ~internal\n >>=? fun {ctxt; storage; lazy_storage_diff; operations} ->\n Contract.update_script_storage\n ctxt\n destination\n storage\n lazy_storage_diff\n >>=? fun ctxt ->\n Fees.record_paid_storage_space ctxt destination\n >>=? fun (ctxt, new_size, paid_storage_size_diff, fees) ->\n Contract.originated_from_current_nonce\n ~since:before_operation\n ~until:ctxt\n >|=? fun originated_contracts ->\n let result =\n Transaction_result\n {\n storage = Some storage;\n lazy_storage_diff;\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract payer, Debited fees);\n (Contract source, Debited amount);\n (Contract destination, Credited amount) ];\n originated_contracts;\n consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;\n storage_size = new_size;\n paid_storage_size_diff;\n allocated_destination_contract;\n }\n in\n (ctxt, result, operations) )\n | Origination {delegate; script; preorigination; credit} ->\n Script.force_decode_in_context ctxt script.storage\n >>?= fun (unparsed_storage, ctxt) ->\n (* see [note] *)\n Gas.consume ctxt (Script.deserialized_cost unparsed_storage)\n >>?= fun ctxt ->\n Script.force_decode_in_context ctxt script.code\n >>?= fun (unparsed_code, ctxt) ->\n (* see [note] *)\n Gas.consume ctxt (Script.deserialized_cost unparsed_code)\n >>?= fun ctxt ->\n Script_ir_translator.parse_script\n ctxt\n ~legacy:false\n ~allow_forged_in_storage:internal\n script\n >>=? fun (Ex_script parsed_script, ctxt) ->\n Script_ir_translator.collect_lazy_storage\n ctxt\n parsed_script.storage_type\n parsed_script.storage\n >>?= fun (to_duplicate, ctxt) ->\n let to_update = Script_ir_translator.no_lazy_storage_id in\n Script_ir_translator.extract_lazy_storage_diff\n ctxt\n Optimized\n parsed_script.storage_type\n parsed_script.storage\n ~to_duplicate\n ~to_update\n ~temporary:false\n >>=? fun (storage, lazy_storage_diff, ctxt) ->\n Script_ir_translator.unparse_data\n ctxt\n Optimized\n parsed_script.storage_type\n storage\n >>=? fun (storage, ctxt) ->\n let storage = Script.lazy_expr (Micheline.strip_locations storage) in\n let script = {script with storage} in\n Contract.spend ctxt source credit\n >>=? fun ctxt ->\n ( match preorigination with\n | Some contract ->\n assert internal ;\n (* The preorigination field is only used to early return\n the address of an originated contract in Michelson.\n It cannot come from the outside. *)\n ok (ctxt, contract)\n | None ->\n Contract.fresh_contract_from_current_nonce ctxt )\n >>?= fun (ctxt, contract) ->\n Contract.originate\n ctxt\n contract\n ~delegate\n ~balance:credit\n ~script:(script, lazy_storage_diff)\n >>=? fun ctxt ->\n Fees.origination_burn ctxt\n >>?= fun (ctxt, origination_burn) ->\n Fees.record_paid_storage_space ctxt contract\n >|=? fun (ctxt, size, paid_storage_size_diff, fees) ->\n let result =\n Origination_result\n {\n lazy_storage_diff;\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract payer, Debited fees);\n (Contract payer, Debited origination_burn);\n (Contract source, Debited credit);\n (Contract contract, Credited credit) ];\n originated_contracts = [contract];\n consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt;\n storage_size = size;\n paid_storage_size_diff;\n }\n in\n (ctxt, result, [])\n | Delegation delegate ->\n Delegate.set ctxt source delegate\n >|=? fun ctxt ->\n ( ctxt,\n Delegation_result\n {consumed_gas = Gas.consumed ~since:before_operation ~until:ctxt},\n [] )\n\ntype success_or_failure = Success of context | Failure\n\nlet apply_internal_manager_operations ctxt mode ~payer ~chain_id ops =\n let rec apply ctxt applied worklist =\n match worklist with\n | [] ->\n Lwt.return (Success ctxt, List.rev applied)\n | Internal_operation ({source; operation; nonce} as op) :: rest -> (\n ( if internal_nonce_already_recorded ctxt nonce then\n fail (Internal_operation_replay (Internal_operation op))\n else\n let ctxt = record_internal_nonce ctxt nonce in\n apply_manager_operation_content\n ctxt\n mode\n ~source\n ~payer\n ~chain_id\n ~internal:true\n operation )\n >>= function\n | Error errors ->\n let result =\n Internal_operation_result\n (op, Failed (manager_kind op.operation, errors))\n in\n let skipped =\n List.rev_map\n (fun (Internal_operation op) ->\n Internal_operation_result\n (op, Skipped (manager_kind op.operation)))\n rest\n in\n Lwt.return (Failure, List.rev (skipped @ (result :: applied)))\n | Ok (ctxt, result, emitted) ->\n apply\n ctxt\n (Internal_operation_result (op, Applied result) :: applied)\n (rest @ emitted) )\n in\n apply ctxt [] ops\n\nlet precheck_manager_contents (type kind) ctxt\n (op : kind Kind.manager contents) : context tzresult Lwt.t =\n let (Manager_operation\n {source; fee; counter; operation; gas_limit; storage_limit}) =\n op\n in\n Gas.check_limit ctxt gas_limit\n >>?= fun () ->\n let ctxt = Gas.set_limit ctxt gas_limit in\n Fees.check_storage_limit ctxt storage_limit\n >>?= fun () ->\n Contract.must_be_allocated ctxt (Contract.implicit_contract source)\n >>=? fun () ->\n Contract.check_counter_increment ctxt source counter\n >>=? fun () ->\n ( match operation with\n | Reveal pk ->\n Contract.reveal_manager_key ctxt source pk\n | Transaction {parameters; _} ->\n Lwt.return\n (* Fail quickly if not enough gas for minimal deserialization cost *)\n @@ record_trace Gas_quota_exceeded_init_deserialize\n @@ ( Gas.check_enough ctxt (Script.minimal_deserialize_cost parameters)\n >>? fun () ->\n (* Fail if not enough gas for complete deserialization cost *)\n Script.force_decode_in_context ctxt parameters\n >|? fun (_arg, ctxt) -> ctxt )\n | Origination {script; _} ->\n Lwt.return\n @@ record_trace Gas_quota_exceeded_init_deserialize\n @@ (* Fail quickly if not enough gas for minimal deserialization cost *)\n ( Gas.(\n check_enough\n ctxt\n ( Script.minimal_deserialize_cost script.code\n +@ Script.minimal_deserialize_cost script.storage ))\n >>? fun () ->\n (* Fail if not enough gas for complete deserialization cost *)\n Script.force_decode_in_context ctxt script.code\n >>? fun (_code, ctxt) ->\n Script.force_decode_in_context ctxt script.storage\n >|? fun (_storage, ctxt) -> ctxt )\n | _ ->\n return ctxt )\n >>=? fun ctxt ->\n Contract.increment_counter ctxt source\n >>=? fun ctxt ->\n Contract.spend ctxt (Contract.implicit_contract source) fee\n >>=? fun ctxt -> Lwt.return (add_fees ctxt fee)\n\nlet apply_manager_contents (type kind) ctxt mode chain_id\n (op : kind Kind.manager contents) :\n ( success_or_failure\n * kind manager_operation_result\n * packed_internal_operation_result list )\n Lwt.t =\n let (Manager_operation {source; operation; gas_limit; storage_limit}) = op in\n (* We do not expose the internal scaling to the users. Instead, we multiply\n the specified gas limit by the internal scaling. *)\n let ctxt = Gas.set_limit ctxt gas_limit in\n let ctxt = Fees.start_counting_storage_fees ctxt in\n let source = Contract.implicit_contract source in\n apply_manager_operation_content\n ctxt\n mode\n ~source\n ~payer:source\n ~internal:false\n ~chain_id\n operation\n >>= function\n | Ok (ctxt, operation_results, internal_operations) -> (\n apply_internal_manager_operations\n ctxt\n mode\n ~payer:source\n ~chain_id\n internal_operations\n >>= function\n | (Success ctxt, internal_operations_results) -> (\n Fees.burn_storage_fees ctxt ~storage_limit ~payer:source\n >|= function\n | Ok ctxt ->\n ( Success ctxt,\n Applied operation_results,\n internal_operations_results )\n | Error errors ->\n ( Failure,\n Backtracked (operation_results, Some errors),\n internal_operations_results ) )\n | (Failure, internal_operations_results) ->\n Lwt.return\n (Failure, Applied operation_results, internal_operations_results) )\n | Error errors ->\n Lwt.return (Failure, Failed (manager_kind operation, errors), [])\n\nlet skipped_operation_result :\n type kind. kind manager_operation -> kind manager_operation_result =\n function\n | operation -> (\n match operation with\n | Reveal _ ->\n Applied\n ( Reveal_result {consumed_gas = Gas.Arith.zero}\n : kind successful_manager_operation_result )\n | _ ->\n Skipped (manager_kind operation) )\n\nlet rec mark_skipped :\n type kind.\n baker:Signature.Public_key_hash.t ->\n Level.t ->\n kind Kind.manager contents_list ->\n kind Kind.manager contents_result_list =\n fun ~baker level -> function\n | Single (Manager_operation {source; fee; operation}) ->\n let source = Contract.implicit_contract source in\n Single_result\n (Manager_operation_result\n {\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract source, Debited fee);\n (Fees (baker, level.cycle), Credited fee) ];\n operation_result = skipped_operation_result operation;\n internal_operation_results = [];\n })\n | Cons (Manager_operation {source; fee; operation}, rest) ->\n let source = Contract.implicit_contract source in\n Cons_result\n ( Manager_operation_result\n {\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract source, Debited fee);\n (Fees (baker, level.cycle), Credited fee) ];\n operation_result = skipped_operation_result operation;\n internal_operation_results = [];\n },\n mark_skipped ~baker level rest )\n\nlet rec precheck_manager_contents_list :\n type kind.\n Alpha_context.t ->\n kind Kind.manager contents_list ->\n context tzresult Lwt.t =\n fun ctxt contents_list ->\n match contents_list with\n | Single (Manager_operation _ as op) ->\n precheck_manager_contents ctxt op\n | Cons ((Manager_operation _ as op), rest) ->\n precheck_manager_contents ctxt op\n >>=? fun ctxt -> precheck_manager_contents_list ctxt rest\n\nlet check_manager_signature ctxt chain_id (op : _ Kind.manager contents_list)\n raw_operation =\n (* Currently, the [op] only contains one signature, so\n all operations are required to be from the same manager. This may\n change in the future, allowing several managers to group-sign a\n sequence of transactions. *)\n let check_same_manager (source, source_key) manager =\n match manager with\n | None ->\n (* Consistency already checked by\n [reveal_manager_key] in [precheck_manager_contents]. *)\n ok (source, source_key)\n | Some (manager, manager_key) ->\n if Signature.Public_key_hash.equal source manager then\n ok (source, Option.first_some manager_key source_key)\n else error Inconsistent_sources\n in\n let rec find_source :\n type kind.\n kind Kind.manager contents_list ->\n (Signature.public_key_hash * Signature.public_key option) option ->\n (Signature.public_key_hash * Signature.public_key option) tzresult =\n fun contents_list manager ->\n let source (type kind) = function\n | (Manager_operation {source; operation = Reveal key; _} :\n kind Kind.manager contents) ->\n (source, Some key)\n | Manager_operation {source; _} ->\n (source, None)\n in\n match contents_list with\n | Single op ->\n check_same_manager (source op) manager\n | Cons (op, rest) ->\n check_same_manager (source op) manager\n >>? fun manager -> find_source rest (Some manager)\n in\n find_source op None\n >>?= fun (source, source_key) ->\n ( match source_key with\n | Some key ->\n return key\n | None ->\n Contract.get_manager_key ctxt source )\n >>=? fun public_key ->\n Lwt.return (Operation.check_signature public_key chain_id raw_operation)\n\nlet rec apply_manager_contents_list_rec :\n type kind.\n Alpha_context.t ->\n Script_ir_translator.unparsing_mode ->\n public_key_hash ->\n Chain_id.t ->\n kind Kind.manager contents_list ->\n (success_or_failure * kind Kind.manager contents_result_list) Lwt.t =\n fun ctxt mode baker chain_id contents_list ->\n let level = Level.current ctxt in\n match contents_list with\n | Single (Manager_operation {source; fee; _} as op) ->\n let source = Contract.implicit_contract source in\n apply_manager_contents ctxt mode chain_id op\n >|= fun (ctxt_result, operation_result, internal_operation_results) ->\n let result =\n Manager_operation_result\n {\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract source, Debited fee);\n (Fees (baker, level.cycle), Credited fee) ];\n operation_result;\n internal_operation_results;\n }\n in\n (ctxt_result, Single_result result)\n | Cons ((Manager_operation {source; fee; _} as op), rest) -> (\n let source = Contract.implicit_contract source in\n apply_manager_contents ctxt mode chain_id op\n >>= function\n | (Failure, operation_result, internal_operation_results) ->\n let result =\n Manager_operation_result\n {\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract source, Debited fee);\n (Fees (baker, level.cycle), Credited fee) ];\n operation_result;\n internal_operation_results;\n }\n in\n Lwt.return\n (Failure, Cons_result (result, mark_skipped ~baker level rest))\n | (Success ctxt, operation_result, internal_operation_results) ->\n let result =\n Manager_operation_result\n {\n balance_updates =\n Delegate.cleanup_balance_updates\n [ (Contract source, Debited fee);\n (Fees (baker, level.cycle), Credited fee) ];\n operation_result;\n internal_operation_results;\n }\n in\n apply_manager_contents_list_rec ctxt mode baker chain_id rest\n >|= fun (ctxt_result, results) ->\n (ctxt_result, Cons_result (result, results)) )\n\nlet mark_backtracked results =\n let rec mark_contents_list :\n type kind.\n kind Kind.manager contents_result_list ->\n kind Kind.manager contents_result_list = function\n | Single_result (Manager_operation_result op) ->\n Single_result\n (Manager_operation_result\n {\n balance_updates = op.balance_updates;\n operation_result =\n mark_manager_operation_result op.operation_result;\n internal_operation_results =\n List.map\n mark_internal_operation_results\n op.internal_operation_results;\n })\n | Cons_result (Manager_operation_result op, rest) ->\n Cons_result\n ( Manager_operation_result\n {\n balance_updates = op.balance_updates;\n operation_result =\n mark_manager_operation_result op.operation_result;\n internal_operation_results =\n List.map\n mark_internal_operation_results\n op.internal_operation_results;\n },\n mark_contents_list rest )\n and mark_internal_operation_results\n (Internal_operation_result (kind, result)) =\n Internal_operation_result (kind, mark_manager_operation_result result)\n and mark_manager_operation_result :\n type kind. kind manager_operation_result -> kind manager_operation_result\n = function\n | (Failed _ | Skipped _ | Backtracked _) as result ->\n result\n | Applied (Reveal_result _) as result ->\n result\n | Applied result ->\n Backtracked (result, None)\n in\n mark_contents_list results\n [@@coq_axiom \"non-top-level mutual recursion\"]\n\nlet apply_manager_contents_list ctxt mode baker chain_id contents_list =\n apply_manager_contents_list_rec ctxt mode baker chain_id contents_list\n >>= fun (ctxt_result, results) ->\n match ctxt_result with\n | Failure ->\n Lwt.return (ctxt (* backtracked *), mark_backtracked results)\n | Success ctxt ->\n Lazy_storage.cleanup_temporaries ctxt >|= fun ctxt -> (ctxt, results)\n\nlet apply_contents_list (type kind) ctxt chain_id mode pred_block baker\n (operation : kind operation) (contents_list : kind contents_list) :\n (context * kind contents_result_list) tzresult Lwt.t =\n match contents_list with\n | Single (Endorsement {level}) ->\n let block = operation.shell.branch in\n error_unless\n (Block_hash.equal block pred_block)\n (Wrong_endorsement_predecessor (pred_block, block))\n >>?= fun () ->\n let current_level = (Level.current ctxt).level in\n error_unless\n Raw_level.(succ level = current_level)\n Invalid_endorsement_level\n >>?= fun () ->\n Baking.check_endorsement_rights ctxt chain_id operation\n >>=? fun (delegate, slots, used) ->\n if used then fail (Duplicate_endorsement delegate)\n else\n let ctxt = record_endorsement ctxt delegate in\n let gap = List.length slots in\n Tez.(Constants.endorsement_security_deposit ctxt *? Int64.of_int gap)\n >>?= fun deposit ->\n Delegate.freeze_deposit ctxt delegate deposit\n >>=? fun ctxt ->\n Global.get_block_priority ctxt\n >>=? fun block_priority ->\n Baking.endorsing_reward ctxt ~block_priority gap\n >>?= fun reward ->\n Delegate.freeze_rewards ctxt delegate reward\n >|=? fun ctxt ->\n let level = Level.from_raw ctxt level in\n ( ctxt,\n Single_result\n (Endorsement_result\n {\n balance_updates =\n Delegate.cleanup_balance_updates\n [ ( Contract (Contract.implicit_contract delegate),\n Debited deposit );\n (Deposits (delegate, level.cycle), Credited deposit);\n (Rewards (delegate, level.cycle), Credited reward) ];\n delegate;\n slots;\n }) )\n | Single (Seed_nonce_revelation {level; nonce}) ->\n let level = Level.from_raw ctxt level in\n Nonce.reveal ctxt level nonce\n >>=? fun ctxt ->\n let seed_nonce_revelation_tip =\n Constants.seed_nonce_revelation_tip ctxt\n in\n Lwt.return\n ( add_rewards ctxt seed_nonce_revelation_tip\n >|? fun ctxt ->\n ( ctxt,\n Single_result\n (Seed_nonce_revelation_result\n [ ( Rewards (baker, level.cycle),\n Credited seed_nonce_revelation_tip ) ]) ) )\n | Single (Double_endorsement_evidence {op1; op2}) -> (\n match (op1.protocol_data.contents, op2.protocol_data.contents) with\n | (Single (Endorsement e1), Single (Endorsement e2))\n when Raw_level.(e1.level = e2.level)\n && not (Block_hash.equal op1.shell.branch op2.shell.branch) ->\n let level = Level.from_raw ctxt e1.level in\n let oldest_level = Level.last_allowed_fork_level ctxt in\n fail_unless\n Level.(level < Level.current ctxt)\n (Too_early_double_endorsement_evidence\n {level = level.level; current = (Level.current ctxt).level})\n >>=? fun () ->\n fail_unless\n Raw_level.(oldest_level <= level.level)\n (Outdated_double_endorsement_evidence\n {level = level.level; last = oldest_level})\n >>=? fun () ->\n Baking.check_endorsement_rights ctxt chain_id op1\n >>=? fun (delegate1, _, _) ->\n Baking.check_endorsement_rights ctxt chain_id op2\n >>=? fun (delegate2, _, _) ->\n fail_unless\n (Signature.Public_key_hash.equal delegate1 delegate2)\n (Inconsistent_double_endorsement_evidence {delegate1; delegate2})\n >>=? fun () ->\n Delegate.has_frozen_balance ctxt delegate1 level.cycle\n >>=? fun valid ->\n fail_unless valid Unrequired_double_endorsement_evidence\n >>=? fun () ->\n Delegate.punish ctxt delegate1 level.cycle\n >>=? fun (ctxt, balance) ->\n Lwt.return Tez.(balance.deposit +? balance.fees)\n >>=? fun burned ->\n let reward =\n match Tez.(burned /? 2L) with Ok v -> v | Error _ -> Tez.zero\n in\n add_rewards ctxt reward\n >>?= fun ctxt ->\n let current_cycle = (Level.current ctxt).cycle in\n return\n ( ctxt,\n Single_result\n (Double_endorsement_evidence_result\n (Delegate.cleanup_balance_updates\n [ ( Deposits (delegate1, level.cycle),\n Debited balance.deposit );\n (Fees (delegate1, level.cycle), Debited balance.fees);\n ( Rewards (delegate1, level.cycle),\n Debited balance.rewards );\n (Rewards (baker, current_cycle), Credited reward) ])) )\n | (_, _) ->\n fail Invalid_double_endorsement_evidence )\n | Single (Double_baking_evidence {bh1; bh2}) ->\n let hash1 = Block_header.hash bh1 in\n let hash2 = Block_header.hash bh2 in\n fail_unless\n ( Compare.Int32.(bh1.shell.level = bh2.shell.level)\n && not (Block_hash.equal hash1 hash2) )\n (Invalid_double_baking_evidence\n {hash1; level1 = bh1.shell.level; hash2; level2 = bh2.shell.level})\n >>=? fun () ->\n Lwt.return (Raw_level.of_int32 bh1.shell.level)\n >>=? fun raw_level ->\n let oldest_level = Level.last_allowed_fork_level ctxt in\n fail_unless\n Raw_level.(raw_level < (Level.current ctxt).level)\n (Too_early_double_baking_evidence\n {level = raw_level; current = (Level.current ctxt).level})\n >>=? fun () ->\n fail_unless\n Raw_level.(oldest_level <= raw_level)\n (Outdated_double_baking_evidence\n {level = raw_level; last = oldest_level})\n >>=? fun () ->\n let level = Level.from_raw ctxt raw_level in\n Roll.baking_rights_owner\n ctxt\n level\n ~priority:bh1.protocol_data.contents.priority\n >>=? fun delegate1 ->\n Baking.check_signature bh1 chain_id delegate1\n >>=? fun () ->\n Roll.baking_rights_owner\n ctxt\n level\n ~priority:bh2.protocol_data.contents.priority\n >>=? fun delegate2 ->\n Baking.check_signature bh2 chain_id delegate2\n >>=? fun () ->\n fail_unless\n (Signature.Public_key.equal delegate1 delegate2)\n (Inconsistent_double_baking_evidence\n {\n delegate1 = Signature.Public_key.hash delegate1;\n delegate2 = Signature.Public_key.hash delegate2;\n })\n >>=? fun () ->\n let delegate = Signature.Public_key.hash delegate1 in\n Delegate.has_frozen_balance ctxt delegate level.cycle\n >>=? fun valid ->\n fail_unless valid Unrequired_double_baking_evidence\n >>=? fun () ->\n Delegate.punish ctxt delegate level.cycle\n >>=? fun (ctxt, balance) ->\n Tez.(balance.deposit +? balance.fees)\n >>?= fun burned ->\n let reward =\n match Tez.(burned /? 2L) with Ok v -> v | Error _ -> Tez.zero\n in\n Lwt.return\n ( add_rewards ctxt reward\n >|? fun ctxt ->\n let current_cycle = (Level.current ctxt).cycle in\n ( ctxt,\n Single_result\n (Double_baking_evidence_result\n (Delegate.cleanup_balance_updates\n [ (Deposits (delegate, level.cycle), Debited balance.deposit);\n (Fees (delegate, level.cycle), Debited balance.fees);\n (Rewards (delegate, level.cycle), Debited balance.rewards);\n (Rewards (baker, current_cycle), Credited reward) ])) ) )\n | Single (Activate_account {id = pkh; activation_code}) -> (\n let blinded_pkh =\n Blinded_public_key_hash.of_ed25519_pkh activation_code pkh\n in\n Commitment.get_opt ctxt blinded_pkh\n >>=? function\n | None ->\n fail (Invalid_activation {pkh})\n | Some amount ->\n Commitment.delete ctxt blinded_pkh\n >>=? fun ctxt ->\n let contract = Contract.implicit_contract (Signature.Ed25519 pkh) in\n Contract.(credit ctxt contract amount)\n >|=? fun ctxt ->\n ( ctxt,\n Single_result\n (Activate_account_result [(Contract contract, Credited amount)])\n ) )\n | Single (Proposals {source; period; proposals}) ->\n Roll.delegate_pubkey ctxt source\n >>=? fun delegate ->\n Operation.check_signature delegate chain_id operation\n >>?= fun () ->\n Voting_period.get_current ctxt\n >>=? fun {index = current_period; _} ->\n error_unless\n Compare.Int32.(current_period = period)\n (Wrong_voting_period (current_period, period))\n >>?= fun () ->\n Amendment.record_proposals ctxt source proposals\n >|=? fun ctxt -> (ctxt, Single_result Proposals_result)\n | Single (Ballot {source; period; proposal; ballot}) ->\n Roll.delegate_pubkey ctxt source\n >>=? fun delegate ->\n Operation.check_signature delegate chain_id operation\n >>?= fun () ->\n Voting_period.get_current ctxt\n >>=? fun {index = current_period; _} ->\n error_unless\n Compare.Int32.(current_period = period)\n (Wrong_voting_period (current_period, period))\n >>?= fun () ->\n Amendment.record_ballot ctxt source proposal ballot\n >|=? fun ctxt -> (ctxt, Single_result Ballot_result)\n | Single (Manager_operation _) as op ->\n precheck_manager_contents_list ctxt op\n >>=? fun ctxt ->\n check_manager_signature ctxt chain_id op operation\n >>=? fun () ->\n apply_manager_contents_list ctxt mode baker chain_id op >|= ok\n | Cons (Manager_operation _, _) as op ->\n precheck_manager_contents_list ctxt op\n >>=? fun ctxt ->\n check_manager_signature ctxt chain_id op operation\n >>=? fun () ->\n apply_manager_contents_list ctxt mode baker chain_id op >|= ok\n\nlet apply_operation ctxt chain_id mode pred_block baker hash operation =\n let ctxt = Contract.init_origination_nonce ctxt hash in\n apply_contents_list\n ctxt\n chain_id\n mode\n pred_block\n baker\n operation\n operation.protocol_data.contents\n >|=? fun (ctxt, result) ->\n let ctxt = Gas.set_unlimited ctxt in\n let ctxt = Contract.unset_origination_nonce ctxt in\n (ctxt, {contents = result})\n\nlet may_snapshot_roll ctxt =\n let level = Alpha_context.Level.current ctxt in\n let blocks_per_roll_snapshot = Constants.blocks_per_roll_snapshot ctxt in\n if\n Compare.Int32.equal\n (Int32.rem level.cycle_position blocks_per_roll_snapshot)\n (Int32.pred blocks_per_roll_snapshot)\n then Alpha_context.Roll.snapshot_rolls ctxt\n else return ctxt\n\nlet may_start_new_cycle ctxt =\n match Baking.dawn_of_a_new_cycle ctxt with\n | None ->\n return (ctxt, [], [])\n | Some last_cycle ->\n Seed.cycle_end ctxt last_cycle\n >>=? fun (ctxt, unrevealed) ->\n Roll.cycle_end ctxt last_cycle\n >>=? fun ctxt ->\n Delegate.cycle_end ctxt last_cycle unrevealed\n >>=? fun (ctxt, update_balances, deactivated) ->\n Bootstrap.cycle_end ctxt last_cycle\n >|=? fun ctxt -> (ctxt, update_balances, deactivated)\n\nlet endorsement_rights_of_pred_level ctxt =\n match Level.pred ctxt (Level.current ctxt) with\n | None ->\n assert false (* genesis *)\n | Some pred_level ->\n Baking.endorsement_rights ctxt pred_level\n\nlet begin_full_construction ctxt pred_timestamp protocol_data =\n Alpha_context.Global.set_block_priority\n ctxt\n protocol_data.Block_header.priority\n >>=? fun ctxt ->\n Baking.check_baking_rights ctxt protocol_data pred_timestamp\n >>=? fun (delegate_pk, block_delay) ->\n let ctxt = Fitness.increase ctxt in\n endorsement_rights_of_pred_level ctxt\n >|=? fun rights ->\n let ctxt = init_endorsements ctxt rights in\n (ctxt, protocol_data, delegate_pk, block_delay)\n\nlet begin_partial_construction ctxt =\n let ctxt = Fitness.increase ctxt in\n endorsement_rights_of_pred_level ctxt\n >|=? fun rights -> init_endorsements ctxt rights\n\nlet begin_application ctxt chain_id block_header pred_timestamp =\n Alpha_context.Global.set_block_priority\n ctxt\n block_header.Block_header.protocol_data.contents.priority\n >>=? fun ctxt ->\n let current_level = Alpha_context.Level.current ctxt in\n Baking.check_proof_of_work_stamp ctxt block_header\n >>?= fun () ->\n Baking.check_fitness_gap ctxt block_header\n >>?= fun () ->\n Baking.check_baking_rights\n ctxt\n block_header.protocol_data.contents\n pred_timestamp\n >>=? fun (delegate_pk, block_delay) ->\n Baking.check_signature block_header chain_id delegate_pk\n >>=? fun () ->\n let has_commitment =\n Option.is_some block_header.protocol_data.contents.seed_nonce_hash\n in\n error_unless\n Compare.Bool.(has_commitment = current_level.expected_commitment)\n (Invalid_commitment {expected = current_level.expected_commitment})\n >>?= fun () ->\n let ctxt = Fitness.increase ctxt in\n endorsement_rights_of_pred_level ctxt\n >|=? fun rights ->\n let ctxt = init_endorsements ctxt rights in\n (ctxt, delegate_pk, block_delay)\n\nlet check_minimum_endorsements ctxt protocol_data block_delay\n included_endorsements =\n let minimum = Baking.minimum_allowed_endorsements ctxt ~block_delay in\n let timestamp = Timestamp.current ctxt in\n error_unless\n Compare.Int.(included_endorsements >= minimum)\n (Not_enough_endorsements_for_priority\n {\n required = minimum;\n priority = protocol_data.Block_header.priority;\n endorsements = included_endorsements;\n timestamp;\n })\n\nlet finalize_application ctxt protocol_data delegate ~block_delay =\n let included_endorsements = included_endorsements ctxt in\n check_minimum_endorsements\n ctxt\n protocol_data\n block_delay\n included_endorsements\n >>?= fun () ->\n let deposit = Constants.block_security_deposit ctxt in\n add_deposit ctxt delegate deposit\n >>?= fun ctxt ->\n Baking.baking_reward\n ctxt\n ~block_priority:protocol_data.priority\n ~included_endorsements\n >>?= fun reward ->\n add_rewards ctxt reward\n >>?= fun ctxt ->\n Signature.Public_key_hash.Map.fold\n (fun delegate deposit ctxt ->\n ctxt >>=? fun ctxt -> Delegate.freeze_deposit ctxt delegate deposit)\n (get_deposits ctxt)\n (return ctxt)\n >>=? fun ctxt ->\n (* end of level (from this point nothing should fail) *)\n let fees = Alpha_context.get_fees ctxt in\n Delegate.freeze_fees ctxt delegate fees\n >>=? fun ctxt ->\n let rewards = Alpha_context.get_rewards ctxt in\n Delegate.freeze_rewards ctxt delegate rewards\n >>=? fun ctxt ->\n ( match protocol_data.Block_header.seed_nonce_hash with\n | None ->\n return ctxt\n | Some nonce_hash ->\n Nonce.record_hash ctxt {nonce_hash; delegate; rewards; fees} )\n >>=? fun ctxt ->\n (* end of cycle *)\n may_snapshot_roll ctxt\n >>=? fun ctxt ->\n may_start_new_cycle ctxt\n >>=? fun (ctxt, balance_updates, deactivated) ->\n Amendment.may_start_new_voting_period ctxt\n >>=? fun ctxt ->\n let cycle = (Level.current ctxt).cycle in\n let balance_updates =\n Delegate.(\n cleanup_balance_updates\n ( [ (Contract (Contract.implicit_contract delegate), Debited deposit);\n (Deposits (delegate, cycle), Credited deposit);\n (Rewards (delegate, cycle), Credited reward) ]\n @ balance_updates ))\n in\n let consumed_gas =\n Gas.Arith.sub\n (Gas.Arith.fp @@ Constants.hard_gas_limit_per_block ctxt)\n (Alpha_context.Gas.block_level ctxt)\n in\n (* This value is different than the new [voting_period_info] below for\n compatibility reasons, the field [voting_period_kind] is deprecated and will\n be removed in a future version. *)\n Alpha_context.Voting_period.get_current_info ctxt\n >>=? fun {voting_period = {kind; _}; _} ->\n Alpha_context.Voting_period.get_rpc_fixed_current_info ctxt\n >|=? fun ({voting_period; position; _} as voting_period_info) ->\n let level_info = Alpha_context.Level.current ctxt in\n let receipt =\n Apply_results.\n {\n baker = delegate;\n level =\n Level.to_deprecated_type\n level_info\n ~voting_period_index:voting_period.index\n ~voting_period_position:position;\n level_info;\n voting_period_info;\n voting_period_kind = kind;\n nonce_hash = protocol_data.seed_nonce_hash;\n consumed_gas;\n deactivated;\n balance_updates;\n }\n in\n (ctxt, receipt)\n" ;
} ;
{ name = "Services_registration" ;
interface = None ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\ntype rpc_context = {\n block_hash : Block_hash.t;\n block_header : Block_header.shell_header;\n context : Alpha_context.t;\n}\n\nlet rpc_init ({block_hash; block_header; context} : Updater.rpc_context) =\n let level = block_header.level in\n let timestamp = block_header.timestamp in\n let fitness = block_header.fitness in\n Alpha_context.prepare\n ~level\n ~predecessor_timestamp:timestamp\n ~timestamp\n ~fitness\n context\n >|=? fun context -> {block_hash; block_header; context}\n\nlet rpc_services =\n ref (RPC_directory.empty : Updater.rpc_context RPC_directory.t)\n\nlet register0_fullctxt s f =\n rpc_services :=\n RPC_directory.register !rpc_services s (fun ctxt q i ->\n rpc_init ctxt >>=? fun ctxt -> f ctxt q i)\n\nlet opt_register0_fullctxt s f =\n rpc_services :=\n RPC_directory.opt_register !rpc_services s (fun ctxt q i ->\n rpc_init ctxt >>=? fun ctxt -> f ctxt q i)\n\nlet register0 s f = register0_fullctxt s (fun {context; _} -> f context)\n\nlet register0_noctxt s f =\n rpc_services := RPC_directory.register !rpc_services s (fun _ q i -> f q i)\n\nlet register1_fullctxt s f =\n rpc_services :=\n RPC_directory.register !rpc_services s (fun (ctxt, arg) q i ->\n rpc_init ctxt >>=? fun ctxt -> f ctxt arg q i)\n\nlet register1 s f = register1_fullctxt s (fun {context; _} x -> f context x)\n\nlet register1_noctxt s f =\n rpc_services :=\n RPC_directory.register !rpc_services s (fun (_, arg) q i -> f arg q i)\n\nlet register2_fullctxt s f =\n rpc_services :=\n RPC_directory.register !rpc_services s (fun ((ctxt, arg1), arg2) q i ->\n rpc_init ctxt >>=? fun ctxt -> f ctxt arg1 arg2 q i)\n\nlet register2 s f =\n register2_fullctxt s (fun {context; _} a1 a2 q i -> f context a1 a2 q i)\n\nlet get_rpc_services () =\n let p =\n RPC_directory.map\n (fun c ->\n rpc_init c >|= function Error _ -> assert false | Ok c -> c.context)\n (Storage_description.build_directory Alpha_context.description)\n in\n RPC_directory.register_dynamic_directory\n !rpc_services\n RPC_path.(open_root / \"context\" / \"raw\" / \"json\")\n (fun _ -> Lwt.return p)\n" ;
} ;
{ name = "Constants_services" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nval errors :\n 'a #RPC_context.simple ->\n 'a ->\n Data_encoding.json_schema shell_tzresult Lwt.t\n\n(** Returns all the constants of the protocol *)\nval all : 'a #RPC_context.simple -> 'a -> Constants.t shell_tzresult Lwt.t\n\nval register : unit -> unit\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nlet custom_root =\n ( RPC_path.(open_root / \"context\" / \"constants\")\n : RPC_context.t RPC_path.context )\n\nmodule S = struct\n open Data_encoding\n\n let errors =\n RPC_service.get_service\n ~description:\"Schema for all the RPC errors from this protocol version\"\n ~query:RPC_query.empty\n ~output:json_schema\n RPC_path.(custom_root / \"errors\")\n\n let all =\n RPC_service.get_service\n ~description:\"All constants\"\n ~query:RPC_query.empty\n ~output:Alpha_context.Constants.encoding\n custom_root\nend\n\nlet register () =\n let open Services_registration in\n register0_noctxt S.errors (fun () () ->\n return Data_encoding.Json.(schema error_encoding)) ;\n register0 S.all (fun ctxt () () ->\n let open Constants in\n return {fixed; parametric = parametric ctxt})\n\nlet errors ctxt block = RPC_context.make_call0 S.errors ctxt block () ()\n\nlet all ctxt block = RPC_context.make_call0 S.all ctxt block () ()\n" ;
} ;
{ name = "Sapling_services" ;
interface = None ;
implementation = "(* The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE. *)\n\nopen Alpha_context\n\nlet custom_root =\n ( RPC_path.(open_root / \"context\" / \"sapling\")\n : RPC_context.t RPC_path.context )\n\ntype diff_query = {\n offset_commitment : Int64.t option;\n offset_nullifier : Int64.t option;\n}\n\nmodule S = struct\n module Args = struct\n type ('query, 'output) t = {\n name : string;\n description : string;\n query : 'query RPC_query.t;\n output : 'output Data_encoding.t;\n f : context -> Sapling.Id.t -> 'query -> 'output tzresult Lwt.t;\n }\n\n let get_diff_query : diff_query RPC_query.t =\n let open RPC_query in\n query (fun offset_commitment offset_nullifier ->\n {offset_commitment; offset_nullifier})\n |+ opt_field\n ~descr:\n \"Commitments and ciphertexts are returned from the specified \\\n offset up to the most recent.\"\n \"offset_commitment\"\n RPC_arg.int64\n (fun {offset_commitment; _} -> offset_commitment)\n |+ opt_field\n ~descr:\n \"Nullifiers are returned from the specified offset up to the \\\n most recent.\"\n \"offset_nullifier\"\n RPC_arg.int64\n (fun {offset_nullifier; _} -> offset_nullifier)\n |> seal\n\n let encoding =\n let open Data_encoding in\n merge_objs\n (obj1 (req \"root\" Sapling.root_encoding))\n Sapling.diff_encoding\n\n let get_diff =\n {\n name = \"get_diff\";\n description =\n \"Returns the root and a diff of a state starting from an optional \\\n offset which is zero by default.\";\n query = get_diff_query;\n output = encoding;\n f =\n (fun ctxt id {offset_commitment; offset_nullifier} ->\n Sapling.get_diff ctxt id ?offset_commitment ?offset_nullifier ());\n }\n end\n\n let make_service Args.{name; description; query; output; f} =\n let path = RPC_path.(custom_root /: Sapling.rpc_arg / name) in\n let service = RPC_service.get_service ~description ~query ~output path in\n (service, fun ctxt id q () -> f ctxt id q)\n\n let get_diff = make_service Args.get_diff\nend\n\nlet register () =\n let reg (service, f) = Services_registration.register1 service f in\n reg S.get_diff\n\nlet mk_call1 (service, _f) ctxt block id q =\n RPC_context.make_call1 service ctxt block id q ()\n\nlet get_diff ctxt block id ?offset_commitment ?offset_nullifier () =\n mk_call1 S.get_diff ctxt block id {offset_commitment; offset_nullifier}\n" ;
} ;
{ name = "Contract_services" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nval list : 'a #RPC_context.simple -> 'a -> Contract.t list shell_tzresult Lwt.t\n\ntype info = {\n balance : Tez.t;\n delegate : public_key_hash option;\n counter : counter option;\n script : Script.t option;\n}\n\nval info_encoding : info Data_encoding.t\n\nval info :\n 'a #RPC_context.simple -> 'a -> Contract.t -> info shell_tzresult Lwt.t\n\nval balance :\n 'a #RPC_context.simple -> 'a -> Contract.t -> Tez.t shell_tzresult Lwt.t\n\nval manager_key :\n 'a #RPC_context.simple ->\n 'a ->\n public_key_hash ->\n public_key option shell_tzresult Lwt.t\n\nval delegate :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n public_key_hash shell_tzresult Lwt.t\n\nval delegate_opt :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n public_key_hash option shell_tzresult Lwt.t\n\nval counter :\n 'a #RPC_context.simple ->\n 'a ->\n public_key_hash ->\n counter shell_tzresult Lwt.t\n\nval script :\n 'a #RPC_context.simple -> 'a -> Contract.t -> Script.t shell_tzresult Lwt.t\n\nval script_opt :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n Script.t option shell_tzresult Lwt.t\n\nval storage :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n Script.expr shell_tzresult Lwt.t\n\nval entrypoint_type :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n string ->\n Script.expr shell_tzresult Lwt.t\n\nval list_entrypoints :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n (Michelson_v1_primitives.prim list list * (string * Script.expr) list)\n shell_tzresult\n Lwt.t\n\nval storage_opt :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n Script.expr option shell_tzresult Lwt.t\n\nval big_map_get :\n 'a #RPC_context.simple ->\n 'a ->\n Big_map.Id.t ->\n Script_expr_hash.t ->\n Script.expr shell_tzresult Lwt.t\n\nval contract_big_map_get_opt :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n Script.expr * Script.expr ->\n Script.expr option shell_tzresult Lwt.t\n\nval single_sapling_get_diff :\n 'a #RPC_context.simple ->\n 'a ->\n Contract.t ->\n ?offset_commitment:int64 ->\n ?offset_nullifier:int64 ->\n unit ->\n (Sapling.root * Sapling.diff) shell_tzresult Lwt.t\n\nval register : unit -> unit\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nlet custom_root =\n ( RPC_path.(open_root / \"context\" / \"contracts\")\n : RPC_context.t RPC_path.context )\n\nlet big_map_root =\n ( RPC_path.(open_root / \"context\" / \"big_maps\")\n : RPC_context.t RPC_path.context )\n\ntype info = {\n balance : Tez.t;\n delegate : public_key_hash option;\n counter : counter option;\n script : Script.t option;\n}\n\nlet info_encoding =\n let open Data_encoding in\n conv\n (fun {balance; delegate; script; counter} ->\n (balance, delegate, script, counter))\n (fun (balance, delegate, script, counter) ->\n {balance; delegate; script; counter})\n @@ obj4\n (req \"balance\" Tez.encoding)\n (opt \"delegate\" Signature.Public_key_hash.encoding)\n (opt \"script\" Script.encoding)\n (opt \"counter\" n)\n\nmodule S = struct\n open Data_encoding\n\n let balance =\n RPC_service.get_service\n ~description:\"Access the balance of a contract.\"\n ~query:RPC_query.empty\n ~output:Tez.encoding\n RPC_path.(custom_root /: Contract.rpc_arg / \"balance\")\n\n let manager_key =\n RPC_service.get_service\n ~description:\"Access the manager of a contract.\"\n ~query:RPC_query.empty\n ~output:(option Signature.Public_key.encoding)\n RPC_path.(custom_root /: Contract.rpc_arg / \"manager_key\")\n\n let delegate =\n RPC_service.get_service\n ~description:\"Access the delegate of a contract, if any.\"\n ~query:RPC_query.empty\n ~output:Signature.Public_key_hash.encoding\n RPC_path.(custom_root /: Contract.rpc_arg / \"delegate\")\n\n let counter =\n RPC_service.get_service\n ~description:\"Access the counter of a contract, if any.\"\n ~query:RPC_query.empty\n ~output:z\n RPC_path.(custom_root /: Contract.rpc_arg / \"counter\")\n\n let script =\n RPC_service.get_service\n ~description:\"Access the code and data of the contract.\"\n ~query:RPC_query.empty\n ~output:Script.encoding\n RPC_path.(custom_root /: Contract.rpc_arg / \"script\")\n\n let storage =\n RPC_service.get_service\n ~description:\"Access the data of the contract.\"\n ~query:RPC_query.empty\n ~output:Script.expr_encoding\n RPC_path.(custom_root /: Contract.rpc_arg / \"storage\")\n\n let entrypoint_type =\n RPC_service.get_service\n ~description:\"Return the type of the given entrypoint of the contract\"\n ~query:RPC_query.empty\n ~output:Script.expr_encoding\n RPC_path.(\n custom_root /: Contract.rpc_arg / \"entrypoints\" /: RPC_arg.string)\n\n let list_entrypoints =\n RPC_service.get_service\n ~description:\"Return the list of entrypoints of the contract\"\n ~query:RPC_query.empty\n ~output:\n (obj2\n (dft\n \"unreachable\"\n (Data_encoding.list\n (obj1\n (req\n \"path\"\n (Data_encoding.list\n Michelson_v1_primitives.prim_encoding))))\n [])\n (req \"entrypoints\" (assoc Script.expr_encoding)))\n RPC_path.(custom_root /: Contract.rpc_arg / \"entrypoints\")\n\n let contract_big_map_get_opt =\n RPC_service.post_service\n ~description:\n \"Access the value associated with a key in a big map of the contract \\\n (deprecated).\"\n ~query:RPC_query.empty\n ~input:\n (obj2\n (req \"key\" Script.expr_encoding)\n (req \"type\" Script.expr_encoding))\n ~output:(option Script.expr_encoding)\n RPC_path.(custom_root /: Contract.rpc_arg / \"big_map_get\")\n\n let big_map_get =\n RPC_service.get_service\n ~description:\"Access the value associated with a key in a big map.\"\n ~query:RPC_query.empty\n ~output:Script.expr_encoding\n RPC_path.(big_map_root /: Big_map.Id.rpc_arg /: Script_expr_hash.rpc_arg)\n\n let info =\n RPC_service.get_service\n ~description:\"Access the complete status of a contract.\"\n ~query:RPC_query.empty\n ~output:info_encoding\n RPC_path.(custom_root /: Contract.rpc_arg)\n\n let list =\n RPC_service.get_service\n ~description:\n \"All existing contracts (including non-empty default contracts).\"\n ~query:RPC_query.empty\n ~output:(list Contract.encoding)\n custom_root\n\n module Sapling = struct\n (*\n Sapling: these RPCs are like Sapling RPCs (sapling_services.ml)\n specialized for contracts containing a single sapling state.\n *)\n\n let single_sapling_get_id ctxt contract_id =\n Contract.get_script ctxt contract_id\n >>=? fun (ctxt, script) ->\n match script with\n | None ->\n raise Not_found\n | Some script ->\n let ctxt = Gas.set_unlimited ctxt in\n Script_ir_translator.parse_script\n ctxt\n ~legacy:true\n ~allow_forged_in_storage:true\n script\n >|= fun tzresult ->\n tzresult\n >>? fun (Ex_script script, ctxt) ->\n Script_ir_translator.get_single_sapling_state\n ctxt\n script.storage_type\n script.storage\n\n let make_service\n Sapling_services.S.Args.{name; description; query; output; f} =\n let name = \"single_sapling_\" ^ name in\n let path = RPC_path.(custom_root /: Contract.rpc_arg / name) in\n let service = RPC_service.get_service ~description ~query ~output path in\n ( service,\n fun ctxt contract_id q () ->\n single_sapling_get_id ctxt contract_id\n >>=? fun (sapling_id, ctxt) -> f ctxt sapling_id q )\n\n let get_diff = make_service Sapling_services.S.Args.get_diff\n\n let register () =\n let reg (service, f) = Services_registration.register1 service f in\n reg get_diff\n\n let mk_call1 (service, _f) ctxt block id q =\n RPC_context.make_call1 service ctxt block id q ()\n end\nend\n\nlet register () =\n let open Services_registration in\n register0 S.list (fun ctxt () () -> Contract.list ctxt >|= ok) ;\n let register_field s f =\n register1 s (fun ctxt contract () () ->\n Contract.exists ctxt contract\n >>=? function true -> f ctxt contract | false -> raise Not_found)\n in\n let register_opt_field s f =\n register_field s (fun ctxt a1 ->\n f ctxt a1 >|=? function None -> raise Not_found | Some v -> v)\n in\n let do_big_map_get ctxt id key =\n let open Script_ir_translator in\n let ctxt = Gas.set_unlimited ctxt in\n Big_map.exists ctxt id\n >>=? fun (ctxt, types) ->\n match types with\n | None ->\n raise Not_found\n | Some (_, value_type) -> (\n parse_big_map_value_ty ctxt ~legacy:true (Micheline.root value_type)\n >>?= fun (Ex_ty value_type, ctxt) ->\n Big_map.get_opt ctxt id key\n >>=? fun (_ctxt, value) ->\n match value with\n | None ->\n raise Not_found\n | Some value ->\n parse_data\n ctxt\n ~legacy:true\n ~allow_forged:true\n value_type\n (Micheline.root value)\n >>=? fun (value, ctxt) ->\n unparse_data ctxt Readable value_type value\n >|=? fun (value, _ctxt) -> Micheline.strip_locations value )\n in\n register_field S.balance Contract.get_balance ;\n register1 S.manager_key (fun ctxt contract () () ->\n match Contract.is_implicit contract with\n | None ->\n raise Not_found\n | Some mgr -> (\n Contract.is_manager_key_revealed ctxt mgr\n >>=? function\n | false ->\n return_none\n | true ->\n Contract.get_manager_key ctxt mgr >>=? return_some )) ;\n register_opt_field S.delegate Delegate.get ;\n register1 S.counter (fun ctxt contract () () ->\n match Contract.is_implicit contract with\n | None ->\n raise Not_found\n | Some mgr ->\n Contract.get_counter ctxt mgr) ;\n register_opt_field S.script (fun c v ->\n Contract.get_script c v >|=? fun (_, v) -> v) ;\n register_opt_field S.storage (fun ctxt contract ->\n Contract.get_script ctxt contract\n >>=? fun (ctxt, script) ->\n match script with\n | None ->\n return_none\n | Some script ->\n let ctxt = Gas.set_unlimited ctxt in\n let open Script_ir_translator in\n parse_script ctxt ~legacy:true ~allow_forged_in_storage:true script\n >>=? fun (Ex_script script, ctxt) ->\n unparse_script ctxt Readable script\n >>=? fun (script, ctxt) ->\n Script.force_decode_in_context ctxt script.storage\n >>?= fun (storage, _ctxt) -> return_some storage) ;\n register2 S.entrypoint_type (fun ctxt v entrypoint () () ->\n Contract.get_script_code ctxt v\n >>=? fun (_, expr) ->\n match expr with\n | None ->\n raise Not_found\n | Some expr ->\n let ctxt = Gas.set_unlimited ctxt in\n let legacy = true in\n let open Script_ir_translator in\n Lwt.return\n ( Script.force_decode_in_context ctxt expr\n >>? fun (expr, _) ->\n parse_toplevel ~legacy expr\n >>? (fun (arg_type, _, _, root_name) ->\n parse_parameter_ty ctxt ~legacy arg_type\n >>? fun (Ex_ty arg_type, _) ->\n Script_ir_translator.find_entrypoint\n ~root_name\n arg_type\n entrypoint)\n |> function\n | Ok (_f, Ex_ty ty) ->\n unparse_ty ctxt ty\n >|? fun (ty_node, _) -> Micheline.strip_locations ty_node\n | Error _ ->\n raise Not_found )) ;\n register1 S.list_entrypoints (fun ctxt v () () ->\n Contract.get_script_code ctxt v\n >>=? fun (_, expr) ->\n match expr with\n | None ->\n raise Not_found\n | Some expr ->\n let ctxt = Gas.set_unlimited ctxt in\n let legacy = true in\n let open Script_ir_translator in\n Lwt.return\n ( Script.force_decode_in_context ctxt expr\n >>? fun (expr, _) ->\n parse_toplevel ~legacy expr\n >>? (fun (arg_type, _, _, root_name) ->\n parse_parameter_ty ctxt ~legacy arg_type\n >>? fun (Ex_ty arg_type, _) ->\n Script_ir_translator.list_entrypoints\n ~root_name\n arg_type\n ctxt)\n >|? fun (unreachable_entrypoint, map) ->\n ( unreachable_entrypoint,\n Entrypoints_map.fold\n (fun entry (_, ty) acc ->\n (entry, Micheline.strip_locations ty) :: acc)\n map\n [] ) )) ;\n register1 S.contract_big_map_get_opt (fun ctxt contract () (key, key_type) ->\n Contract.get_script ctxt contract\n >>=? fun (ctxt, script) ->\n Script_ir_translator.parse_comparable_ty ctxt (Micheline.root key_type)\n >>?= fun (Ex_comparable_ty key_type, ctxt) ->\n Script_ir_translator.parse_comparable_data\n ctxt\n key_type\n (Micheline.root key)\n >>=? fun (key, ctxt) ->\n Script_ir_translator.hash_comparable_data ctxt key_type key\n >>=? fun (key, ctxt) ->\n match script with\n | None ->\n raise Not_found\n | Some script -> (\n let ctxt = Gas.set_unlimited ctxt in\n let open Script_ir_translator in\n parse_script ctxt ~legacy:true ~allow_forged_in_storage:true script\n >>=? fun (Ex_script script, ctxt) ->\n Script_ir_translator.collect_lazy_storage\n ctxt\n script.storage_type\n script.storage\n >>?= fun (ids, _ctxt) ->\n match Script_ir_translator.list_of_big_map_ids ids with\n | [] | _ :: _ :: _ ->\n return_none\n | [id] -> (\n try do_big_map_get ctxt id key >>=? return_some\n with Not_found -> return_none ) )) ;\n register2 S.big_map_get (fun ctxt id key () () -> do_big_map_get ctxt id key) ;\n register_field S.info (fun ctxt contract ->\n Contract.get_balance ctxt contract\n >>=? fun balance ->\n Delegate.get ctxt contract\n >>=? fun delegate ->\n ( match Contract.is_implicit contract with\n | Some manager ->\n Contract.get_counter ctxt manager\n >>=? fun counter -> return_some counter\n | None ->\n return_none )\n >>=? fun counter ->\n Contract.get_script ctxt contract\n >>=? fun (ctxt, script) ->\n ( match script with\n | None ->\n return (None, ctxt)\n | Some script ->\n let ctxt = Gas.set_unlimited ctxt in\n let open Script_ir_translator in\n parse_script ctxt ~legacy:true ~allow_forged_in_storage:true script\n >>=? fun (Ex_script script, ctxt) ->\n unparse_script ctxt Readable script\n >|=? fun (script, ctxt) -> (Some script, ctxt) )\n >|=? fun (script, _ctxt) -> {balance; delegate; script; counter}) ;\n S.Sapling.register ()\n\nlet list ctxt block = RPC_context.make_call0 S.list ctxt block () ()\n\nlet info ctxt block contract =\n RPC_context.make_call1 S.info ctxt block contract () ()\n\nlet balance ctxt block contract =\n RPC_context.make_call1 S.balance ctxt block contract () ()\n\nlet manager_key ctxt block mgr =\n RPC_context.make_call1\n S.manager_key\n ctxt\n block\n (Contract.implicit_contract mgr)\n ()\n ()\n\nlet delegate ctxt block contract =\n RPC_context.make_call1 S.delegate ctxt block contract () ()\n\nlet delegate_opt ctxt block contract =\n RPC_context.make_opt_call1 S.delegate ctxt block contract () ()\n\nlet counter ctxt block mgr =\n RPC_context.make_call1\n S.counter\n ctxt\n block\n (Contract.implicit_contract mgr)\n ()\n ()\n\nlet script ctxt block contract =\n RPC_context.make_call1 S.script ctxt block contract () ()\n\nlet script_opt ctxt block contract =\n RPC_context.make_opt_call1 S.script ctxt block contract () ()\n\nlet storage ctxt block contract =\n RPC_context.make_call1 S.storage ctxt block contract () ()\n\nlet entrypoint_type ctxt block contract entrypoint =\n RPC_context.make_call2 S.entrypoint_type ctxt block contract entrypoint () ()\n\nlet list_entrypoints ctxt block contract =\n RPC_context.make_call1 S.list_entrypoints ctxt block contract () ()\n\nlet storage_opt ctxt block contract =\n RPC_context.make_opt_call1 S.storage ctxt block contract () ()\n\nlet big_map_get ctxt block id key =\n RPC_context.make_call2 S.big_map_get ctxt block id key () ()\n\nlet contract_big_map_get_opt ctxt block contract key =\n RPC_context.make_call1 S.contract_big_map_get_opt ctxt block contract () key\n\nlet single_sapling_get_diff ctxt block id ?offset_commitment ?offset_nullifier\n () =\n S.Sapling.(mk_call1 get_diff)\n ctxt\n block\n id\n Sapling_services.{offset_commitment; offset_nullifier}\n" ;
} ;
{ name = "Delegate_services" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nval list :\n 'a #RPC_context.simple ->\n 'a ->\n ?active:bool ->\n ?inactive:bool ->\n unit ->\n Signature.Public_key_hash.t list shell_tzresult Lwt.t\n\ntype info = {\n balance : Tez.t;\n frozen_balance : Tez.t;\n frozen_balance_by_cycle : Delegate.frozen_balance Cycle.Map.t;\n staking_balance : Tez.t;\n delegated_contracts : Contract_repr.t list;\n delegated_balance : Tez.t;\n deactivated : bool;\n grace_period : Cycle.t;\n voting_power : int32;\n}\n\nval info_encoding : info Data_encoding.t\n\nval info :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n info shell_tzresult Lwt.t\n\nval balance :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Tez.t shell_tzresult Lwt.t\n\nval frozen_balance :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Tez.t shell_tzresult Lwt.t\n\nval frozen_balance_by_cycle :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Delegate.frozen_balance Cycle.Map.t shell_tzresult Lwt.t\n\nval staking_balance :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Tez.t shell_tzresult Lwt.t\n\nval delegated_contracts :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Contract_repr.t list shell_tzresult Lwt.t\n\nval delegated_balance :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Tez.t shell_tzresult Lwt.t\n\nval deactivated :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n bool shell_tzresult Lwt.t\n\nval grace_period :\n 'a #RPC_context.simple ->\n 'a ->\n Signature.Public_key_hash.t ->\n Cycle.t shell_tzresult Lwt.t\n\nval voting_power :\n 'a #RPC_context.simple -> 'a -> public_key_hash -> int32 shell_tzresult Lwt.t\n\nmodule Baking_rights : sig\n type t = {\n level : Raw_level.t;\n delegate : Signature.Public_key_hash.t;\n priority : int;\n timestamp : Timestamp.t option;\n }\n\n (** Retrieves the list of delegates allowed to bake a block.\n\n By default, it gives the best baking priorities for bakers\n that have at least one opportunity below the 64th priority for\n the next block.\n\n Parameters [levels] and [cycles] can be used to specify the\n (valid) level(s) in the past or future at which the baking rights\n have to be returned. Parameter [delegates] can be used to\n restrict the results to the given delegates. If parameter [all]\n is [true], all the baking opportunities for each baker at each level\n are returned, instead of just the first one.\n\n Returns the list of baking slots. Also returns the minimal\n timestamps that correspond to these slots. The timestamps are\n omitted for levels in the past, and are only estimates for levels\n later that the next block, based on the hypothesis that all\n predecessor blocks were baked at the first priority. *)\n val get :\n 'a #RPC_context.simple ->\n ?levels:Raw_level.t list ->\n ?cycles:Cycle.t list ->\n ?delegates:Signature.public_key_hash list ->\n ?all:bool ->\n ?max_priority:int ->\n 'a ->\n t list shell_tzresult Lwt.t\nend\n\nmodule Endorsing_rights : sig\n type t = {\n level : Raw_level.t;\n delegate : Signature.Public_key_hash.t;\n slots : int list;\n estimated_time : Timestamp.t option;\n }\n\n (** Retrieves the delegates allowed to endorse a block.\n\n By default, it gives the endorsement slots for bakers that have\n at least one in the next block.\n\n Parameters [levels] and [cycles] can be used to specify the\n (valid) level(s) in the past or future at which the endorsement\n rights have to be returned. Parameter [delegates] can be used to\n restrict the results to the given delegates. Returns the list of\n endorsement slots. Also returns the minimal timestamps that\n correspond to these slots.\n\n Timestamps are omitted for levels in the past, and are only\n estimates for levels later that the next block, based on the\n hypothesis that all predecessor blocks were baked at the first\n priority. *)\n val get :\n 'a #RPC_context.simple ->\n ?levels:Raw_level.t list ->\n ?cycles:Cycle.t list ->\n ?delegates:Signature.public_key_hash list ->\n 'a ->\n t list shell_tzresult Lwt.t\nend\n\nmodule Endorsing_power : sig\n val get :\n 'a #RPC_context.simple ->\n 'a ->\n Alpha_context.packed_operation ->\n Chain_id.t ->\n int shell_tzresult Lwt.t\nend\n\nmodule Required_endorsements : sig\n val get :\n 'a #RPC_context.simple -> 'a -> Period.t -> int shell_tzresult Lwt.t\nend\n\nmodule Minimal_valid_time : sig\n val get :\n 'a #RPC_context.simple -> 'a -> int -> int -> Time.t shell_tzresult Lwt.t\nend\n\n(* temporary export for deprecated unit test *)\nval endorsement_rights :\n Alpha_context.t -> Level.t -> public_key_hash list tzresult Lwt.t\n\nval baking_rights :\n Alpha_context.t ->\n int option ->\n (Raw_level.t * (public_key_hash * Time.t option) list) tzresult Lwt.t\n\nval endorsing_power :\n Alpha_context.t ->\n Alpha_context.packed_operation * Chain_id.t ->\n int tzresult Lwt.t\n\nval required_endorsements : Alpha_context.t -> Alpha_context.Period.t -> int\n\nval minimal_valid_time : Alpha_context.t -> int -> int -> Time.t tzresult\n\nval register : unit -> unit\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2020 Metastate AG <hello@metastate.dev> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\ntype info = {\n balance : Tez.t;\n frozen_balance : Tez.t;\n frozen_balance_by_cycle : Delegate.frozen_balance Cycle.Map.t;\n staking_balance : Tez.t;\n delegated_contracts : Contract_repr.t list;\n delegated_balance : Tez.t;\n deactivated : bool;\n grace_period : Cycle.t;\n voting_power : int32;\n}\n\nlet info_encoding =\n let open Data_encoding in\n conv\n (fun { balance;\n frozen_balance;\n frozen_balance_by_cycle;\n staking_balance;\n delegated_contracts;\n delegated_balance;\n deactivated;\n grace_period;\n voting_power } ->\n ( balance,\n frozen_balance,\n frozen_balance_by_cycle,\n staking_balance,\n delegated_contracts,\n delegated_balance,\n deactivated,\n grace_period,\n voting_power ))\n (fun ( balance,\n frozen_balance,\n frozen_balance_by_cycle,\n staking_balance,\n delegated_contracts,\n delegated_balance,\n deactivated,\n grace_period,\n voting_power ) ->\n {\n balance;\n frozen_balance;\n frozen_balance_by_cycle;\n staking_balance;\n delegated_contracts;\n delegated_balance;\n deactivated;\n grace_period;\n voting_power;\n })\n (obj9\n (req \"balance\" Tez.encoding)\n (req \"frozen_balance\" Tez.encoding)\n (req \"frozen_balance_by_cycle\" Delegate.frozen_balance_by_cycle_encoding)\n (req \"staking_balance\" Tez.encoding)\n (req \"delegated_contracts\" (list Contract_repr.encoding))\n (req \"delegated_balance\" Tez.encoding)\n (req \"deactivated\" bool)\n (req \"grace_period\" Cycle.encoding)\n (req \"voting_power\" int32))\n\nmodule S = struct\n let path = RPC_path.(open_root / \"context\" / \"delegates\")\n\n open Data_encoding\n\n type list_query = {active : bool; inactive : bool}\n\n let list_query : list_query RPC_query.t =\n let open RPC_query in\n query (fun active inactive -> {active; inactive})\n |+ flag \"active\" (fun t -> t.active)\n |+ flag \"inactive\" (fun t -> t.inactive)\n |> seal\n\n let list_delegate =\n RPC_service.get_service\n ~description:\"Lists all registered delegates.\"\n ~query:list_query\n ~output:(list Signature.Public_key_hash.encoding)\n path\n\n let path = RPC_path.(path /: Signature.Public_key_hash.rpc_arg)\n\n let info =\n RPC_service.get_service\n ~description:\"Everything about a delegate.\"\n ~query:RPC_query.empty\n ~output:info_encoding\n path\n\n let balance =\n RPC_service.get_service\n ~description:\n \"Returns the full balance of a given delegate, including the frozen \\\n balances.\"\n ~query:RPC_query.empty\n ~output:Tez.encoding\n RPC_path.(path / \"balance\")\n\n let frozen_balance =\n RPC_service.get_service\n ~description:\n \"Returns the total frozen balances of a given delegate, this includes \\\n the frozen deposits, rewards and fees.\"\n ~query:RPC_query.empty\n ~output:Tez.encoding\n RPC_path.(path / \"frozen_balance\")\n\n let frozen_balance_by_cycle =\n RPC_service.get_service\n ~description:\n \"Returns the frozen balances of a given delegate, indexed by the \\\n cycle by which it will be unfrozen\"\n ~query:RPC_query.empty\n ~output:Delegate.frozen_balance_by_cycle_encoding\n RPC_path.(path / \"frozen_balance_by_cycle\")\n\n let staking_balance =\n RPC_service.get_service\n ~description:\n \"Returns the total amount of tokens delegated to a given delegate. \\\n This includes the balances of all the contracts that delegate to it, \\\n but also the balance of the delegate itself and its frozen fees and \\\n deposits. The rewards do not count in the delegated balance until \\\n they are unfrozen.\"\n ~query:RPC_query.empty\n ~output:Tez.encoding\n RPC_path.(path / \"staking_balance\")\n\n let delegated_contracts =\n RPC_service.get_service\n ~description:\n \"Returns the list of contracts that delegate to a given delegate.\"\n ~query:RPC_query.empty\n ~output:(list Contract_repr.encoding)\n RPC_path.(path / \"delegated_contracts\")\n\n let delegated_balance =\n RPC_service.get_service\n ~description:\n \"Returns the balances of all the contracts that delegate to a given \\\n delegate. This excludes the delegate's own balance and its frozen \\\n balances.\"\n ~query:RPC_query.empty\n ~output:Tez.encoding\n RPC_path.(path / \"delegated_balance\")\n\n let deactivated =\n RPC_service.get_service\n ~description:\n \"Tells whether the delegate is currently tagged as deactivated or not.\"\n ~query:RPC_query.empty\n ~output:bool\n RPC_path.(path / \"deactivated\")\n\n let grace_period =\n RPC_service.get_service\n ~description:\n \"Returns the cycle by the end of which the delegate might be \\\n deactivated if she fails to execute any delegate action. A \\\n deactivated delegate might be reactivated (without loosing any \\\n rolls) by simply re-registering as a delegate. For deactivated \\\n delegates, this value contains the cycle by which they were \\\n deactivated.\"\n ~query:RPC_query.empty\n ~output:Cycle.encoding\n RPC_path.(path / \"grace_period\")\n\n let voting_power =\n RPC_service.get_service\n ~description:\n \"The number of rolls in the vote listings for a given delegate\"\n ~query:RPC_query.empty\n ~output:Data_encoding.int32\n RPC_path.(path / \"voting_power\")\nend\n\nlet register () =\n let open Services_registration in\n register0 S.list_delegate (fun ctxt q () ->\n Delegate.list ctxt\n >>= fun delegates ->\n match q with\n | {active = true; inactive = false} ->\n filter_s\n (fun pkh -> Delegate.deactivated ctxt pkh >|=? not)\n delegates\n | {active = false; inactive = true} ->\n filter_s (fun pkh -> Delegate.deactivated ctxt pkh) delegates\n | _ ->\n return delegates) ;\n register1 S.info (fun ctxt pkh () () ->\n Delegate.full_balance ctxt pkh\n >>=? fun balance ->\n Delegate.frozen_balance ctxt pkh\n >>=? fun frozen_balance ->\n Delegate.frozen_balance_by_cycle ctxt pkh\n >>= fun frozen_balance_by_cycle ->\n Delegate.staking_balance ctxt pkh\n >>=? fun staking_balance ->\n Delegate.delegated_contracts ctxt pkh\n >>= fun delegated_contracts ->\n Delegate.delegated_balance ctxt pkh\n >>=? fun delegated_balance ->\n Delegate.deactivated ctxt pkh\n >>=? fun deactivated ->\n Delegate.grace_period ctxt pkh\n >>=? fun grace_period ->\n Vote.get_voting_power_free ctxt pkh\n >|=? fun voting_power ->\n {\n balance;\n frozen_balance;\n frozen_balance_by_cycle;\n staking_balance;\n delegated_contracts;\n delegated_balance;\n deactivated;\n grace_period;\n voting_power;\n }) ;\n register1 S.balance (fun ctxt pkh () () -> Delegate.full_balance ctxt pkh) ;\n register1 S.frozen_balance (fun ctxt pkh () () ->\n Delegate.frozen_balance ctxt pkh) ;\n register1 S.frozen_balance_by_cycle (fun ctxt pkh () () ->\n Delegate.frozen_balance_by_cycle ctxt pkh >|= ok) ;\n register1 S.staking_balance (fun ctxt pkh () () ->\n Delegate.staking_balance ctxt pkh) ;\n register1 S.delegated_contracts (fun ctxt pkh () () ->\n Delegate.delegated_contracts ctxt pkh >|= ok) ;\n register1 S.delegated_balance (fun ctxt pkh () () ->\n Delegate.delegated_balance ctxt pkh) ;\n register1 S.deactivated (fun ctxt pkh () () -> Delegate.deactivated ctxt pkh) ;\n register1 S.grace_period (fun ctxt pkh () () ->\n Delegate.grace_period ctxt pkh) ;\n register1 S.voting_power (fun ctxt pkh () () ->\n Vote.get_voting_power_free ctxt pkh)\n\nlet list ctxt block ?(active = true) ?(inactive = false) () =\n RPC_context.make_call0 S.list_delegate ctxt block {active; inactive} ()\n\nlet info ctxt block pkh = RPC_context.make_call1 S.info ctxt block pkh () ()\n\nlet balance ctxt block pkh =\n RPC_context.make_call1 S.balance ctxt block pkh () ()\n\nlet frozen_balance ctxt block pkh =\n RPC_context.make_call1 S.frozen_balance ctxt block pkh () ()\n\nlet frozen_balance_by_cycle ctxt block pkh =\n RPC_context.make_call1 S.frozen_balance_by_cycle ctxt block pkh () ()\n\nlet staking_balance ctxt block pkh =\n RPC_context.make_call1 S.staking_balance ctxt block pkh () ()\n\nlet delegated_contracts ctxt block pkh =\n RPC_context.make_call1 S.delegated_contracts ctxt block pkh () ()\n\nlet delegated_balance ctxt block pkh =\n RPC_context.make_call1 S.delegated_balance ctxt block pkh () ()\n\nlet deactivated ctxt block pkh =\n RPC_context.make_call1 S.deactivated ctxt block pkh () ()\n\nlet grace_period ctxt block pkh =\n RPC_context.make_call1 S.grace_period ctxt block pkh () ()\n\nlet voting_power ctxt block pkh =\n RPC_context.make_call1 S.voting_power ctxt block pkh () ()\n\nlet requested_levels ~default ctxt cycles levels =\n match (levels, cycles) with\n | ([], []) ->\n ok [default]\n | (levels, cycles) ->\n (* explicitly fail when requested levels or cycle are in the past...\n or too far in the future... *)\n let levels =\n List.sort_uniq\n Level.compare\n (List.concat\n ( List.map (Level.from_raw ctxt) levels\n :: List.map (Level.levels_in_cycle ctxt) cycles ))\n in\n map\n (fun level ->\n let current_level = Level.current ctxt in\n if Level.(level <= current_level) then ok (level, None)\n else\n Baking.earlier_predecessor_timestamp ctxt level\n >|? fun timestamp -> (level, Some timestamp))\n levels\n\nmodule Baking_rights = struct\n type t = {\n level : Raw_level.t;\n delegate : Signature.Public_key_hash.t;\n priority : int;\n timestamp : Timestamp.t option;\n }\n\n let encoding =\n let open Data_encoding in\n conv\n (fun {level; delegate; priority; timestamp} ->\n (level, delegate, priority, timestamp))\n (fun (level, delegate, priority, timestamp) ->\n {level; delegate; priority; timestamp})\n (obj4\n (req \"level\" Raw_level.encoding)\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"priority\" uint16)\n (opt \"estimated_time\" Timestamp.encoding))\n\n module S = struct\n open Data_encoding\n\n let custom_root = RPC_path.(open_root / \"helpers\" / \"baking_rights\")\n\n type baking_rights_query = {\n levels : Raw_level.t list;\n cycles : Cycle.t list;\n delegates : Signature.Public_key_hash.t list;\n max_priority : int option;\n all : bool;\n }\n\n let baking_rights_query =\n let open RPC_query in\n query (fun levels cycles delegates max_priority all ->\n {levels; cycles; delegates; max_priority; all})\n |+ multi_field \"level\" Raw_level.rpc_arg (fun t -> t.levels)\n |+ multi_field \"cycle\" Cycle.rpc_arg (fun t -> t.cycles)\n |+ multi_field \"delegate\" Signature.Public_key_hash.rpc_arg (fun t ->\n t.delegates)\n |+ opt_field \"max_priority\" RPC_arg.int (fun t -> t.max_priority)\n |+ flag \"all\" (fun t -> t.all)\n |> seal\n\n let baking_rights =\n RPC_service.get_service\n ~description:\n \"Retrieves the list of delegates allowed to bake a block.\\n\\\n By default, it gives the best baking priorities for bakers that \\\n have at least one opportunity below the 64th priority for the next \\\n block.\\n\\\n Parameters `level` and `cycle` can be used to specify the (valid) \\\n level(s) in the past or future at which the baking rights have to \\\n be returned. When asked for (a) whole cycle(s), baking \\\n opportunities are given by default up to the priority 8.\\n\\\n Parameter `delegate` can be used to restrict the results to the \\\n given delegates. If parameter `all` is set, all the baking \\\n opportunities for each baker at each level are returned, instead \\\n of just the first one.\\n\\\n Returns the list of baking slots. Also returns the minimal \\\n timestamps that correspond to these slots. The timestamps are \\\n omitted for levels in the past, and are only estimates for levels \\\n later that the next block, based on the hypothesis that all \\\n predecessor blocks were baked at the first priority.\"\n ~query:baking_rights_query\n ~output:(list encoding)\n custom_root\n end\n\n let baking_priorities ctxt max_prio (level, pred_timestamp) =\n Baking.baking_priorities ctxt level\n >>=? fun contract_list ->\n let rec loop l acc priority =\n if Compare.Int.(priority > max_prio) then return (List.rev acc)\n else\n let (Misc.LCons (pk, next)) = l in\n let delegate = Signature.Public_key.hash pk in\n ( match pred_timestamp with\n | None ->\n ok_none\n | Some pred_timestamp ->\n Baking.minimal_time ctxt priority pred_timestamp\n >|? fun t -> Some t )\n >>?= fun timestamp ->\n let acc =\n {level = level.level; delegate; priority; timestamp} :: acc\n in\n next () >>=? fun l -> loop l acc (priority + 1)\n in\n loop contract_list [] 0\n\n let baking_priorities_of_delegates ctxt ~all ~max_prio delegates\n (level, pred_timestamp) =\n Baking.baking_priorities ctxt level\n >>=? fun contract_list ->\n let rec loop l acc priority delegates =\n match delegates with\n | [] ->\n return (List.rev acc)\n | _ :: _ -> (\n if Compare.Int.(priority > max_prio) then return (List.rev acc)\n else\n let (Misc.LCons (pk, next)) = l in\n next ()\n >>=? fun l ->\n match\n List.partition\n (fun (pk', _) -> Signature.Public_key.equal pk pk')\n delegates\n with\n | ([], _) ->\n loop l acc (priority + 1) delegates\n | ((_, delegate) :: _, delegates') ->\n ( match pred_timestamp with\n | None ->\n ok_none\n | Some pred_timestamp ->\n Baking.minimal_time ctxt priority pred_timestamp\n >|? fun t -> Some t )\n >>?= fun timestamp ->\n let acc =\n {level = level.level; delegate; priority; timestamp} :: acc\n in\n let delegates'' = if all then delegates else delegates' in\n loop l acc (priority + 1) delegates'' )\n in\n loop contract_list [] 0 delegates\n\n let remove_duplicated_delegates rights =\n List.rev @@ fst\n @@ List.fold_left\n (fun (acc, previous) r ->\n if Signature.Public_key_hash.Set.mem r.delegate previous then\n (acc, previous)\n else\n (r :: acc, Signature.Public_key_hash.Set.add r.delegate previous))\n ([], Signature.Public_key_hash.Set.empty)\n rights\n\n let register () =\n let open Services_registration in\n register0 S.baking_rights (fun ctxt q () ->\n requested_levels\n ~default:\n ( Level.succ ctxt (Level.current ctxt),\n Some (Timestamp.current ctxt) )\n ctxt\n q.cycles\n q.levels\n >>?= fun levels ->\n let max_priority =\n match q.max_priority with\n | Some max ->\n max\n | None -> (\n match q.cycles with [] -> 64 | _ :: _ -> 8 )\n in\n match q.delegates with\n | [] ->\n map_s (baking_priorities ctxt max_priority) levels\n >|=? fun rights ->\n let rights =\n if q.all then rights\n else List.map remove_duplicated_delegates rights\n in\n List.concat rights\n | _ :: _ as delegates ->\n Lwt_list.filter_map_s\n (fun delegate ->\n Contract.get_manager_key ctxt delegate\n >>= function\n | Ok pk ->\n Lwt.return (Some (pk, delegate))\n | Error _ ->\n Lwt.return_none)\n delegates\n >>= fun delegates ->\n map_s\n (fun level ->\n baking_priorities_of_delegates\n ctxt\n q.all\n max_priority\n delegates\n level)\n levels\n >|=? List.concat)\n\n let get ctxt ?(levels = []) ?(cycles = []) ?(delegates = []) ?(all = false)\n ?max_priority block =\n RPC_context.make_call0\n S.baking_rights\n ctxt\n block\n {levels; cycles; delegates; max_priority; all}\n ()\nend\n\nmodule Endorsing_rights = struct\n type t = {\n level : Raw_level.t;\n delegate : Signature.Public_key_hash.t;\n slots : int list;\n estimated_time : Time.t option;\n }\n\n let encoding =\n let open Data_encoding in\n conv\n (fun {level; delegate; slots; estimated_time} ->\n (level, delegate, slots, estimated_time))\n (fun (level, delegate, slots, estimated_time) ->\n {level; delegate; slots; estimated_time})\n (obj4\n (req \"level\" Raw_level.encoding)\n (req \"delegate\" Signature.Public_key_hash.encoding)\n (req \"slots\" (list uint16))\n (opt \"estimated_time\" Timestamp.encoding))\n\n module S = struct\n open Data_encoding\n\n let custom_root = RPC_path.(open_root / \"helpers\" / \"endorsing_rights\")\n\n type endorsing_rights_query = {\n levels : Raw_level.t list;\n cycles : Cycle.t list;\n delegates : Signature.Public_key_hash.t list;\n }\n\n let endorsing_rights_query =\n let open RPC_query in\n query (fun levels cycles delegates -> {levels; cycles; delegates})\n |+ multi_field \"level\" Raw_level.rpc_arg (fun t -> t.levels)\n |+ multi_field \"cycle\" Cycle.rpc_arg (fun t -> t.cycles)\n |+ multi_field \"delegate\" Signature.Public_key_hash.rpc_arg (fun t ->\n t.delegates)\n |> seal\n\n let endorsing_rights =\n RPC_service.get_service\n ~description:\n \"Retrieves the delegates allowed to endorse a block.\\n\\\n By default, it gives the endorsement slots for delegates that have \\\n at least one in the next block.\\n\\\n Parameters `level` and `cycle` can be used to specify the (valid) \\\n level(s) in the past or future at which the endorsement rights \\\n have to be returned. Parameter `delegate` can be used to restrict \\\n the results to the given delegates.\\n\\\n Returns the list of endorsement slots. Also returns the minimal \\\n timestamps that correspond to these slots. The timestamps are \\\n omitted for levels in the past, and are only estimates for levels \\\n later that the next block, based on the hypothesis that all \\\n predecessor blocks were baked at the first priority.\"\n ~query:endorsing_rights_query\n ~output:(list encoding)\n custom_root\n end\n\n let endorsement_slots ctxt (level, estimated_time) =\n Baking.endorsement_rights ctxt level\n >|=? fun rights ->\n Signature.Public_key_hash.Map.fold\n (fun delegate (_, slots, _) acc ->\n {level = level.level; delegate; slots; estimated_time} :: acc)\n rights\n []\n\n let register () =\n let open Services_registration in\n register0 S.endorsing_rights (fun ctxt q () ->\n requested_levels\n ~default:(Level.current ctxt, Some (Timestamp.current ctxt))\n ctxt\n q.cycles\n q.levels\n >>?= fun levels ->\n map_s (endorsement_slots ctxt) levels\n >|=? fun rights ->\n let rights = List.concat rights in\n match q.delegates with\n | [] ->\n rights\n | _ :: _ as delegates ->\n let is_requested p =\n List.exists\n (Signature.Public_key_hash.equal p.delegate)\n delegates\n in\n List.filter is_requested rights)\n\n let get ctxt ?(levels = []) ?(cycles = []) ?(delegates = []) block =\n RPC_context.make_call0\n S.endorsing_rights\n ctxt\n block\n {levels; cycles; delegates}\n ()\nend\n\nmodule Endorsing_power = struct\n let endorsing_power ctxt (operation, chain_id) =\n let (Operation_data data) = operation.protocol_data in\n match data.contents with\n | Single (Endorsement _) ->\n Baking.check_endorsement_rights\n ctxt\n chain_id\n {shell = operation.shell; protocol_data = data}\n >|=? fun (_, slots, _) -> List.length slots\n | _ ->\n failwith \"Operation is not an endorsement\"\n\n module S = struct\n let endorsing_power =\n let open Data_encoding in\n RPC_service.post_service\n ~description:\n \"Get the endorsing power of an endorsement, that is, the number of \\\n slots that the endorser has\"\n ~query:RPC_query.empty\n ~input:\n (obj2\n (req \"endorsement_operation\" Operation.encoding)\n (req \"chain_id\" Chain_id.encoding))\n ~output:int31\n RPC_path.(open_root / \"endorsing_power\")\n end\n\n let register () =\n let open Services_registration in\n register0 S.endorsing_power (fun ctxt () (op, chain_id) ->\n endorsing_power ctxt (op, chain_id))\n\n let get ctxt block op chain_id =\n RPC_context.make_call0 S.endorsing_power ctxt block () (op, chain_id)\nend\n\nmodule Required_endorsements = struct\n let required_endorsements ctxt block_delay =\n Baking.minimum_allowed_endorsements ctxt ~block_delay\n\n module S = struct\n type t = {block_delay : Period.t}\n\n let required_endorsements_query =\n let open RPC_query in\n query (fun block_delay -> {block_delay})\n |+ field \"block_delay\" Period.rpc_arg Period.zero (fun t ->\n t.block_delay)\n |> seal\n\n let required_endorsements =\n let open Data_encoding in\n RPC_service.get_service\n ~description:\n \"Minimum number of endorsements for a block to be valid, given a \\\n delay of the block's timestamp with respect to the minimum time to \\\n bake at the block's priority\"\n ~query:required_endorsements_query\n ~output:int31\n RPC_path.(open_root / \"required_endorsements\")\n end\n\n let register () =\n let open Services_registration in\n register0 S.required_endorsements (fun ctxt {block_delay} () ->\n return @@ required_endorsements ctxt block_delay)\n\n let get ctxt block block_delay =\n RPC_context.make_call0 S.required_endorsements ctxt block {block_delay} ()\nend\n\nmodule Minimal_valid_time = struct\n let minimal_valid_time ctxt ~priority ~endorsing_power =\n Baking.minimal_valid_time ctxt ~priority ~endorsing_power\n\n module S = struct\n type t = {priority : int; endorsing_power : int}\n\n let minimal_valid_time_query =\n let open RPC_query in\n query (fun priority endorsing_power -> {priority; endorsing_power})\n |+ field \"priority\" RPC_arg.int 0 (fun t -> t.priority)\n |+ field \"endorsing_power\" RPC_arg.int 0 (fun t -> t.endorsing_power)\n |> seal\n\n let minimal_valid_time =\n RPC_service.get_service\n ~description:\n \"Minimal valid time for a block given a priority and an endorsing \\\n power.\"\n ~query:minimal_valid_time_query\n ~output:Time.encoding\n RPC_path.(open_root / \"minimal_valid_time\")\n end\n\n let register () =\n let open Services_registration in\n register0 S.minimal_valid_time (fun ctxt {priority; endorsing_power} () ->\n Lwt.return @@ minimal_valid_time ctxt ~priority ~endorsing_power)\n\n let get ctxt block priority endorsing_power =\n RPC_context.make_call0\n S.minimal_valid_time\n ctxt\n block\n {priority; endorsing_power}\n ()\nend\n\nlet register () =\n register () ;\n Baking_rights.register () ;\n Endorsing_rights.register () ;\n Endorsing_power.register () ;\n Required_endorsements.register () ;\n Minimal_valid_time.register ()\n\nlet endorsement_rights ctxt level =\n Endorsing_rights.endorsement_slots ctxt (level, None)\n >|=? fun l -> List.map (fun {Endorsing_rights.delegate; _} -> delegate) l\n\nlet baking_rights ctxt max_priority =\n let max = match max_priority with None -> 64 | Some m -> m in\n let level = Level.current ctxt in\n Baking_rights.baking_priorities ctxt max (level, None)\n >|=? fun l ->\n ( level.level,\n List.map\n (fun {Baking_rights.delegate; timestamp; _} -> (delegate, timestamp))\n l )\n\nlet endorsing_power ctxt operation =\n Endorsing_power.endorsing_power ctxt operation\n\nlet required_endorsements ctxt delay =\n Required_endorsements.required_endorsements ctxt delay\n\nlet minimal_valid_time ctxt priority endorsing_power =\n Minimal_valid_time.minimal_valid_time ctxt priority endorsing_power\n" ;
} ;
{ name = "Helpers_services" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\ntype error += Cannot_parse_operation (* `Branch *)\n\nval current_level :\n 'a #RPC_context.simple ->\n ?offset:int32 ->\n 'a ->\n Level.compat_t shell_tzresult Lwt.t\n\nval levels_in_current_cycle :\n 'a #RPC_context.simple ->\n ?offset:int32 ->\n 'a ->\n (Raw_level.t * Raw_level.t) shell_tzresult Lwt.t\n\nmodule Scripts : sig\n module Traced_interpreter : sig\n type error += Cannot_serialize_log\n end\n\n val run_code :\n 'a #RPC_context.simple ->\n 'a ->\n ?gas:Gas.Arith.integral ->\n ?entrypoint:string ->\n script:Script.expr ->\n storage:Script.expr ->\n input:Script.expr ->\n amount:Tez.t ->\n balance:Tez.t ->\n chain_id:Chain_id.t ->\n source:Contract.t option ->\n payer:Contract.t option ->\n (Script.expr * packed_internal_operation list * Lazy_storage.diffs option)\n shell_tzresult\n Lwt.t\n\n val trace_code :\n 'a #RPC_context.simple ->\n 'a ->\n ?gas:Gas.Arith.integral ->\n ?entrypoint:string ->\n script:Script.expr ->\n storage:Script.expr ->\n input:Script.expr ->\n amount:Tez.t ->\n balance:Tez.t ->\n chain_id:Chain_id.t ->\n source:Contract.t option ->\n payer:Contract.t option ->\n ( Script.expr\n * packed_internal_operation list\n * Script_interpreter.execution_trace\n * Lazy_storage.diffs option )\n shell_tzresult\n Lwt.t\n\n val typecheck_code :\n 'a #RPC_context.simple ->\n 'a ->\n ?gas:Gas.Arith.integral ->\n ?legacy:bool ->\n script:Script.expr ->\n (Script_tc_errors.type_map * Gas.t) shell_tzresult Lwt.t\n\n val typecheck_data :\n 'a #RPC_context.simple ->\n 'a ->\n ?gas:Gas.Arith.integral ->\n ?legacy:bool ->\n data:Script.expr ->\n ty:Script.expr ->\n Gas.t shell_tzresult Lwt.t\n\n val pack_data :\n 'a #RPC_context.simple ->\n 'a ->\n ?gas:Gas.Arith.integral ->\n data:Script.expr ->\n ty:Script.expr ->\n (bytes * Gas.t) shell_tzresult Lwt.t\n\n val run_operation :\n 'a #RPC_context.simple ->\n 'a ->\n op:packed_operation ->\n chain_id:Chain_id.t ->\n (packed_protocol_data * Apply_results.packed_operation_metadata)\n shell_tzresult\n Lwt.t\n\n val entrypoint_type :\n 'a #RPC_context.simple ->\n 'a ->\n script:Script.expr ->\n entrypoint:string ->\n Script.expr shell_tzresult Lwt.t\n\n val list_entrypoints :\n 'a #RPC_context.simple ->\n 'a ->\n script:Script.expr ->\n (Michelson_v1_primitives.prim list list * (string * Script.expr) list)\n shell_tzresult\n Lwt.t\nend\n\nmodule Forge : sig\n module Manager : sig\n val operations :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n ?sourcePubKey:public_key ->\n counter:counter ->\n fee:Tez.t ->\n gas_limit:Gas.Arith.integral ->\n storage_limit:Z.t ->\n packed_manager_operation list ->\n bytes shell_tzresult Lwt.t\n\n val reveal :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n sourcePubKey:public_key ->\n counter:counter ->\n fee:Tez.t ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val transaction :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n ?sourcePubKey:public_key ->\n counter:counter ->\n amount:Tez.t ->\n destination:Contract.t ->\n ?entrypoint:string ->\n ?parameters:Script.expr ->\n gas_limit:Gas.Arith.integral ->\n storage_limit:Z.t ->\n fee:Tez.t ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val origination :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n ?sourcePubKey:public_key ->\n counter:counter ->\n balance:Tez.t ->\n ?delegatePubKey:public_key_hash ->\n script:Script.t ->\n gas_limit:Gas.Arith.integral ->\n storage_limit:Z.t ->\n fee:Tez.t ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val delegation :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n ?sourcePubKey:public_key ->\n counter:counter ->\n fee:Tez.t ->\n public_key_hash option ->\n bytes shell_tzresult Lwt.t\n end\n\n val endorsement :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n level:Raw_level.t ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val proposals :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n period:int32 ->\n proposals:Protocol_hash.t list ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val ballot :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n source:public_key_hash ->\n period:int32 ->\n proposal:Protocol_hash.t ->\n ballot:Vote.ballot ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val seed_nonce_revelation :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n level:Raw_level.t ->\n nonce:Nonce.t ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val double_baking_evidence :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n bh1:Block_header.t ->\n bh2:Block_header.t ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val double_endorsement_evidence :\n 'a #RPC_context.simple ->\n 'a ->\n branch:Block_hash.t ->\n op1:Kind.endorsement operation ->\n op2:Kind.endorsement operation ->\n unit ->\n bytes shell_tzresult Lwt.t\n\n val protocol_data :\n 'a #RPC_context.simple ->\n 'a ->\n priority:int ->\n ?seed_nonce_hash:Nonce_hash.t ->\n ?proof_of_work_nonce:bytes ->\n unit ->\n bytes shell_tzresult Lwt.t\nend\n\nmodule Parse : sig\n val operations :\n 'a #RPC_context.simple ->\n 'a ->\n ?check:bool ->\n Operation.raw list ->\n Operation.packed list shell_tzresult Lwt.t\n\n val block :\n 'a #RPC_context.simple ->\n 'a ->\n Block_header.shell_header ->\n bytes ->\n Block_header.protocol_data shell_tzresult Lwt.t\nend\n\nval register : unit -> unit\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\ntype error += Cannot_parse_operation (* `Branch *)\n\nlet () =\n register_error_kind\n `Branch\n ~id:\"operation.cannot_parse\"\n ~title:\"Cannot parse operation\"\n ~description:\"The operation is ill-formed or for another protocol version\"\n ~pp:(fun ppf () -> Format.fprintf ppf \"The operation cannot be parsed\")\n Data_encoding.unit\n (function Cannot_parse_operation -> Some () | _ -> None)\n (fun () -> Cannot_parse_operation)\n\nlet parse_operation (op : Operation.raw) =\n match\n Data_encoding.Binary.of_bytes Operation.protocol_data_encoding op.proto\n with\n | Some protocol_data ->\n ok {shell = op.shell; protocol_data}\n | None ->\n error Cannot_parse_operation\n\nlet path = RPC_path.(open_root / \"helpers\")\n\nmodule Scripts = struct\n module S = struct\n open Data_encoding\n\n let path = RPC_path.(path / \"scripts\")\n\n let run_code_input_encoding =\n obj10\n (req \"script\" Script.expr_encoding)\n (req \"storage\" Script.expr_encoding)\n (req \"input\" Script.expr_encoding)\n (req \"amount\" Tez.encoding)\n (req \"balance\" Tez.encoding)\n (req \"chain_id\" Chain_id.encoding)\n (opt \"source\" Contract.encoding)\n (opt \"payer\" Contract.encoding)\n (opt \"gas\" Gas.Arith.z_integral_encoding)\n (dft \"entrypoint\" string \"default\")\n\n let trace_encoding =\n def \"scripted.trace\" @@ list\n @@ obj3\n (req \"location\" Script.location_encoding)\n (req \"gas\" Gas.encoding)\n (req\n \"stack\"\n (list\n (obj2 (req \"item\" Script.expr_encoding) (opt \"annot\" string))))\n\n let run_code =\n RPC_service.post_service\n ~description:\"Run a piece of code in the current context\"\n ~query:RPC_query.empty\n ~input:run_code_input_encoding\n ~output:\n (conv\n (fun (storage, operations, lazy_storage_diff) ->\n (storage, operations, lazy_storage_diff, lazy_storage_diff))\n (fun ( storage,\n operations,\n legacy_lazy_storage_diff,\n lazy_storage_diff ) ->\n let lazy_storage_diff =\n Option.first_some lazy_storage_diff legacy_lazy_storage_diff\n in\n (storage, operations, lazy_storage_diff))\n (obj4\n (req \"storage\" Script.expr_encoding)\n (req \"operations\" (list Operation.internal_operation_encoding))\n (opt \"big_map_diff\" Lazy_storage.legacy_big_map_diff_encoding)\n (opt \"lazy_storage_diff\" Lazy_storage.encoding)))\n RPC_path.(path / \"run_code\")\n\n let trace_code =\n RPC_service.post_service\n ~description:\n \"Run a piece of code in the current context, keeping a trace\"\n ~query:RPC_query.empty\n ~input:run_code_input_encoding\n ~output:\n (conv\n (fun (storage, operations, trace, lazy_storage_diff) ->\n ( storage,\n operations,\n trace,\n lazy_storage_diff,\n lazy_storage_diff ))\n (fun ( storage,\n operations,\n trace,\n legacy_lazy_storage_diff,\n lazy_storage_diff ) ->\n let lazy_storage_diff =\n Option.first_some lazy_storage_diff legacy_lazy_storage_diff\n in\n (storage, operations, trace, lazy_storage_diff))\n (obj5\n (req \"storage\" Script.expr_encoding)\n (req \"operations\" (list Operation.internal_operation_encoding))\n (req \"trace\" trace_encoding)\n (opt \"big_map_diff\" Lazy_storage.legacy_big_map_diff_encoding)\n (opt \"lazy_storage_diff\" Lazy_storage.encoding)))\n RPC_path.(path / \"trace_code\")\n\n let typecheck_code =\n RPC_service.post_service\n ~description:\"Typecheck a piece of code in the current context\"\n ~query:RPC_query.empty\n ~input:\n (obj3\n (req \"program\" Script.expr_encoding)\n (opt \"gas\" Gas.Arith.z_integral_encoding)\n (opt \"legacy\" bool))\n ~output:\n (obj2\n (req \"type_map\" Script_tc_errors_registration.type_map_enc)\n (req \"gas\" Gas.encoding))\n RPC_path.(path / \"typecheck_code\")\n\n let typecheck_data =\n RPC_service.post_service\n ~description:\n \"Check that some data expression is well formed and of a given type \\\n in the current context\"\n ~query:RPC_query.empty\n ~input:\n (obj4\n (req \"data\" Script.expr_encoding)\n (req \"type\" Script.expr_encoding)\n (opt \"gas\" Gas.Arith.z_integral_encoding)\n (opt \"legacy\" bool))\n ~output:(obj1 (req \"gas\" Gas.encoding))\n RPC_path.(path / \"typecheck_data\")\n\n let pack_data =\n RPC_service.post_service\n ~description:\n \"Computes the serialized version of some data expression using the \\\n same algorithm as script instruction PACK\"\n ~input:\n (obj3\n (req \"data\" Script.expr_encoding)\n (req \"type\" Script.expr_encoding)\n (opt \"gas\" Gas.Arith.z_integral_encoding))\n ~output:(obj2 (req \"packed\" bytes) (req \"gas\" Gas.encoding))\n ~query:RPC_query.empty\n RPC_path.(path / \"pack_data\")\n\n let run_operation =\n RPC_service.post_service\n ~description:\"Run an operation without signature checks\"\n ~query:RPC_query.empty\n ~input:\n (obj2\n (req \"operation\" Operation.encoding)\n (req \"chain_id\" Chain_id.encoding))\n ~output:Apply_results.operation_data_and_metadata_encoding\n RPC_path.(path / \"run_operation\")\n\n let entrypoint_type =\n RPC_service.post_service\n ~description:\"Return the type of the given entrypoint\"\n ~query:RPC_query.empty\n ~input:\n (obj2\n (req \"script\" Script.expr_encoding)\n (dft \"entrypoint\" string \"default\"))\n ~output:(obj1 (req \"entrypoint_type\" Script.expr_encoding))\n RPC_path.(path / \"entrypoint\")\n\n let list_entrypoints =\n RPC_service.post_service\n ~description:\"Return the list of entrypoints of the given script\"\n ~query:RPC_query.empty\n ~input:(obj1 (req \"script\" Script.expr_encoding))\n ~output:\n (obj2\n (dft\n \"unreachable\"\n (Data_encoding.list\n (obj1\n (req\n \"path\"\n (Data_encoding.list\n Michelson_v1_primitives.prim_encoding))))\n [])\n (req \"entrypoints\" (assoc Script.expr_encoding)))\n RPC_path.(path / \"entrypoints\")\n end\n\n module Traced_interpreter = struct\n type error += Cannot_serialize_log\n\n let () =\n (* Cannot serialize log *)\n register_error_kind\n `Temporary\n ~id:\"michelson_v1.cannot_serialize_log\"\n ~title:\"Not enough gas to serialize execution trace\"\n ~description:\n \"Execution trace with stacks was to big to be serialized with the \\\n provided gas\"\n Data_encoding.empty\n (function Cannot_serialize_log -> Some () | _ -> None)\n (fun () -> Cannot_serialize_log)\n\n type log_element =\n | Log :\n context * Script.location * 'a * 'a Script_typed_ir.stack_ty\n -> log_element\n\n let unparse_stack ctxt (stack, stack_ty) =\n (* We drop the gas limit as this function is only used for debugging/errors. *)\n let ctxt = Gas.set_unlimited ctxt in\n let rec unparse_stack :\n type a.\n a Script_typed_ir.stack_ty * a ->\n (Script.expr * string option) list tzresult Lwt.t = function\n | (Empty_t, ()) ->\n return_nil\n | (Item_t (ty, rest_ty, annot), (v, rest)) ->\n Script_ir_translator.unparse_data ctxt Readable ty v\n >>=? fun (data, _ctxt) ->\n unparse_stack (rest_ty, rest)\n >|=? fun rest ->\n let annot =\n match Script_ir_annot.unparse_var_annot annot with\n | [] ->\n None\n | [a] ->\n Some a\n | _ ->\n assert false\n in\n let data = Micheline.strip_locations data in\n (data, annot) :: rest\n in\n unparse_stack (stack_ty, stack)\n\n module Trace_logger () : Script_interpreter.STEP_LOGGER = struct\n let log : log_element list ref = ref []\n\n let log_interp ctxt (descr : (_, _) Script_typed_ir.descr) stack =\n log := Log (ctxt, descr.loc, stack, descr.bef) :: !log\n\n let log_entry _ctxt _descr _stack = ()\n\n let log_exit ctxt (descr : (_, _) Script_typed_ir.descr) stack =\n log := Log (ctxt, descr.loc, stack, descr.aft) :: !log\n\n let get_log () =\n map_s\n (fun (Log (ctxt, loc, stack, stack_ty)) ->\n trace Cannot_serialize_log (unparse_stack ctxt (stack, stack_ty))\n >>=? fun stack -> return (loc, Gas.level ctxt, stack))\n !log\n >>=? fun res -> return (Some (List.rev res))\n end\n\n let execute ctxt mode step_constants ~script ~entrypoint ~parameter =\n let module Logger = Trace_logger () in\n let open Script_interpreter in\n let logger = (module Logger : STEP_LOGGER) in\n execute\n ~logger\n ctxt\n mode\n step_constants\n ~script\n ~entrypoint\n ~parameter\n ~internal:true\n >>=? fun {ctxt; storage; lazy_storage_diff; operations} ->\n Logger.get_log ()\n >|=? fun trace ->\n let trace = Option.value ~default:[] trace in\n ({ctxt; storage; lazy_storage_diff; operations}, trace)\n end\n\n let typecheck_data :\n legacy:bool ->\n context ->\n Script.expr * Script.expr ->\n context tzresult Lwt.t =\n fun ~legacy ctxt (data, exp_ty) ->\n record_trace\n (Script_tc_errors.Ill_formed_type (None, exp_ty, 0))\n (Script_ir_translator.parse_parameter_ty\n ctxt\n ~legacy\n (Micheline.root exp_ty))\n >>?= fun (Ex_ty exp_ty, ctxt) ->\n trace_eval\n (fun () ->\n Lwt.return\n ( Script_ir_translator.serialize_ty_for_error ctxt exp_ty\n >|? fun (exp_ty, _ctxt) ->\n Script_tc_errors.Ill_typed_data (None, data, exp_ty) ))\n (let allow_forged =\n true\n (* Safe since we ignore the value afterwards. *)\n in\n Script_ir_translator.parse_data\n ctxt\n ~legacy\n ~allow_forged\n exp_ty\n (Micheline.root data))\n >|=? fun (_, ctxt) -> ctxt\n\n let register () =\n let open Services_registration in\n let originate_dummy_contract ctxt script balance =\n let ctxt = Contract.init_origination_nonce ctxt Operation_hash.zero in\n Lwt.return (Contract.fresh_contract_from_current_nonce ctxt)\n >>=? fun (ctxt, dummy_contract) ->\n Contract.originate\n ctxt\n dummy_contract\n ~balance\n ~delegate:None\n ~script:(script, None)\n >>=? fun ctxt -> return (ctxt, dummy_contract)\n in\n register0\n S.run_code\n (fun ctxt\n ()\n ( code,\n storage,\n parameter,\n amount,\n balance,\n chain_id,\n source,\n payer,\n gas,\n entrypoint )\n ->\n let storage = Script.lazy_expr storage in\n let code = Script.lazy_expr code in\n originate_dummy_contract ctxt {storage; code} balance\n >>=? fun (ctxt, dummy_contract) ->\n let (source, payer) =\n match (source, payer) with\n | (Some source, Some payer) ->\n (source, payer)\n | (Some source, None) ->\n (source, source)\n | (None, Some payer) ->\n (payer, payer)\n | (None, None) ->\n (dummy_contract, dummy_contract)\n in\n let gas =\n match gas with\n | Some gas ->\n gas\n | None ->\n Constants.hard_gas_limit_per_operation ctxt\n in\n let ctxt = Gas.set_limit ctxt gas in\n let step_constants =\n let open Script_interpreter in\n {source; payer; self = dummy_contract; amount; chain_id}\n in\n Script_interpreter.execute\n ctxt\n Readable\n step_constants\n ~script:{storage; code}\n ~entrypoint\n ~parameter\n ~internal:true\n >|=? fun {Script_interpreter.storage; operations; lazy_storage_diff; _} ->\n (storage, operations, lazy_storage_diff)) ;\n register0\n S.trace_code\n (fun ctxt\n ()\n ( code,\n storage,\n parameter,\n amount,\n balance,\n chain_id,\n source,\n payer,\n gas,\n entrypoint )\n ->\n let storage = Script.lazy_expr storage in\n let code = Script.lazy_expr code in\n originate_dummy_contract ctxt {storage; code} balance\n >>=? fun (ctxt, dummy_contract) ->\n let (source, payer) =\n match (source, payer) with\n | (Some source, Some payer) ->\n (source, payer)\n | (Some source, None) ->\n (source, source)\n | (None, Some payer) ->\n (payer, payer)\n | (None, None) ->\n (dummy_contract, dummy_contract)\n in\n let gas =\n match gas with\n | Some gas ->\n gas\n | None ->\n Constants.hard_gas_limit_per_operation ctxt\n in\n let ctxt = Gas.set_limit ctxt gas in\n let step_constants =\n let open Script_interpreter in\n {source; payer; self = dummy_contract; amount; chain_id}\n in\n Traced_interpreter.execute\n ctxt\n Readable\n step_constants\n ~script:{storage; code}\n ~entrypoint\n ~parameter\n >|=? fun ( { Script_interpreter.storage;\n operations;\n lazy_storage_diff;\n _ },\n trace ) ->\n (storage, operations, trace, lazy_storage_diff)) ;\n register0 S.typecheck_code (fun ctxt () (expr, maybe_gas, legacy) ->\n let legacy = Option.value ~default:false legacy in\n let ctxt =\n match maybe_gas with\n | None ->\n Gas.set_unlimited ctxt\n | Some gas ->\n Gas.set_limit ctxt gas\n in\n Script_ir_translator.typecheck_code ~legacy ctxt expr\n >|=? fun (res, ctxt) -> (res, Gas.level ctxt)) ;\n register0 S.typecheck_data (fun ctxt () (data, ty, maybe_gas, legacy) ->\n let legacy = Option.value ~default:false legacy in\n let ctxt =\n match maybe_gas with\n | None ->\n Gas.set_unlimited ctxt\n | Some gas ->\n Gas.set_limit ctxt gas\n in\n typecheck_data ~legacy ctxt (data, ty) >|=? fun ctxt -> Gas.level ctxt) ;\n register0 S.pack_data (fun ctxt () (expr, typ, maybe_gas) ->\n let open Script_ir_translator in\n let ctxt =\n match maybe_gas with\n | None ->\n Gas.set_unlimited ctxt\n | Some gas ->\n Gas.set_limit ctxt gas\n in\n parse_packable_ty ctxt ~legacy:true (Micheline.root typ)\n >>?= fun (Ex_ty typ, ctxt) ->\n parse_data\n ctxt\n ~legacy:true\n ~allow_forged:true\n typ\n (Micheline.root expr)\n >>=? fun (data, ctxt) ->\n Script_ir_translator.pack_data ctxt typ data\n >|=? fun (bytes, ctxt) -> (bytes, Gas.level ctxt)) ;\n register0\n S.run_operation\n (fun ctxt\n ()\n ({shell; protocol_data = Operation_data protocol_data}, chain_id)\n ->\n (* this code is a duplicate of Apply without signature check *)\n let partial_precheck_manager_contents (type kind) ctxt\n (op : kind Kind.manager contents) : context tzresult Lwt.t =\n let (Manager_operation\n {source; fee; counter; operation; gas_limit; storage_limit}) =\n op\n in\n Gas.check_limit ctxt gas_limit\n >>?= fun () ->\n let ctxt = Gas.set_limit ctxt gas_limit in\n Fees.check_storage_limit ctxt storage_limit\n >>?= fun () ->\n Contract.must_be_allocated ctxt (Contract.implicit_contract source)\n >>=? fun () ->\n Contract.check_counter_increment ctxt source counter\n >>=? fun () ->\n ( match operation with\n | Reveal pk ->\n Contract.reveal_manager_key ctxt source pk\n | Transaction {parameters; _} ->\n (* Here the data comes already deserialized, so we need to fake the deserialization to mimic apply *)\n let arg_bytes =\n Data_encoding.Binary.to_bytes_exn\n Script.lazy_expr_encoding\n parameters\n in\n let arg =\n match\n Data_encoding.Binary.of_bytes\n Script.lazy_expr_encoding\n arg_bytes\n with\n | Some arg ->\n arg\n | None ->\n assert false\n in\n (* Fail quickly if not enough gas for minimal deserialization cost *)\n Lwt.return\n @@ record_trace Apply.Gas_quota_exceeded_init_deserialize\n @@ ( Gas.check_enough ctxt (Script.minimal_deserialize_cost arg)\n >>? fun () ->\n (* Fail if not enough gas for complete deserialization cost *)\n Script.force_decode_in_context ctxt arg\n >|? fun (_arg, ctxt) -> ctxt )\n | Origination {script; _} ->\n (* Here the data comes already deserialized, so we need to fake the deserialization to mimic apply *)\n let script_bytes =\n Data_encoding.Binary.to_bytes_exn Script.encoding script\n in\n let script =\n match\n Data_encoding.Binary.of_bytes Script.encoding script_bytes\n with\n | Some script ->\n script\n | None ->\n assert false\n in\n Lwt.return\n @@ record_trace Apply.Gas_quota_exceeded_init_deserialize\n @@ ( Gas.(\n check_enough\n (* Fail quickly if not enough gas for minimal deserialization cost *)\n ctxt\n ( Script.minimal_deserialize_cost script.code\n +@ Script.minimal_deserialize_cost script.storage ))\n >>? fun () ->\n (* Fail if not enough gas for complete deserialization cost *)\n Script.force_decode_in_context ctxt script.code\n >>? fun (_code, ctxt) ->\n Script.force_decode_in_context ctxt script.storage\n >|? fun (_storage, ctxt) -> ctxt )\n | _ ->\n return ctxt )\n >>=? fun ctxt ->\n Contract.get_manager_key ctxt source\n >>=? fun _public_key ->\n (* signature check unplugged from here *)\n Contract.increment_counter ctxt source\n >>=? fun ctxt ->\n Contract.spend ctxt (Contract.implicit_contract source) fee\n in\n let rec partial_precheck_manager_contents_list :\n type kind.\n Alpha_context.t ->\n kind Kind.manager contents_list ->\n context tzresult Lwt.t =\n fun ctxt contents_list ->\n match contents_list with\n | Single (Manager_operation _ as op) ->\n partial_precheck_manager_contents ctxt op\n | Cons ((Manager_operation _ as op), rest) ->\n partial_precheck_manager_contents ctxt op\n >>=? fun ctxt -> partial_precheck_manager_contents_list ctxt rest\n in\n let ret contents =\n ( Operation_data protocol_data,\n Apply_results.Operation_metadata {contents} )\n in\n let operation : _ operation = {shell; protocol_data} in\n let hash = Operation.hash {shell; protocol_data} in\n let ctxt = Contract.init_origination_nonce ctxt hash in\n let baker = Signature.Public_key_hash.zero in\n match protocol_data.contents with\n | Single (Manager_operation _) as op ->\n partial_precheck_manager_contents_list ctxt op\n >>=? fun ctxt ->\n Apply.apply_manager_contents_list ctxt Optimized baker chain_id op\n >|= fun (_ctxt, result) -> ok @@ ret result\n | Cons (Manager_operation _, _) as op ->\n partial_precheck_manager_contents_list ctxt op\n >>=? fun ctxt ->\n Apply.apply_manager_contents_list ctxt Optimized baker chain_id op\n >|= fun (_ctxt, result) -> ok @@ ret result\n | _ ->\n Apply.apply_contents_list\n ctxt\n chain_id\n Optimized\n shell.branch\n baker\n operation\n operation.protocol_data.contents\n >|=? fun (_ctxt, result) -> ret result) ;\n register0 S.entrypoint_type (fun ctxt () (expr, entrypoint) ->\n let ctxt = Gas.set_unlimited ctxt in\n let legacy = false in\n let open Script_ir_translator in\n Lwt.return\n ( parse_toplevel ~legacy expr\n >>? (fun (arg_type, _, _, root_name) ->\n parse_parameter_ty ctxt ~legacy arg_type\n >>? fun (Ex_ty arg_type, _) ->\n Script_ir_translator.find_entrypoint\n ~root_name\n arg_type\n entrypoint)\n >>? fun (_f, Ex_ty ty) ->\n unparse_ty ctxt ty\n >|? fun (ty_node, _) -> Micheline.strip_locations ty_node )) ;\n register0 S.list_entrypoints (fun ctxt () expr ->\n let ctxt = Gas.set_unlimited ctxt in\n let legacy = false in\n let open Script_ir_translator in\n Lwt.return\n ( parse_toplevel ~legacy expr\n >>? fun (arg_type, _, _, root_name) ->\n parse_parameter_ty ctxt ~legacy arg_type\n >>? fun (Ex_ty arg_type, _) ->\n Script_ir_translator.list_entrypoints ~root_name arg_type ctxt\n >|? fun (unreachable_entrypoint, map) ->\n ( unreachable_entrypoint,\n Entrypoints_map.fold\n (fun entry (_, ty) acc ->\n (entry, Micheline.strip_locations ty) :: acc)\n map\n [] ) ))\n\n let run_code ctxt block ?gas ?(entrypoint = \"default\") ~script ~storage\n ~input ~amount ~balance ~chain_id ~source ~payer =\n RPC_context.make_call0\n S.run_code\n ctxt\n block\n ()\n ( script,\n storage,\n input,\n amount,\n balance,\n chain_id,\n source,\n payer,\n gas,\n entrypoint )\n\n let trace_code ctxt block ?gas ?(entrypoint = \"default\") ~script ~storage\n ~input ~amount ~balance ~chain_id ~source ~payer =\n RPC_context.make_call0\n S.trace_code\n ctxt\n block\n ()\n ( script,\n storage,\n input,\n amount,\n balance,\n chain_id,\n source,\n payer,\n gas,\n entrypoint )\n\n let typecheck_code ctxt block ?gas ?legacy ~script =\n RPC_context.make_call0 S.typecheck_code ctxt block () (script, gas, legacy)\n\n let typecheck_data ctxt block ?gas ?legacy ~data ~ty =\n RPC_context.make_call0\n S.typecheck_data\n ctxt\n block\n ()\n (data, ty, gas, legacy)\n\n let pack_data ctxt block ?gas ~data ~ty =\n RPC_context.make_call0 S.pack_data ctxt block () (data, ty, gas)\n\n let run_operation ctxt block ~op ~chain_id =\n RPC_context.make_call0 S.run_operation ctxt block () (op, chain_id)\n\n let entrypoint_type ctxt block ~script ~entrypoint =\n RPC_context.make_call0 S.entrypoint_type ctxt block () (script, entrypoint)\n\n let list_entrypoints ctxt block ~script =\n RPC_context.make_call0 S.list_entrypoints ctxt block () script\nend\n\nmodule Forge = struct\n module S = struct\n open Data_encoding\n\n let path = RPC_path.(path / \"forge\")\n\n let operations =\n RPC_service.post_service\n ~description:\"Forge an operation\"\n ~query:RPC_query.empty\n ~input:Operation.unsigned_encoding\n ~output:bytes\n RPC_path.(path / \"operations\")\n\n let empty_proof_of_work_nonce =\n Bytes.make Constants_repr.proof_of_work_nonce_size '\\000'\n\n let protocol_data =\n RPC_service.post_service\n ~description:\"Forge the protocol-specific part of a block header\"\n ~query:RPC_query.empty\n ~input:\n (obj3\n (req \"priority\" uint16)\n (opt \"nonce_hash\" Nonce_hash.encoding)\n (dft\n \"proof_of_work_nonce\"\n (Fixed.bytes Alpha_context.Constants.proof_of_work_nonce_size)\n empty_proof_of_work_nonce))\n ~output:(obj1 (req \"protocol_data\" bytes))\n RPC_path.(path / \"protocol_data\")\n end\n\n let register () =\n let open Services_registration in\n register0_noctxt S.operations (fun () (shell, proto) ->\n return\n (Data_encoding.Binary.to_bytes_exn\n Operation.unsigned_encoding\n (shell, proto))) ;\n register0_noctxt\n S.protocol_data\n (fun () (priority, seed_nonce_hash, proof_of_work_nonce) ->\n return\n (Data_encoding.Binary.to_bytes_exn\n Block_header.contents_encoding\n {priority; seed_nonce_hash; proof_of_work_nonce}))\n\n module Manager = struct\n let operations ctxt block ~branch ~source ?sourcePubKey ~counter ~fee\n ~gas_limit ~storage_limit operations =\n Contract_services.manager_key ctxt block source\n >>= function\n | Error _ as e ->\n Lwt.return e\n | Ok revealed ->\n let ops =\n List.map\n (fun (Manager operation) ->\n Contents\n (Manager_operation\n {\n source;\n counter;\n operation;\n fee;\n gas_limit;\n storage_limit;\n }))\n operations\n in\n let ops =\n match (sourcePubKey, revealed) with\n | (None, _) | (_, Some _) ->\n ops\n | (Some pk, None) ->\n let operation = Reveal pk in\n Contents\n (Manager_operation\n {\n source;\n counter;\n operation;\n fee;\n gas_limit;\n storage_limit;\n })\n :: ops\n in\n RPC_context.make_call0\n S.operations\n ctxt\n block\n ()\n ({branch}, Operation.of_list ops)\n\n let reveal ctxt block ~branch ~source ~sourcePubKey ~counter ~fee () =\n operations\n ctxt\n block\n ~branch\n ~source\n ~sourcePubKey\n ~counter\n ~fee\n ~gas_limit:Gas.Arith.zero\n ~storage_limit:Z.zero\n []\n\n let transaction ctxt block ~branch ~source ?sourcePubKey ~counter ~amount\n ~destination ?(entrypoint = \"default\") ?parameters ~gas_limit\n ~storage_limit ~fee () =\n let parameters =\n Option.fold\n ~some:Script.lazy_expr\n ~none:Script.unit_parameter\n parameters\n in\n operations\n ctxt\n block\n ~branch\n ~source\n ?sourcePubKey\n ~counter\n ~fee\n ~gas_limit\n ~storage_limit\n [Manager (Transaction {amount; parameters; destination; entrypoint})]\n\n let origination ctxt block ~branch ~source ?sourcePubKey ~counter ~balance\n ?delegatePubKey ~script ~gas_limit ~storage_limit ~fee () =\n operations\n ctxt\n block\n ~branch\n ~source\n ?sourcePubKey\n ~counter\n ~fee\n ~gas_limit\n ~storage_limit\n [ Manager\n (Origination\n {\n delegate = delegatePubKey;\n script;\n credit = balance;\n preorigination = None;\n }) ]\n\n let delegation ctxt block ~branch ~source ?sourcePubKey ~counter ~fee\n delegate =\n operations\n ctxt\n block\n ~branch\n ~source\n ?sourcePubKey\n ~counter\n ~fee\n ~gas_limit:Gas.Arith.zero\n ~storage_limit:Z.zero\n [Manager (Delegation delegate)]\n end\n\n let operation ctxt block ~branch operation =\n RPC_context.make_call0\n S.operations\n ctxt\n block\n ()\n ({branch}, Contents_list (Single operation))\n\n let endorsement ctxt b ~branch ~level () =\n operation ctxt b ~branch (Endorsement {level})\n\n let proposals ctxt b ~branch ~source ~period ~proposals () =\n operation ctxt b ~branch (Proposals {source; period; proposals})\n\n let ballot ctxt b ~branch ~source ~period ~proposal ~ballot () =\n operation ctxt b ~branch (Ballot {source; period; proposal; ballot})\n\n let seed_nonce_revelation ctxt block ~branch ~level ~nonce () =\n operation ctxt block ~branch (Seed_nonce_revelation {level; nonce})\n\n let double_baking_evidence ctxt block ~branch ~bh1 ~bh2 () =\n operation ctxt block ~branch (Double_baking_evidence {bh1; bh2})\n\n let double_endorsement_evidence ctxt block ~branch ~op1 ~op2 () =\n operation ctxt block ~branch (Double_endorsement_evidence {op1; op2})\n\n let empty_proof_of_work_nonce =\n Bytes.make Constants_repr.proof_of_work_nonce_size '\\000'\n\n let protocol_data ctxt block ~priority ?seed_nonce_hash\n ?(proof_of_work_nonce = empty_proof_of_work_nonce) () =\n RPC_context.make_call0\n S.protocol_data\n ctxt\n block\n ()\n (priority, seed_nonce_hash, proof_of_work_nonce)\nend\n\nmodule Parse = struct\n module S = struct\n open Data_encoding\n\n let path = RPC_path.(path / \"parse\")\n\n let operations =\n RPC_service.post_service\n ~description:\"Parse operations\"\n ~query:RPC_query.empty\n ~input:\n (obj2\n (req \"operations\" (list (dynamic_size Operation.raw_encoding)))\n (opt \"check_signature\" bool))\n ~output:(list (dynamic_size Operation.encoding))\n RPC_path.(path / \"operations\")\n\n let block =\n RPC_service.post_service\n ~description:\"Parse a block\"\n ~query:RPC_query.empty\n ~input:Block_header.raw_encoding\n ~output:Block_header.protocol_data_encoding\n RPC_path.(path / \"block\")\n end\n\n let parse_protocol_data protocol_data =\n match\n Data_encoding.Binary.of_bytes\n Block_header.protocol_data_encoding\n protocol_data\n with\n | None ->\n failwith \"Cant_parse_protocol_data\"\n | Some protocol_data ->\n protocol_data\n\n let register () =\n let open Services_registration in\n register0 S.operations (fun _ctxt () (operations, check) ->\n map_s\n (fun raw ->\n parse_operation raw\n >>?= fun op ->\n ( match check with\n | Some true ->\n return_unit (* FIXME *)\n (* I.check_signature ctxt *)\n (* op.protocol_data.signature op.shell op.protocol_data.contents *)\n | Some false | None ->\n return_unit )\n >|=? fun () -> op)\n operations) ;\n register0_noctxt S.block (fun () raw_block ->\n return @@ parse_protocol_data raw_block.protocol_data)\n\n let operations ctxt block ?check operations =\n RPC_context.make_call0 S.operations ctxt block () (operations, check)\n\n let block ctxt block shell protocol_data =\n RPC_context.make_call0\n S.block\n ctxt\n block\n ()\n ({shell; protocol_data} : Block_header.raw)\nend\n\nmodule S = struct\n open Data_encoding\n\n type level_query = {offset : int32}\n\n let level_query : level_query RPC_query.t =\n let open RPC_query in\n query (fun offset -> {offset})\n |+ field \"offset\" RPC_arg.int32 0l (fun t -> t.offset)\n |> seal\n\n let current_level =\n RPC_service.get_service\n ~description:\n \"Returns the level of the interrogated block, or the one of a block \\\n located `offset` blocks after in the chain (or before when \\\n negative). For instance, the next block if `offset` is 1.\"\n ~query:level_query\n ~output:Level.compat_encoding\n RPC_path.(path / \"current_level\")\n\n let levels_in_current_cycle =\n RPC_service.get_service\n ~description:\"Levels of a cycle\"\n ~query:level_query\n ~output:\n (obj2 (req \"first\" Raw_level.encoding) (req \"last\" Raw_level.encoding))\n RPC_path.(path / \"levels_in_current_cycle\")\nend\n\nlet register () =\n Scripts.register () ;\n Forge.register () ;\n Parse.register () ;\n let open Services_registration in\n register0 S.current_level (fun ctxt q () ->\n let level =\n Level.from_raw ctxt ~offset:q.offset (Level.current ctxt).level\n in\n Alpha_context.Voting_period.get_rpc_fixed_current_info ctxt\n >|=? fun {voting_period; remaining; _} ->\n let blocks_per_voting_period = Constants.blocks_per_voting_period ctxt in\n let div_rem = Int32.(rem q.offset blocks_per_voting_period) in\n let index_offset =\n Int32.(\n add\n (div q.offset blocks_per_voting_period)\n (if Compare.Int32.(div_rem > remaining) then 1l else 0l))\n in\n let voting_period_index = Int32.add voting_period.index index_offset in\n let start_position =\n Int32.(\n add\n voting_period.start_position\n (mul index_offset blocks_per_voting_period))\n in\n let voting_period_position =\n Int32.(sub level.level_position start_position)\n in\n Level.to_deprecated_type\n level\n ~voting_period_index\n ~voting_period_position) ;\n register0 S.levels_in_current_cycle (fun ctxt q () ->\n let levels = Level.levels_in_current_cycle ctxt ~offset:q.offset () in\n match levels with\n | [] ->\n raise Not_found\n | _ ->\n let first = List.hd (List.rev levels) in\n let last = List.hd levels in\n return (first.level, last.level))\n\nlet current_level ctxt ?(offset = 0l) block =\n RPC_context.make_call0 S.current_level ctxt block {offset} ()\n\nlet levels_in_current_cycle ctxt ?(offset = 0l) block =\n RPC_context.make_call0 S.levels_in_current_cycle ctxt block {offset} ()\n" ;
} ;
{ name = "Voting_services" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nval ballots : 'a #RPC_context.simple -> 'a -> Vote.ballots shell_tzresult Lwt.t\n\nval ballot_list :\n 'a #RPC_context.simple ->\n 'a ->\n (Signature.Public_key_hash.t * Vote.ballot) list shell_tzresult Lwt.t\n\nval current_period :\n 'a #RPC_context.simple -> 'a -> Voting_period.info shell_tzresult Lwt.t\n\nval successor_period :\n 'a #RPC_context.simple -> 'a -> Voting_period.info shell_tzresult Lwt.t\n\nval current_quorum :\n 'a #RPC_context.simple -> 'a -> Int32.t shell_tzresult Lwt.t\n\nval listings :\n 'a #RPC_context.simple ->\n 'a ->\n (Signature.Public_key_hash.t * int32) list shell_tzresult Lwt.t\n\nval proposals :\n 'a #RPC_context.simple ->\n 'a ->\n Int32.t Protocol_hash.Map.t shell_tzresult Lwt.t\n\nval current_proposal :\n 'a #RPC_context.simple -> 'a -> Protocol_hash.t option shell_tzresult Lwt.t\n\nval register : unit -> unit\n\nval total_voting_power :\n 'a #RPC_context.simple -> 'a -> Int32.t shell_tzresult Lwt.t\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nmodule S = struct\n let path = RPC_path.(open_root / \"votes\")\n\n let ballots =\n RPC_service.get_service\n ~description:\"Sum of ballots casted so far during a voting period.\"\n ~query:RPC_query.empty\n ~output:Vote.ballots_encoding\n RPC_path.(path / \"ballots\")\n\n let ballot_list =\n RPC_service.get_service\n ~description:\"Ballots casted so far during a voting period.\"\n ~query:RPC_query.empty\n ~output:\n Data_encoding.(\n list\n (obj2\n (req \"pkh\" Signature.Public_key_hash.encoding)\n (req \"ballot\" Vote.ballot_encoding)))\n RPC_path.(path / \"ballot_list\")\n\n let current_period =\n RPC_service.get_service\n ~description:\n \"Returns the voting period (index, kind, starting position) and \\\n related information (position, remaining) of the interrogated block.\"\n ~query:RPC_query.empty\n ~output:Voting_period.info_encoding\n RPC_path.(path / \"current_period\")\n\n let successor_period =\n RPC_service.get_service\n ~description:\n \"Returns the voting period (index, kind, starting position) and \\\n related information (position, remaining) of the next block.\"\n ~query:RPC_query.empty\n ~output:Voting_period.info_encoding\n RPC_path.(path / \"successor_period\")\n\n let current_period_kind_deprecated =\n RPC_service.get_service\n ~description:\n \"Current period kind. This RPC is DEPRECATED: use \\\n `..<block_id>/votes/current_period` RPC instead.\"\n ~query:RPC_query.empty\n ~output:Voting_period.kind_encoding\n RPC_path.(path / \"current_period_kind\")\n\n let current_quorum =\n RPC_service.get_service\n ~description:\"Current expected quorum.\"\n ~query:RPC_query.empty\n ~output:Data_encoding.int32\n RPC_path.(path / \"current_quorum\")\n\n let listings =\n RPC_service.get_service\n ~description:\n \"List of delegates with their voting weight, in number of rolls.\"\n ~query:RPC_query.empty\n ~output:Vote.listings_encoding\n RPC_path.(path / \"listings\")\n\n let proposals =\n RPC_service.get_service\n ~description:\"List of proposals with number of supporters.\"\n ~query:RPC_query.empty\n ~output:(Protocol_hash.Map.encoding Data_encoding.int32)\n RPC_path.(path / \"proposals\")\n\n let current_proposal =\n RPC_service.get_service\n ~description:\"Current proposal under evaluation.\"\n ~query:RPC_query.empty\n ~output:(Data_encoding.option Protocol_hash.encoding)\n RPC_path.(path / \"current_proposal\")\n\n let total_voting_power =\n RPC_service.get_service\n ~description:\n \"Total number of rolls for the delegates in the voting listings.\"\n ~query:RPC_query.empty\n ~output:Data_encoding.int32\n RPC_path.(path / \"total_voting_power\")\nend\n\nlet register () =\n let open Services_registration in\n register0 S.ballots (fun ctxt () () -> Vote.get_ballots ctxt) ;\n register0 S.ballot_list (fun ctxt () () -> Vote.get_ballot_list ctxt >|= ok) ;\n register0 S.current_period (fun ctxt () () ->\n Voting_period.get_rpc_fixed_current_info ctxt) ;\n register0 S.successor_period (fun ctxt () () ->\n Voting_period.get_rpc_fixed_succ_info ctxt) ;\n register0 S.current_period_kind_deprecated (fun ctxt () () ->\n Voting_period.get_current_info ctxt\n >|=? fun {voting_period; _} -> voting_period.kind) ;\n register0 S.current_quorum (fun ctxt () () -> Vote.get_current_quorum ctxt) ;\n register0 S.proposals (fun ctxt () () -> Vote.get_proposals ctxt) ;\n register0 S.listings (fun ctxt () () -> Vote.get_listings ctxt >|= ok) ;\n register0 S.current_proposal (fun ctxt () () ->\n (* this would be better implemented using get_option in get_current_proposal *)\n Vote.get_current_proposal ctxt\n >|= function\n | Ok p ->\n ok_some p\n | Error (Raw_context.Storage_error (Missing_key _) :: _) ->\n ok_none\n | Error _ as e ->\n e) ;\n register0 S.total_voting_power (fun ctxt () () ->\n Vote.get_total_voting_power_free ctxt)\n\nlet ballots ctxt block = RPC_context.make_call0 S.ballots ctxt block () ()\n\nlet ballot_list ctxt block =\n RPC_context.make_call0 S.ballot_list ctxt block () ()\n\nlet current_period ctxt block =\n RPC_context.make_call0 S.current_period ctxt block () ()\n\nlet successor_period ctxt block =\n RPC_context.make_call0 S.successor_period ctxt block () ()\n\nlet current_quorum ctxt block =\n RPC_context.make_call0 S.current_quorum ctxt block () ()\n\nlet listings ctxt block = RPC_context.make_call0 S.listings ctxt block () ()\n\nlet proposals ctxt block = RPC_context.make_call0 S.proposals ctxt block () ()\n\nlet current_proposal ctxt block =\n RPC_context.make_call0 S.current_proposal ctxt block () ()\n\nlet total_voting_power ctxt block =\n RPC_context.make_call0 S.total_voting_power ctxt block () ()\n" ;
} ;
{ name = "Alpha_services" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nmodule Seed : sig\n val get : 'a #RPC_context.simple -> 'a -> Seed.seed shell_tzresult Lwt.t\nend\n\nmodule Nonce : sig\n type info = Revealed of Nonce.t | Missing of Nonce_hash.t | Forgotten\n\n val get :\n 'a #RPC_context.simple -> 'a -> Raw_level.t -> info shell_tzresult Lwt.t\nend\n\nmodule Contract = Contract_services\nmodule Constants = Constants_services\nmodule Delegate = Delegate_services\nmodule Helpers = Helpers_services\nmodule Forge = Helpers_services.Forge\nmodule Parse = Helpers_services.Parse\nmodule Voting = Voting_services\nmodule Sapling = Sapling_services\n\nval register : unit -> unit\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* Copyright (c) 2019-2020 Nomadic Labs <contact@nomadic-labs.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\nopen Alpha_context\n\nlet custom_root = RPC_path.open_root\n\nmodule Seed = struct\n module S = struct\n open Data_encoding\n\n let seed =\n RPC_service.post_service\n ~description:\"Seed of the cycle to which the block belongs.\"\n ~query:RPC_query.empty\n ~input:empty\n ~output:Seed.seed_encoding\n RPC_path.(custom_root / \"context\" / \"seed\")\n end\n\n let () =\n let open Services_registration in\n register0 S.seed (fun ctxt () () ->\n let l = Level.current ctxt in\n Seed.for_cycle ctxt l.cycle)\n\n let get ctxt block = RPC_context.make_call0 S.seed ctxt block () ()\nend\n\nmodule Nonce = struct\n type info = Revealed of Nonce.t | Missing of Nonce_hash.t | Forgotten\n\n let info_encoding =\n let open Data_encoding in\n union\n [ case\n (Tag 0)\n ~title:\"Revealed\"\n (obj1 (req \"nonce\" Nonce.encoding))\n (function Revealed nonce -> Some nonce | _ -> None)\n (fun nonce -> Revealed nonce);\n case\n (Tag 1)\n ~title:\"Missing\"\n (obj1 (req \"hash\" Nonce_hash.encoding))\n (function Missing nonce -> Some nonce | _ -> None)\n (fun nonce -> Missing nonce);\n case\n (Tag 2)\n ~title:\"Forgotten\"\n empty\n (function Forgotten -> Some () | _ -> None)\n (fun () -> Forgotten) ]\n\n module S = struct\n let get =\n RPC_service.get_service\n ~description:\"Info about the nonce of a previous block.\"\n ~query:RPC_query.empty\n ~output:info_encoding\n RPC_path.(custom_root / \"context\" / \"nonces\" /: Raw_level.rpc_arg)\n end\n\n let register () =\n let open Services_registration in\n register1 S.get (fun ctxt raw_level () () ->\n let level = Level.from_raw ctxt raw_level in\n Nonce.get ctxt level\n >|= function\n | Ok (Revealed nonce) ->\n ok (Revealed nonce)\n | Ok (Unrevealed {nonce_hash; _}) ->\n ok (Missing nonce_hash)\n | Error _ ->\n ok Forgotten)\n\n let get ctxt block level =\n RPC_context.make_call1 S.get ctxt block level () ()\nend\n\nmodule Contract = Contract_services\nmodule Constants = Constants_services\nmodule Delegate = Delegate_services\nmodule Helpers = Helpers_services\nmodule Forge = Helpers_services.Forge\nmodule Parse = Helpers_services.Parse\nmodule Voting = Voting_services\nmodule Sapling = Sapling_services\n\nlet register () =\n Contract.register () ;\n Constants.register () ;\n Delegate.register () ;\n Helpers.register () ;\n Nonce.register () ;\n Voting.register () ;\n Sapling.register ()\n" ;
} ;
{ name = "Main" ;
interface = Some "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(** Tezos Protocol Implementation - Protocol Signature Instance *)\n\ntype validation_mode =\n | Application of {\n block_header : Alpha_context.Block_header.t;\n baker : Alpha_context.public_key_hash;\n block_delay : Alpha_context.Period.t;\n }\n | Partial_application of {\n block_header : Alpha_context.Block_header.t;\n baker : Alpha_context.public_key_hash;\n block_delay : Alpha_context.Period.t;\n }\n | Partial_construction of {predecessor : Block_hash.t}\n | Full_construction of {\n predecessor : Block_hash.t;\n protocol_data : Alpha_context.Block_header.contents;\n baker : Alpha_context.public_key_hash;\n block_delay : Alpha_context.Period.t;\n }\n\ntype validation_state = {\n mode : validation_mode;\n chain_id : Chain_id.t;\n ctxt : Alpha_context.t;\n op_count : int;\n}\n\ntype operation_data = Alpha_context.packed_protocol_data\n\ntype operation = Alpha_context.packed_operation = {\n shell : Operation.shell_header;\n protocol_data : operation_data;\n}\n\ninclude\n Updater.PROTOCOL\n with type block_header_data = Alpha_context.Block_header.protocol_data\n and type block_header_metadata = Apply_results.block_metadata\n and type block_header = Alpha_context.Block_header.t\n and type operation_data := operation_data\n and type operation_receipt = Apply_results.packed_operation_metadata\n and type operation := operation\n and type validation_state := validation_state\n" ;
implementation = "(*****************************************************************************)\n(* *)\n(* Open Source License *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)\n(* *)\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"),*)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n(* *)\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n(* *)\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n(* *)\n(*****************************************************************************)\n\n(* Tezos Protocol Implementation - Protocol Signature Instance *)\n\ntype block_header_data = Alpha_context.Block_header.protocol_data\n\ntype block_header = Alpha_context.Block_header.t = {\n shell : Block_header.shell_header;\n protocol_data : block_header_data;\n}\n\nlet block_header_data_encoding =\n Alpha_context.Block_header.protocol_data_encoding\n\ntype block_header_metadata = Apply_results.block_metadata\n\nlet block_header_metadata_encoding = Apply_results.block_metadata_encoding\n\ntype operation_data = Alpha_context.packed_protocol_data =\n | Operation_data :\n 'kind Alpha_context.Operation.protocol_data\n -> operation_data\n\nlet operation_data_encoding = Alpha_context.Operation.protocol_data_encoding\n\ntype operation_receipt = Apply_results.packed_operation_metadata =\n | Operation_metadata :\n 'kind Apply_results.operation_metadata\n -> operation_receipt\n | No_operation_metadata : operation_receipt\n\nlet operation_receipt_encoding = Apply_results.operation_metadata_encoding\n\nlet operation_data_and_receipt_encoding =\n Apply_results.operation_data_and_metadata_encoding\n\ntype operation = Alpha_context.packed_operation = {\n shell : Operation.shell_header;\n protocol_data : operation_data;\n}\n\nlet acceptable_passes = Alpha_context.Operation.acceptable_passes\n\nlet max_block_length = Alpha_context.Block_header.max_header_length\n\nlet max_operation_data_length =\n Alpha_context.Constants.max_operation_data_length\n\nlet validation_passes =\n let open Alpha_context.Constants in\n Updater.\n [ (* 32 endorsements *)\n {max_size = 32 * 1024; max_op = Some 32};\n (* 32k of voting operations *)\n {max_size = 32 * 1024; max_op = None};\n (* revelations, wallet activations and denunciations *)\n {\n max_size = max_anon_ops_per_block * 1024;\n max_op = Some max_anon_ops_per_block;\n };\n (* 512kB *)\n {max_size = 512 * 1024; max_op = None} ]\n\nlet rpc_services =\n Alpha_services.register () ;\n Services_registration.get_rpc_services ()\n\ntype validation_mode =\n | Application of {\n block_header : Alpha_context.Block_header.t;\n baker : Alpha_context.public_key_hash;\n block_delay : Alpha_context.Period.t;\n }\n | Partial_application of {\n block_header : Alpha_context.Block_header.t;\n baker : Alpha_context.public_key_hash;\n block_delay : Alpha_context.Period.t;\n }\n | Partial_construction of {predecessor : Block_hash.t}\n | Full_construction of {\n predecessor : Block_hash.t;\n protocol_data : Alpha_context.Block_header.contents;\n baker : Alpha_context.public_key_hash;\n block_delay : Alpha_context.Period.t;\n }\n\ntype validation_state = {\n mode : validation_mode;\n chain_id : Chain_id.t;\n ctxt : Alpha_context.t;\n op_count : int;\n}\n\nlet current_context {ctxt; _} = return (Alpha_context.finalize ctxt).context\n\nlet begin_partial_application ~chain_id ~ancestor_context:ctxt\n ~predecessor_timestamp ~predecessor_fitness\n (block_header : Alpha_context.Block_header.t) =\n let level = block_header.shell.level in\n let fitness = predecessor_fitness in\n let timestamp = block_header.shell.timestamp in\n Alpha_context.prepare ~level ~predecessor_timestamp ~timestamp ~fitness ctxt\n >>=? fun ctxt ->\n Apply.begin_application ctxt chain_id block_header predecessor_timestamp\n >|=? fun (ctxt, baker, block_delay) ->\n let mode =\n Partial_application\n {block_header; baker = Signature.Public_key.hash baker; block_delay}\n in\n {mode; chain_id; ctxt; op_count = 0}\n\nlet begin_application ~chain_id ~predecessor_context:ctxt\n ~predecessor_timestamp ~predecessor_fitness\n (block_header : Alpha_context.Block_header.t) =\n let level = block_header.shell.level in\n let fitness = predecessor_fitness in\n let timestamp = block_header.shell.timestamp in\n Alpha_context.prepare ~level ~predecessor_timestamp ~timestamp ~fitness ctxt\n >>=? fun ctxt ->\n Apply.begin_application ctxt chain_id block_header predecessor_timestamp\n >|=? fun (ctxt, baker, block_delay) ->\n let mode =\n Application\n {block_header; baker = Signature.Public_key.hash baker; block_delay}\n in\n {mode; chain_id; ctxt; op_count = 0}\n\nlet begin_construction ~chain_id ~predecessor_context:ctxt\n ~predecessor_timestamp ~predecessor_level:pred_level\n ~predecessor_fitness:pred_fitness ~predecessor ~timestamp\n ?(protocol_data : block_header_data option) () =\n let level = Int32.succ pred_level in\n let fitness = pred_fitness in\n Alpha_context.prepare ~level ~predecessor_timestamp ~timestamp ~fitness ctxt\n >>=? fun ctxt ->\n ( match protocol_data with\n | None ->\n Apply.begin_partial_construction ctxt\n >|=? fun ctxt ->\n let mode = Partial_construction {predecessor} in\n (mode, ctxt)\n | Some proto_header ->\n Apply.begin_full_construction\n ctxt\n predecessor_timestamp\n proto_header.contents\n >|=? fun (ctxt, protocol_data, baker, block_delay) ->\n let mode =\n let baker = Signature.Public_key.hash baker in\n Full_construction {predecessor; baker; protocol_data; block_delay}\n in\n (mode, ctxt) )\n >|=? fun (mode, ctxt) -> {mode; chain_id; ctxt; op_count = 0}\n\nlet apply_operation ({mode; chain_id; ctxt; op_count; _} as data)\n (operation : Alpha_context.packed_operation) =\n match mode with\n | Partial_application _\n when not\n (List.exists\n (Compare.Int.equal 0)\n (Alpha_context.Operation.acceptable_passes operation)) ->\n (* Multipass validation only considers operations in pass 0. *)\n let op_count = op_count + 1 in\n return ({data with ctxt; op_count}, No_operation_metadata)\n | _ ->\n let {shell; protocol_data = Operation_data protocol_data} = operation in\n let operation : _ Alpha_context.operation = {shell; protocol_data} in\n let (predecessor, baker) =\n match mode with\n | Partial_application\n {block_header = {shell = {predecessor; _}; _}; baker}\n | Application {block_header = {shell = {predecessor; _}; _}; baker}\n | Full_construction {predecessor; baker; _} ->\n (predecessor, baker)\n | Partial_construction {predecessor} ->\n (predecessor, Signature.Public_key_hash.zero)\n in\n Apply.apply_operation\n ctxt\n chain_id\n Optimized\n predecessor\n baker\n (Alpha_context.Operation.hash operation)\n operation\n >|=? fun (ctxt, result) ->\n let op_count = op_count + 1 in\n ({data with ctxt; op_count}, Operation_metadata result)\n\nlet finalize_block {mode; ctxt; op_count} =\n match mode with\n | Partial_construction _ ->\n Alpha_context.Voting_period.get_current_info ctxt\n >>=? fun {voting_period = {kind; _}; _} ->\n Alpha_context.Voting_period.get_rpc_fixed_current_info ctxt\n >>=? fun ({voting_period; position; _} as voting_period_info) ->\n let level_info = Alpha_context.Level.current ctxt in\n let baker = Signature.Public_key_hash.zero in\n Signature.Public_key_hash.Map.fold\n (fun delegate deposit ctxt ->\n ctxt\n >>=? fun ctxt ->\n Alpha_context.Delegate.freeze_deposit ctxt delegate deposit)\n (Alpha_context.get_deposits ctxt)\n (return ctxt)\n >|=? fun ctxt ->\n let ctxt = Alpha_context.finalize ctxt in\n ( ctxt,\n Apply_results.\n {\n baker;\n level =\n Alpha_context.Level.to_deprecated_type\n level_info\n ~voting_period_index:voting_period.index\n ~voting_period_position:position;\n level_info;\n voting_period_kind = kind;\n voting_period_info;\n nonce_hash = None;\n consumed_gas = Alpha_context.Gas.Arith.zero;\n deactivated = [];\n balance_updates = [];\n } )\n | Partial_application {block_header; baker; block_delay} ->\n let included_endorsements = Alpha_context.included_endorsements ctxt in\n Apply.check_minimum_endorsements\n ctxt\n block_header.protocol_data.contents\n block_delay\n included_endorsements\n >>?= fun () ->\n Alpha_context.Voting_period.get_current_info ctxt\n >>=? fun {voting_period = {kind; _}; _} ->\n Alpha_context.Voting_period.get_rpc_fixed_current_info ctxt\n >|=? fun ({voting_period; position; _} as voting_period_info) ->\n let level_info = Alpha_context.Level.current ctxt in\n let ctxt = Alpha_context.finalize ctxt in\n ( ctxt,\n Apply_results.\n {\n baker;\n level =\n Alpha_context.Level.to_deprecated_type\n level_info\n ~voting_period_index:voting_period.index\n ~voting_period_position:position;\n level_info;\n voting_period_kind = kind;\n voting_period_info;\n nonce_hash = None;\n consumed_gas = Alpha_context.Gas.Arith.zero;\n deactivated = [];\n balance_updates = [];\n } )\n | Application\n { baker;\n block_delay;\n block_header = {protocol_data = {contents = protocol_data; _}; _} }\n | Full_construction {protocol_data; baker; block_delay; _} ->\n Apply.finalize_application ctxt protocol_data baker ~block_delay\n >|=? fun (ctxt, receipt) ->\n let level = Alpha_context.Level.current ctxt in\n let priority = protocol_data.priority in\n let raw_level = Alpha_context.Raw_level.to_int32 level.level in\n let fitness = Alpha_context.Fitness.current ctxt in\n let commit_message =\n Format.asprintf\n \"lvl %ld, fit 1:%Ld, prio %d, %d ops\"\n raw_level\n fitness\n priority\n op_count\n in\n let ctxt = Alpha_context.finalize ~commit_message ctxt in\n (ctxt, receipt)\n\nlet compare_operations op1 op2 =\n let open Alpha_context in\n let (Operation_data op1) = op1.protocol_data in\n let (Operation_data op2) = op2.protocol_data in\n match (op1.contents, op2.contents) with\n | (Single (Endorsement _), Single (Endorsement _)) ->\n 0\n | (_, Single (Endorsement _)) ->\n 1\n | (Single (Endorsement _), _) ->\n -1\n | (Single (Seed_nonce_revelation _), Single (Seed_nonce_revelation _)) ->\n 0\n | (_, Single (Seed_nonce_revelation _)) ->\n 1\n | (Single (Seed_nonce_revelation _), _) ->\n -1\n | ( Single (Double_endorsement_evidence _),\n Single (Double_endorsement_evidence _) ) ->\n 0\n | (_, Single (Double_endorsement_evidence _)) ->\n 1\n | (Single (Double_endorsement_evidence _), _) ->\n -1\n | (Single (Double_baking_evidence _), Single (Double_baking_evidence _)) ->\n 0\n | (_, Single (Double_baking_evidence _)) ->\n 1\n | (Single (Double_baking_evidence _), _) ->\n -1\n | (Single (Activate_account _), Single (Activate_account _)) ->\n 0\n | (_, Single (Activate_account _)) ->\n 1\n | (Single (Activate_account _), _) ->\n -1\n | (Single (Proposals _), Single (Proposals _)) ->\n 0\n | (_, Single (Proposals _)) ->\n 1\n | (Single (Proposals _), _) ->\n -1\n | (Single (Ballot _), Single (Ballot _)) ->\n 0\n | (_, Single (Ballot _)) ->\n 1\n | (Single (Ballot _), _) ->\n -1\n (* Manager operations with smaller counter are pre-validated first. *)\n | (Single (Manager_operation op1), Single (Manager_operation op2)) ->\n Z.compare op1.counter op2.counter\n | (Cons (Manager_operation op1, _), Single (Manager_operation op2)) ->\n Z.compare op1.counter op2.counter\n | (Single (Manager_operation op1), Cons (Manager_operation op2, _)) ->\n Z.compare op1.counter op2.counter\n | (Cons (Manager_operation op1, _), Cons (Manager_operation op2, _)) ->\n Z.compare op1.counter op2.counter\n\nlet init ctxt block_header =\n let level = block_header.Block_header.level in\n let fitness = block_header.fitness in\n let timestamp = block_header.timestamp in\n let typecheck (ctxt : Alpha_context.context)\n (script : Alpha_context.Script.t) =\n let allow_forged_in_storage =\n false\n (* There should be no forged value in bootstrap contracts. *)\n in\n Script_ir_translator.parse_script\n ctxt\n ~legacy:false\n ~allow_forged_in_storage\n script\n >>=? fun (Ex_script parsed_script, ctxt) ->\n Script_ir_translator.extract_lazy_storage_diff\n ctxt\n Optimized\n parsed_script.storage_type\n parsed_script.storage\n ~to_duplicate:Script_ir_translator.no_lazy_storage_id\n ~to_update:Script_ir_translator.no_lazy_storage_id\n ~temporary:false\n >>=? fun (storage, lazy_storage_diff, ctxt) ->\n Script_ir_translator.unparse_data\n ctxt\n Optimized\n parsed_script.storage_type\n storage\n >|=? fun (storage, ctxt) ->\n let storage =\n Alpha_context.Script.lazy_expr (Micheline.strip_locations storage)\n in\n (({script with storage}, lazy_storage_diff), ctxt)\n in\n Alpha_context.prepare_first_block ~typecheck ~level ~timestamp ~fitness ctxt\n >|=? fun ctxt -> Alpha_context.finalize ctxt\n\n(* Vanity nonce: 0000000710783884 *)\n" ;
}] ;
}
end
module Registered =
Tezos_protocol_updater.Registered_protocol.Register_embedded_V1
(Tezos_protocol_008_PtEdo2Zk.Environment)
(Tezos_protocol_008_PtEdo2Zk.Protocol.Main)
(Source)