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

module Source = struct
  let hash =
    Some (Tezos_crypto.Protocol_hash.of_b58check_exn "ProtoALphaALphaALphaALphaALphaALphaALphaALphaDdp3zK")
  let sources = Tezos_base.Protocol.
{ expected_env = V0 ;
  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\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 = function\n    | xs when Compare.Int.(n <= 0) ->\n        Some (List.rev acc, xs)\n    | [] ->\n        None\n    | x :: xs ->\n        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  | 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 registred 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 registred 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 registred in the subcontext will be shared by the external\n    context. One should provide a function to list all the registred\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 -> return (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        return (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 -> return (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 -> return 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\n                  handler.get (k, key) (i - 1)\n                  >>=? fun value -> return (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\nval encoding : t Data_encoding.t\n\nval rpc_arg : t RPC_arg.t\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 = MBytes.t\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  MBytes.of_hex (`Hex h)\n\nmodule Index = H\n" ;
                } ;
                { name = "Qty_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\nmodule type QTY = sig\n  val id : string\nend\n\nmodule type S = sig\n  type qty\n\n  type error +=\n    | Addition_overflow of qty * qty (* `Temporary *)\n    | Subtraction_underflow of qty * qty (* `Temporary *)\n    | Multiplication_overflow of qty * int64 (* `Temporary *)\n    | Negative_multiplicator of qty * int64 (* `Temporary *)\n    | Invalid_divisor of qty * int64\n\n  (* `Temporary *)\n\n  val id : string\n\n  val zero : qty\n\n  val one_mutez : qty\n\n  val one_cent : qty\n\n  val fifty_cents : qty\n\n  val one : qty\n\n  val ( -? ) : qty -> qty -> qty tzresult\n\n  val ( +? ) : qty -> qty -> qty tzresult\n\n  val ( *? ) : qty -> int64 -> qty tzresult\n\n  val ( /? ) : qty -> int64 -> qty tzresult\n\n  val to_mutez : qty -> int64\n\n  (** [of_mutez n] (micro tez) is None if n is negative *)\n  val of_mutez : int64 -> qty option\n\n  (** [of_mutez_exn n] fails if n is negative.\n      It should only be used at toplevel for constants. *)\n  val of_mutez_exn : int64 -> qty\n\n  (** It should only be used at toplevel for constants. *)\n  val add_exn : qty -> qty -> qty\n\n  (** It should only be used at toplevel for constants. *)\n  val mul_exn : qty -> int -> qty\n\n  val encoding : qty Data_encoding.t\n\n  val to_int64 : qty -> int64\n\n  include Compare.S with type t := qty\n\n  val pp : Format.formatter -> qty -> unit\n\n  val of_string : string -> qty option\n\n  val to_string : qty -> string\nend\n\nmodule Make (T : QTY) : S = struct\n  type qty = int64 (* invariant: positive *)\n\n  type error +=\n    | Addition_overflow of qty * qty (* `Temporary *)\n    | Subtraction_underflow of qty * qty (* `Temporary *)\n    | Multiplication_overflow of qty * int64 (* `Temporary *)\n    | Negative_multiplicator of qty * int64 (* `Temporary *)\n    | Invalid_divisor of qty * int64\n\n  (* `Temporary *)\n\n  include Compare.Int64\n\n  let zero = 0L\n\n  (* all other constant are defined from the value of one micro tez *)\n  let one_mutez = 1L\n\n  let one_cent = Int64.mul one_mutez 10_000L\n\n  let fifty_cents = Int64.mul one_cent 50L\n\n  (* 1 tez = 100 cents = 1_000_000 mutez *)\n  let one = Int64.mul one_cent 100L\n\n  let id = T.id\n\n  let 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\n            && 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      try\n        Some\n          (Int64.of_string\n             (remove_commas left ^ pad_to_six (remove_commas right)))\n      with _ -> None\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\n  let 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    Format.fprintf ppf \"%a\" left ints ;\n    if Compare.Int.(decs > 0) then Format.fprintf ppf \".%a\" right decs\n\n  let to_string t = Format.asprintf \"%a\" pp t\n\n  let ( - ) t1 t2 = if t2 <= t1 then Some (Int64.sub t1 t2) else None\n\n  let ( -? ) t1 t2 =\n    match t1 - t2 with\n    | None ->\n        error (Subtraction_underflow (t1, t2))\n    | Some v ->\n        ok v\n\n  let ( +? ) t1 t2 =\n    let t = Int64.add t1 t2 in\n    if t < t1 then error (Addition_overflow (t1, t2)) else ok t\n\n  let ( *? ) 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\n  let ( /? ) t d =\n    if d <= 0L then error (Invalid_divisor (t, d)) else ok (Int64.div t d)\n\n  let add_exn t1 t2 =\n    let t = Int64.add t1 t2 in\n    if t <= 0L then invalid_arg \"add_exn\" else t\n\n  let 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\n  let of_mutez t = if t < 0L then None else Some t\n\n  let of_mutez_exn x =\n    match of_mutez x with None -> invalid_arg \"Qty.of_mutez\" | Some v -> v\n\n  let to_int64 t = t\n\n  let to_mutez t = t\n\n  let encoding =\n    let open Data_encoding in\n    check_size 10 (conv Z.of_int64 (Json.wrap_error Z.to_int64) n)\n\n  let () =\n    let open Data_encoding in\n    register_error_kind\n      `Temporary\n      ~id:(T.id ^ \".addition_overflow\")\n      ~title:(\"Overflowing \" ^ T.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          T.id\n          pp\n          opb\n          T.id)\n      ~description:(\"An addition of two \" ^ T.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:(T.id ^ \".subtraction_underflow\")\n      ~title:(\"Underflowing \" ^ T.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          T.id\n          pp\n          opb\n          T.id)\n      ~description:(\"An subtraction of two \" ^ T.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:(T.id ^ \".multiplication_overflow\")\n      ~title:(\"Overflowing \" ^ T.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          T.id\n          opb)\n      ~description:\n        (\"A multiplication of a \" ^ T.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:(T.id ^ \".negative_multiplicator\")\n      ~title:(\"Negative \" ^ T.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          T.id\n          opb)\n      ~description:\n        (\"Multiplication of a \" ^ T.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:(T.id ^ \".invalid_divisor\")\n      ~title:(\"Invalid \" ^ T.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          T.id\n          opb)\n      ~description:\n        (\"Multiplication of a \" ^ T.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))\nend\n" ;
                } ;
                { name = "Tez_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 tez = t\n\ninclude Qty_repr.S with type qty := 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\ninclude Qty_repr.Make (struct\n  let id = \"tez\"\nend)\n\ntype t = qty\n\ntype tez = qty\n\nlet encoding = Data_encoding.def \"mutez\" @@ encoding\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 -> 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:\"Substracting timestamps resulted in negative period.\"\n    ~pp:(fun ppf () ->\n      Format.fprintf ppf \"Substracting timestamps resulted in negative period.\")\n    Data_encoding.empty\n    (function Timestamp_sub -> Some () | _ -> None)\n    (fun () -> Timestamp_sub)\n\nlet of_seconds s = try Some (of_seconds (Int64.of_string s)) with _ -> None\n\nlet to_seconds = to_seconds\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 = "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_revelations_per_block = 32\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_revelations_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_revelations_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_revelations_per_block,\n           max_operation_data_length,\n           max_proposals_per_delegate ) ->\n      {\n        proof_of_work_nonce_size;\n        nonce_length;\n        max_revelations_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_revelations_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_revelations_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 : Z.t;\n  hard_gas_limit_per_block : Z.t;\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 \"hard_gas_limit_per_operation\" z)\n          (req \"hard_gas_limit_per_block\" z))\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 = MBytes.create 8 in\n  MBytes.set_int64 b 0 i ; b\n\nlet int64_of_bytes b =\n  if Compare.Int.(MBytes.length b <> 8) then error Invalid_fitness\n  else ok (MBytes.get_int64 b 0)\n\nlet from_int64 fitness =\n  [MBytes.of_string Constants_repr.version_number; int64_to_bytes fitness]\n\nlet to_int64 = function\n  | [version; fitness]\n    when Compare.String.(\n           MBytes.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           MBytes.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    match Int32.of_string str with\n    | exception _ ->\n        Error \"Cannot parse level\"\n    | raw_level ->\n        Ok raw_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\n    | [s] -> (\n      try Some (Int32.of_string s) with _ -> None )\n    | _ ->\n        None\n\n  let rpc_arg = rpc_arg\n\n  let encoding = encoding\n\n  let compare = compare\nend\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(** A voting period can be of 4 kinds and is uniquely identified as a counter\n    since the root. *)\n\ntype t\n\ntype voting_period = t\n\nval encoding : voting_period Data_encoding.t\n\nval rpc_arg : voting_period RPC_arg.arg\n\nval pp : Format.formatter -> voting_period -> unit\n\ninclude Compare.S with type t := voting_period\n\nval to_int32 : voting_period -> int32\n\nval of_int32_exn : int32 -> voting_period\n\nval root : voting_period\n\nval succ : voting_period -> voting_period\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\nval kind_encoding : kind 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 = int32\n\ntype voting_period = 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 voting_period = Int32.to_string voting_period in\n  let destruct str =\n    match Int32.of_string str with\n    | exception _ ->\n        Error \"Cannot parse voting period\"\n    | voting_period ->\n        Ok voting_period\n  in\n  RPC_arg.make\n    ~descr:\"A voting period\"\n    ~name:\"voting_period\"\n    ~construct\n    ~destruct\n    ()\n\nlet root = 0l\n\nlet succ = Int32.succ\n\nlet to_int32 l = l\n\nlet of_int32_exn l =\n  if Compare.Int32.(l >= 0l) then l\n  else invalid_arg \"Voting_period_repr.of_int32\"\n\ntype kind = Proposal | Testing_vote | Testing | Promotion_vote\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" ;
                } ;
                { 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(*                                                                           *)\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    match Int32.of_string str with\n    | exception _ ->\n        Error \"Cannot parse cycle\"\n    | cycle ->\n        Ok 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\n    | [s] -> (\n      try Some (Int32.of_string s) with _ -> None )\n    | _ ->\n        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\n                            starts protocol alpha. This is specific to the\n                            protocol alpha. Other protocols might or might not\n                            include a similar notion. *)\n  cycle : Cycle_repr.t;\n      (** The current cycle's number. Note that cycles are a\n                          protocol-specific notion. As a result, the cycle\n                          number starts at 0 with the first block of protocol\n                          alpha. *)\n  cycle_position : int32;\n      (** The current level of the block relative to the first\n                            block of the current cycle. *)\n  voting_period : Voting_period_repr.t;\n  voting_period_position : int32;\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 : Raw_level_repr.t -> level\n\nval from_raw :\n  first_level:Raw_level_repr.t ->\n  blocks_per_cycle:int32 ->\n  blocks_per_voting_period:int32 ->\n  blocks_per_commitment:int32 ->\n  Raw_level_repr.t ->\n  level\n\nval diff : level -> level -> int32\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  voting_period : Voting_period_repr.t;\n  voting_period_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) (vote %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    Voting_period_repr.pp\n    l.voting_period\n    l.voting_period_position\n\nlet 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.\"\n          Voting_period_repr.encoding)\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.\"\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 first_level =\n  {\n    level = first_level;\n    level_position = 0l;\n    cycle = Cycle_repr.root;\n    cycle_position = 0l;\n    voting_period = Voting_period_repr.root;\n    voting_period_position = 0l;\n    expected_commitment = false;\n  }\n\nlet from_raw ~first_level ~blocks_per_cycle ~blocks_per_voting_period\n    ~blocks_per_commitment level =\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 voting_period =\n    Voting_period_repr.of_int32_exn\n      (Int32.div level_position blocks_per_voting_period)\n  in\n  let voting_period_position =\n    Int32.rem level_position blocks_per_voting_period\n  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  {\n    level;\n    level_position;\n    cycle;\n    cycle_position;\n    voting_period;\n    voting_period_position;\n    expected_commitment;\n  }\n\nlet diff {level = l1; _} {level = l2; _} =\n  Int32.sub (Raw_level_repr.to_int32 l1) (Raw_level_repr.to_int32 l2)\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 globaly 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 -> MBytes.t 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 -> MBytes.t * 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(** [intial_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 : MBytes.t -> 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 = MBytes.t\n\nlet nonce_encoding = Data_encoding.Fixed.bytes Constants_repr.nonce_length\n\nlet init = \"Laissez-faire les proprietaires.\"\n\nlet zero_bytes = MBytes.of_string (String.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 [MBytes.of_string init])\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 = MBytes.get_int32 b 0 in\n  let r = Int32.logxor higher i in\n  let res = MBytes.copy b in\n  MBytes.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 (MBytes.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.(MBytes.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.(MBytes.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 = "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\ntype t = Unaccounted | Limited of {remaining : Z.t}\n\ntype internal_gas\n\nval encoding : t Data_encoding.encoding\n\nval pp : Format.formatter -> t -> unit\n\ntype cost\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 consume :\n  Z.t -> t -> internal_gas -> cost -> (Z.t * t * internal_gas) tzresult\n\nval check_enough : Z.t -> t -> internal_gas -> cost -> unit tzresult\n\nval internal_gas_zero : internal_gas\n\nval free : cost\n\nval atomic_step_cost : int -> cost\n\nval step_cost : int -> cost\n\nval alloc_cost : int -> cost\n\nval alloc_bytes_cost : int -> cost\n\nval alloc_mbytes_cost : int -> cost\n\nval alloc_bits_cost : int -> cost\n\nval read_bytes_cost : Z.t -> cost\n\nval write_bytes_cost : Z.t -> cost\n\nval ( *@ ) : int -> 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\ntype t = Unaccounted | Limited of {remaining : Z.t}\n\ntype internal_gas = Z.t\n\ntype cost = {\n  allocations : Z.t;\n  steps : Z.t;\n  reads : Z.t;\n  writes : Z.t;\n  bytes_read : Z.t;\n  bytes_written : Z.t;\n}\n\nlet encoding =\n  let open Data_encoding in\n  union\n    [ case\n        (Tag 0)\n        ~title:\"Limited\"\n        z\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 \"%s units remaining\" (Z.to_string remaining)\n\nlet cost_encoding =\n  let open Data_encoding in\n  conv\n    (fun {allocations; steps; reads; writes; bytes_read; bytes_written} ->\n      (allocations, steps, reads, writes, bytes_read, bytes_written))\n    (fun (allocations, steps, reads, writes, bytes_read, bytes_written) ->\n      {allocations; steps; reads; writes; bytes_read; bytes_written})\n    (obj6\n       (req \"allocations\" z)\n       (req \"steps\" z)\n       (req \"reads\" z)\n       (req \"writes\" z)\n       (req \"bytes_read\" z)\n       (req \"bytes_written\" z))\n\nlet pp_cost ppf {allocations; steps; reads; writes; bytes_read; bytes_written}\n    =\n  Format.fprintf\n    ppf\n    \"(steps: %s, allocs: %s, reads: %s (%s bytes), writes: %s (%s bytes))\"\n    (Z.to_string steps)\n    (Z.to_string allocations)\n    (Z.to_string reads)\n    (Z.to_string bytes_read)\n    (Z.to_string writes)\n    (Z.to_string bytes_written)\n\ntype error += Block_quota_exceeded (* `Temporary *)\n\ntype error += Operation_quota_exceeded (* `Temporary *)\n\nlet allocation_weight = Z.of_int 2\n\nlet step_weight = Z.of_int 1\n\nlet read_base_weight = Z.of_int 100\n\nlet write_base_weight = Z.of_int 160\n\nlet byte_read_weight = Z.of_int 10\n\nlet byte_written_weight = Z.of_int 15\n\nlet rescaling_bits = 7\n\nlet rescaling_mask = Z.sub (Z.shift_left Z.one rescaling_bits) Z.one\n\nlet scale (z : Z.t) = Z.shift_left z rescaling_bits\n\nlet rescale (z : Z.t) = Z.shift_right z rescaling_bits\n\nlet cost_to_internal_gas (cost : cost) : internal_gas =\n  Z.add\n    (Z.add\n       (Z.mul cost.allocations allocation_weight)\n       (Z.mul cost.steps step_weight))\n    (Z.add\n       (Z.add\n          (Z.mul cost.reads read_base_weight)\n          (Z.mul cost.writes write_base_weight))\n       (Z.add\n          (Z.mul cost.bytes_read byte_read_weight)\n          (Z.mul cost.bytes_written byte_written_weight)))\n\nlet internal_gas_to_gas internal_gas : Z.t * internal_gas =\n  let gas = rescale internal_gas in\n  let rest = Z.logand internal_gas rescaling_mask in\n  (gas, rest)\n\nlet consume block_gas operation_gas internal_gas cost =\n  match operation_gas with\n  | Unaccounted ->\n      ok (block_gas, Unaccounted, internal_gas)\n  | Limited {remaining} ->\n      let cost_internal_gas = cost_to_internal_gas cost in\n      let total_internal_gas = Z.add cost_internal_gas internal_gas in\n      let (gas, rest) = internal_gas_to_gas total_internal_gas in\n      if Compare.Z.(gas > Z.zero) then\n        let remaining = Z.sub remaining gas in\n        let block_remaining = Z.sub block_gas gas in\n        if Compare.Z.(remaining < Z.zero) then error Operation_quota_exceeded\n        else if Compare.Z.(block_remaining < Z.zero) then\n          error Block_quota_exceeded\n        else ok (block_remaining, Limited {remaining}, rest)\n      else ok (block_gas, operation_gas, total_internal_gas)\n\nlet check_enough block_gas operation_gas internal_gas cost =\n  consume block_gas operation_gas internal_gas cost\n  >|? fun (_block_remainig, _remaining, _internal_gas) -> ()\n\nlet internal_gas_zero : internal_gas = Z.zero\n\nlet alloc_cost n =\n  {\n    allocations = scale (Z.of_int (n + 1));\n    steps = Z.zero;\n    reads = Z.zero;\n    writes = Z.zero;\n    bytes_read = Z.zero;\n    bytes_written = Z.zero;\n  }\n\nlet alloc_bytes_cost n = alloc_cost ((n + 7) / 8)\n\nlet alloc_bits_cost n = alloc_cost ((n + 63) / 64)\n\nlet atomic_step_cost n =\n  {\n    allocations = Z.zero;\n    steps = Z.of_int (2 * n);\n    reads = Z.zero;\n    writes = Z.zero;\n    bytes_read = Z.zero;\n    bytes_written = Z.zero;\n  }\n\nlet step_cost n =\n  {\n    allocations = Z.zero;\n    steps = scale (Z.of_int n);\n    reads = Z.zero;\n    writes = Z.zero;\n    bytes_read = Z.zero;\n    bytes_written = Z.zero;\n  }\n\nlet free =\n  {\n    allocations = Z.zero;\n    steps = Z.zero;\n    reads = Z.zero;\n    writes = Z.zero;\n    bytes_read = Z.zero;\n    bytes_written = Z.zero;\n  }\n\nlet read_bytes_cost n =\n  {\n    allocations = Z.zero;\n    steps = Z.zero;\n    reads = scale Z.one;\n    writes = Z.zero;\n    bytes_read = scale n;\n    bytes_written = Z.zero;\n  }\n\nlet write_bytes_cost n =\n  {\n    allocations = Z.zero;\n    steps = Z.zero;\n    reads = Z.zero;\n    writes = Z.one;\n    bytes_read = Z.zero;\n    bytes_written = scale n;\n  }\n\nlet ( +@ ) x y =\n  {\n    allocations = Z.add x.allocations y.allocations;\n    steps = Z.add x.steps y.steps;\n    reads = Z.add x.reads y.reads;\n    writes = Z.add x.writes y.writes;\n    bytes_read = Z.add x.bytes_read y.bytes_read;\n    bytes_written = Z.add x.bytes_written y.bytes_written;\n  }\n\nlet ( *@ ) x y =\n  {\n    allocations = Z.mul (Z.of_int x) y.allocations;\n    steps = Z.mul (Z.of_int x) y.steps;\n    reads = Z.mul (Z.of_int x) y.reads;\n    writes = Z.mul (Z.of_int x) y.writes;\n    bytes_read = Z.mul (Z.of_int x) y.bytes_read;\n    bytes_written = Z.mul (Z.of_int x) y.bytes_written;\n  }\n\nlet alloc_mbytes_cost n = alloc_cost 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 = "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 arbitraty 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. *)\nand n = Natural_tag\n\n(** Flag for relative numbers. *)\nand 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 to an OCaml [int64], returns [None] on overflow. *)\nval to_int64 : _ num -> int64 option\n\n(** Conversion from an OCaml [int]. *)\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 [int64]. *)\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 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(*                                                                           *)\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 += Unknown_primitive_name of string (* `Permanent *)\n\ntype error += Invalid_case of string (* `Permanent *)\n\ntype error +=\n  | Invalid_primitive_name of\n      string Micheline.canonical * Micheline.canonical_location\n\n(* `Permanent *)\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_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_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_PUSH\n  | I_RIGHT\n  | I_SIZE\n  | I_SOME\n  | I_SOURCE\n  | I_SENDER\n  | I_SELF\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_DIG\n  | I_DUG\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_chain_id\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" ;
                  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 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_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_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_PUSH\n  | I_RIGHT\n  | I_SIZE\n  | I_SOME\n  | I_SOURCE\n  | I_SENDER\n  | I_SELF\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_DIG\n  | I_DUG\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_chain_id\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_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_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_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_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_DIG ->\n      \"DIG\"\n  | I_DUG ->\n      \"DUG\"\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_chain_id ->\n      \"chain_id\"\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  | \"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  | \"LAMBDA\" ->\n      ok I_LAMBDA\n  | \"LE\" ->\n      ok I_LE\n  | \"LEFT\" ->\n      ok I_LEFT\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  | \"PUSH\" ->\n      ok I_PUSH\n  | \"RIGHT\" ->\n      ok I_RIGHT\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  | \"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  | \"DIG\" ->\n      ok I_DIG\n  | \"DUG\" ->\n      ok I_DUG\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  | \"chain_id\" ->\n      ok T_chain_id\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        List.fold_left\n          (fun acc arg ->\n            acc >>? fun args -> convert arg >>? fun arg -> ok (arg :: args))\n          (ok [])\n          args\n        >>? fun args -> ok (Prim (0, prim, List.rev args, annot))\n    | Seq (_, args) ->\n        List.fold_left\n          (fun acc arg ->\n            acc >>? fun args -> convert arg >>? fun arg -> ok (arg :: args))\n          (ok [])\n          args\n        >>? fun args -> ok (Seq (0, List.rev args))\n  in\n  convert (root expr) >>? fun expr -> ok (strip_locations expr)\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\nlet prim_encoding =\n  let open Data_encoding in\n  def \"michelson.v1.primitives\"\n  @@ string_enum\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 here, for backward compatibility of the encoding. *)\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" ;
                } ;
                { 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 : MBytes.t -> Gas_limit_repr.cost\n\nval traversal_cost : node -> Gas_limit_repr.cost\n\nval node_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 : MBytes.t -> 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 prim_node_cost_nonrec_of_length : int -> 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 -> (MBytes.t * 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" ;
                  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 (MBytes.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 rec node_size node =\n  let open Micheline in\n  match node with\n  | Int (_, n) ->\n      int_node_size n\n  | String (_, s) ->\n      string_node_size s\n  | Bytes (_, s) ->\n      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          (blocks + nblocks, words + nwords))\n        (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          (blocks + nblocks, words + nwords))\n        (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.Int.max 0 (blocks - 1) *@ alloc_cost 0)\n  +@ alloc_cost words +@ step_cost blocks\n\nlet node_cost node = cost_of_size (node_size node)\n\nlet int_node_cost n = cost_of_size (int_node_size n)\n\nlet int_node_cost_of_numbits n = cost_of_size (int_node_size_of_numbits n)\n\nlet string_node_cost s = cost_of_size (string_node_size s)\n\nlet string_node_cost_of_length s = cost_of_size (string_node_size_of_length s)\n\nlet bytes_node_cost s = cost_of_size (bytes_node_size s)\n\nlet bytes_node_cost_of_length s = cost_of_size (bytes_node_size_of_length s)\n\nlet prim_node_cost_nonrec args annot =\n  cost_of_size (prim_node_size_nonrec args annot)\n\nlet prim_node_cost_nonrec_of_length n_args annot =\n  cost_of_size (prim_node_size_nonrec_of_lengths n_args annot)\n\nlet seq_node_cost_nonrec args = cost_of_size (seq_node_size_nonrec args)\n\nlet seq_node_cost_nonrec_of_length n_args =\n  cost_of_size (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_mbytes_cost (MBytes.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 -> MBytes.( = ) 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" ;
                } ;
                { name = "Legacy_script_support_repr" ;
                  interface = Some "(*****************************************************************************)\n(*                                                                           *)\n(* Open Source License                                                       *)\n(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com>     *)\n(* Copyright (c) 2019 Nomadic Labs <contact@nomadic-labs.com>                *)\n(* Copyright (c) 2019 Cryptium Labs <contact@cryptium-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 code mimics the now defunct scriptless KT1s.\n\n    The manager contract is from:\n    https://gitlab.com/nomadic-labs/mi-cho-coq/blob/7b42f2e970e1541af54f8a9b6820b4f18e847575/src/contracts/manager.tz\n    The formal proof is at:\n    https://gitlab.com/nomadic-labs/mi-cho-coq/blob/a7603e12021166e15890f6d504feebec2f945502/src/contracts_coq/manager.v *)\nval manager_script_code : Script_repr.lazy_expr\n\n(** This code mimics the now defunct \"spendable\" flags of KT1s by\n    adding a [do] entrypoint, preserving the original script's at\n    'default' entrypoint.\n\n    The pseudo-code for the applied transformations is from:\n    https://gitlab.com/nomadic-labs/mi-cho-coq/blob/7b42f2e970e1541af54f8a9b6820b4f18e847575/src/contracts/transform/add_do.tz *)\nval add_do :\n  manager_pkh:Signature.Public_key_hash.t ->\n  script_code:Script_repr.lazy_expr ->\n  script_storage:Script_repr.lazy_expr ->\n  (Script_repr.lazy_expr * Script_repr.lazy_expr) tzresult Lwt.t\n\n(** This code mimics the now defunct \"spendable\" flags of KT1s by\n    adding a [do] entrypoint, preserving the original script's at\n    'default' entrypoint.\n\n    The pseudo-code for the applied transformations is from:\n    https://gitlab.com/nomadic-labs/mi-cho-coq/blob/7b42f2e970e1541af54f8a9b6820b4f18e847575/src/contracts/transform/add_set_delegate.tz *)\nval add_set_delegate :\n  manager_pkh:Signature.Public_key_hash.t ->\n  script_code:Script_repr.lazy_expr ->\n  script_storage:Script_repr.lazy_expr ->\n  (Script_repr.lazy_expr * Script_repr.lazy_expr) tzresult Lwt.t\n\n(** Checks if a contract was declaring a default entrypoint somewhere\n   else than at the root, in which case its type changes when\n   entrypoints are activated. *)\nval has_default_entrypoint : Script_repr.lazy_expr -> bool\n\n(** Adds a [%root] annotation on the toplevel parameter construct. *)\nval add_root_entrypoint :\n  script_code:Script_repr.lazy_expr -> Script_repr.lazy_expr 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 Nomadic Labs <contact@nomadic-labs.com>                *)\n(* Copyright (c) 2019 Cryptium Labs <contact@cryptium-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 manager_script_code : Script_repr.lazy_expr =\n  let open Micheline in\n  let open Michelson_v1_primitives in\n  Script_repr.lazy_expr @@ strip_locations\n  @@ Seq\n       ( 0,\n         [ Prim\n             ( 0,\n               K_parameter,\n               [ Prim\n                   ( 0,\n                     T_or,\n                     [ Prim\n                         ( 0,\n                           T_lambda,\n                           [ Prim (0, T_unit, [], []);\n                             Prim\n                               (0, T_list, [Prim (0, T_operation, [], [])], [])\n                           ],\n                           [\"%do\"] );\n                       Prim (0, T_unit, [], [\"%default\"]) ],\n                     [] ) ],\n               [] );\n           Prim (0, K_storage, [Prim (0, T_key_hash, [], [])], []);\n           Prim\n             ( 0,\n               K_code,\n               [ Seq\n                   ( 0,\n                     [ Seq\n                         ( 0,\n                           [ Seq\n                               ( 0,\n                                 [ Prim (0, I_DUP, [], []);\n                                   Prim (0, I_CAR, [], []);\n                                   Prim\n                                     ( 0,\n                                       I_DIP,\n                                       [Seq (0, [Prim (0, I_CDR, [], [])])],\n                                       [] ) ] ) ] );\n                       Prim\n                         ( 0,\n                           I_IF_LEFT,\n                           [ Seq\n                               ( 0,\n                                 [ Prim\n                                     ( 0,\n                                       I_PUSH,\n                                       [ Prim (0, T_mutez, [], []);\n                                         Int (0, Z.zero) ],\n                                       [] );\n                                   Prim (0, I_AMOUNT, [], []);\n                                   Seq\n                                     ( 0,\n                                       [ Seq\n                                           ( 0,\n                                             [ Prim (0, I_COMPARE, [], []);\n                                               Prim (0, I_EQ, [], []) ] );\n                                         Prim\n                                           ( 0,\n                                             I_IF,\n                                             [ Seq (0, []);\n                                               Seq\n                                                 ( 0,\n                                                   [ Seq\n                                                       ( 0,\n                                                         [ Prim\n                                                             (0, I_UNIT, [], []);\n                                                           Prim\n                                                             ( 0,\n                                                               I_FAILWITH,\n                                                               [],\n                                                               [] ) ] ) ] ) ],\n                                             [] ) ] );\n                                   Seq\n                                     ( 0,\n                                       [ Prim\n                                           ( 0,\n                                             I_DIP,\n                                             [ Seq\n                                                 (0, [Prim (0, I_DUP, [], [])])\n                                             ],\n                                             [] );\n                                         Prim (0, I_SWAP, [], []) ] );\n                                   Prim (0, I_IMPLICIT_ACCOUNT, [], []);\n                                   Prim (0, I_ADDRESS, [], []);\n                                   Prim (0, I_SENDER, [], []);\n                                   Seq\n                                     ( 0,\n                                       [ Seq\n                                           ( 0,\n                                             [ Prim (0, I_COMPARE, [], []);\n                                               Prim (0, I_EQ, [], []) ] );\n                                         Prim\n                                           ( 0,\n                                             I_IF,\n                                             [ Seq (0, []);\n                                               Seq\n                                                 ( 0,\n                                                   [ Seq\n                                                       ( 0,\n                                                         [ Prim\n                                                             (0, I_UNIT, [], []);\n                                                           Prim\n                                                             ( 0,\n                                                               I_FAILWITH,\n                                                               [],\n                                                               [] ) ] ) ] ) ],\n                                             [] ) ] );\n                                   Prim (0, I_UNIT, [], []);\n                                   Prim (0, I_EXEC, [], []);\n                                   Prim (0, I_PAIR, [], []) ] );\n                             Seq\n                               ( 0,\n                                 [ Prim (0, I_DROP, [], []);\n                                   Prim\n                                     ( 0,\n                                       I_NIL,\n                                       [Prim (0, T_operation, [], [])],\n                                       [] );\n                                   Prim (0, I_PAIR, [], []) ] ) ],\n                           [] ) ] ) ],\n               [] ) ] )\n\n(* Find the toplevel expression with a given prim type from list,\n   because they can be in arbitrary order. *)\nlet find_toplevel toplevel exprs =\n  let open Micheline in\n  let rec iter toplevel = function\n    | (Prim (_, prim, _, _) as found) :: _\n      when String.equal toplevel (Michelson_v1_primitives.string_of_prim prim)\n      ->\n        Some found\n    | _ :: rest ->\n        iter toplevel rest\n    | [] ->\n        None\n  in\n  iter (Michelson_v1_primitives.string_of_prim toplevel) exprs\n\nlet add_do :\n    manager_pkh:Signature.Public_key_hash.t ->\n    script_code:Script_repr.lazy_expr ->\n    script_storage:Script_repr.lazy_expr ->\n    (Script_repr.lazy_expr * Script_repr.lazy_expr) tzresult Lwt.t =\n fun ~manager_pkh ~script_code ~script_storage ->\n  let open Micheline in\n  let open Michelson_v1_primitives in\n  Lwt.return (Script_repr.force_decode script_code)\n  >>=? fun (script_code_expr, _gas_cost) ->\n  Lwt.return (Script_repr.force_decode script_storage)\n  >>|? fun (script_storage_expr, _gas_cost) ->\n  let storage_expr = root script_storage_expr in\n  match root script_code_expr with\n  | Seq (_, toplevel) -> (\n    match\n      ( find_toplevel K_parameter toplevel,\n        find_toplevel K_storage toplevel,\n        find_toplevel K_code toplevel )\n    with\n    | ( Some\n          (Prim\n            ( _,\n              K_parameter,\n              [Prim (_, parameter_type, parameter_expr, parameter_annot)],\n              prim_param_annot )),\n        Some\n          (Prim\n            ( _,\n              K_storage,\n              [ Prim\n                  (_, code_storage_type, code_storage_expr, code_storage_annot)\n              ],\n              k_storage_annot )),\n        Some (Prim (_, K_code, [code_expr], code_annot)) ) ->\n        (* Note that we intentionally don't deal with potential duplicate entrypoints in this migration as there already might be some in contracts that we don't touch. *)\n        let migrated_code =\n          Seq\n            ( 0,\n              [ Prim\n                  ( 0,\n                    K_parameter,\n                    [ Prim\n                        ( 0,\n                          T_or,\n                          [ Prim\n                              ( 0,\n                                T_lambda,\n                                [ Prim (0, T_unit, [], []);\n                                  Prim\n                                    ( 0,\n                                      T_list,\n                                      [Prim (0, T_operation, [], [])],\n                                      [] ) ],\n                                [\"%do\"] );\n                            Prim\n                              ( 0,\n                                parameter_type,\n                                parameter_expr,\n                                \"%default\" :: parameter_annot ) ],\n                          [] ) ],\n                    prim_param_annot );\n                Prim\n                  ( 0,\n                    K_storage,\n                    [ Prim\n                        ( 0,\n                          T_pair,\n                          [ Prim (0, T_key_hash, [], []);\n                            Prim\n                              ( 0,\n                                code_storage_type,\n                                code_storage_expr,\n                                code_storage_annot ) ],\n                          [] ) ],\n                    k_storage_annot );\n                Prim\n                  ( 0,\n                    K_code,\n                    [ Seq\n                        ( 0,\n                          [ Prim (0, I_DUP, [], []);\n                            Prim (0, I_CAR, [], []);\n                            Prim\n                              ( 0,\n                                I_IF_LEFT,\n                                [ Seq\n                                    ( 0,\n                                      [ Prim\n                                          ( 0,\n                                            I_PUSH,\n                                            [ Prim (0, T_mutez, [], []);\n                                              Int (0, Z.zero) ],\n                                            [] );\n                                        Prim (0, I_AMOUNT, [], []);\n                                        Seq\n                                          ( 0,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_COMPARE, [], []);\n                                                    Prim (0, I_EQ, [], []) ] );\n                                              Prim\n                                                ( 0,\n                                                  I_IF,\n                                                  [ Seq (0, []);\n                                                    Seq\n                                                      ( 0,\n                                                        [ Seq\n                                                            ( 0,\n                                                              [ Prim\n                                                                  ( 0,\n                                                                    I_UNIT,\n                                                                    [],\n                                                                    [] );\n                                                                Prim\n                                                                  ( 0,\n                                                                    I_FAILWITH,\n                                                                    [],\n                                                                    [] ) ] ) ]\n                                                      ) ],\n                                                  [] ) ] );\n                                        Seq\n                                          ( 0,\n                                            [ Prim\n                                                ( 0,\n                                                  I_DIP,\n                                                  [ Seq\n                                                      ( 0,\n                                                        [ Prim\n                                                            (0, I_DUP, [], [])\n                                                        ] ) ],\n                                                  [] );\n                                              Prim (0, I_SWAP, [], []) ] );\n                                        Prim (0, I_CDR, [], []);\n                                        Prim (0, I_CAR, [], []);\n                                        Prim (0, I_IMPLICIT_ACCOUNT, [], []);\n                                        Prim (0, I_ADDRESS, [], []);\n                                        Prim (0, I_SENDER, [], []);\n                                        Seq\n                                          ( 0,\n                                            [ Prim (0, I_COMPARE, [], []);\n                                              Prim (0, I_NEQ, [], []);\n                                              Prim\n                                                ( 0,\n                                                  I_IF,\n                                                  [ Seq\n                                                      ( 0,\n                                                        [ Prim\n                                                            ( 0,\n                                                              I_SENDER,\n                                                              [],\n                                                              [] );\n                                                          Prim\n                                                            ( 0,\n                                                              I_PUSH,\n                                                              [ Prim\n                                                                  ( 0,\n                                                                    T_string,\n                                                                    [],\n                                                                    [] );\n                                                                String\n                                                                  ( 0,\n                                                                    \"Only the \\\n                                                                     owner \\\n                                                                     can \\\n                                                                     operate.\"\n                                                                  ) ],\n                                                              [] );\n                                                          Prim\n                                                            (0, I_PAIR, [], []);\n                                                          Prim\n                                                            ( 0,\n                                                              I_FAILWITH,\n                                                              [],\n                                                              [] ) ] );\n                                                    Seq\n                                                      ( 0,\n                                                        [ Prim\n                                                            (0, I_UNIT, [], []);\n                                                          Prim\n                                                            (0, I_EXEC, [], []);\n                                                          Prim\n                                                            ( 0,\n                                                              I_DIP,\n                                                              [ Seq\n                                                                  ( 0,\n                                                                    [ Prim\n                                                                        ( 0,\n                                                                          I_CDR,\n                                                                          [],\n                                                                          [] )\n                                                                    ] ) ],\n                                                              [] );\n                                                          Prim\n                                                            (0, I_PAIR, [], [])\n                                                        ] ) ],\n                                                  [] ) ] ) ] );\n                                  Seq\n                                    ( 0,\n                                      [ Prim\n                                          ( 0,\n                                            I_DIP,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_CDR, [], []);\n                                                    Prim (0, I_DUP, [], []);\n                                                    Prim (0, I_CDR, [], []) ]\n                                                ) ],\n                                            [] );\n                                        Prim (0, I_PAIR, [], []);\n                                        code_expr;\n                                        Prim (0, I_SWAP, [], []);\n                                        Prim (0, I_CAR, [], []);\n                                        Prim (0, I_SWAP, [], []);\n                                        Seq\n                                          ( 0,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_DUP, [], []);\n                                                    Prim (0, I_CAR, [], []);\n                                                    Prim\n                                                      ( 0,\n                                                        I_DIP,\n                                                        [ Seq\n                                                            ( 0,\n                                                              [ Prim\n                                                                  ( 0,\n                                                                    I_CDR,\n                                                                    [],\n                                                                    [] ) ] ) ],\n                                                        [] ) ] ) ] );\n                                        Prim\n                                          ( 0,\n                                            I_DIP,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_SWAP, [], []);\n                                                    Prim (0, I_PAIR, [], []) ]\n                                                ) ],\n                                            [] );\n                                        Prim (0, I_PAIR, [], []) ] ) ],\n                                [] ) ] ) ],\n                    code_annot ) ] )\n        in\n        let migrated_storage =\n          Prim\n            ( 0,\n              D_Pair,\n              [ (* Instead of\n                   `String (0, Signature.Public_key_hash.to_b58check manager_pkh)`\n                   the storage is written as unparsed with [Optimized] *)\n                Bytes\n                  ( 0,\n                    Data_encoding.Binary.to_bytes_exn\n                      Signature.Public_key_hash.encoding\n                      manager_pkh );\n                storage_expr ],\n              [] )\n        in\n        ( Script_repr.lazy_expr @@ strip_locations migrated_code,\n          Script_repr.lazy_expr @@ strip_locations migrated_storage )\n    | _ ->\n        (script_code, script_storage) )\n  | _ ->\n      (script_code, script_storage)\n\nlet add_set_delegate :\n    manager_pkh:Signature.Public_key_hash.t ->\n    script_code:Script_repr.lazy_expr ->\n    script_storage:Script_repr.lazy_expr ->\n    (Script_repr.lazy_expr * Script_repr.lazy_expr) tzresult Lwt.t =\n fun ~manager_pkh ~script_code ~script_storage ->\n  let open Micheline in\n  let open Michelson_v1_primitives in\n  Lwt.return (Script_repr.force_decode script_code)\n  >>=? fun (script_code_expr, _gas_cost) ->\n  Lwt.return (Script_repr.force_decode script_storage)\n  >>|? fun (script_storage_expr, _gas_cost) ->\n  let storage_expr = root script_storage_expr in\n  match root script_code_expr with\n  | Seq (_, toplevel) -> (\n    match\n      ( find_toplevel K_parameter toplevel,\n        find_toplevel K_storage toplevel,\n        find_toplevel K_code toplevel )\n    with\n    | ( Some\n          (Prim\n            ( _,\n              K_parameter,\n              [Prim (_, parameter_type, parameter_expr, parameter_annot)],\n              prim_param_annot )),\n        Some\n          (Prim\n            ( _,\n              K_storage,\n              [ Prim\n                  (_, code_storage_type, code_storage_expr, code_storage_annot)\n              ],\n              k_storage_annot )),\n        Some (Prim (_, K_code, [code_expr], code_annot)) ) ->\n        (* Note that we intentionally don't deal with potential duplicate entrypoints in this migration as there already might be some in contracts that we don't touch. *)\n        let migrated_code =\n          Seq\n            ( 0,\n              [ Prim\n                  ( 0,\n                    K_parameter,\n                    [ Prim\n                        ( 0,\n                          T_or,\n                          [ Prim\n                              ( 0,\n                                T_or,\n                                [ Prim (0, T_key_hash, [], [\"%set_delegate\"]);\n                                  Prim (0, T_unit, [], [\"%remove_delegate\"]) ],\n                                [] );\n                            Prim\n                              ( 0,\n                                parameter_type,\n                                parameter_expr,\n                                \"%default\" :: parameter_annot ) ],\n                          [] ) ],\n                    prim_param_annot );\n                Prim\n                  ( 0,\n                    K_storage,\n                    [ Prim\n                        ( 0,\n                          T_pair,\n                          [ Prim (0, T_key_hash, [], []);\n                            Prim\n                              ( 0,\n                                code_storage_type,\n                                code_storage_expr,\n                                code_storage_annot ) ],\n                          [] ) ],\n                    k_storage_annot );\n                Prim\n                  ( 0,\n                    K_code,\n                    [ Seq\n                        ( 0,\n                          [ Prim (0, I_DUP, [], []);\n                            Prim (0, I_CAR, [], []);\n                            Prim\n                              ( 0,\n                                I_IF_LEFT,\n                                [ Seq\n                                    ( 0,\n                                      [ Prim\n                                          ( 0,\n                                            I_PUSH,\n                                            [ Prim (0, T_mutez, [], []);\n                                              Int (0, Z.zero) ],\n                                            [] );\n                                        Prim (0, I_AMOUNT, [], []);\n                                        Seq\n                                          ( 0,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_COMPARE, [], []);\n                                                    Prim (0, I_EQ, [], []) ] );\n                                              Prim\n                                                ( 0,\n                                                  I_IF,\n                                                  [ Seq (0, []);\n                                                    Seq\n                                                      ( 0,\n                                                        [ Seq\n                                                            ( 0,\n                                                              [ Prim\n                                                                  ( 0,\n                                                                    I_UNIT,\n                                                                    [],\n                                                                    [] );\n                                                                Prim\n                                                                  ( 0,\n                                                                    I_FAILWITH,\n                                                                    [],\n                                                                    [] ) ] ) ]\n                                                      ) ],\n                                                  [] ) ] );\n                                        Seq\n                                          ( 0,\n                                            [ Prim\n                                                ( 0,\n                                                  I_DIP,\n                                                  [ Seq\n                                                      ( 0,\n                                                        [ Prim\n                                                            (0, I_DUP, [], [])\n                                                        ] ) ],\n                                                  [] );\n                                              Prim (0, I_SWAP, [], []) ] );\n                                        Prim (0, I_CDR, [], []);\n                                        Prim (0, I_CAR, [], []);\n                                        Prim (0, I_IMPLICIT_ACCOUNT, [], []);\n                                        Prim (0, I_ADDRESS, [], []);\n                                        Prim (0, I_SENDER, [], []);\n                                        Seq\n                                          ( 0,\n                                            [ Prim (0, I_COMPARE, [], []);\n                                              Prim (0, I_NEQ, [], []);\n                                              Prim\n                                                ( 0,\n                                                  I_IF,\n                                                  [ Seq\n                                                      ( 0,\n                                                        [ Prim\n                                                            ( 0,\n                                                              I_SENDER,\n                                                              [],\n                                                              [] );\n                                                          Prim\n                                                            ( 0,\n                                                              I_PUSH,\n                                                              [ Prim\n                                                                  ( 0,\n                                                                    T_string,\n                                                                    [],\n                                                                    [] );\n                                                                String\n                                                                  ( 0,\n                                                                    \"Only the \\\n                                                                     owner \\\n                                                                     can \\\n                                                                     operate.\"\n                                                                  ) ],\n                                                              [] );\n                                                          Prim\n                                                            (0, I_PAIR, [], []);\n                                                          Prim\n                                                            ( 0,\n                                                              I_FAILWITH,\n                                                              [],\n                                                              [] ) ] );\n                                                    Seq\n                                                      ( 0,\n                                                        [ Prim\n                                                            ( 0,\n                                                              I_DIP,\n                                                              [ Seq\n                                                                  ( 0,\n                                                                    [ Prim\n                                                                        ( 0,\n                                                                          I_CDR,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_NIL,\n                                                                          [ Prim\n                                                                              ( \n                                                                              0,\n                                                                               T_operation,\n                                                                               [],\n                                                                               []\n                                                                              )\n                                                                          ],\n                                                                          [] )\n                                                                    ] ) ],\n                                                              [] );\n                                                          Prim\n                                                            ( 0,\n                                                              I_IF_LEFT,\n                                                              [ Seq\n                                                                  ( 0,\n                                                                    [ Prim\n                                                                        ( 0,\n                                                                          I_SOME,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_SET_DELEGATE,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_CONS,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_PAIR,\n                                                                          [],\n                                                                          [] )\n                                                                    ] );\n                                                                Seq\n                                                                  ( 0,\n                                                                    [ Prim\n                                                                        ( 0,\n                                                                          I_DROP,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_NONE,\n                                                                          [ Prim\n                                                                              ( \n                                                                              0,\n                                                                               T_key_hash,\n                                                                               [],\n                                                                               []\n                                                                              )\n                                                                          ],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_SET_DELEGATE,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_CONS,\n                                                                          [],\n                                                                          [] );\n                                                                      Prim\n                                                                        ( 0,\n                                                                          I_PAIR,\n                                                                          [],\n                                                                          [] )\n                                                                    ] ) ],\n                                                              [] ) ] ) ],\n                                                  [] ) ] ) ] );\n                                  Seq\n                                    ( 0,\n                                      [ Prim\n                                          ( 0,\n                                            I_DIP,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_CDR, [], []);\n                                                    Prim (0, I_DUP, [], []);\n                                                    Prim (0, I_CDR, [], []) ]\n                                                ) ],\n                                            [] );\n                                        Prim (0, I_PAIR, [], []);\n                                        code_expr;\n                                        Prim (0, I_SWAP, [], []);\n                                        Prim (0, I_CAR, [], []);\n                                        Prim (0, I_SWAP, [], []);\n                                        Seq\n                                          ( 0,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_DUP, [], []);\n                                                    Prim (0, I_CAR, [], []);\n                                                    Prim\n                                                      ( 0,\n                                                        I_DIP,\n                                                        [ Seq\n                                                            ( 0,\n                                                              [ Prim\n                                                                  ( 0,\n                                                                    I_CDR,\n                                                                    [],\n                                                                    [] ) ] ) ],\n                                                        [] ) ] ) ] );\n                                        Prim\n                                          ( 0,\n                                            I_DIP,\n                                            [ Seq\n                                                ( 0,\n                                                  [ Prim (0, I_SWAP, [], []);\n                                                    Prim (0, I_PAIR, [], []) ]\n                                                ) ],\n                                            [] );\n                                        Prim (0, I_PAIR, [], []) ] ) ],\n                                [] ) ] ) ],\n                    code_annot ) ] )\n        in\n        let migrated_storage =\n          Prim\n            ( 0,\n              D_Pair,\n              [ (* Instead of\n                   `String (0, Signature.Public_key_hash.to_b58check manager_pkh)`\n                   the storage is written as unparsed with [Optimized] *)\n                Bytes\n                  ( 0,\n                    Data_encoding.Binary.to_bytes_exn\n                      Signature.Public_key_hash.encoding\n                      manager_pkh );\n                storage_expr ],\n              [] )\n        in\n        ( Script_repr.lazy_expr @@ strip_locations migrated_code,\n          Script_repr.lazy_expr @@ strip_locations migrated_storage )\n    | _ ->\n        (script_code, script_storage) )\n  | _ ->\n      (script_code, script_storage)\n\nlet has_default_entrypoint expr =\n  let open Micheline in\n  let open Michelson_v1_primitives in\n  match Script_repr.force_decode expr with\n  | Error _ ->\n      false\n  | Ok (expr, _) -> (\n    match root expr with\n    | Seq (_, toplevel) -> (\n      match find_toplevel K_parameter toplevel with\n      | Some (Prim (_, K_parameter, [_], [\"%default\"])) ->\n          false\n      | Some (Prim (_, K_parameter, [parameter_expr], _)) ->\n          let rec has_default = function\n            | Prim (_, T_or, [l; r], annots) ->\n                List.exists (String.equal \"%default\") annots\n                || has_default l || has_default r\n            | Prim (_, _, _, annots) ->\n                List.exists (String.equal \"%default\") annots\n            | _ ->\n                false\n          in\n          has_default parameter_expr\n      | Some _ | None ->\n          false )\n    | _ ->\n        false )\n\nlet add_root_entrypoint :\n    script_code:Script_repr.lazy_expr -> Script_repr.lazy_expr tzresult Lwt.t =\n fun ~script_code ->\n  let open Micheline in\n  let open Michelson_v1_primitives in\n  Lwt.return (Script_repr.force_decode script_code)\n  >>|? fun (script_code_expr, _gas_cost) ->\n  match root script_code_expr with\n  | Seq (_, toplevel) ->\n      let migrated_code =\n        Seq\n          ( 0,\n            List.map\n              (function\n                | Prim (_, K_parameter, [parameter_expr], _) ->\n                    Prim (0, K_parameter, [parameter_expr], [\"%root\"])\n                | Prim (_, K_code, exprs, annots) ->\n                    let rec rewrite_self = function\n                      | ( Int _\n                        | String _\n                        | Bytes _\n                        | Prim (_, I_CREATE_CONTRACT, _, _) ) as leaf ->\n                          leaf\n                      | Prim (_, I_SELF, [], annots) ->\n                          Prim (0, I_SELF, [], \"%root\" :: annots)\n                      | Prim (_, name, args, annots) ->\n                          Prim (0, name, List.map rewrite_self args, annots)\n                      | Seq (_, args) ->\n                          Seq (0, List.map rewrite_self args)\n                    in\n                    Prim (0, K_code, List.map rewrite_self exprs, annots)\n                | other ->\n                    other)\n              toplevel )\n      in\n      Script_repr.lazy_expr @@ strip_locations migrated_code\n  | _ ->\n      script_code\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) = MBytes.to_hex raw_key in\n    let (`Hex index_key) = MBytes.to_hex (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 = MBytes.of_hex (`Hex key) in\n        let (`Hex index_key) = MBytes.to_hex (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      try Some (Int32.of_string s) with _ -> None )\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 : MBytes.t;\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 : MBytes.t;\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        MBytes.create Constants_repr.proof_of_work_nonce_size;\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 : MBytes.t}\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 : Voting_period_repr.t;\n      proposals : Protocol_hash.t list;\n    }\n      -> Kind.proposals contents\n  | Ballot : {\n      source : Signature.Public_key_hash.t;\n      period : Voting_period_repr.t;\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 : Z.t;\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 Lwt.t\n\nval check_signature_sync :\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 : MBytes.t}\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 : Voting_period_repr.t;\n      proposals : Protocol_hash.t list;\n    }\n      -> Kind.proposals contents\n  | Ballot : {\n      source : Signature.Public_key_hash.t;\n      period : Voting_period_repr.t;\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 : Z.t;\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\" Voting_period_repr.encoding)\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\" Voting_period_repr.encoding)\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 n))\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_sync (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 check_signature pk chain_id op =\n  Lwt.return (check_signature_sync pk chain_id op)\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 reveeld, 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 = "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\n(** An internal storage error that should not happen *)\ntype storage_error =\n  | Incompatible_protocol_version of string\n  | Missing_key of string list * [`Get | `Set | `Del | `Copy]\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 MBytes.t\n\ntype error += Failed_to_decode_parameter of Data_encoding.json * string\n\nval storage_error : storage_error -> 'a tzresult Lwt.t\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 =\n  | Genesis of Parameters_repr.t\n  | Alpha_previous\n  | Carthage_006\n\nval prepare_first_block :\n  level:int32 ->\n  timestamp:Time.t ->\n  fitness:Fitness.t ->\n  Context.t ->\n  (previous_protocol * context) 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 Lwt.t\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 Lwt.t\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 ->\n  Signature.Public_key_hash.t ->\n  Tez_repr.t ->\n  context tzresult Lwt.t\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 -> Z.t -> unit tzresult\n\nval set_gas_limit : t -> Z.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 -> Z.t\n\nval block_gas_level : t -> Z.t\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 = MBytes.t\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      valus 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:([`Key of key | `Dir of key] -> '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 endorsment in the map as used. *)\nval record_endorsement : context -> Signature.Public_key_hash.t -> context\n\n(** Provide a fresh identifier for a temporary big map (negative index). *)\nval fresh_temporary_big_map : context -> context * Z.t\n\n(** Reset the temporary big_map identifier generator to [-1]. *)\nval reset_temporary_big_map : context -> context\n\n(** Iterate over all created temporary big maps since the last {!reset_temporary_big_map}. *)\nval temporary_big_maps : context -> ('a -> Z.t -> 'a Lwt.t) -> 'a -> 'a 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 : Z.t;\n  operation_gas : Gas_limit_repr.t;\n  internal_gas : Gas_limit_repr.internal_gas;\n  storage_space_to_pay : Z.t option;\n  allocated_contracts : int option;\n  origination_nonce : Contract_repr.origination_nonce option;\n  temporary_big_map : Z.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  Lwt.return Tez_repr.(ctxt.fees +? fees)\n  >>=? fun fees -> return {ctxt with fees}\n\nlet add_rewards ctxt rewards =\n  Lwt.return Tez_repr.(ctxt.rewards +? rewards)\n  >>=? fun rewards -> return {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  Lwt.return Tez_repr.(previous +? deposit)\n  >>=? fun deposit ->\n  let deposits =\n    Signature.Public_key_hash.Map.add delegate deposit ctxt.deposits\n  in\n  return {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 attemped 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 =\n  if\n    Compare.Z.(remaining > ctxt.constants.hard_gas_limit_per_operation)\n    || Compare.Z.(remaining < Z.zero)\n  then error Gas_limit_too_high\n  else ok ()\n\nlet set_gas_limit ctxt remaining =\n  {\n    ctxt with\n    operation_gas = Limited {remaining};\n    internal_gas = Gas_limit_repr.internal_gas_zero;\n  }\n\nlet set_gas_unlimited ctxt = {ctxt with operation_gas = Unaccounted}\n\nlet consume_gas ctxt cost =\n  Gas_limit_repr.consume\n    ctxt.block_gas\n    ctxt.operation_gas\n    ctxt.internal_gas\n    cost\n  >>? fun (block_gas, operation_gas, internal_gas) ->\n  ok {ctxt with block_gas; operation_gas; internal_gas}\n\nlet check_enough_gas ctxt cost =\n  Gas_limit_repr.check_enough\n    ctxt.block_gas\n    ctxt.operation_gas\n    ctxt.internal_gas\n    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      Z.sub before after\n  | (_, _) ->\n      Z.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 storage_error =\n  | Incompatible_protocol_version of string\n  | Missing_key of string list * [`Get | `Set | `Del | `Copy]\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 = fail (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 = \"alpha_current\"\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        return 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 >>= fun ctxt -> return ctxt\n\ntype error += Failed_to_parse_parameter of MBytes.t\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        (MBytes.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.del 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            return (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        return constants )\n\nlet patch_constants ctxt f =\n  let constants = f ctxt.constants in\n  set_constants ctxt.context constants\n  >>= fun context -> Lwt.return {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 = MBytes.to_string bytes in\n      if Compare.String.(s = version_value) then return_unit\n      else storage_error (Incompatible_protocol_version s)\n\nlet prepare ~level ~predecessor_timestamp ~timestamp ~fitness ctxt =\n  Lwt.return (Raw_level_repr.of_int32 level)\n  >>=? fun level ->\n  Lwt.return (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.from_raw\n      ~first_level\n      ~blocks_per_cycle:constants.Constants_repr.blocks_per_cycle\n      ~blocks_per_voting_period:\n        constants.Constants_repr.blocks_per_voting_period\n      ~blocks_per_commitment:constants.Constants_repr.blocks_per_commitment\n      level\n  in\n  return\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      internal_gas = Gas_limit_repr.internal_gas_zero;\n      storage_space_to_pay = None;\n      allocated_contracts = None;\n      block_gas = constants.Constants_repr.hard_gas_limit_per_block;\n      origination_nonce = None;\n      temporary_big_map = Z.sub Z.zero Z.one;\n      internal_nonce = 0;\n      internal_nonces_used = Int_set.empty;\n    }\n\ntype previous_protocol =\n  | Genesis of Parameters_repr.t\n  | Alpha_previous\n  | Carthage_006\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 = MBytes.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) -> return (Genesis param, ctxt)\n            else if Compare.String.(s = \"alpha_previous\") then\n              return (Alpha_previous, ctxt)\n            else if Compare.String.(s = \"carthage_006\") then\n              return (Carthage_006, ctxt)\n            else storage_error (Incompatible_protocol_version s))\n  >>=? fun (previous_proto, ctxt) ->\n  Context.set ctxt version_key (MBytes.of_string version_value)\n  >>= fun ctxt -> return (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      Lwt.return (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 >>= fun ctxt -> return ctxt\n  | Alpha_previous | Carthage_006 ->\n      return ctxt )\n  >>=? fun ctxt ->\n  prepare ctxt ~level ~predecessor_timestamp:timestamp ~timestamp ~fitness\n  >>=? fun ctxt -> return (previous_proto, ctxt)\n\nlet activate ({context = c; _} as s) h =\n  Updater.activate c h >>= fun c -> Lwt.return {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 -> Lwt.return {s with context = c}\n\n(* Generic context ********************************************************)\n\ntype key = string list\n\ntype value = MBytes.t\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:([`Key of key | `Dir of key] -> '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\n  | None -> storage_error (Missing_key (k, `Get)) | Some v -> return 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      storage_error (Missing_key (k, `Set))\n  | true ->\n      Context.set ctxt.context k v\n      >>= fun context -> return {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      storage_error (Existing_key k)\n  | false ->\n      Context.set ctxt.context k v\n      >>= fun context -> return {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\n  >>= fun context -> Lwt.return {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      storage_error (Missing_key (k, `Del))\n  | true ->\n      Context.del ctxt.context k >>= fun context -> return {ctxt with context}\n\n(* Do not verify before deleting *)\nlet remove ctxt k =\n  Context.del ctxt.context k >>= fun context -> Lwt.return {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\n  >>= fun context -> Lwt.return {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      return {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 fresh_temporary_big_map ctxt =\n  ( {ctxt with temporary_big_map = Z.sub ctxt.temporary_big_map Z.one},\n    ctxt.temporary_big_map )\n\nlet reset_temporary_big_map ctxt =\n  {ctxt with temporary_big_map = Z.sub Z.zero Z.one}\n\nlet temporary_big_maps ctxt f acc =\n  let rec iter acc id =\n    if Z.equal id ctxt.temporary_big_map then Lwt.return acc\n    else f acc id >>= fun acc -> iter acc (Z.sub id Z.one)\n  in\n  iter acc (Z.sub Z.zero Z.one)\n" ;
                } ;
                { name = "Storage_sigs" ;
                  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(** {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      valus 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      valus 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      valus 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      valus 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\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(*                                                                           *)\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_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 Wrap_indexed_data_storage\n    (C : Indexed_data_storage) (K : sig\n      type t\n\n      val wrap : t -> C.key\n\n      val unwrap : C.key -> t option\n    end) :\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(*                                                                           *)\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        MBytes.create 0\nend\n\nlet len_name = \"len\"\n\nlet data_name = \"data\"\n\nlet encode_len_value bytes =\n  let length = MBytes.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      fail (Raw_context.Storage_error (Corrupted_data key))\n  | Some len ->\n      return 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        return_none\n    | Some b -> (\n        let key = C.absolute_key t N.name in\n        match of_bytes ~key b with\n        | Ok v ->\n            return_some v\n        | Error _ as err ->\n            Lwt.return err )\n\n  let init t v =\n    C.init t N.name (to_bytes v) >>=? fun t -> return (C.project t)\n\n  let set t v = C.set t N.name (to_bytes v) >>=? fun t -> return (C.project t)\n\n  let init_set t v =\n    C.init_set t N.name (to_bytes v) >>= fun t -> Lwt.return (C.project t)\n\n  let set_option t v =\n    C.set_option t N.name (Option.map ~f:to_bytes v)\n    >>= fun t -> Lwt.return (C.project t)\n\n  let remove t = C.remove t N.name >>= fun t -> Lwt.return (C.project t)\n\n  let delete t = C.delete t N.name >>=? fun t -> return (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 = MBytes.of_string \"inited\"\n\n  let mem s i = C.mem s (I.to_path i [])\n\n  let add s i =\n    C.init_set s (I.to_path i []) inited >>= fun t -> Lwt.return (C.project t)\n\n  let del s i =\n    C.remove s (I.to_path i []) >>= fun t -> Lwt.return (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 -> Lwt.return (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 >>= return)\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        return_none\n    | Some b -> (\n        let key = C.absolute_key s (I.to_path i []) in\n        match of_bytes ~key b with\n        | Ok v ->\n            return_some v\n        | Error _ as err ->\n            Lwt.return err )\n\n  let set s i v =\n    C.set s (I.to_path i []) (to_bytes v) >>=? fun t -> return (C.project t)\n\n  let init s i v =\n    C.init s (I.to_path i []) (to_bytes v) >>=? fun t -> return (C.project t)\n\n  let init_set s i v =\n    C.init_set s (I.to_path i []) (to_bytes v)\n    >>= fun t -> Lwt.return (C.project t)\n\n  let set_option s i v =\n    C.set_option s (I.to_path i []) (Option.map ~f:to_bytes v)\n    >>= fun t -> Lwt.return (C.project t)\n\n  let remove s i =\n    C.remove s (I.to_path i []) >>= fun t -> Lwt.return (C.project t)\n\n  let delete s i =\n    C.delete s (I.to_path i []) >>=? fun t -> return (C.project t)\n\n  let clear s = C.remove_rec s [] >>= fun t -> Lwt.return (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 >>= return)\n         C.description\n         I.args)\n      V.encoding\nend\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 = 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 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 =\n    Lwt.return (C.consume_gas c (Gas_limit_repr.read_bytes_cost Z.zero))\n\n  let existing_size c i =\n    C.get_option c (len_key i)\n    >>= function\n    | None ->\n        return (0, false)\n    | Some len ->\n        decode_len_value (len_key i) len >>=? fun len -> return (len, true)\n\n  let consume_read_gas get c i =\n    get c (len_key i)\n    >>=? fun len ->\n    decode_len_value (len_key i) len\n    >>=? fun len ->\n    Lwt.return\n      (C.consume_gas c (Gas_limit_repr.read_bytes_cost (Z.of_int len)))\n\n  let consume_serialize_write_gas set c i v =\n    let bytes = to_bytes v in\n    let len = MBytes.length bytes in\n    Lwt.return (C.consume_gas c (Gas_limit_repr.alloc_mbytes_cost len))\n    >>=? fun c ->\n    Lwt.return\n      (C.consume_gas c (Gas_limit_repr.write_bytes_cost (Z.of_int len)))\n    >>=? fun c ->\n    set c (len_key i) (encode_len_value bytes) >>=? fun c -> return (c, bytes)\n\n  let consume_remove_gas del c i =\n    Lwt.return (C.consume_gas c (Gas_limit_repr.write_bytes_cost Z.zero))\n    >>=? fun c -> del c (len_key i)\n\n  let mem s i =\n    consume_mem_gas s\n    >>=? fun s ->\n    C.mem s (data_key i) >>= fun exists -> return (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 -> return (C.project s, v)\n\n  let get_option s i =\n    consume_mem_gas s\n    >>=? fun s ->\n    C.mem s (data_key i)\n    >>= fun exists ->\n    if exists then get s i >>=? fun (s, v) -> return (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 = MBytes.length bytes - prev_size in\n    return (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 = MBytes.length bytes in\n    return (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 >>= return 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 = MBytes.length bytes - prev_size in\n    return (C.project t, size_diff, existed)\n\n  let remove s i =\n    let remove s i = C.remove s i >>= return 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 -> return (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 ->\n    C.delete s (data_key i) >>=? fun t -> return (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) -> return v)\n      (register_indexed_subcontext\n         ~list:(fun c -> keys_unaccounted c >>= return)\n         C.description\n         I.args)\n      V.encoding\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)\n    >>=? fun t -> return (C.project t)\n\n  let delete_snapshot s id =\n    C.remove_rec s (snapshot_path id) >>= fun t -> Lwt.return (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 -> Lwt.return (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 >>= return)\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 -> return (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 -> return (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 -> Lwt.return (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 -> Lwt.return (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 -> return (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 -> Lwt.return (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 -> Lwt.return (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_)\n      >>=? fun t -> return (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 = MBytes.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      Lwt.return (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      Lwt.return (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          Lwt.return s)\n      >>= fun t -> Lwt.return (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          return_none\n      | Some b -> (\n          let key = Raw_context.absolute_key (pack s i) N.name in\n          match of_bytes ~key b with\n          | Ok v ->\n              return_some v\n          | Error _ as err ->\n              Lwt.return err )\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      return (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      return (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      Lwt.return (C.project s)\n\n    let set_option s i v =\n      Raw_context.set_option (pack s i) N.name (Option.map ~f:to_bytes v)\n      >>= fun c ->\n      let (s, _) = unpack c in\n      Lwt.return (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      Lwt.return (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      return (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          Lwt.return s)\n      >>= fun t -> Lwt.return (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 consume_mem_gas c =\n      Lwt.return\n        (Raw_context.consume_gas c (Gas_limit_repr.read_bytes_cost Z.zero))\n\n    let existing_size c =\n      Raw_context.get_option c len_name\n      >>= function\n      | None ->\n          return (0, false)\n      | Some len ->\n          decode_len_value len_name len >>=? fun len -> return (len, true)\n\n    let consume_read_gas get c =\n      get c len_name\n      >>=? fun len ->\n      decode_len_value len_name len\n      >>=? fun len ->\n      Lwt.return\n        (Raw_context.consume_gas\n           c\n           (Gas_limit_repr.read_bytes_cost (Z.of_int len)))\n\n    let consume_write_gas set c v =\n      let bytes = to_bytes v in\n      let len = MBytes.length bytes in\n      Lwt.return\n        (Raw_context.consume_gas\n           c\n           (Gas_limit_repr.write_bytes_cost (Z.of_int len)))\n      >>=? fun c ->\n      set c len_name (encode_len_value bytes) >>=? fun c -> return (c, bytes)\n\n    let consume_remove_gas del c =\n      Lwt.return\n        (Raw_context.consume_gas c (Gas_limit_repr.write_bytes_cost Z.zero))\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\n      >>= fun res -> return (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)\n      >>=? fun v -> return (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) -> return (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 = MBytes.length bytes - prev_size in\n      return (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 = MBytes.length bytes in\n      return (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 >>= return 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 = MBytes.length bytes - prev_size in\n      return (Raw_context.project c, size_diff, existed)\n\n    let remove s i =\n      let remove c k = Raw_context.remove c k >>= return 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 -> return (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 -> return (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) -> return v)\n        (register_named_subcontext Raw_context.description N.name)\n        V.encoding\n  end\nend\n\nmodule Wrap_indexed_data_storage\n    (C : Indexed_data_storage) (K : sig\n      type t\n\n      val wrap : t -> C.key\n\n      val unwrap : C.key -> t option\n    end) =\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 possesed 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 desactivated. *)\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  module Next : sig\n    val incr : Raw_context.t -> (Raw_context.t * Z.t) 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:(Z.t -> 'a -> 'a Lwt.t) -> 'a Lwt.t\n\n  val list : Raw_context.t -> Z.t list Lwt.t\n\n  val remove_rec : Raw_context.t -> Z.t -> Raw_context.t Lwt.t\n\n  val copy :\n    Raw_context.t -> from:Z.t -> to_:Z.t -> Raw_context.t tzresult Lwt.t\n\n  type key = Raw_context.t * Z.t\n\n  val rpc_arg : Z.t 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 = Z.t\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 = Z.t\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 = Z.t\n       and type value = Script_repr.expr\n       and type t := Raw_context.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 Current_period_kind :\n    Single_data_storage\n      with type value = Voting_period_repr.kind\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 Int = struct\n  type t = int\n\n  let encoding = Data_encoding.uint16\nend\n\nmodule Int32 = struct\n  type t = Int32.t\n\n  let encoding = Data_encoding.int32\nend\n\nmodule Z = struct\n  include Z\n\n  let encoding = Data_encoding.z\nend\n\nmodule Int_index = 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    (Int)\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 serilization and deserialization of expr in this\n     module *)\n  module Make_carbonated_map_expr (N : Storage_sigs.NAME) = 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      Lwt.return\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) ->\n         Raw_context.consume_gas ctxt value_cost )\n\n    let consume_serialize_gas ctxt value =\n      Lwt.return\n      @@ ( Script_repr.force_bytes value\n         >>? fun (_value, value_cost) ->\n         Raw_context.consume_gas ctxt value_cost )\n\n    let get ctxt contract =\n      I.get ctxt contract\n      >>=? fun (ctxt, value) ->\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      match value_opt with\n      | None ->\n          return (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  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              (Z)\n\n    let incr ctxt =\n      get ctxt\n      >>=? fun i -> set ctxt (Z.succ i) >>=? fun ctxt -> return (ctxt, i)\n\n    let init ctxt = init ctxt Z.zero\n  end\n\n  module Index = struct\n    type t = Z.t\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 \"Cannot parse big map id\"\n        | id ->\n            Ok id\n      in\n      RPC_arg.make\n        ~descr:\"A big map identifier\"\n        ~name:\"big_map_id\"\n        ~construct\n        ~destruct\n        ()\n\n    let encoding =\n      Data_encoding.def\n        \"big_map_id\"\n        ~title:\"Big map identifier\"\n        ~description:\"A big map identifier\"\n        Z.encoding\n\n    let compare = Compare.Z.compare\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 index_key) = MBytes.to_hex (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 :: Z.to_string c\n      :: 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 c = Z.of_string key in\n          let raw_key = Data_encoding.Binary.to_bytes_exn encoding c in\n          let (`Hex index_key) = MBytes.to_hex (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          Some 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 * Z.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      Lwt.return\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      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      match value_opt with\n      | None ->\n          return (ctxt, None)\n      | Some value ->\n          consume_deserialize_gas ctxt value >>|? fun ctxt -> (ctxt, value_opt)\n  end\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         (Int_index)\n      (Roll_repr)\n\n  module Roll_snapshot =\n    Indexed_context.Make_map\n      (struct\n        let name = [\"roll_snapshot\"]\n      end)\n      (Int)\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 Current_period_kind =\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 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         (Int)\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 = Cycle.Nonce.mem (ctxt, l.cycle) l.level\n\n    let get ctxt l = Cycle.Nonce.get (ctxt, l.cycle) l.level\n\n    let get_option ctxt l = Cycle.Nonce.get_option (ctxt, l.cycle) l.level\n\n    let set ctxt l v = Cycle.Nonce.set (ctxt, l.cycle) l.level v\n\n    let init ctxt l v = Cycle.Nonce.init (ctxt, l.cycle) l.level v\n\n    let init_set ctxt l v = Cycle.Nonce.init_set (ctxt, l.cycle) l.level v\n\n    let set_option ctxt l v = Cycle.Nonce.set_option (ctxt, l.cycle) l.level v\n\n    let delete ctxt l = Cycle.Nonce.delete (ctxt, l.cycle) l.level\n\n    let remove ctxt l = 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.from_raw\n    ~first_level\n    ~blocks_per_cycle:constants.Constants_repr.blocks_per_cycle\n    ~blocks_per_voting_period:constants.Constants_repr.blocks_per_voting_period\n    ~blocks_per_commitment:constants.Constants_repr.blocks_per_commitment\n    l\n\nlet root c = Level_repr.root (Raw_context.first_level c)\n\nlet succ c l = from_raw c (Raw_level_repr.succ l.level)\n\nlet pred c l =\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 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 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 : MBytes.t -> 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 =\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  fail_unless\n    (Seed_repr.check_hash nonce unrevealed.nonce_hash)\n    Unexpected_nonce\n  >>=? fun () ->\n  Storage.Seed.Nonce.set ctxt level (Revealed nonce)\n  >>=? fun ctxt -> return ctxt\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 ->\n            return (c, Seed_repr.nonce random_seed nonce, unrevealed)\n        | Unrevealed u ->\n            Storage.Seed.Nonce.delete c level\n            >>=? fun c -> return (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\n      >>=? fun c -> return (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  fail_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(*                                                                           *)\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\n   Basic roll manipulation.\n\n   If storage related to roll (a.k.a. `Storage.Roll`) are 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*)\n\ntype error +=\n  | Consume_roll_change\n  | No_roll_for_delegate\n  | No_roll_snapshot_for_cycle of Cycle_repr.t\n  | Unregistered_delegate of Signature.Public_key_hash.t\n\n(* `Permanent *)\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(*                                                                           *)\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  | Consume_roll_change (* `Permanent *)\n  | No_roll_for_delegate (* `Permanent *)\n  | No_roll_snapshot_for_cycle of Cycle_repr.t (* `Permanent *)\n  | Unregistered_delegate of Signature.Public_key_hash.t\n\n(* `Permanent *)\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 c contract =\n  Storage.Contract.Delegate.get_option c 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 c cycle =\n  Storage.Roll.Snapshot_for_cycle.get c cycle\n  >>=? fun index ->\n  Storage.Roll.Snapshot_for_cycle.delete c cycle\n  >>=? fun c ->\n  Storage.Roll.Last_for_snapshot.delete (c, cycle) index\n  >>=? fun c ->\n  Storage.Roll.Owner.delete_snapshot c (cycle, index) >>= fun c -> return c\n\nlet fold ctxt ~f init =\n  Storage.Roll.Next.get ctxt\n  >>=? fun last ->\n  let rec loop ctxt roll acc =\n    acc\n    >>=? fun 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) (return acc)\n      | Some delegate ->\n          loop ctxt (Roll_repr.succ roll) (f roll delegate acc)\n  in\n  loop ctxt Roll_repr.first (return 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 ->\n  Storage.Roll.Last_for_snapshot.init (ctxt, cycle) index last\n  >>=? fun ctxt -> return ctxt\n\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 [MBytes.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        >>=? fun ctxt -> return ctxt)\n    ctxt\n    Misc.(0 --> (max_index - 1))\n  >>=? fun ctxt -> return ctxt\n\n(* Roll selection *)\n\nmodule Random = struct\n  let int32_to_bytes i =\n    let b = MBytes.create 4 in\n    MBytes.set_int32 b 0 i ; b\n\n  let level_random seed use level =\n    let position = level.Level_repr.cycle_position in\n    Seed_repr.initialize_new\n      seed\n      [MBytes.of_string (\"level \" ^ use ^ \":\"); int32_to_bytes position]\n\n  let owner c kind level 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    fail_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 c delegate =\n  Storage.Roll.Delegate_change.get_option c delegate\n  >>=? function None -> return Tez_repr.zero | Some change -> return change\n\nmodule Delegate = struct\n  let fresh_roll c =\n    Storage.Roll.Next.get c\n    >>=? fun roll ->\n    Storage.Roll.Next.set c (Roll_repr.succ roll) >>=? fun c -> return (roll, c)\n\n  let get_limbo_roll c =\n    Storage.Roll.Limbo.get_option c\n    >>=? function\n    | None ->\n        fresh_roll c\n        >>=? fun (roll, c) ->\n        Storage.Roll.Limbo.init c roll >>=? fun c -> return (roll, c)\n    | Some roll ->\n        return (roll, c)\n\n  let consume_roll_change c delegate =\n    let tokens_per_roll = Constants_storage.tokens_per_roll c in\n    Storage.Roll.Delegate_change.get c delegate\n    >>=? fun change ->\n    trace Consume_roll_change (Lwt.return Tez_repr.(change -? tokens_per_roll))\n    >>=? fun new_change ->\n    Storage.Roll.Delegate_change.set c delegate new_change\n\n  let recover_roll_change c delegate =\n    let tokens_per_roll = Constants_storage.tokens_per_roll c in\n    Storage.Roll.Delegate_change.get c delegate\n    >>=? fun change ->\n    Lwt.return Tez_repr.(change +? tokens_per_roll)\n    >>=? fun new_change ->\n    Storage.Roll.Delegate_change.set c delegate new_change\n\n  let pop_roll_from_delegate c delegate =\n    recover_roll_change c delegate\n    >>=? fun c ->\n    (* beginning:\n       delegate : roll -> successor_roll -> ...\n       limbo : limbo_head -> ...\n    *)\n    Storage.Roll.Limbo.get_option c\n    >>=? fun limbo_head ->\n    Storage.Roll.Delegate_roll_list.get_option c delegate\n    >>=? function\n    | None ->\n        fail No_roll_for_delegate\n    | Some roll ->\n        Storage.Roll.Owner.delete c roll\n        >>=? fun c ->\n        Storage.Roll.Successor.get_option c roll\n        >>=? fun successor_roll ->\n        Storage.Roll.Delegate_roll_list.set_option c delegate successor_roll\n        >>= fun c ->\n        (* delegate : successor_roll -> ...\n           roll ------^\n           limbo : limbo_head -> ... *)\n        Storage.Roll.Successor.set_option c roll limbo_head\n        >>= fun c ->\n        (* delegate : successor_roll -> ...\n           roll ------v\n           limbo : limbo_head -> ... *)\n        Storage.Roll.Limbo.init_set c roll\n        >>= fun c ->\n        (* delegate : successor_roll -> ...\n           limbo : roll -> limbo_head -> ... *)\n        return (roll, c)\n\n  let create_roll_in_delegate c delegate delegate_pk =\n    consume_roll_change c delegate\n    >>=? fun c ->\n    (* beginning:\n       delegate : delegate_head -> ...\n       limbo : roll -> limbo_successor -> ...\n    *)\n    Storage.Roll.Delegate_roll_list.get_option c delegate\n    >>=? fun delegate_head ->\n    get_limbo_roll c\n    >>=? fun (roll, c) ->\n    Storage.Roll.Owner.init c roll delegate_pk\n    >>=? fun c ->\n    Storage.Roll.Successor.get_option c roll\n    >>=? fun limbo_successor ->\n    Storage.Roll.Limbo.set_option c limbo_successor\n    >>= fun c ->\n    (* delegate : delegate_head -> ...\n       roll ------v\n       limbo : limbo_successor -> ... *)\n    Storage.Roll.Successor.set_option c roll delegate_head\n    >>= fun c ->\n    (* delegate : delegate_head -> ...\n       roll ------^\n       limbo : limbo_successor -> ... *)\n    Storage.Roll.Delegate_roll_list.init_set c delegate roll\n    >>= fun c ->\n    (* delegate : roll -> delegate_head -> ...\n       limbo : limbo_successor -> ... *)\n    return c\n\n  let ensure_inited c delegate =\n    Storage.Roll.Delegate_change.mem c delegate\n    >>= function\n    | true ->\n        return c\n    | false ->\n        Storage.Roll.Delegate_change.init c delegate Tez_repr.zero\n\n  let is_inactive c delegate =\n    Storage.Contract.Inactive_delegate.mem\n      c\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        c\n        (Contract_repr.implicit_contract delegate)\n      >>=? function\n      | Some last_active_cycle ->\n          let {Level_repr.cycle = current_cycle} =\n            Raw_context.current_level c\n          in\n          return 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          return_false\n\n  let add_amount c delegate amount =\n    ensure_inited c delegate\n    >>=? fun c ->\n    let tokens_per_roll = Constants_storage.tokens_per_roll c in\n    Storage.Roll.Delegate_change.get c delegate\n    >>=? fun change ->\n    Lwt.return Tez_repr.(amount +? change)\n    >>=? fun change ->\n    Storage.Roll.Delegate_change.set c delegate change\n    >>=? fun c ->\n    delegate_pubkey c delegate\n    >>=? fun delegate_pk ->\n    let rec loop c change =\n      if Tez_repr.(change < tokens_per_roll) then return c\n      else\n        Lwt.return Tez_repr.(change -? tokens_per_roll)\n        >>=? fun change ->\n        create_roll_in_delegate c delegate delegate_pk\n        >>=? fun c -> loop c change\n    in\n    is_inactive c delegate\n    >>=? fun inactive ->\n    if inactive then return c\n    else\n      loop c change\n      >>=? fun c ->\n      Storage.Roll.Delegate_roll_list.get_option c delegate\n      >>=? fun rolls ->\n      match rolls with\n      | None ->\n          return c\n      | Some _ ->\n          Storage.Active_delegates_with_rolls.add c delegate\n          >>= fun c -> return c\n\n  let remove_amount c delegate amount =\n    let tokens_per_roll = Constants_storage.tokens_per_roll c in\n    let rec loop c change =\n      if Tez_repr.(amount <= change) then return (c, change)\n      else\n        pop_roll_from_delegate c delegate\n        >>=? fun (_, c) ->\n        Lwt.return Tez_repr.(change +? tokens_per_roll)\n        >>=? fun change -> loop c change\n    in\n    Storage.Roll.Delegate_change.get c delegate\n    >>=? fun change ->\n    is_inactive c delegate\n    >>=? fun inactive ->\n    ( if inactive then return (c, change)\n    else\n      loop c change\n      >>=? fun (c, change) ->\n      Storage.Roll.Delegate_roll_list.get_option c delegate\n      >>=? fun rolls ->\n      match rolls with\n      | None ->\n          Storage.Active_delegates_with_rolls.del c delegate\n          >>= fun c -> return (c, change)\n      | Some _ ->\n          return (c, change) )\n    >>=? fun (c, change) ->\n    Lwt.return Tez_repr.(change -? amount)\n    >>=? fun change -> Storage.Roll.Delegate_change.set c 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          Lwt.return 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    >>=? fun ctxt -> return ctxt\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          Lwt.return 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\n          >>= fun ctxt -> return ctxt\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  List.fold_left\n    (fun ctxt c ->\n      ctxt\n      >>=? fun ctxt ->\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    (return 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  >>=? fun ctxt -> return ctxt\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  >>=? fun ctxt -> return ctxt\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\n    Lwt.return Tez_repr.(old_tokens_per_roll -? new_tokens_per_roll)\n  else Lwt.return Tez_repr.(new_tokens_per_roll -? old_tokens_per_roll) )\n  >>=? fun abs_diff ->\n  Storage.Delegates.fold ctxt (Ok ctxt) (fun pkh ctxt ->\n      Lwt.return ctxt\n      >>=? fun ctxt ->\n      count_rolls ctxt pkh\n      >>=? fun rolls ->\n      Lwt.return 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 (tipically 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  >>= fun c -> return c\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      >>= fun c -> return c\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      return @@ Signature.Public_key_hash.equal delegate current_delegate\n  | None ->\n      return_false\n\nlet init ctxt contract delegate =\n  known ctxt delegate\n  >>=? fun known_delegate ->\n  fail_unless known_delegate (Roll_storage.Unregistered_delegate delegate)\n  >>=? fun () ->\n  registered ctxt delegate\n  >>=? fun is_registered ->\n  fail_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 ->\n        Storage.Contract.Delegate.remove c contract >>= fun c -> return c\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        fail_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 ->\n          Roll_storage.Delegate.set_active c delegate >>=? fun c -> return c\n        else return c )\n        >>=? fun c -> 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  >>=? function None -> return Tez_repr.zero | Some frozen -> return frozen\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  Lwt.return 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\n  >>= fun ctxt -> return ctxt\n\nlet freeze_deposit ctxt delegate amount =\n  let {Level_repr.cycle; _} = 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  Lwt.return\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  >>=? function None -> return Tez_repr.zero | Some frozen -> return frozen\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  Lwt.return 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\n  >>= fun ctxt -> return ctxt\n\nlet freeze_fees ctxt delegate amount =\n  let {Level_repr.cycle; _} = 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 -> return (new_amount, ctxt)\n  | Error _ ->\n      Roll_storage.Delegate.remove_amount ctxt delegate old_amount\n      >>=? fun ctxt -> return (Tez_repr.zero, ctxt) )\n  >>=? fun (new_amount, ctxt) ->\n  Storage.Contract.Frozen_fees.init_set (ctxt, contract) cycle new_amount\n  >>= fun ctxt -> return ctxt\n\nlet get_frozen_rewards ctxt contract cycle =\n  Storage.Contract.Frozen_rewards.get_option (ctxt, contract) cycle\n  >>=? function None -> return Tez_repr.zero | Some frozen -> return frozen\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  Lwt.return 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\n  >>= fun ctxt -> return ctxt\n\nlet freeze_rewards ctxt delegate amount =\n  let {Level_repr.cycle; _} = 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  >>= fun ctxt -> return ctxt\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  Lwt.return Tez_repr.(deposit +? fees)\n  >>=? fun unfrozen_amount ->\n  Lwt.return Tez_repr.(unfrozen_amount +? rewards)\n  >>=? fun unfrozen_amount ->\n  Lwt.return 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  return\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      List.fold_left\n        (fun acc (u : Nonce_storage.unrevealed) ->\n          acc\n          >>=? fun (ctxt, balance_updates) ->\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          return (ctxt, bus @ balance_updates))\n        (return (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          Lwt.return acc\n          >>=? fun (ctxt, bus) ->\n          unfreeze ctxt delegate unfrozen_cycle\n          >>=? fun (ctxt, balance_updates) ->\n          return (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          Lwt.return 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 -> return (ctxt, delegate :: deactivated)\n          else return (ctxt, deactivated))\n      >>=? fun (ctxt, deactivated) ->\n      return (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 -> return (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 -> return 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  >>= fun map -> Lwt.return 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 -> Lwt.return 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 -> Lwt.return 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 -> Lwt.return Tez_repr.(acc +? amount))\n  >>= fun balance -> Lwt.return balance\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 Tez_repr.(token_per_rolls *? rolls)\n  >>=? fun balance -> Lwt.return 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 -> Lwt.return 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 -> Lwt.return 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 = "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_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\ntype big_map_diff_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 Z.t * Z.t\n  | Alloc of {\n      big_map : Z.t;\n      key_type : Script_repr.expr;\n      value_type : Script_repr.expr;\n    }\n\ntype big_map_diff = big_map_diff_item list\n\nval big_map_diff_encoding : big_map_diff Data_encoding.t\n\nval update_script_storage :\n  Raw_context.t ->\n  Contract_repr.t ->\n  Script_repr.expr ->\n  big_map_diff 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 originate :\n  Raw_context.t ->\n  ?prepaid_bootstrap_storage:bool ->\n  Contract_repr.t ->\n  balance:Tez_repr.t ->\n  script:Script_repr.t * big_map_diff 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 Lwt.t\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(*                                                                           *)\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 %s not yet reached for contract %a (expected %s)\"\n        (Z.to_string found)\n        Contract_repr.pp\n        contract\n        (Z.to_string 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 %s already used for contract %a (expected %s)\"\n        (Z.to_string found)\n        Contract_repr.pp\n        contract\n        (Z.to_string 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\ntype big_map_diff_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 Z.t * Z.t\n  | Alloc of {\n      big_map : Z.t;\n      key_type : Script_repr.expr;\n      value_type : Script_repr.expr;\n    }\n\ntype big_map_diff = big_map_diff_item list\n\nlet big_map_diff_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\nlet big_map_diff_encoding =\n  let open Data_encoding in\n  def \"contract.big_map_diff\" @@ list big_map_diff_item_encoding\n\nlet big_map_key_cost = 65\n\nlet big_map_cost = 33\n\nlet update_script_big_map c = function\n  | None ->\n      return (c, Z.zero)\n  | Some diff ->\n      fold_left_s\n        (fun (c, total) -> function Clear id ->\n              Storage.Big_map.Total_bytes.get c id\n              >>=? fun size ->\n              Storage.Big_map.remove_rec c id\n              >>= fun c ->\n              if Compare.Z.(id < Z.zero) then return (c, total)\n              else return (c, Z.sub (Z.sub total size) (Z.of_int big_map_cost))\n          | Copy (from, to_) ->\n              Storage.Big_map.copy c ~from ~to_\n              >>=? fun c ->\n              if Compare.Z.(to_ < Z.zero) then return (c, total)\n              else\n                Storage.Big_map.Total_bytes.get c from\n                >>=? fun size ->\n                return (c, Z.add (Z.add total size) (Z.of_int big_map_cost))\n          | Alloc {big_map; key_type; value_type} ->\n              Storage.Big_map.Total_bytes.init c big_map Z.zero\n              >>=? fun c ->\n              (* Annotations are erased to allow sharing on\n                 [Copy]. The types from the contract code are used,\n                 these ones are only used to make sure they are\n                 compatible during transmissions between contracts,\n                 and only need to be compatible, annotations\n                 nonwhistanding. *)\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 c big_map key_type\n              >>=? fun c ->\n              Storage.Big_map.Value_type.init c big_map value_type\n              >>=? fun c ->\n              if Compare.Z.(big_map < Z.zero) then return (c, total)\n              else return (c, Z.add total (Z.of_int big_map_cost))\n          | Update {big_map; diff_key_hash; diff_value = None} ->\n              Storage.Big_map.Contents.remove (c, big_map) diff_key_hash\n              >>=? fun (c, freed, existed) ->\n              let freed =\n                if existed then freed + big_map_key_cost else freed\n              in\n              Storage.Big_map.Total_bytes.get c big_map\n              >>=? fun size ->\n              Storage.Big_map.Total_bytes.set\n                c\n                big_map\n                (Z.sub size (Z.of_int freed))\n              >>=? fun c ->\n              if Compare.Z.(big_map < Z.zero) then return (c, total)\n              else return (c, Z.sub total (Z.of_int freed))\n          | Update {big_map; diff_key_hash; diff_value = Some v} ->\n              Storage.Big_map.Contents.init_set (c, big_map) diff_key_hash v\n              >>=? fun (c, size_diff, existed) ->\n              let size_diff =\n                if existed then size_diff else size_diff + big_map_key_cost\n              in\n              Storage.Big_map.Total_bytes.get c big_map\n              >>=? fun size ->\n              Storage.Big_map.Total_bytes.set\n                c\n                big_map\n                (Z.add size (Z.of_int size_diff))\n              >>=? fun c ->\n              if Compare.Z.(big_map < Z.zero) then return (c, total)\n              else return (c, Z.add total (Z.of_int size_diff)))\n        (c, Z.zero)\n        diff\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}, big_map_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_big_map c big_map_diff\n      >>=? fun (c, big_map_size) ->\n      let total_size =\n        Z.add (Z.add (Z.of_int code_size) (Z.of_int storage_size)) big_map_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 originate c ?prepaid_bootstrap_storage contract ~balance ~script ~delegate\n    =\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 ->\n      Storage.Contract.Used_storage_space.remove c contract\n      >>= fun c -> return c\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  Lwt.return (Raw_context.increment_origination_nonce c)\n  >>=? fun (c, nonce) -> return (c, Contract_repr.originated_contract nonce)\n\nlet originated_from_current_nonce ~since:ctxt_since ~until:ctxt_until =\n  Lwt.return (Raw_context.origination_nonce ctxt_since)\n  >>=? fun since ->\n  Lwt.return (Raw_context.origination_nonce ctxt_until)\n  >>=? fun until ->\n  filter_map_s\n    (fun contract ->\n      exists ctxt_until contract\n      >>=? function true -> return_some contract | false -> return_none)\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 >>=? fun c -> return c\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 update_script_storage c contract storage big_map_diff =\n  let storage = Script_repr.lazy_expr storage in\n  update_script_big_map c big_map_diff\n  >>=? fun (c, big_map_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 big_map_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    Storage.Contract.Code.mem c contract\n    >>=? fun (c, target_has_code) ->\n    fail_unless target_has_code (Empty_transaction contract)\n    >>=? fun () -> return 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      Lwt.return 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 -> Storage.Big_map.Next.init c\n\nlet used_storage_space c contract =\n  Storage.Contract.Used_storage_space.get_option c contract\n  >>=? function None -> return Z.zero | Some fees -> return fees\n\nlet paid_storage_space c contract =\n  Storage.Contract.Paid_storage_space.get_option c contract\n  >>=? function None -> return Z.zero | Some paid_space -> return paid_space\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 -> return (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 * Contract_storage.big_map_diff option)\n            * 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      >>=? fun ctxt -> return ctxt\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.originate\n    ctxt\n    contract\n    ~balance:amount\n    ~prepaid_bootstrap_storage:true\n    ~script\n    ~delegate:(Some delegate)\n  >>=? fun ctxt -> return ctxt\n\nlet init ctxt ~typecheck ?ramp_up_cycles ?no_reward_cycles accounts contracts =\n  let nonce =\n    Operation_hash.hash_bytes [MBytes.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      Lwt.return\n        Tez_repr.(constants.block_security_deposit /? Int64.of_int cycles)\n      >>=? fun block_step ->\n      Lwt.return\n        Tez_repr.(\n          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          Lwt.return Tez_repr.(block_step *? Int64.of_int cycle)\n          >>=? fun block_security_deposit ->\n          Lwt.return 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      >>=? fun ctxt -> return ctxt\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             >>= fun ctxt -> return ctxt)\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      >>= fun ctxt -> return ctxt\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 ?(gap = 1) ctxt =\n  let fitness = current ctxt in\n  Raw_context.set_current_fitness ctxt (Int64.add (Int64.of_int gap) fitness)\n" ;
                } ;
                { name = "Vote_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(** 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 freeze_listings : Raw_context.t -> Raw_context.t tzresult Lwt.t\n\nval clear_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_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_period_kind :\n  Raw_context.t -> Voting_period_repr.kind tzresult Lwt.t\n\nval set_current_period_kind :\n  Raw_context.t -> Voting_period_repr.kind -> 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 : Raw_context.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  >>=? function None -> return 0 | Some count -> return count\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 ->\n  Storage.Vote.Proposals.add ctxt (proposal, proposer)\n  >>= fun ctxt -> return ctxt\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        ok (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            ok {ballots with yay = count ballots.yay}\n        | Nay ->\n            ok {ballots with nay = count ballots.nay}\n        | Pass ->\n            ok {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 freeze_listings 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      >>=? (function None -> return 0l | Some count -> return count)\n      >>=? fun count ->\n      Storage.Vote.Listings.init_set ctxt delegate (Int32.succ count)\n      >>= fun ctxt -> return (ctxt, Int32.succ total))\n  >>=? fun (ctxt, total) ->\n  Storage.Vote.Listings_size.init 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 clear_listings ctxt =\n  Storage.Vote.Listings.clear ctxt\n  >>= fun ctxt ->\n  Storage.Vote.Listings_size.remove ctxt >>= fun ctxt -> return ctxt\n\nlet get_current_period_kind = Storage.Vote.Current_period_kind.get\n\nlet set_current_period_kind = Storage.Vote.Current_period_kind.set\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  return\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 =\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 ->\n  Storage.Vote.Current_period_kind.init ctxt Proposal\n  >>=? fun ctxt -> return ctxt\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 >>=? fun ctxt -> return ctxt\n" ;
                } ;
                { name = "Init_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\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) ->\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 ctxt\n      >>=? fun ctxt ->\n      Storage.Block_priority.init ctxt 0\n      >>=? fun ctxt ->\n      Vote_storage.freeze_listings ctxt >>=? fun ctxt -> return ctxt\n  | Alpha_previous ->\n      return ctxt\n  | Carthage_006 ->\n      return 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 :\n  Raw_context.t -> (Raw_context.t * Tez_repr.t) tzresult Lwt.t\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  Lwt.return Tez_repr.(cost_per_byte *? Int64.of_int origination_size)\n  >>=? fun to_be_paid ->\n  return (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 Tez_repr.(cost_per_byte *? Z.to_int64 to_be_paid)\n  >>=? fun to_burn -> return (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    Lwt.return 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 transfering 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      >>=? fun c -> return c\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 ()\n\nlet start_counting_storage_fees c = Raw_context.init_storage_space_to_pay c\n" ;
                } ;
                { name = "Alpha_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\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 -> 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  type t = private Unaccounted | Limited of {remaining : Z.t}\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 : int -> cost\n\n  val step_cost : int -> cost\n\n  val alloc_cost : int -> cost\n\n  val alloc_bytes_cost : int -> cost\n\n  val alloc_mbytes_cost : int -> cost\n\n  val alloc_bits_cost : int -> cost\n\n  val read_bytes_cost : Z.t -> cost\n\n  val write_bytes_cost : Z.t -> cost\n\n  val ( *@ ) : int -> cost -> cost\n\n  val ( +@ ) : cost -> cost -> cost\n\n  val check_limit : context -> Z.t -> unit tzresult\n\n  val set_limit : context -> Z.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 -> Z.t\n\n  val block_level : context -> Z.t\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_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_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_PUSH\n    | I_RIGHT\n    | I_SIZE\n    | I_SOME\n    | I_SOURCE\n    | I_SENDER\n    | I_SELF\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_DIG\n    | I_DUG\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_chain_id\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 : MBytes.t -> Gas.cost\n\n  val traversal_cost : node -> Gas.cost\n\n  val node_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 : MBytes.t -> 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 prim_node_cost_nonrec_of_length : int -> 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 : context -> lazy_expr -> (expr * context) tzresult Lwt.t\n\n  val force_bytes : context -> lazy_expr -> (MBytes.t * context) tzresult Lwt.t\n\n  val unit_parameter : lazy_expr\n\n  module Legacy_support : sig\n    val manager_script_code : lazy_expr\n\n    val add_do :\n      manager_pkh:Signature.Public_key_hash.t ->\n      script_code:lazy_expr ->\n      script_storage:lazy_expr ->\n      (lazy_expr * lazy_expr) tzresult Lwt.t\n\n    val add_set_delegate :\n      manager_pkh:Signature.Public_key_hash.t ->\n      script_code:lazy_expr ->\n      script_storage:lazy_expr ->\n      (lazy_expr * lazy_expr) tzresult Lwt.t\n\n    val has_default_entrypoint : lazy_expr -> bool\n\n    val add_root_entrypoint : script_code:lazy_expr -> lazy_expr tzresult Lwt.t\n  end\nend\n\nmodule Constants : sig\n  (** Fixed constants *)\n  type fixed = {\n    proof_of_work_nonce_size : int;\n    nonce_length : int;\n    max_revelations_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_revelations_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 : Z.t;\n    hard_gas_limit_per_block : Z.t;\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 -> Z.t\n\n  val hard_gas_limit_per_block : context -> Z.t\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 Voting_period : sig\n  include BASIC_DATA\n\n  type voting_period = t\n\n  val rpc_arg : voting_period RPC_arg.arg\n\n  val root : voting_period\n\n  val succ : voting_period -> voting_period\n\n  type kind = Proposal | Testing_vote | Testing | Promotion_vote\n\n  val kind_encoding : kind Data_encoding.encoding\n\n  val to_int32 : voting_period -> int32\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    voting_period : Voting_period.t;\n    voting_period_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\nend\n\nmodule Fitness : sig\n  include module type of Fitness\n\n  type fitness = t\n\n  val increase : ?gap:int -> 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 : MBytes.t -> 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  type id = Z.t\n\n  val fresh : context -> (context * id) tzresult Lwt.t\n\n  val fresh_temporary : context -> context * id\n\n  val mem :\n    context -> id -> Script_expr_hash.t -> (context * bool) tzresult Lwt.t\n\n  val get_opt :\n    context ->\n    id ->\n    Script_expr_hash.t ->\n    (context * Script.expr option) tzresult Lwt.t\n\n  val rpc_arg : id RPC_arg.t\n\n  val cleanup_temporary : context -> context Lwt.t\n\n  val exists :\n    context ->\n    id ->\n    (context * (Script.expr * Script.expr) option) 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 init_origination_nonce : context -> Operation_hash.t -> context\n\n  val unset_origination_nonce : context -> context\n\n  val fresh_contract_from_current_nonce :\n    context -> (context * t) tzresult Lwt.t\n\n  val originated_from_current_nonce :\n    since:context -> until:context -> contract list tzresult Lwt.t\n\n  type big_map_diff_item =\n    | Update of {\n        big_map : Big_map.id;\n        diff_key : Script.expr;\n        diff_key_hash : Script_expr_hash.t;\n        diff_value : Script.expr option;\n      }\n    | Clear of Big_map.id\n    | Copy of Big_map.id * Big_map.id\n    | Alloc of {\n        big_map : Big_map.id;\n        key_type : Script.expr;\n        value_type : Script.expr;\n      }\n\n  type big_map_diff = big_map_diff_item list\n\n  val big_map_diff_encoding : big_map_diff Data_encoding.t\n\n  val originate :\n    context ->\n    contract ->\n    balance:Tez.t ->\n    script:Script.t * big_map_diff 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    big_map_diff 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 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 freeze_listings : context -> context tzresult Lwt.t\n\n  val clear_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 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_period_kind : context -> Voting_period.kind tzresult Lwt.t\n\n  val set_current_period_kind :\n    context -> Voting_period.kind -> context tzresult 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 : MBytes.t;\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 : Voting_period.t;\n      proposals : Protocol_hash.t list;\n    }\n      -> Kind.proposals contents\n  | Ballot : {\n      source : Signature.Public_key_hash.t;\n      period : Voting_period.t;\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 : Z.t;\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 Lwt.t\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 : MBytes.t}\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 Lwt.t\n\n  val check_signature_sync :\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 * Contract.big_map_diff option) * context) tzresult\n            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 Lwt.t\n\nval add_rewards : context -> Tez.t -> context tzresult Lwt.t\n\nval add_deposit :\n  context -> Signature.Public_key_hash.t -> Tez.t -> context tzresult Lwt.t\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(*                                                                           *)\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 ctxt lexpr =\n    Lwt.return\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 ctxt lexpr =\n    Lwt.return\n      ( Script_repr.force_bytes lexpr\n      >>? fun (b, cost) ->\n      Raw_context.consume_gas ctxt cost >|? fun ctxt -> (b, ctxt) )\n\n  module Legacy_support = Legacy_script_support_repr\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 = Voting_period_repr\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\nend\n\nmodule Level = struct\n  include Level_repr\n  include Level_storage\nend\n\nmodule Contract = struct\n  include Contract_repr\n  include Contract_storage\n\n  let originate c contract ~balance ~script ~delegate =\n    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  type id = Z.t\n\n  let fresh = Storage.Big_map.Next.incr\n\n  let fresh_temporary = Raw_context.fresh_temporary_big_map\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 rpc_arg = Storage.Big_map.rpc_arg\n\n  let cleanup_temporary c =\n    Raw_context.temporary_big_maps c Storage.Big_map.remove_rec c\n    >>= fun c -> Lwt.return (Raw_context.reset_temporary_big_map c)\n\n  let exists c id =\n    Lwt.return\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\n        >>=? fun kv -> return (c, Some (kt, kv))\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(*                                                                           *)\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 annot = [var_annot | type_annot | field_annot]\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 comb = Comb\n\ntype leaf = Leaf\n\ntype (_, _) comparable_struct =\n  | Int_key : type_annot option -> (z num, _) comparable_struct\n  | Nat_key : type_annot option -> (n num, _) comparable_struct\n  | String_key : type_annot option -> (string, _) comparable_struct\n  | Bytes_key : type_annot option -> (MBytes.t, _) comparable_struct\n  | Mutez_key : type_annot option -> (Tez.t, _) comparable_struct\n  | Bool_key : type_annot option -> (bool, _) comparable_struct\n  | Key_hash_key : type_annot option -> (public_key_hash, _) comparable_struct\n  | Timestamp_key :\n      type_annot option\n      -> (Script_timestamp.t, _) comparable_struct\n  | Address_key : type_annot option -> (address, _) comparable_struct\n  | Pair_key :\n      (('a, leaf) comparable_struct * field_annot option)\n      * (('b, comb) comparable_struct * field_annot option)\n      * type_annot option\n      -> (('a, 'b) pair, comb) comparable_struct\n\ntype 'a comparable_ty = ('a, comb) comparable_struct\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 * Contract.big_map_diff option\n\ntype ('arg, 'storage) script = {\n  code : (('arg, 'storage) pair, (operation list, 'storage) pair) lambda;\n  arg_type : 'arg ty;\n  storage : 'storage;\n  storage_type : 'storage ty;\n  root_name : string 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 -> MBytes.t 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      * bool\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      * bool\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 * bool -> 'v option ty\n  | List_t : 'v ty * type_annot option * bool -> 'v list ty\n  | Set_t : 'v comparable_ty * type_annot option -> 'v set ty\n  | Map_t :\n      'k comparable_ty * 'v ty * type_annot option * bool\n      -> ('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  | Operation_t : type_annot option -> operation ty\n  | Chain_id_t : type_annot option -> Chain_id.t 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 : Z.t option;\n  diff : ('key, 'value option) map;\n  key_type : 'key ty;\n  value_type : 'value ty;\n}\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. *)\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  (* 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  | Left : ('l * 'rest, ('l, 'r) union * 'rest) instr\n  | 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 list * 'rest), 'a list * 'rest) instr\n  | Nil : ('rest, 'a list * 'rest) instr\n  | If_cons :\n      ('a * ('a list * 'bef), 'aft) descr * ('bef, 'aft) descr\n      -> ('a list * 'bef, 'aft) instr\n  | List_map :\n      ('a * 'rest, 'b * 'rest) descr\n      -> ('a list * 'rest, 'b list * 'rest) instr\n  | List_iter : ('a * 'rest, 'rest) descr -> ('a list * 'rest, 'rest) instr\n  | List_size : ('a 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_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  (* string operations *)\n  | Concat_string : (string 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 : (MBytes.t list * 'rest, MBytes.t * 'rest) instr\n  | Concat_bytes_pair : (MBytes.t * (MBytes.t * 'rest), MBytes.t * 'rest) instr\n  | Slice_bytes\n      : (n num * (n num * (MBytes.t * 'rest)), MBytes.t option * 'rest) instr\n  | Bytes_size : (MBytes.t * '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  | Create_account\n      : ( public_key_hash * (public_key_hash option * (bool * (Tez.t * 'rest))),\n          operation * (address * 'rest) )\n        instr\n  | Implicit_account\n      : (public_key_hash * 'rest, unit typed_contract * 'rest) instr\n  | Create_contract :\n      'g ty * 'p ty * ('p * 'g, operation list * 'g) lambda * string option\n      -> ( public_key_hash\n           * (public_key_hash option * (bool * (bool * (Tez.t * ('g * 'rest))))),\n           operation * (address * 'rest) )\n         instr\n  | Create_contract_2 :\n      'g ty * 'p ty * ('p * 'g, operation list * 'g) lambda * string 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  | Check_signature\n      : (public_key * (signature * (MBytes.t * 'rest)), bool * 'rest) instr\n  | Hash_key : (public_key * 'rest, public_key_hash * 'rest) instr\n  | Pack : 'a ty -> ('a * 'rest, MBytes.t * 'rest) instr\n  | Unpack : 'a ty -> (MBytes.t * 'rest, 'a option * 'rest) instr\n  | Blake2b : (MBytes.t * 'rest, MBytes.t * 'rest) instr\n  | Sha256 : (MBytes.t * 'rest, MBytes.t * 'rest) instr\n  | Sha512 : (MBytes.t * 'rest, MBytes.t * 'rest) instr\n  | Steps_to_quota\n      : (* TODO: check that it always returns a nat *)\n      ('rest, n num * '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  | Amount : ('rest, Tez.t * 'rest) 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\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\ntype ex_big_map = Ex_bm : ('key, 'value) big_map -> ex_big_map\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\n(* Auxiliary types for error documentation *)\ntype namespace =\n  | Type_namespace\n  | Constant_namespace\n  | Instr_namespace\n  | Keyword_namespace\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 +=\n  | Invalid_namespace of Script.location * prim * namespace * 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 += Missing_field of prim\n\ntype error += Duplicate_field of Script.location * prim\n\ntype error += Unexpected_big_map 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\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\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 += 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" ;
                } ;
                { 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 Legacy : sig\n    val z_to_int64 : Gas.cost\n\n    val hash : MBytes.t -> int -> Gas.cost\n\n    val map_to_list : ('b, 'c) Script_typed_ir.map -> Gas.cost\n\n    val set_update : 'a -> bool -> 'a Script_typed_ir.set -> Gas.cost\n  end\n\n  module Interpreter : sig\n    val cycle : Gas.cost\n\n    val loop_cycle : Gas.cost\n\n    val loop_size : Gas.cost\n\n    val loop_iter : Gas.cost\n\n    val loop_map : Gas.cost\n\n    val nop : Gas.cost\n\n    val stack_op : Gas.cost\n\n    val stack_n_op : int -> Gas.cost\n\n    val bool_binop : 'a -> 'b -> Gas.cost\n\n    val bool_unop : 'a -> Gas.cost\n\n    val pair : Gas.cost\n\n    val pair_access : Gas.cost\n\n    val cons : Gas.cost\n\n    val variant_no_data : Gas.cost\n\n    val branch : Gas.cost\n\n    val concat_string : string list -> Gas.cost\n\n    val concat_bytes : MBytes.t list -> Gas.cost\n\n    val slice_string : int -> Gas.cost\n\n    val map_mem : 'a -> ('a, 'b) Script_typed_ir.map -> Gas.cost\n\n    val map_to_list : ('a, 'b) Script_typed_ir.map -> Gas.cost\n\n    val map_get : 'a -> ('a, 'b) Script_typed_ir.map -> Gas.cost\n\n    val map_update :\n      'a -> 'b option -> ('a, 'b) Script_typed_ir.map -> Gas.cost\n\n    val map_size : Gas.cost\n\n    val set_to_list : 'a Script_typed_ir.set -> Gas.cost\n\n    val set_update : 'a -> bool -> 'a Script_typed_ir.set -> Gas.cost\n\n    val set_mem : 'a -> 'a Script_typed_ir.set -> Gas.cost\n\n    val mul : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val div : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val add : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val sub : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val abs : 'a Script_int.num -> Gas.cost\n\n    val neg : 'a Script_int.num -> Gas.cost\n\n    val int : 'a -> Gas.cost\n\n    val add_timestamp : Script_timestamp.t -> 'a Script_int.num -> Gas.cost\n\n    val sub_timestamp : Script_timestamp.t -> 'a Script_int.num -> Gas.cost\n\n    val diff_timestamps : Script_timestamp.t -> Script_timestamp.t -> Gas.cost\n\n    val empty_set : Gas.cost\n\n    val set_size : Gas.cost\n\n    val empty_map : Gas.cost\n\n    val int64_op : Gas.cost\n\n    val z_to_int64 : Gas.cost\n\n    val int64_to_z : Gas.cost\n\n    val logor : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val logand : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val logxor : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val lognot : 'a Script_int.num -> Gas.cost\n\n    val shift_left : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val shift_right : 'a Script_int.num -> 'b Script_int.num -> Gas.cost\n\n    val exec : Gas.cost\n\n    val push : Gas.cost\n\n    val compare_res : Gas.cost\n\n    val unpack_failed : MBytes.t -> Gas.cost\n\n    val address : Gas.cost\n\n    val contract : Gas.cost\n\n    val transfer : Gas.cost\n\n    val create_account : Gas.cost\n\n    val create_contract : Gas.cost\n\n    val implicit_account : Gas.cost\n\n    val set_delegate : Gas.cost\n\n    val balance : Gas.cost\n\n    val now : Gas.cost\n\n    val check_signature : public_key -> MBytes.t -> Gas.cost\n\n    val hash_key : Gas.cost\n\n    val hash_blake2b : MBytes.t -> Gas.cost\n\n    val hash_sha256 : MBytes.t -> Gas.cost\n\n    val hash_sha512 : MBytes.t -> Gas.cost\n\n    val steps_to_quota : Gas.cost\n\n    val source : Gas.cost\n\n    val self : Gas.cost\n\n    val amount : Gas.cost\n\n    val chain_id : Gas.cost\n\n    val wrap : Gas.cost\n\n    val compare : 'a Script_typed_ir.comparable_ty -> 'a -> 'a -> Gas.cost\n\n    val apply : Gas.cost\n  end\n\n  module Typechecking : sig\n    val cycle : Gas.cost\n\n    val unit : Gas.cost\n\n    val bool : Gas.cost\n\n    val tez : Gas.cost\n\n    val z : Z.t -> Gas.cost\n\n    val string : int -> Gas.cost\n\n    val bytes : int -> Gas.cost\n\n    val int_of_string : string -> Gas.cost\n\n    val string_timestamp : Gas.cost\n\n    val key : Gas.cost\n\n    val key_hash : Gas.cost\n\n    val signature : Gas.cost\n\n    val chain_id : Gas.cost\n\n    val contract : Gas.cost\n\n    (** Gas.Cost of getting the code for a contract *)\n    val get_script : Gas.cost\n\n    val contract_exists : Gas.cost\n\n    (** Additional Gas.cost of parsing a pair over the Gas.cost of parsing each type  *)\n    val pair : Gas.cost\n\n    val union : Gas.cost\n\n    val lambda : Gas.cost\n\n    val some : Gas.cost\n\n    val none : Gas.cost\n\n    val list_element : Gas.cost\n\n    val set_element : int -> Gas.cost\n\n    val map_element : int -> Gas.cost\n\n    val primitive_type : Gas.cost\n\n    val one_arg_type : Gas.cost\n\n    val two_arg_type : Gas.cost\n\n    val operation : int -> Gas.cost\n\n    (** Cost of parsing a type *)\n    val type_ : int -> Gas.cost\n\n    (** Cost of parsing an instruction *)\n    val instr : ('a, 'b) Script_typed_ir.instr -> Gas.cost\n  end\n\n  module Unparse : sig\n    val prim_cost : int -> Script.annot -> Gas.cost\n\n    val seq_cost : int -> Gas.cost\n\n    val cycle : Gas.cost\n\n    val unit : Gas.cost\n\n    val bool : Gas.cost\n\n    val z : Z.t -> Gas.cost\n\n    val int : 'a Script_int.num -> Gas.cost\n\n    val tez : Gas.cost\n\n    val string : string -> Gas.cost\n\n    val bytes : MBytes.t -> Gas.cost\n\n    val timestamp : Script_timestamp.t -> Gas.cost\n\n    val key : Gas.cost\n\n    val key_hash : Gas.cost\n\n    val signature : Gas.cost\n\n    val operation : MBytes.t -> Gas.cost\n\n    val chain_id : MBytes.t -> Gas.cost\n\n    val contract : Gas.cost\n\n    (** Additional Gas.cost of parsing a pair over the Gas.cost of parsing each type  *)\n    val pair : Gas.cost\n\n    val union : Gas.cost\n\n    val some : Gas.cost\n\n    val none : Gas.cost\n\n    val list_element : Gas.cost\n\n    val set_element : Gas.cost\n\n    val map_element : Gas.cost\n\n    val one_arg_type : Script.annot -> Gas.cost\n\n    val two_arg_type : Script.annot -> Gas.cost\n\n    val set_to_list : 'a Script_typed_ir.set -> Gas.cost\n\n    val map_to_list : ('a, 'b) Script_typed_ir.map -> Gas.cost\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\nopen Alpha_context\nopen Gas\n\nmodule Cost_of = struct\n  let log2 =\n    let rec help acc = function 0 -> acc | n -> help (acc + 1) (n / 2) in\n    help 1\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  (* For now, returns size in bytes, but this could get more complicated... *)\n  let rec size_of_comparable :\n      type a b. (a, b) Script_typed_ir.comparable_struct -> a -> int =\n   fun wit v ->\n    match wit with\n    | Int_key _ ->\n        int_bytes v\n    | Nat_key _ ->\n        int_bytes v\n    | String_key _ ->\n        String.length v\n    | Bytes_key _ ->\n        MBytes.length v\n    | Bool_key _ ->\n        8\n    | Key_hash_key _ ->\n        Signature.Public_key_hash.size\n    | Timestamp_key _ ->\n        timestamp_bytes v\n    | Address_key _ ->\n        Signature.Public_key_hash.size\n    | Mutez_key _ ->\n        8\n    | Pair_key ((l, _), (r, _), _) ->\n        let (lval, rval) = v in\n        size_of_comparable l lval + size_of_comparable r rval\n\n  let string length = alloc_bytes_cost length\n\n  let bytes length = alloc_mbytes_cost length\n\n  let manager_operation = step_cost 10_000\n\n  module Legacy = struct\n    let zint z = alloc_bits_cost (Z.numbits z)\n\n    let set_to_list : type item. item Script_typed_ir.set -> cost =\n     fun (module Box) -> alloc_cost @@ Pervasives.(Box.size * 2)\n\n    let map_to_list : type key value. (key, value) Script_typed_ir.map -> cost\n        =\n     fun (module Box) ->\n      let size = snd Box.boxed in\n      3 *@ alloc_cost size\n\n    let z_to_int64 = step_cost 2 +@ alloc_cost 1\n\n    let hash data len = (10 *@ step_cost (MBytes.length data)) +@ bytes len\n\n    let set_access : type elt. elt -> elt Script_typed_ir.set -> int =\n     fun _key (module Box) -> log2 @@ Box.size\n\n    let set_update key _presence set = set_access key set *@ alloc_cost 3\n  end\n\n  module Interpreter = struct\n    let cycle = atomic_step_cost 10\n\n    let nop = free\n\n    let stack_op = atomic_step_cost 10\n\n    let push = atomic_step_cost 10\n\n    let wrap = atomic_step_cost 10\n\n    let variant_no_data = atomic_step_cost 10\n\n    let branch = atomic_step_cost 10\n\n    let pair = atomic_step_cost 10\n\n    let pair_access = atomic_step_cost 10\n\n    let cons = atomic_step_cost 10\n\n    let loop_size = atomic_step_cost 5\n\n    let loop_cycle = atomic_step_cost 10\n\n    let loop_iter = atomic_step_cost 20\n\n    let loop_map = atomic_step_cost 30\n\n    let empty_set = atomic_step_cost 10\n\n    let set_to_list : type elt. elt Script_typed_ir.set -> cost =\n     fun (module Box) -> atomic_step_cost (Box.size * 20)\n\n    let set_mem : type elt. elt -> elt Script_typed_ir.set -> cost =\n     fun elt (module Box) ->\n      let elt_bytes = size_of_comparable Box.elt_ty elt in\n      atomic_step_cost ((1 + (elt_bytes / 82)) * log2 Box.size)\n\n    let set_update : type elt. elt -> bool -> elt Script_typed_ir.set -> cost =\n     fun elt _ (module Box) ->\n      let elt_bytes = size_of_comparable Box.elt_ty elt in\n      atomic_step_cost ((1 + (elt_bytes / 82)) * log2 Box.size)\n\n    let set_size = atomic_step_cost 10\n\n    let empty_map = atomic_step_cost 10\n\n    let map_to_list : type key value. (key, value) Script_typed_ir.map -> cost\n        =\n     fun (module Box) ->\n      let size = snd Box.boxed in\n      atomic_step_cost (size * 20)\n\n    let map_access :\n        type key value. key -> (key, value) Script_typed_ir.map -> cost =\n     fun key (module Box) ->\n      let map_card = snd Box.boxed in\n      let key_bytes = size_of_comparable Box.key_ty key in\n      atomic_step_cost ((1 + (key_bytes / 70)) * log2 map_card)\n\n    let map_mem = map_access\n\n    let map_get = map_access\n\n    let map_update :\n        type key value.\n        key -> value option -> (key, value) Script_typed_ir.map -> cost =\n     fun key _value (module Box) ->\n      let map_card = snd Box.boxed in\n      let key_bytes = size_of_comparable Box.key_ty key in\n      atomic_step_cost ((1 + (key_bytes / 38)) * log2 map_card)\n\n    let map_size = atomic_step_cost 10\n\n    let add_timestamp (t1 : Script_timestamp.t) (t2 : 'a Script_int.num) =\n      let bytes1 = timestamp_bytes t1 in\n      let bytes2 = int_bytes t2 in\n      atomic_step_cost (51 + (Compare.Int.max bytes1 bytes2 / 62))\n\n    let sub_timestamp = add_timestamp\n\n    let diff_timestamps (t1 : Script_timestamp.t) (t2 : Script_timestamp.t) =\n      let bytes1 = timestamp_bytes t1 in\n      let bytes2 = timestamp_bytes t2 in\n      atomic_step_cost (51 + (Compare.Int.max bytes1 bytes2 / 62))\n\n    let rec concat_loop l acc =\n      match l with [] -> 30 | _ :: tl -> concat_loop tl (acc + 30)\n\n    let concat_string string_list =\n      atomic_step_cost (concat_loop string_list 0)\n\n    let slice_string string_length =\n      atomic_step_cost (40 + (string_length / 70))\n\n    let concat_bytes bytes_list = atomic_step_cost (concat_loop bytes_list 0)\n\n    let int64_op = atomic_step_cost 61\n\n    let z_to_int64 = atomic_step_cost 20\n\n    let int64_to_z = atomic_step_cost 20\n\n    let bool_binop _ _ = atomic_step_cost 10\n\n    let bool_unop _ = atomic_step_cost 10\n\n    let abs int = atomic_step_cost (61 + (int_bytes int / 70))\n\n    let int _int = free\n\n    let neg = abs\n\n    let add i1 i2 =\n      atomic_step_cost\n        (51 + (Compare.Int.max (int_bytes i1) (int_bytes i2) / 62))\n\n    let sub = add\n\n    let mul i1 i2 =\n      let bytes = Compare.Int.max (int_bytes i1) (int_bytes i2) in\n      atomic_step_cost (51 + (bytes / 6 * log2 bytes))\n\n    let indic_lt x y = if Compare.Int.(x < y) then 1 else 0\n\n    let div i1 i2 =\n      let bytes1 = int_bytes i1 in\n      let bytes2 = int_bytes i2 in\n      let cost = indic_lt bytes2 bytes1 * (bytes1 - bytes2) * bytes2 in\n      atomic_step_cost (51 + (cost / 3151))\n\n    let shift_left _i _shift_bits = atomic_step_cost 30\n\n    let shift_right _i _shift_bits = atomic_step_cost 30\n\n    let logor i1 i2 =\n      let bytes1 = int_bytes i1 in\n      let bytes2 = int_bytes i2 in\n      atomic_step_cost (51 + (Compare.Int.max bytes1 bytes2 / 70))\n\n    let logand i1 i2 =\n      let bytes1 = int_bytes i1 in\n      let bytes2 = int_bytes i2 in\n      atomic_step_cost (51 + (Compare.Int.min bytes1 bytes2 / 70))\n\n    let logxor = logor\n\n    let lognot i = atomic_step_cost (51 + (int_bytes i / 20))\n\n    let exec = atomic_step_cost 10\n\n    let compare_bool _ _ = atomic_step_cost 30\n\n    let compare_string s1 s2 =\n      let bytes1 = String.length s1 in\n      let bytes2 = String.length s2 in\n      atomic_step_cost (30 + (Compare.Int.min bytes1 bytes2 / 123))\n\n    let compare_bytes b1 b2 =\n      let bytes1 = MBytes.length b1 in\n      let bytes2 = MBytes.length b2 in\n      atomic_step_cost (30 + (Compare.Int.min bytes1 bytes2 / 123))\n\n    let compare_tez _ _ = atomic_step_cost 30\n\n    let compare_zint i1 i2 =\n      atomic_step_cost\n        (51 + (Compare.Int.min (int_bytes i1) (int_bytes i2) / 82))\n\n    let compare_key_hash _ _ = atomic_step_cost 92\n\n    let compare_timestamp t1 t2 =\n      let bytes1 = timestamp_bytes t1 in\n      let bytes2 = timestamp_bytes t2 in\n      atomic_step_cost (51 + (Compare.Int.min bytes1 bytes2 / 82))\n\n    let compare_address _ _ = atomic_step_cost 92\n\n    let compare_res = atomic_step_cost 30\n\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 = MBytes.length bytes in\n      (len *@ alloc_mbytes_cost 1)\n      +@ (len *@ (log2 len *@ (alloc_cost 3 +@ step_cost 1)))\n\n    let address = atomic_step_cost 10\n\n    let contract = step_cost 10000\n\n    let transfer = step_cost 10\n\n    let create_account = step_cost 10\n\n    let create_contract = step_cost 10\n\n    let implicit_account = step_cost 10\n\n    let set_delegate = step_cost 10 +@ write_bytes_cost (Z.of_int 32)\n\n    let balance = atomic_step_cost 10\n\n    let now = atomic_step_cost 10\n\n    let check_signature_secp256k1 bytes = atomic_step_cost (10342 + (bytes / 5))\n\n    let check_signature_ed25519 bytes = atomic_step_cost (36864 + (bytes / 5))\n\n    let check_signature_p256 bytes = atomic_step_cost (36864 + (bytes / 5))\n\n    let check_signature (pkey : Signature.public_key) bytes =\n      match pkey with\n      | Ed25519 _ ->\n          check_signature_ed25519 (MBytes.length bytes)\n      | Secp256k1 _ ->\n          check_signature_secp256k1 (MBytes.length bytes)\n      | P256 _ ->\n          check_signature_p256 (MBytes.length bytes)\n\n    let hash_key = atomic_step_cost 30\n\n    let hash_blake2b b = atomic_step_cost (102 + (MBytes.length b / 5))\n\n    let hash_sha256 b = atomic_step_cost (409 + MBytes.length b)\n\n    let hash_sha512 b =\n      let bytes = MBytes.length b in\n      atomic_step_cost (409 + ((bytes lsr 1) + (bytes lsr 4)))\n\n    let steps_to_quota = atomic_step_cost 10\n\n    let source = atomic_step_cost 10\n\n    let self = atomic_step_cost 10\n\n    let amount = atomic_step_cost 10\n\n    let chain_id = step_cost 1\n\n    let stack_n_op n =\n      atomic_step_cost (20 + ((n lsr 1) + (n lsr 2) + (n lsr 4)))\n\n    let apply = alloc_cost 8 +@ step_cost 1\n\n    let rec compare :\n        type a s. (a, s) Script_typed_ir.comparable_struct -> a -> a -> cost =\n     fun ty x y ->\n      match ty with\n      | Bool_key _ ->\n          compare_bool x y\n      | String_key _ ->\n          compare_string x y\n      | Bytes_key _ ->\n          compare_bytes x y\n      | Mutez_key _ ->\n          compare_tez x y\n      | Int_key _ ->\n          compare_zint x y\n      | Nat_key _ ->\n          compare_zint x y\n      | Key_hash_key _ ->\n          compare_key_hash x y\n      | Timestamp_key _ ->\n          compare_timestamp x y\n      | Address_key _ ->\n          compare_address x y\n      | Pair_key ((tl, _), (tr, _), _) ->\n          (* Reasonable over-approximation of the cost of lexicographic comparison. *)\n          let (xl, xr) = x and (yl, yr) = y in\n          compare tl xl yl +@ compare tr xr yr\n  end\n\n  module Typechecking = struct\n    let cycle = step_cost 1\n\n    let bool = free\n\n    let unit = free\n\n    let string = string\n\n    let bytes = bytes\n\n    let z = Legacy.zint\n\n    let int_of_string str =\n      alloc_cost @@ Pervasives.( / ) (String.length str) 5\n\n    let tez = step_cost 1 +@ alloc_cost 1\n\n    let string_timestamp = step_cost 3 +@ alloc_cost 3\n\n    let key = step_cost 3 +@ alloc_cost 3\n\n    let key_hash = step_cost 1 +@ alloc_cost 1\n\n    let signature = step_cost 1 +@ alloc_cost 1\n\n    let chain_id = step_cost 1 +@ alloc_cost 1\n\n    let contract = step_cost 5\n\n    let get_script = step_cost 20 +@ alloc_cost 5\n\n    let contract_exists = step_cost 15 +@ alloc_cost 5\n\n    let pair = alloc_cost 2\n\n    let union = alloc_cost 1\n\n    let lambda = alloc_cost 5 +@ step_cost 3\n\n    let some = alloc_cost 1\n\n    let none = alloc_cost 0\n\n    let list_element = alloc_cost 2 +@ step_cost 1\n\n    let set_element size = log2 size *@ (alloc_cost 3 +@ step_cost 2)\n\n    let map_element size = log2 size *@ (alloc_cost 4 +@ step_cost 2)\n\n    let primitive_type = alloc_cost 1\n\n    let one_arg_type = alloc_cost 2\n\n    let two_arg_type = alloc_cost 3\n\n    let operation b = bytes b\n\n    let type_ nb_args = alloc_cost (nb_args + 1)\n\n    (* Cost of parsing instruction, is cost of allocation of\n       constructor + cost of contructor parameters + cost of\n       allocation on the stack type *)\n    let instr : type b a. (b, a) Script_typed_ir.instr -> cost =\n     fun i ->\n      let open Script_typed_ir in\n      alloc_cost 1\n      +@\n      (* cost of allocation of constructor *)\n      match i with\n      | Drop ->\n          alloc_cost 0\n      | Dup ->\n          alloc_cost 1\n      | Swap ->\n          alloc_cost 0\n      | Const _ ->\n          alloc_cost 1\n      | Cons_pair ->\n          alloc_cost 2\n      | Car ->\n          alloc_cost 1\n      | Cdr ->\n          alloc_cost 1\n      | Cons_some ->\n          alloc_cost 2\n      | Cons_none _ ->\n          alloc_cost 3\n      | If_none _ ->\n          alloc_cost 2\n      | Left ->\n          alloc_cost 3\n      | Right ->\n          alloc_cost 3\n      | If_left _ ->\n          alloc_cost 2\n      | Cons_list ->\n          alloc_cost 1\n      | Nil ->\n          alloc_cost 1\n      | If_cons _ ->\n          alloc_cost 2\n      | List_map _ ->\n          alloc_cost 5\n      | List_iter _ ->\n          alloc_cost 4\n      | List_size ->\n          alloc_cost 1\n      | Empty_set _ ->\n          alloc_cost 1\n      | Set_iter _ ->\n          alloc_cost 4\n      | Set_mem ->\n          alloc_cost 1\n      | Set_update ->\n          alloc_cost 1\n      | Set_size ->\n          alloc_cost 1\n      | Empty_map _ ->\n          alloc_cost 2\n      | Map_map _ ->\n          alloc_cost 5\n      | Map_iter _ ->\n          alloc_cost 4\n      | Map_mem ->\n          alloc_cost 1\n      | Map_get ->\n          alloc_cost 1\n      | Map_update ->\n          alloc_cost 1\n      | Map_size ->\n          alloc_cost 1\n      | Empty_big_map _ ->\n          alloc_cost 2\n      | Big_map_mem ->\n          alloc_cost 1\n      | Big_map_get ->\n          alloc_cost 1\n      | Big_map_update ->\n          alloc_cost 1\n      | Concat_string ->\n          alloc_cost 1\n      | Concat_string_pair ->\n          alloc_cost 1\n      | Concat_bytes ->\n          alloc_cost 1\n      | Concat_bytes_pair ->\n          alloc_cost 1\n      | Slice_string ->\n          alloc_cost 1\n      | Slice_bytes ->\n          alloc_cost 1\n      | String_size ->\n          alloc_cost 1\n      | Bytes_size ->\n          alloc_cost 1\n      | Add_seconds_to_timestamp ->\n          alloc_cost 1\n      | Add_timestamp_to_seconds ->\n          alloc_cost 1\n      | Sub_timestamp_seconds ->\n          alloc_cost 1\n      | Diff_timestamps ->\n          alloc_cost 1\n      | Add_tez ->\n          alloc_cost 1\n      | Sub_tez ->\n          alloc_cost 1\n      | Mul_teznat ->\n          alloc_cost 1\n      | Mul_nattez ->\n          alloc_cost 1\n      | Ediv_teznat ->\n          alloc_cost 1\n      | Ediv_tez ->\n          alloc_cost 1\n      | Or ->\n          alloc_cost 1\n      | And ->\n          alloc_cost 1\n      | Xor ->\n          alloc_cost 1\n      | Not ->\n          alloc_cost 1\n      | Is_nat ->\n          alloc_cost 1\n      | Neg_nat ->\n          alloc_cost 1\n      | Neg_int ->\n          alloc_cost 1\n      | Abs_int ->\n          alloc_cost 1\n      | Int_nat ->\n          alloc_cost 1\n      | Add_intint ->\n          alloc_cost 1\n      | Add_intnat ->\n          alloc_cost 1\n      | Add_natint ->\n          alloc_cost 1\n      | Add_natnat ->\n          alloc_cost 1\n      | Sub_int ->\n          alloc_cost 1\n      | Mul_intint ->\n          alloc_cost 1\n      | Mul_intnat ->\n          alloc_cost 1\n      | Mul_natint ->\n          alloc_cost 1\n      | Mul_natnat ->\n          alloc_cost 1\n      | Ediv_intint ->\n          alloc_cost 1\n      | Ediv_intnat ->\n          alloc_cost 1\n      | Ediv_natint ->\n          alloc_cost 1\n      | Ediv_natnat ->\n          alloc_cost 1\n      | Lsl_nat ->\n          alloc_cost 1\n      | Lsr_nat ->\n          alloc_cost 1\n      | Or_nat ->\n          alloc_cost 1\n      | And_nat ->\n          alloc_cost 1\n      | And_int_nat ->\n          alloc_cost 1\n      | Xor_nat ->\n          alloc_cost 1\n      | Not_nat ->\n          alloc_cost 1\n      | Not_int ->\n          alloc_cost 1\n      | Seq _ ->\n          alloc_cost 8\n      | If _ ->\n          alloc_cost 8\n      | Loop _ ->\n          alloc_cost 4\n      | Loop_left _ ->\n          alloc_cost 5\n      | Dip _ ->\n          alloc_cost 4\n      | Exec ->\n          alloc_cost 1\n      | Apply _ ->\n          alloc_cost 1\n      | Lambda _ ->\n          alloc_cost 2\n      | Failwith _ ->\n          alloc_cost 1\n      | Nop ->\n          alloc_cost 0\n      | Compare _ ->\n          alloc_cost 1\n      | Eq ->\n          alloc_cost 1\n      | Neq ->\n          alloc_cost 1\n      | Lt ->\n          alloc_cost 1\n      | Gt ->\n          alloc_cost 1\n      | Le ->\n          alloc_cost 1\n      | Ge ->\n          alloc_cost 1\n      | Address ->\n          alloc_cost 1\n      | Contract _ ->\n          alloc_cost 2\n      | Transfer_tokens ->\n          alloc_cost 1\n      | Create_account ->\n          alloc_cost 2\n      | Implicit_account ->\n          alloc_cost 1\n      | Create_contract _ ->\n          alloc_cost 8\n      (* Deducted the cost of removed arguments manager, spendable and delegatable:\n           - manager: key_hash = 1\n           - spendable: bool = 0\n           - delegatable: bool = 0\n        *)\n      | Create_contract_2 _ ->\n          alloc_cost 7\n      | Set_delegate ->\n          alloc_cost 1\n      | Now ->\n          alloc_cost 1\n      | Balance ->\n          alloc_cost 1\n      | Check_signature ->\n          alloc_cost 1\n      | Hash_key ->\n          alloc_cost 1\n      | Pack _ ->\n          alloc_cost 2\n      | Unpack _ ->\n          alloc_cost 2\n      | Blake2b ->\n          alloc_cost 1\n      | Sha256 ->\n          alloc_cost 1\n      | Sha512 ->\n          alloc_cost 1\n      | Steps_to_quota ->\n          alloc_cost 1\n      | Source ->\n          alloc_cost 1\n      | Sender ->\n          alloc_cost 1\n      | Self _ ->\n          alloc_cost 2\n      | Amount ->\n          alloc_cost 1\n      | Dig (n, _) ->\n          n *@ alloc_cost 1 (* _ is a unary development of n *)\n      | Dug (n, _) ->\n          n *@ alloc_cost 1\n      | Dipn (n, _, _) ->\n          n *@ alloc_cost 1\n      | Dropn (n, _) ->\n          n *@ alloc_cost 1\n      | ChainId ->\n          alloc_cost 1\n  end\n\n  module Unparse = struct\n    let prim_cost l annot = Script.prim_node_cost_nonrec_of_length l annot\n\n    let seq_cost = Script.seq_node_cost_nonrec_of_length\n\n    let string_cost length = Script.string_node_cost_of_length length\n\n    let cycle = step_cost 1\n\n    let bool = prim_cost 0 []\n\n    let unit = prim_cost 0 []\n\n    (* We count the length of strings and bytes to prevent hidden\n       miscalculations due to non detectable expansion of sharing. *)\n    let string s = Script.string_node_cost s\n\n    let bytes s = Script.bytes_node_cost s\n\n    let z i = Script.int_node_cost i\n\n    let int i = Script.int_node_cost (Script_int.to_zint i)\n\n    let tez = Script.int_node_cost_of_numbits 60 (* int64 bound *)\n\n    let timestamp x = Script_timestamp.to_zint x |> Script_int.of_zint |> int\n\n    let operation bytes = Script.bytes_node_cost bytes\n\n    let chain_id bytes = Script.bytes_node_cost bytes\n\n    let key = string_cost 54\n\n    let key_hash = string_cost 36\n\n    let signature = string_cost 128\n\n    let contract = string_cost 36\n\n    let pair = prim_cost 2 []\n\n    let union = prim_cost 1 []\n\n    let some = prim_cost 1 []\n\n    let none = prim_cost 0 []\n\n    let list_element = alloc_cost 2\n\n    let set_element = alloc_cost 2\n\n    let map_element = alloc_cost 2\n\n    let one_arg_type = prim_cost 1\n\n    let two_arg_type = prim_cost 2\n\n    let set_to_list = Legacy.set_to_list\n\n    let map_to_list = Legacy.map_to_list\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_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_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(** Convertions 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(** Same as {!error_unexpected_annot} in Lwt. *)\nval fail_unexpected_annot : int -> 'a list -> unit tzresult Lwt.t\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_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_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 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),\n      (None | Some (`Field_annot \"\")),\n      Some (`Field_annot f) ) ->\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 [] -> ok () | _ :: _ -> error (Unexpected_annotation loc)\n\nlet fail_unexpected_annot loc annot =\n  Lwt.return (error_unexpected_annot loc annot)\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 () 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 ()\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\nlet parse_annots loc ?(allow_special_var = false)\n    ?(allow_special_field = false) l =\n  (* allow emtpty 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 len = String.length s in\n    ( if Compare.Int.(len > max_annot_length) then\n      error (Unexpected_annotation loc)\n    else ok () )\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' | '_' ->\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) && List.mem '@' specials ->\n          ok @@ (wrap (Some \"@\") :: acc)\n      | '%' when List.mem '%' 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 a) s acc\n        | '@' ->\n            sub_or_wildcard\n              ~specials:(if allow_special_var then ['%'] else [])\n              (fun a -> `Var_annot a)\n              s\n              acc\n        | '%' ->\n            sub_or_wildcard\n              ~specials:(if allow_special_field then ['@'] else [])\n              (fun a -> `Field_annot a)\n              s\n              acc\n        | _ ->\n            error (Unexpected_annotation loc))\n    (ok [])\n    l\n  >|? List.rev\n\nlet opt_var_of_var_opt = function\n  | `Var_annot None ->\n      None\n  | `Var_annot (Some a) ->\n      Some (`Var_annot a)\n\nlet opt_field_of_field_opt = function\n  | `Field_annot None ->\n      None\n  | `Field_annot (Some a) ->\n      Some (`Field_annot a)\n\nlet opt_type_of_type_opt = function\n  | `Type_annot None ->\n      None\n  | `Type_annot (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 _ as a), true, _, _, _, _, _)\n          | ((`Var_annot _ as a), false, [], _, _, _, _) ->\n              (true, opt_var_of_var_opt a :: rv, false, rt, false, rf)\n          | ((`Type_annot _ as a), _, _, true, _, _, _)\n          | ((`Type_annot _ as a), _, _, false, [], _, _) ->\n              (false, rv, true, opt_type_of_type_opt a :: rt, false, rf)\n          | ((`Field_annot _ as a), _, _, _, _, true, _)\n          | ((`Field_annot _ as 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      let field_annot =\n        match field_annot with\n        | None ->\n            None\n        | Some field_annot ->\n            Some\n              (`Field_annot\n                (String.sub field_annot 1 (String.length field_annot - 1)))\n      in\n      ok (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 ()\n  | (Some (`Field_annot s1), Some (`Field_annot s2)) ->\n      if String.equal s1 s2 then ok ()\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))\n    when Compare.String.equal s1 s2 ->\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 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 =\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  in\n  (v, f)\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 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 : string 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\n\ntype type_logger =\n  int ->\n  (Script.expr * Script.annot) list ->\n  (Script.expr * Script.annot) list ->\n  unit\n\n(* ---- Sets and Maps -------------------------------------------------------*)\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  '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_comparable : 'a Script_typed_ir.comparable_ty -> 'a -> 'a -> int\n\nval parse_data :\n  ?type_logger:type_logger ->\n  context ->\n  legacy: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 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\nval parse_ty :\n  context ->\n  legacy:bool ->\n  allow_big_map:bool ->\n  allow_operation:bool ->\n  allow_contract:bool ->\n  Script.node ->\n  (ex_ty * context) tzresult\n\nval parse_packable_ty :\n  context -> legacy:bool -> Script.node -> (ex_ty * context) tzresult\n\nval unparse_ty :\n  context -> 'a Script_typed_ir.ty -> (Script.node * context) tzresult Lwt.t\n\nval parse_toplevel :\n  legacy:bool ->\n  Script.expr ->\n  (Script.node * Script.node * Script.node * string option) tzresult\n\nval add_field_annot :\n  [`Field_annot of string] option ->\n  [`Var_annot of string] option ->\n  Script.node ->\n  Script.node\n\nval typecheck_code :\n  context -> Script.expr -> (type_map * context) tzresult Lwt.t\n\nval typecheck_data :\n  ?type_logger:type_logger ->\n  context ->\n  Script.expr * Script.expr ->\n  context tzresult Lwt.t\n\nval parse_script :\n  ?type_logger:type_logger ->\n  context ->\n  legacy: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:string 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:string 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 -> (MBytes.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 big_map_ids\n\nval no_big_map_id : big_map_ids\n\nval collect_big_maps :\n  context ->\n  'a Script_typed_ir.ty ->\n  'a ->\n  (big_map_ids * context) tzresult Lwt.t\n\nval list_of_big_map_ids : big_map_ids -> Z.t list\n\nval extract_big_map_diff :\n  context ->\n  unparsing_mode ->\n  temporary:bool ->\n  to_duplicate:big_map_ids ->\n  to_update:big_map_ids ->\n  'a Script_typed_ir.ty ->\n  'a ->\n  ('a * Contract.big_map_diff option * 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\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.Unparse\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 : string option;\n      legacy_create_contract_literal : bool;\n    }\n      -> tc_context\n\ntype unparsing_mode = Optimized | Readable\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 a. (t, a) comparable_struct -> int =\n fun ty ->\n  (* No wildcard to force the update when comparable_ty chages. *)\n  match ty with\n  | Int_key _ ->\n      1\n  | Nat_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  | Timestamp_key _ ->\n      1\n  | Address_key _ ->\n      1\n  | Pair_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  | 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  | 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  | Chain_id_t _ ->\n      1\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). *)\nlet number_of_generated_growing_types : type b a. (b, a) instr -> int =\n  function\n  | Drop ->\n      0\n  | Dup ->\n      0\n  | Swap ->\n      0\n  | Const _ ->\n      1\n  | Cons_pair ->\n      1\n  | Car ->\n      0\n  | Cdr ->\n      0\n  | Cons_some ->\n      1\n  | Cons_none _ ->\n      1\n  | If_none _ ->\n      0\n  | Left ->\n      0\n  | Right ->\n      0\n  | If_left _ ->\n      0\n  | Cons_list ->\n      1\n  | Nil ->\n      1\n  | If_cons _ ->\n      0\n  | List_map _ ->\n      1\n  | List_size ->\n      0\n  | List_iter _ ->\n      1\n  | Empty_set _ ->\n      1\n  | Set_iter _ ->\n      0\n  | Set_mem ->\n      0\n  | Set_update ->\n      0\n  | Set_size ->\n      0\n  | Empty_map _ ->\n      1\n  | Map_map _ ->\n      1\n  | Map_iter _ ->\n      1\n  | Map_mem ->\n      0\n  | Map_get ->\n      0\n  | Map_update ->\n      0\n  | Map_size ->\n      0\n  | Empty_big_map _ ->\n      1\n  | Big_map_get ->\n      0\n  | Big_map_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  | Lambda _ ->\n      1\n  | Failwith _ ->\n      1\n  | Nop ->\n      0\n  | Compare _ ->\n      1\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  | Contract _ ->\n      1\n  | Transfer_tokens ->\n      1\n  | Create_account ->\n      0\n  | Implicit_account ->\n      0\n  | Create_contract _ ->\n      1\n  | Create_contract_2 _ ->\n      1\n  | Now ->\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  | Steps_to_quota ->\n      0\n  | Source ->\n      0\n  | Sender ->\n      0\n  | Self _ ->\n      1\n  | Amount ->\n      0\n  | Set_delegate ->\n      0\n  | Pack _ ->\n      0\n  | Unpack _ ->\n      1\n  | Dig _ ->\n      0\n  | Dug _ ->\n      0\n  | Dipn _ ->\n      0\n  | Dropn _ ->\n      0\n  | ChainId ->\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 = 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 namespace = function\n  | K_parameter | K_storage | K_code ->\n      Keyword_namespace\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      Constant_namespace\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_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_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_PUSH\n  | I_RIGHT\n  | I_SIZE\n  | I_SOME\n  | I_SOURCE\n  | I_SENDER\n  | I_SELF\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_DIG\n  | I_DUG ->\n      Instr_namespace\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_chain_id ->\n      Type_namespace\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    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.mem kind kinds then return_unit\n  else\n    let loc = location expr in\n    fail (Invalid_kind (loc, kinds, kind))\n\n(* ---- Sets and Maps -------------------------------------------------------*)\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 rec compare_comparable :\n    type a s. (a, s) comparable_struct -> a -> a -> int =\n fun kind ->\n  match kind with\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  | 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\n      @@ fun (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  | Bytes_key _ ->\n      wrap_compare MBytes.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\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 s. (a, s) comparable_struct -> a ty =\n  function\n  | Int_key tname ->\n      Int_t tname\n  | Nat_key tname ->\n      Nat_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  | Timestamp_key tname ->\n      Timestamp_t tname\n  | Address_key tname ->\n      Address_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          false )\n\nlet rec comparable_ty_of_ty : type a. a ty -> a comparable_ty option = function\n  | Int_t tname ->\n      Some (Int_key tname)\n  | Nat_t tname ->\n      Some (Nat_key tname)\n  | String_t tname ->\n      Some (String_key tname)\n  | Bytes_t tname ->\n      Some (Bytes_key tname)\n  | Mutez_t tname ->\n      Some (Mutez_key tname)\n  | Bool_t tname ->\n      Some (Bool_key tname)\n  | Key_hash_t tname ->\n      Some (Key_hash_key tname)\n  | Timestamp_t tname ->\n      Some (Timestamp_key tname)\n  | Address_t tname ->\n      Some (Address_key tname)\n  | Pair_t ((l, al, _), (r, ar, _), pname, _) -> (\n    match comparable_ty_of_ty r with\n    | None ->\n        None\n    | Some rty -> (\n      match comparable_ty_of_ty l with\n      | None ->\n          None\n      | Some (Pair_key _) ->\n          None (* not a comb *)\n      | Some (Int_key tname) ->\n          Some (Pair_key ((Int_key tname, al), (rty, ar), pname))\n      | Some (Nat_key tname) ->\n          Some (Pair_key ((Nat_key tname, al), (rty, ar), pname))\n      | Some (String_key tname) ->\n          Some (Pair_key ((String_key tname, al), (rty, ar), pname))\n      | Some (Bytes_key tname) ->\n          Some (Pair_key ((Bytes_key tname, al), (rty, ar), pname))\n      | Some (Mutez_key tname) ->\n          Some (Pair_key ((Mutez_key tname, al), (rty, ar), pname))\n      | Some (Bool_key tname) ->\n          Some (Pair_key ((Bool_key tname, al), (rty, ar), pname))\n      | Some (Key_hash_key tname) ->\n          Some (Pair_key ((Key_hash_key tname, al), (rty, ar), pname))\n      | Some (Timestamp_key tname) ->\n          Some (Pair_key ((Timestamp_key tname, al), (rty, ar), pname))\n      | Some (Address_key tname) ->\n          Some (Pair_key ((Address_key tname, al), (rty, ar), pname)) ) )\n  | _ ->\n      None\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 :\n    type a s. (a, s) comparable_struct -> Script.node = function\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  | 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  | 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  | 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      Prim (-1, T_pair, [tl; tr], unparse_type_annot pname)\n\nlet rec unparse_ty_no_lwt :\n    type a. context -> a ty -> (Script.node * context) tzresult =\n fun ctxt ty ->\n  Gas.consume ctxt Unparse_costs.cycle\n  >>? fun ctxt ->\n  let return ctxt (name, args, annot) =\n    let result = Prim (-1, name, args, annot) in\n    Gas.consume ctxt (Unparse_costs.prim_cost (List.length args) annot)\n    >>? fun ctxt -> 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  | 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  | Signature_t tname ->\n      return ctxt (T_signature, [], 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  | Contract_t (ut, tname) ->\n      unparse_ty_no_lwt 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_no_lwt ctxt utl\n      >>? fun (utl, ctxt) ->\n      let tl = add_field_annot l_field l_var utl in\n      unparse_ty_no_lwt ctxt utr\n      >>? fun (utr, ctxt) ->\n      let tr = add_field_annot r_field r_var utr in\n      return ctxt (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_no_lwt ctxt utl\n      >>? fun (utl, ctxt) ->\n      let tl = add_field_annot l_field None utl in\n      unparse_ty_no_lwt 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_no_lwt ctxt uta\n      >>? fun (ta, ctxt) ->\n      unparse_ty_no_lwt 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_no_lwt ctxt ut\n      >>? fun (ut, ctxt) -> return ctxt (T_option, [ut], annot)\n  | List_t (ut, tname, _) ->\n      unparse_ty_no_lwt ctxt ut\n      >>? fun (t, ctxt) -> return ctxt (T_list, [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_no_lwt 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_no_lwt ctxt utr\n      >>? fun (tr, ctxt) ->\n      return ctxt (T_big_map, [ta; tr], unparse_type_annot tname)\n\nlet unparse_ty ctxt ty = Lwt.return (unparse_ty_no_lwt ctxt ty)\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_no_lwt ctxt ty\n  |> record_trace Cannot_serialize_error\n  >|? fun (ty, ctxt) -> (strip_locations (strip_var_annots ty), ctxt)\n\nlet rec unparse_stack :\n    type a.\n    context ->\n    a stack_ty ->\n    ((Script.expr * Script.annot) list * context) tzresult Lwt.t =\n fun ctxt -> function\n  | Empty_t ->\n      return ([], 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      return ((strip_locations uty, unparse_var_annot annot) :: urest, ctxt)\n\nlet serialize_stack_for_error ctxt stack_ty =\n  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  | 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  | Set_t (_, tname) ->\n      tname\n  | Map_t (_, _, tname, _) ->\n      tname\n  | Big_map_t (_, _, tname) ->\n      tname\n\n(* ---- Equality witnesses --------------------------------------------------*)\n\ntype ('ta, 'tb) eq = Eq : ('same, 'same) eq\n\nlet rec comparable_ty_eq :\n    type ta tb s.\n    context ->\n    (ta, s) comparable_struct ->\n    (tb, s) comparable_struct ->\n    (((ta, s) comparable_struct, (tb, s) comparable_struct) eq * context)\n    tzresult =\n fun ctxt ta tb ->\n  Gas.consume ctxt Typecheck_costs.cycle\n  >>? fun ctxt ->\n  match (ta, tb) with\n  | (Int_key _, Int_key _) ->\n      Ok\n        ((Eq : ((ta, s) comparable_struct, (tb, s) comparable_struct) eq), ctxt)\n  | (Nat_key _, Nat_key _) ->\n      Ok (Eq, ctxt)\n  | (String_key _, String_key _) ->\n      Ok (Eq, ctxt)\n  | (Bytes_key _, Bytes_key _) ->\n      Ok (Eq, ctxt)\n  | (Mutez_key _, Mutez_key _) ->\n      Ok (Eq, ctxt)\n  | (Bool_key _, Bool_key _) ->\n      Ok (Eq, ctxt)\n  | (Key_hash_key _, Key_hash_key _) ->\n      Ok (Eq, ctxt)\n  | (Timestamp_key _, Timestamp_key _) ->\n      Ok (Eq, ctxt)\n  | (Address_key _, Address_key _) ->\n      Ok (Eq, ctxt)\n  | ( Pair_key ((lefta, _), (righta, _), _),\n      Pair_key ((leftb, _), (rightb, _), _) ) ->\n      comparable_ty_eq ctxt lefta leftb\n      >>? fun (Eq, ctxt) ->\n      comparable_ty_eq ctxt righta rightb\n      >>? fun (Eq, ctxt) ->\n      Ok\n        ((Eq : ((ta, s) comparable_struct, (tb, s) comparable_struct) eq), 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 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 ty_eq :\n    type ta tb.\n    context -> ta ty -> tb ty -> ((ta ty, tb ty) eq * context) tzresult =\n fun ctxt ta tb ->\n  let ok (eq : (ta ty, tb ty) eq) ctxt nb_args :\n      ((ta ty, tb ty) eq * context) tzresult =\n    Gas.consume ctxt (Typecheck_costs.type_ (2 * nb_args))\n    >>? fun ctxt -> Ok (eq, ctxt)\n  in\n  Gas.consume ctxt Typecheck_costs.cycle\n  >>? fun ctxt ->\n  match (ta, tb) with\n  | (Unit_t _, Unit_t _) ->\n      ok Eq ctxt 0\n  | (Int_t _, Int_t _) ->\n      ok Eq ctxt 0\n  | (Nat_t _, Nat_t _) ->\n      ok Eq ctxt 0\n  | (Key_t _, Key_t _) ->\n      ok Eq ctxt 0\n  | (Key_hash_t _, Key_hash_t _) ->\n      ok Eq ctxt 0\n  | (String_t _, String_t _) ->\n      ok Eq ctxt 0\n  | (Bytes_t _, Bytes_t _) ->\n      ok Eq ctxt 0\n  | (Signature_t _, Signature_t _) ->\n      ok Eq ctxt 0\n  | (Mutez_t _, Mutez_t _) ->\n      ok Eq ctxt 0\n  | (Timestamp_t _, Timestamp_t _) ->\n      ok Eq ctxt 0\n  | (Chain_id_t _, Chain_id_t _) ->\n      ok Eq ctxt 0\n  | (Address_t _, Address_t _) ->\n      ok Eq ctxt 0\n  | (Bool_t _, Bool_t _) ->\n      ok Eq ctxt 0\n  | (Operation_t _, Operation_t _) ->\n      ok Eq ctxt 0\n  | (Map_t (tal, tar, _, _), Map_t (tbl, tbr, _, _)) ->\n      comparable_ty_eq ctxt tal tbl\n      >>? (fun (Eq, ctxt) ->\n            ty_eq ctxt tar tbr >>? fun (Eq, ctxt) -> ok Eq ctxt 2)\n      |> record_inconsistent ctxt ta tb\n  | (Big_map_t (tal, tar, _), Big_map_t (tbl, tbr, _)) ->\n      comparable_ty_eq ctxt tal tbl\n      >>? (fun (Eq, ctxt) ->\n            ty_eq ctxt tar tbr >>? fun (Eq, ctxt) -> ok Eq ctxt 2)\n      |> record_inconsistent ctxt ta tb\n  | (Set_t (ea, _), Set_t (eb, _)) ->\n      comparable_ty_eq ctxt ea eb\n      >>? (fun (Eq, ctxt) -> ok Eq ctxt 1)\n      |> record_inconsistent ctxt ta tb\n  | ( Pair_t ((tal, _, _), (tar, _, _), _, _),\n      Pair_t ((tbl, _, _), (tbr, _, _), _, _) ) ->\n      ty_eq ctxt tal tbl\n      >>? (fun (Eq, ctxt) ->\n            ty_eq ctxt tar tbr >>? fun (Eq, ctxt) -> ok Eq ctxt 2)\n      |> record_inconsistent ctxt ta tb\n  | (Union_t ((tal, _), (tar, _), _, _), Union_t ((tbl, _), (tbr, _), _, _)) ->\n      ty_eq ctxt tal tbl\n      >>? (fun (Eq, ctxt) ->\n            ty_eq ctxt tar tbr >>? fun (Eq, ctxt) -> ok Eq ctxt 2)\n      |> record_inconsistent ctxt ta tb\n  | (Lambda_t (tal, tar, _), Lambda_t (tbl, tbr, _)) ->\n      ty_eq ctxt tal tbl\n      >>? (fun (Eq, ctxt) ->\n            ty_eq ctxt tar tbr >>? fun (Eq, ctxt) -> ok Eq ctxt 2)\n      |> record_inconsistent ctxt ta tb\n  | (Contract_t (tal, _), Contract_t (tbl, _)) ->\n      ty_eq ctxt tal tbl\n      >>? (fun (Eq, ctxt) -> ok Eq ctxt 1)\n      |> record_inconsistent ctxt ta tb\n  | (Option_t (tva, _, _), Option_t (tvb, _, _)) ->\n      ty_eq ctxt tva tvb\n      >>? (fun (Eq, ctxt) -> ok Eq ctxt 1)\n      |> record_inconsistent ctxt ta tb\n  | (List_t (tva, _, _), List_t (tvb, _, _)) ->\n      ty_eq ctxt tva tvb\n      >>? (fun (Eq, ctxt) -> ok Eq ctxt 1)\n      |> record_inconsistent ctxt ta tb\n  | (_, _) ->\n      serialize_ty_for_error ctxt ta\n      >>? fun (ta, ctxt) ->\n      serialize_ty_for_error ctxt tb\n      >>? fun (tb, _ctxt) -> error (Inconsistent_types (ta, tb))\n\nlet rec stack_ty_eq :\n    type ta tb.\n    context ->\n    int ->\n    ta stack_ty ->\n    tb stack_ty ->\n    ((ta stack_ty, tb stack_ty) eq * context) tzresult =\n fun ctxt lvl ta tb ->\n  match (ta, tb) with\n  | (Item_t (tva, ra, _), Item_t (tvb, rb, _)) ->\n      ty_eq ctxt tva tvb\n      |> record_trace (Bad_stack_item lvl)\n      >>? fun (Eq, ctxt) ->\n      stack_ty_eq ctxt (lvl + 1) ra rb\n      >>? fun (Eq, ctxt) ->\n      (Ok (Eq, ctxt) : ((ta stack_ty, tb stack_ty) eq * context) tzresult)\n  | (Empty_t, Empty_t) ->\n      Ok (Eq, ctxt)\n  | (_, _) ->\n      error Bad_stack_length\n\nlet rec merge_comparable_types :\n    type ta s.\n    legacy:bool ->\n    (ta, s) comparable_struct ->\n    (ta, s) comparable_struct ->\n    (ta, s) comparable_struct tzresult =\n fun ~legacy ta tb ->\n  match (ta, tb) with\n  | (Int_key annot_a, Int_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b >|? fun annot -> Int_key annot\n  | (Nat_key annot_a, Nat_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b >|? fun annot -> Nat_key annot\n  | (String_key annot_a, String_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b\n      >|? fun annot -> String_key annot\n  | (Bytes_key annot_a, Bytes_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b >|? fun annot -> Bytes_key annot\n  | (Mutez_key annot_a, Mutez_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b >|? fun annot -> Mutez_key annot\n  | (Bool_key annot_a, Bool_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b >|? fun annot -> Bool_key annot\n  | (Key_hash_key annot_a, Key_hash_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b\n      >|? fun annot -> Key_hash_key annot\n  | (Timestamp_key annot_a, Timestamp_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b\n      >|? fun annot -> Timestamp_key annot\n  | (Address_key annot_a, Address_key annot_b) ->\n      merge_type_annot ~legacy annot_a annot_b\n      >|? fun annot -> Address_key annot\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 left_a left_b\n      >>? fun left ->\n      merge_comparable_types ~legacy right_a right_b\n      >|? fun right ->\n      Pair_key ((left, annot_left), (right, annot_right), annot)\n  | (_, _) ->\n      assert false\n\n(* FIXME: fix injectivity of some types *)\n\nlet merge_types :\n    type b.\n    legacy:bool ->\n    context ->\n    Script.location ->\n    b ty ->\n    b ty ->\n    (b ty * context) tzresult =\n fun ~legacy ->\n  let rec help : type a. context -> a ty -> a ty -> (a ty * context) tzresult =\n   fun ctxt ty1 ty2 ->\n    match (ty1, ty2) with\n    | (Unit_t tn1, Unit_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Unit_t tname, ctxt)\n    | (Int_t tn1, Int_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Int_t tname, ctxt)\n    | (Nat_t tn1, Nat_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Nat_t tname, ctxt)\n    | (Key_t tn1, Key_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Key_t tname, ctxt)\n    | (Key_hash_t tn1, Key_hash_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2\n        >|? fun tname -> (Key_hash_t tname, ctxt)\n    | (String_t tn1, String_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (String_t tname, ctxt)\n    | (Bytes_t tn1, Bytes_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Bytes_t tname, ctxt)\n    | (Signature_t tn1, Signature_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2\n        >|? fun tname -> (Signature_t tname, ctxt)\n    | (Mutez_t tn1, Mutez_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Mutez_t tname, ctxt)\n    | (Timestamp_t tn1, Timestamp_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2\n        >|? fun tname -> (Timestamp_t tname, ctxt)\n    | (Address_t tn1, Address_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2\n        >|? fun tname -> (Address_t tname, ctxt)\n    | (Bool_t tn1, Bool_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2 >|? fun tname -> (Bool_t tname, ctxt)\n    | (Chain_id_t tn1, Chain_id_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2\n        >|? fun tname -> (Chain_id_t tname, ctxt)\n    | (Operation_t tn1, Operation_t tn2) ->\n        merge_type_annot ~legacy tn1 tn2\n        >|? fun tname -> (Operation_t tname, ctxt)\n    | (Map_t (tal, tar, tn1, has_big_map), Map_t (tbl, tbr, tn2, _)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        help ctxt tar tbr\n        >>? fun (value, ctxt) ->\n        ty_eq ctxt tar value\n        >>? fun (Eq, ctxt) ->\n        merge_comparable_types ~legacy tal tbl\n        >|? fun tk -> (Map_t (tk, value, tname, has_big_map), ctxt)\n    | (Big_map_t (tal, tar, tn1), Big_map_t (tbl, tbr, tn2)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        help ctxt tar tbr\n        >>? fun (value, ctxt) ->\n        ty_eq ctxt tar value\n        >>? fun (Eq, ctxt) ->\n        merge_comparable_types ~legacy tal tbl\n        >|? fun tk -> (Big_map_t (tk, value, tname), ctxt)\n    | (Set_t (ea, tn1), Set_t (eb, tn2)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        merge_comparable_types ~legacy ea eb\n        >|? fun e -> (Set_t (e, tname), ctxt)\n    | ( Pair_t\n          ((tal, l_field1, l_var1), (tar, r_field1, r_var1), tn1, has_big_map),\n        Pair_t ((tbl, l_field2, l_var2), (tbr, r_field2, r_var2), tn2, _) ) ->\n        merge_type_annot ~legacy 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 (left_ty, ctxt) ->\n        help ctxt tar tbr\n        >|? fun (right_ty, ctxt) ->\n        ( Pair_t\n            ( (left_ty, l_field, l_var),\n              (right_ty, r_field, r_var),\n              tname,\n              has_big_map ),\n          ctxt )\n    | ( Union_t ((tal, tal_annot), (tar, tar_annot), tn1, has_big_map),\n        Union_t ((tbl, tbl_annot), (tbr, tbr_annot), tn2, _) ) ->\n        merge_type_annot ~legacy 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 (left_ty, ctxt) ->\n        help ctxt tar tbr\n        >|? fun (right_ty, ctxt) ->\n        ( Union_t\n            ((left_ty, left_annot), (right_ty, right_annot), tname, has_big_map),\n          ctxt )\n    | (Lambda_t (tal, tar, tn1), Lambda_t (tbl, tbr, tn2)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        help ctxt tal tbl\n        >>? fun (left_ty, ctxt) ->\n        help ctxt tar tbr\n        >|? fun (right_ty, ctxt) -> (Lambda_t (left_ty, right_ty, tname), ctxt)\n    | (Contract_t (tal, tn1), Contract_t (tbl, tn2)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        help ctxt tal tbl\n        >|? fun (arg_ty, ctxt) -> (Contract_t (arg_ty, tname), ctxt)\n    | (Option_t (tva, tn1, has_big_map), Option_t (tvb, tn2, _)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        help ctxt tva tvb\n        >|? fun (ty, ctxt) -> (Option_t (ty, tname, has_big_map), ctxt)\n    | (List_t (tva, tn1, has_big_map), List_t (tvb, tn2, _)) ->\n        merge_type_annot ~legacy tn1 tn2\n        >>? fun tname ->\n        help ctxt tva tvb\n        >|? fun (ty, ctxt) -> (List_t (ty, tname, has_big_map), ctxt)\n    | (_, _) ->\n        assert false\n  in\n  fun ctxt loc ty1 ty2 ->\n    record_inconsistent_type_annotations ctxt loc ty1 ty2 (help ctxt ty1 ty2)\n\nlet merge_stacks :\n    type ta.\n    legacy:bool ->\n    Script.location ->\n    context ->\n    ta stack_ty ->\n    ta stack_ty ->\n    (ta stack_ty * context) tzresult =\n fun ~legacy loc ->\n  let rec help :\n      type a.\n      context -> a stack_ty -> a stack_ty -> (a stack_ty * context) tzresult =\n   fun ctxt stack1 stack2 ->\n    match (stack1, stack2) with\n    | (Empty_t, Empty_t) ->\n        ok (Empty_t, ctxt)\n    | (Item_t (ty1, rest1, annot1), Item_t (ty2, rest2, annot2)) ->\n        let annot = merge_var_annot annot1 annot2 in\n        merge_types ~legacy ctxt loc ty1 ty2\n        >>? fun (ty, ctxt) ->\n        help ctxt rest1 rest2\n        >|? fun (rest, ctxt) -> (Item_t (ty, rest, annot), ctxt)\n  in\n  help\n\nlet has_big_map : type t. t ty -> bool = function\n  | Unit_t _ ->\n      false\n  | Int_t _ ->\n      false\n  | Nat_t _ ->\n      false\n  | Signature_t _ ->\n      false\n  | String_t _ ->\n      false\n  | Bytes_t _ ->\n      false\n  | Mutez_t _ ->\n      false\n  | Key_hash_t _ ->\n      false\n  | Key_t _ ->\n      false\n  | Timestamp_t _ ->\n      false\n  | Address_t _ ->\n      false\n  | Bool_t _ ->\n      false\n  | Lambda_t (_, _, _) ->\n      false\n  | Set_t (_, _) ->\n      false\n  | Big_map_t (_, _, _) ->\n      true\n  | Contract_t (_, _) ->\n      false\n  | Operation_t _ ->\n      false\n  | Chain_id_t _ ->\n      false\n  | Pair_t (_, _, _, has_big_map) ->\n      has_big_map\n  | Union_t (_, _, _, has_big_map) ->\n      has_big_map\n  | Option_t (_, _, has_big_map) ->\n      has_big_map\n  | List_t (_, _, has_big_map) ->\n      has_big_map\n  | Map_t (_, _, _, has_big_map) ->\n      has_big_map\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 Lwt.t =\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      trace_eval\n        unmatched_branches\n        ( Lwt.return (stack_ty_eq ctxt 1 aftbt aftbf)\n        >>=? fun (Eq, ctxt) ->\n        Lwt.return (merge_stacks ~legacy loc ctxt aftbt aftbf)\n        >>=? fun (merged_stack, ctxt) ->\n        return\n          ( Typed\n              (branch\n                 {dbt with aft = merged_stack}\n                 {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      return (Failed {descr}, ctxt)\n  | (Typed dbt, Failed {descr = descrf}) ->\n      return (Typed (branch dbt (descrf dbt.aft)), ctxt)\n  | (Failed {descr = descrt}, Typed dbf) ->\n      return (Typed (branch (descrt dbf.aft) dbf), ctxt)\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.cycle\n  >>? fun ctxt ->\n  Gas.consume ctxt (Typecheck_costs.type_ 0)\n  >>? fun ctxt ->\n  match ty with\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_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_timestamp, [], annot) ->\n      parse_type_annot loc annot\n      >|? fun tname -> (Ex_comparable_ty (Timestamp_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_int\n          | T_nat\n          | T_string\n          | T_mutez\n          | T_bool\n          | T_key\n          | T_address\n          | T_timestamp ) 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      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      let right = (right, right_annot) in\n      match left with\n      | Pair_key _ ->\n          error (Comparable_type_expected (loc, Micheline.strip_locations ty))\n      | Int_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Int_key tname, left_annot), right, pname)),\n              ctxt )\n      | Nat_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Nat_key tname, left_annot), right, pname)),\n              ctxt )\n      | String_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((String_key tname, left_annot), right, pname)),\n              ctxt )\n      | Bytes_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Bytes_key tname, left_annot), right, pname)),\n              ctxt )\n      | Mutez_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Mutez_key tname, left_annot), right, pname)),\n              ctxt )\n      | Bool_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Bool_key tname, left_annot), right, pname)),\n              ctxt )\n      | Key_hash_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Key_hash_key tname, left_annot), right, pname)),\n              ctxt )\n      | Timestamp_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Timestamp_key tname, left_annot), right, pname)),\n              ctxt )\n      | Address_key tname ->\n          ok\n            ( Ex_comparable_ty\n                (Pair_key ((Address_key tname, left_annot), right, pname)),\n              ctxt ) )\n  | Prim (loc, T_pair, l, _) ->\n      error (Invalid_arity (loc, T_pair, 2, List.length l))\n  | Prim\n      ( loc,\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        _,\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_int;\n             T_nat;\n             T_string;\n             T_mutez;\n             T_bool;\n             T_key;\n             T_key_hash;\n             T_timestamp ]\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_big_map:false\n    ~allow_operation:false\n    ~allow_contract:legacy\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_big_map:true\n    ~allow_operation:false\n    ~allow_contract: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_big_map:true\n    ~allow_operation:true\n    ~allow_contract:true\n\nand parse_ty :\n    context ->\n    legacy:bool ->\n    allow_big_map:bool ->\n    allow_operation:bool ->\n    allow_contract:bool ->\n    Script.node ->\n    (ex_ty * context) tzresult =\n fun ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract node ->\n  Gas.consume ctxt Typecheck_costs.cycle\n  >>? fun ctxt ->\n  match node with\n  | Prim (loc, T_unit, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Unit_t ty_name), ctxt)\n  | Prim (loc, T_int, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Int_t ty_name), ctxt)\n  | Prim (loc, T_nat, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Nat_t ty_name), ctxt)\n  | Prim (loc, T_string, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (String_t ty_name), ctxt)\n  | Prim (loc, T_bytes, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Bytes_t ty_name), ctxt)\n  | Prim (loc, T_mutez, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Mutez_t ty_name), ctxt)\n  | Prim (loc, T_bool, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Bool_t ty_name), ctxt)\n  | Prim (loc, T_key, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Key_t ty_name), ctxt)\n  | Prim (loc, T_key_hash, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Key_hash_t ty_name), ctxt)\n  | Prim (loc, T_timestamp, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Timestamp_t ty_name), ctxt)\n  | Prim (loc, T_address, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Address_t ty_name), ctxt)\n  | Prim (loc, T_signature, [], annot) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (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 ->\n        Gas.consume ctxt (Typecheck_costs.type_ 0)\n        >|? fun ctxt -> (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 ->\n      Gas.consume ctxt (Typecheck_costs.type_ 0)\n      >|? fun ctxt -> (Ex_ty (Chain_id_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 ->\n        Gas.consume ctxt (Typecheck_costs.type_ 1)\n        >|? fun ctxt -> (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      extract_field_annot utr\n      >>? fun (utr, right_field) ->\n      parse_ty ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract utl\n      >>? fun (Ex_ty tl, ctxt) ->\n      parse_ty ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract utr\n      >>? fun (Ex_ty tr, ctxt) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 2)\n      >|? fun ctxt ->\n      ( Ex_ty\n          (Pair_t\n             ( (tl, left_field, None),\n               (tr, right_field, None),\n               ty_name,\n               has_big_map tl || has_big_map tr )),\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 ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract utl\n      >>? fun (Ex_ty tl, ctxt) ->\n      parse_ty ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract utr\n      >>? fun (Ex_ty tr, ctxt) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 2)\n      >|? fun ctxt ->\n      ( Ex_ty\n          (Union_t\n             ( (tl, left_constr),\n               (tr, right_constr),\n               ty_name,\n               has_big_map tl || has_big_map tr )),\n        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 ->\n      Gas.consume ctxt (Typecheck_costs.type_ 2)\n      >|? fun ctxt -> (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 ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract ut\n      >>? fun (Ex_ty t, ctxt) ->\n      Gas.consume ctxt (Typecheck_costs.type_ 2)\n      >|? fun ctxt -> (Ex_ty (Option_t (t, ty_name, has_big_map t)), ctxt)\n  | Prim (loc, T_list, [ut], annot) ->\n      parse_ty ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract ut\n      >>? fun (Ex_ty t, ctxt) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 1)\n      >|? fun ctxt -> (Ex_ty (List_t (t, ty_name, has_big_map t)), ctxt)\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 ->\n      Gas.consume ctxt (Typecheck_costs.type_ 1)\n      >|? fun ctxt -> (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 ctxt ~legacy ~allow_big_map ~allow_operation ~allow_contract utr\n      >>? fun (Ex_ty tr, ctxt) ->\n      parse_type_annot loc annot\n      >>? fun ty_name ->\n      Gas.consume ctxt (Typecheck_costs.type_ 2)\n      >|? fun ctxt -> (Ex_ty (Map_t (ta, tr, ty_name, has_big_map tr)), ctxt)\n  | Prim (loc, T_big_map, args, annot) when allow_big_map ->\n      parse_big_map_ty ctxt ~legacy loc args annot\n      >>? fun (big_map_ty, ctxt) ->\n      Gas.consume ctxt (Typecheck_costs.type_ 2)\n      >|? fun ctxt -> (big_map_ty, ctxt)\n  | Prim (loc, T_big_map, _, _) ->\n      error (Unexpected_big_map 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 ) as prim ),\n        l,\n        _ ) ->\n      error (Invalid_arity (loc, prim, 0, List.length l))\n  | Prim (loc, ((T_set | T_list | T_option | T_contract) as prim), l, _) ->\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\nand parse_big_map_ty ctxt ~legacy big_map_loc args map_annot =\n  Gas.consume ctxt Typecheck_costs.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_packable_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_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_ty\n          ctxt\n          ~legacy\n          ~allow_big_map:true\n          ~allow_operation:false\n          ~allow_contract:legacy\n          node\n    | [single]\n      when Compare.Int.(String.length single > 0)\n           && Compare.Char.(single.[0] = '%') ->\n        parse_ty\n          ctxt\n          ~legacy\n          ~allow_big_map:true\n          ~allow_operation:false\n          ~allow_contract:legacy\n          node\n    | _ ->\n        (* legacy semantics of big maps used the wrong annotation parser *)\n        Gas.consume ctxt Typecheck_costs.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_ty\n          ctxt\n          ~legacy\n          ~allow_big_map:true\n          ~allow_operation:false\n          ~allow_contract:legacy\n          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        Gas.consume ctxt (Typecheck_costs.type_ 5)\n        >|? fun ctxt ->\n        ( Ex_ty\n            (Pair_t\n               ( (big_map_ty, map_field, None),\n                 (remaining_storage, storage_field, None),\n                 ty_name,\n                 true )),\n          ctxt ) )\n  | _ ->\n      parse_ty\n        ctxt\n        ~legacy\n        ~allow_big_map:true\n        ~allow_operation:false\n        ~allow_contract:legacy\n        node\n\nlet check_packable ~legacy loc root =\n  let rec check : type t. t ty -> unit tzresult = function\n    | Big_map_t _ ->\n        error (Unexpected_big_map loc)\n    | Operation_t _ ->\n        error (Unexpected_operation loc)\n    | Unit_t _ ->\n        ok ()\n    | Int_t _ ->\n        ok ()\n    | Nat_t _ ->\n        ok ()\n    | Signature_t _ ->\n        ok ()\n    | String_t _ ->\n        ok ()\n    | Bytes_t _ ->\n        ok ()\n    | Mutez_t _ ->\n        ok ()\n    | Key_hash_t _ ->\n        ok ()\n    | Key_t _ ->\n        ok ()\n    | Timestamp_t _ ->\n        ok ()\n    | Address_t _ ->\n        ok ()\n    | Bool_t _ ->\n        ok ()\n    | Chain_id_t _ ->\n        ok ()\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    | Set_t (_, _) ->\n        ok ()\n    | Map_t (_, elt_ty, _, _) ->\n        check elt_ty\n    | Lambda_t (_l_ty, _r_ty, _) ->\n        ok ()\n    | Contract_t (_, _) when legacy ->\n        ok ()\n    | Contract_t (_, _) ->\n        error (Unexpected_contract loc)\n  in\n  check root\n\ntype ex_script = Ex_script : ('a, 'c) script -> ex_script\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\n(* Lwt versions *)\nlet parse_var_annot loc ?default annot =\n  Lwt.return (parse_var_annot loc ?default annot)\n\nlet parse_entrypoint_annot loc ?default annot =\n  Lwt.return (parse_entrypoint_annot loc ?default annot)\n\nlet parse_constr_annot loc ?if_special_first ?if_special_second annot =\n  Lwt.return\n    (parse_constr_annot loc ?if_special_first ?if_special_second annot)\n\nlet parse_two_var_annot loc annot = Lwt.return (parse_two_var_annot loc annot)\n\nlet parse_destr_annot loc annot ~default_accessor ~field_name ~pair_annot\n    ~value_annot =\n  Lwt.return\n    (parse_destr_annot\n       loc\n       annot\n       ~default_accessor\n       ~field_name\n       ~pair_annot\n       ~value_annot)\n\nlet parse_var_type_annot loc annot =\n  Lwt.return (parse_var_type_annot loc annot)\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 root_name when Compare.String.(entrypoint = root_name) ->\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) ~(full : full ty)\n    ~(expected : exp ty) ~root_name entrypoint ctxt :\n    (context * string * exp ty) tzresult =\n  match (entrypoint, root_name) with\n  | (\"default\", Some \"root\") -> (\n    match find_entrypoint full ~root_name entrypoint with\n    | Error _ as err ->\n        err\n    | Ok (_, Ex_ty ty) -> (\n      match ty_eq ctxt expected ty with\n      | Ok (Eq, ctxt) ->\n          ok (ctxt, \"default\", (ty : exp ty))\n      | Error _ ->\n          ty_eq ctxt expected full\n          >>? fun (Eq, ctxt) -> ok (ctxt, \"root\", (full : exp ty)) ) )\n  | _ ->\n      find_entrypoint full ~root_name entrypoint\n      >>? fun (_, Ex_ty ty) ->\n      ty_eq ctxt expected ty\n      >>? fun (Eq, 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 \"\" ->\n          (Entrypoints.empty, false)\n      | Some 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 ()\n    else\n      match first_unreachable with\n      | None ->\n          ok ()\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 rec parse_data :\n    type a.\n    ?type_logger:type_logger ->\n    context ->\n    legacy:bool ->\n    a ty ->\n    Script.node ->\n    (a * context) tzresult Lwt.t =\n fun ?type_logger ctxt ~legacy ty script_data ->\n  Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n  >>=? fun ctxt ->\n  let error () =\n    Lwt.return (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 traced body = trace_eval error body in\n  let parse_items ?type_logger loc ctxt expr key_type value_type items\n      item_wrapper =\n    let length = List.length items in\n    fold_left_s\n      (fun (last_value, map, ctxt) item ->\n        Lwt.return (Gas.consume ctxt (Typecheck_costs.map_element length))\n        >>=? fun ctxt ->\n        match item with\n        | Prim (_, D_Elt, [k; v], _) ->\n            parse_comparable_data ?type_logger ctxt key_type k\n            >>=? fun (k, ctxt) ->\n            parse_data ?type_logger ctxt ~legacy value_type v\n            >>=? fun (v, ctxt) ->\n            ( match last_value with\n            | Some value ->\n                if Compare.Int.(0 <= compare_comparable key_type value k) then\n                  if Compare.Int.(0 = compare_comparable key_type value k) then\n                    fail (Duplicate_map_keys (loc, strip_locations expr))\n                  else fail (Unordered_map_keys (loc, strip_locations expr))\n                else return_unit\n            | None ->\n                return_unit )\n            >>=? fun () ->\n            return (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            error () >>=? fail)\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 *)\n  | (Unit_t _, Prim (loc, D_Unit, [], annot)) ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.unit)\n      >>|? fun ctxt -> ((() : a), ctxt)\n  | (Unit_t _, Prim (loc, D_Unit, l, _)) ->\n      traced (fail (Invalid_arity (loc, D_Unit, 0, List.length l)))\n  | (Unit_t _, expr) ->\n      traced (fail (unexpected expr [] Constant_namespace [D_Unit]))\n  (* Booleans *)\n  | (Bool_t _, Prim (loc, D_True, [], annot)) ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.bool)\n      >>|? fun ctxt -> (true, ctxt)\n  | (Bool_t _, Prim (loc, D_False, [], annot)) ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.bool)\n      >>|? fun ctxt -> (false, ctxt)\n  | (Bool_t _, Prim (loc, ((D_True | D_False) as c), l, _)) ->\n      traced (fail (Invalid_arity (loc, c, 0, List.length l)))\n  | (Bool_t _, expr) ->\n      traced (fail (unexpected expr [] Constant_namespace [D_True; D_False]))\n  (* Strings *)\n  | (String_t _, String (_, v)) ->\n      Lwt.return (Gas.consume ctxt (Typecheck_costs.string (String.length 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 return (v, ctxt)\n      else error () >>=? fail\n  | (String_t _, expr) ->\n      traced (fail (Invalid_kind (location expr, [String_kind], kind expr)))\n  (* Byte sequences *)\n  | (Bytes_t _, Bytes (_, v)) ->\n      Lwt.return (Gas.consume ctxt (Typecheck_costs.string (MBytes.length v)))\n      >>=? fun ctxt -> return (v, ctxt)\n  | (Bytes_t _, expr) ->\n      traced (fail (Invalid_kind (location expr, [Bytes_kind], kind expr)))\n  (* Integers *)\n  | (Int_t _, Int (_, v)) ->\n      Lwt.return (Gas.consume ctxt (Typecheck_costs.z v))\n      >>=? fun ctxt -> return (Script_int.of_zint v, ctxt)\n  | (Nat_t _, Int (_, v)) ->\n      Lwt.return (Gas.consume ctxt (Typecheck_costs.z v))\n      >>=? fun ctxt ->\n      let v = Script_int.of_zint v in\n      if Compare.Int.(Script_int.compare v Script_int.zero >= 0) then\n        return (Script_int.abs v, ctxt)\n      else error () >>=? fail\n  | (Int_t _, expr) ->\n      traced (fail (Invalid_kind (location expr, [Int_kind], kind expr)))\n  | (Nat_t _, expr) ->\n      traced (fail (Invalid_kind (location expr, [Int_kind], kind expr)))\n  (* Tez amounts *)\n  | (Mutez_t _, Int (_, v)) -> (\n      Lwt.return\n        ( Gas.consume ctxt Typecheck_costs.tez\n        >>? fun ctxt ->\n        Gas.consume ctxt Michelson_v1_gas.Cost_of.Legacy.z_to_int64 )\n      >>=? fun ctxt ->\n      try\n        match Tez.of_mutez (Z.to_int64 v) with\n        | None ->\n            raise Exit\n        | Some tez ->\n            return (tez, ctxt)\n      with _ -> error () >>=? fail )\n  | (Mutez_t _, expr) ->\n      traced (fail (Invalid_kind (location expr, [Int_kind], kind expr)))\n  (* Timestamps *)\n  | (Timestamp_t _, Int (_, v))\n  (* As unparsed with [Optimized] or out of bounds [Readable]. *) ->\n      Lwt.return (Gas.consume ctxt (Typecheck_costs.z v))\n      >>=? fun ctxt -> return (Script_timestamp.of_zint v, ctxt)\n  | (Timestamp_t _, String (_, s)) (* As unparsed with [Redable]. *) -> (\n      Lwt.return (Gas.consume ctxt Typecheck_costs.string_timestamp)\n      >>=? fun ctxt ->\n      match Script_timestamp.of_string s with\n      | Some v ->\n          return (v, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Timestamp_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Int_kind], kind expr)))\n  (* IDs *)\n  | (Key_t _, Bytes (_, bytes)) -> (\n      (* As unparsed with [Optimized]. *)\n      Lwt.return (Gas.consume ctxt Typecheck_costs.key)\n      >>=? fun ctxt ->\n      match\n        Data_encoding.Binary.of_bytes Signature.Public_key.encoding bytes\n      with\n      | Some k ->\n          return (k, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Key_t _, String (_, s)) -> (\n      (* As unparsed with [Readable]. *)\n      Lwt.return (Gas.consume ctxt Typecheck_costs.key)\n      >>=? fun ctxt ->\n      match Signature.Public_key.of_b58check_opt s with\n      | Some k ->\n          return (k, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Key_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)))\n  | (Key_hash_t _, Bytes (_, bytes)) -> (\n      (* As unparsed with [Optimized]. *)\n      Lwt.return (Gas.consume ctxt Typecheck_costs.key_hash)\n      >>=? fun ctxt ->\n      match\n        Data_encoding.Binary.of_bytes Signature.Public_key_hash.encoding bytes\n      with\n      | Some k ->\n          return (k, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Key_hash_t _, String (_, s)) (* As unparsed with [Readable]. *) -> (\n      Lwt.return (Gas.consume ctxt Typecheck_costs.key_hash)\n      >>=? fun ctxt ->\n      match Signature.Public_key_hash.of_b58check_opt s with\n      | Some k ->\n          return (k, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Key_hash_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)))\n  (* Signatures *)\n  | (Signature_t _, Bytes (_, bytes)) (* As unparsed with [Optimized]. *) -> (\n      Lwt.return (Gas.consume ctxt Typecheck_costs.signature)\n      >>=? fun ctxt ->\n      match Data_encoding.Binary.of_bytes Signature.encoding bytes with\n      | Some k ->\n          return (k, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Signature_t _, String (_, s)) (* As unparsed with [Readable]. *) -> (\n      Lwt.return (Gas.consume ctxt Typecheck_costs.signature)\n      >>=? fun ctxt ->\n      match Signature.of_b58check_opt s with\n      | Some s ->\n          return (s, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Signature_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)))\n  (* Operations *)\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_ids *)\n  | (Chain_id_t _, Bytes (_, bytes)) -> (\n      Lwt.return (Gas.consume ctxt Typecheck_costs.chain_id)\n      >>=? fun ctxt ->\n      match Data_encoding.Binary.of_bytes Chain_id.encoding bytes with\n      | Some k ->\n          return (k, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Chain_id_t _, String (_, s)) -> (\n      Lwt.return (Gas.consume ctxt Typecheck_costs.chain_id)\n      >>=? fun ctxt ->\n      match Chain_id.of_b58check_opt s with\n      | Some s ->\n          return (s, ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Chain_id_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)))\n  (* Addresses *)\n  | (Address_t _, Bytes (loc, bytes)) (* As unparsed with [O[ptimized]. *) -> (\n      Lwt.return (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            fail (Entrypoint_name_too_long entrypoint)\n          else\n            ( match entrypoint with\n            | \"\" ->\n                return \"default\"\n            | \"default\" ->\n                fail (Unexpected_annotation loc)\n            | name ->\n                return name )\n            >>=? fun entrypoint -> return ((c, entrypoint), ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Address_t _, String (loc, s)) (* As unparsed with [Readable]. *) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.contract)\n      >>=? fun ctxt ->\n      ( match String.index_opt s '%' with\n      | None ->\n          return (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 fail (Entrypoint_name_too_long name)\n          else\n            match (String.sub s 0 pos, name) with\n            | (_, \"default\") ->\n                traced (fail (Unexpected_annotation loc))\n            | addr_and_name ->\n                return addr_and_name ) )\n      >>=? fun (addr, entrypoint) ->\n      Lwt.return (Contract.of_b58check addr)\n      >>=? fun c -> return ((c, entrypoint), ctxt)\n  | (Address_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)))\n  (* Contracts *)\n  | (Contract_t (ty, _), Bytes (loc, bytes))\n  (* As unparsed with [Optimized]. *) -> (\n      Lwt.return (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            fail (Entrypoint_name_too_long entrypoint)\n          else\n            ( match entrypoint with\n            | \"\" ->\n                return \"default\"\n            | \"default\" ->\n                traced (fail (Unexpected_annotation loc))\n            | name ->\n                return name )\n            >>=? fun entrypoint ->\n            traced (parse_contract ~legacy ctxt loc ty c ~entrypoint)\n            >>=? fun (ctxt, _) -> return ((ty, (c, entrypoint)), ctxt)\n      | None ->\n          error () >>=? fail )\n  | (Contract_t (ty, _), String (loc, s)) (* As unparsed with [Readable]. *) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.contract)\n      >>=? fun ctxt ->\n      ( match String.index_opt s '%' with\n      | None ->\n          return (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 fail (Entrypoint_name_too_long name)\n          else\n            match (String.sub s 0 pos, name) with\n            | (_, \"default\") ->\n                traced (fail (Unexpected_annotation loc))\n            | addr_and_name ->\n                return addr_and_name ) )\n      >>=? fun (addr, entrypoint) ->\n      traced (Lwt.return (Contract.of_b58check addr))\n      >>=? fun c ->\n      parse_contract ~legacy ctxt loc ty c ~entrypoint\n      >>=? fun (ctxt, _) -> return ((ty, (c, entrypoint)), ctxt)\n  | (Contract_t _, expr) ->\n      traced\n        (fail\n           (Invalid_kind (location expr, [String_kind; Bytes_kind], kind expr)))\n  (* Pairs *)\n  | (Pair_t ((ta, _, _), (tb, _, _), _, _), Prim (loc, D_Pair, [va; vb], annot))\n    ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.pair)\n      >>=? fun ctxt ->\n      traced @@ parse_data ?type_logger ctxt ~legacy ta va\n      >>=? fun (va, ctxt) ->\n      parse_data ?type_logger ctxt ~legacy tb vb\n      >>=? fun (vb, ctxt) -> return ((va, vb), ctxt)\n  | (Pair_t _, Prim (loc, D_Pair, l, _)) ->\n      fail @@ Invalid_arity (loc, D_Pair, 2, List.length l)\n  | (Pair_t _, expr) ->\n      traced (fail (unexpected expr [] Constant_namespace [D_Pair]))\n  (* Unions *)\n  | (Union_t ((tl, _), _, _, _), Prim (loc, D_Left, [v], annot)) ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.union)\n      >>=? fun ctxt ->\n      traced @@ parse_data ?type_logger ctxt ~legacy tl v\n      >>=? fun (v, ctxt) -> return (L v, ctxt)\n  | (Union_t _, Prim (loc, D_Left, l, _)) ->\n      fail @@ Invalid_arity (loc, D_Left, 1, List.length l)\n  | (Union_t (_, (tr, _), _, _), Prim (loc, D_Right, [v], annot)) ->\n      fail_unexpected_annot loc annot\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.union)\n      >>=? fun ctxt ->\n      traced @@ parse_data ?type_logger ctxt ~legacy tr v\n      >>=? fun (v, ctxt) -> return (R v, ctxt)\n  | (Union_t _, Prim (loc, D_Right, l, _)) ->\n      fail @@ Invalid_arity (loc, D_Right, 1, List.length l)\n  | (Union_t _, expr) ->\n      traced (fail (unexpected expr [] Constant_namespace [D_Left; D_Right]))\n  (* Lambdas *)\n  | (Lambda_t (ta, tr, _ty_name), (Seq (_loc, _) as script_instr)) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.lambda)\n      >>=? fun ctxt ->\n      traced\n      @@ parse_returning\n           Lambda\n           ?type_logger\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, _, _), Prim (loc, D_Some, [v], annot)) ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.some)\n      >>=? fun ctxt ->\n      traced @@ parse_data ?type_logger ctxt ~legacy t v\n      >>=? fun (v, ctxt) -> return (Some v, ctxt)\n  | (Option_t _, Prim (loc, D_Some, l, _)) ->\n      fail @@ Invalid_arity (loc, D_Some, 1, List.length l)\n  | (Option_t (_, _, _), Prim (loc, D_None, [], annot)) ->\n      (if legacy then return () else fail_unexpected_annot loc annot)\n      >>=? fun () ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.none)\n      >>=? fun ctxt -> return (None, ctxt)\n  | (Option_t _, Prim (loc, D_None, l, _)) ->\n      fail @@ Invalid_arity (loc, D_None, 0, List.length l)\n  | (Option_t _, expr) ->\n      traced (fail (unexpected expr [] Constant_namespace [D_Some; D_None]))\n  (* Lists *)\n  | (List_t (t, _ty_name, _), Seq (_loc, items)) ->\n      traced\n      @@ fold_right_s\n           (fun v (rest, ctxt) ->\n             Lwt.return (Gas.consume ctxt Typecheck_costs.list_element)\n             >>=? fun ctxt ->\n             parse_data ?type_logger ctxt ~legacy t v\n             >>=? fun (v, ctxt) -> return (v :: rest, ctxt))\n           items\n           ([], ctxt)\n  | (List_t _, expr) ->\n      traced (fail (Invalid_kind (location expr, [Seq_kind], kind expr)))\n  (* Sets *)\n  | (Set_t (t, _ty_name), (Seq (loc, vs) as expr)) ->\n      let length = List.length vs in\n      traced\n      @@ fold_left_s\n           (fun (last_value, set, ctxt) v ->\n             Lwt.return (Gas.consume ctxt (Typecheck_costs.set_element length))\n             >>=? fun ctxt ->\n             parse_comparable_data ?type_logger ctxt t v\n             >>=? fun (v, ctxt) ->\n             ( match last_value with\n             | Some value ->\n                 if Compare.Int.(0 <= compare_comparable t value v) then\n                   if Compare.Int.(0 = compare_comparable t value v) then\n                     fail (Duplicate_set_values (loc, strip_locations expr))\n                   else fail (Unordered_set_values (loc, strip_locations expr))\n                 else return_unit\n             | None ->\n                 return_unit )\n             >>=? fun () ->\n             Lwt.return\n               (Gas.consume\n                  ctxt\n                  (Michelson_v1_gas.Cost_of.Legacy.set_update v false set))\n             >>=? fun ctxt -> return (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 (loc, vs) as expr)) ->\n      parse_items ?type_logger loc 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), (Seq (loc, vs) as expr)) ->\n      parse_items ?type_logger loc ctxt expr tk tv vs (fun x -> Some x)\n      >>|? fun (diff, ctxt) ->\n      ( {id = None; diff; key_type = ty_of_comparable_ty tk; value_type = tv},\n        ctxt )\n  | (Big_map_t (tk, tv, _ty_name), Int (loc, id)) -> (\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_packable_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 tv btv\n            >>? fun (Eq, ctxt) ->\n            ok\n              ( {\n                  id = Some id;\n                  diff = empty_map tk;\n                  key_type = ty_of_comparable_ty tk;\n                  value_type = tv;\n                },\n                ctxt ) ) )\n  | (Big_map_t (_tk, _tv, _), expr) ->\n      traced\n        (fail (Invalid_kind (location expr, [Seq_kind; Int_kind], kind expr)))\n\nand 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  parse_data\n    ?type_logger\n    ctxt\n    ~legacy:false\n    (ty_of_comparable_ty ty)\n    script_data\n\nand parse_returning :\n    type arg ret.\n    ?type_logger:type_logger ->\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 tc_context ctxt ~legacy (arg, arg_annot) ret script_instr ->\n  parse_instr\n    ?type_logger\n    tc_context\n    ctxt\n    ~legacy\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      trace_eval\n        (fun () ->\n          Lwt.return (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        ( Lwt.return (ty_eq ctxt ty ret)\n        >>=? fun (Eq, ctxt) ->\n        Lwt.return (merge_types ~legacy ctxt loc ty ret)\n        >>=? fun (_ret, ctxt) ->\n        return ((Lam (descr, script_instr) : (arg, ret) lambda), ctxt) )\n  | (Typed {loc; aft = stack_ty; _}, ctxt) ->\n      Lwt.return (serialize_ty_for_error ctxt ret)\n      >>=? fun (ret, ctxt) ->\n      serialize_stack_for_error ctxt stack_ty\n      >>=? fun (stack_ty, _ctxt) -> fail (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_int32 (n : (location, prim) Micheline.node) : int tzresult =\n  let error' () =\n    Invalid_syntactic_constant\n      ( location n,\n        strip_locations n,\n        \"a positive 32-bit integer (between 0 and \"\n        ^ Int32.to_string Int32.max_int\n        ^ \")\" )\n  in\n  match n with\n  | Micheline.Int (_, n') -> (\n    try\n      let n'' = Z.to_int n' in\n      if\n        Compare.Int.(0 <= n'')\n        && Compare.Int.(n'' <= Int32.to_int Int32.max_int)\n      then ok n''\n      else error @@ error' ()\n    with _ -> error @@ error' () )\n  | _ ->\n      error @@ error' ()\n\nand parse_instr :\n    type bef.\n    ?type_logger:type_logger ->\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 tc_context ctxt ~legacy script_instr stack_ty ->\n  let _check_item check loc name n m =\n    trace_eval (fun () ->\n        serialize_stack_for_error ctxt stack_ty\n        >>|? fun (stack_ty, _ctxt) -> Bad_stack (loc, name, m, stack_ty))\n    @@ trace (Bad_stack_item n) @@ Lwt.return check\n  in\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 Lwt.t =\n    trace_eval (fun () ->\n        serialize_stack_for_error ctxt stack_ty\n        >>|? fun (stack_ty, _ctxt) -> Bad_stack (loc, name, m, stack_ty))\n    @@ trace (Bad_stack_item n)\n    @@ Lwt.return\n         ( ty_eq ctxt exp got\n         >>? fun (Eq, ctxt) ->\n         merge_types ~legacy ctxt loc exp got\n         >>? fun (ty, ctxt) -> ok ((Eq : (a, b) eq), (ty : a ty), ctxt) )\n  in\n  let check_item_comparable_ty (type a b) (exp : a comparable_ty)\n      (got : b comparable_ty) loc name n m :\n      ((a, b) eq * a comparable_ty * context) tzresult Lwt.t =\n    trace_eval (fun () ->\n        serialize_stack_for_error ctxt stack_ty\n        >>|? fun (stack_ty, _ctxt) -> Bad_stack (loc, name, m, stack_ty))\n    @@ trace (Bad_stack_item n)\n    @@ Lwt.return\n         ( comparable_ty_eq ctxt exp got\n         >>? fun (Eq, ctxt) ->\n         merge_comparable_types ~legacy exp got\n         >>? fun ty -> ok ((Eq : (a, b) eq), (ty : a comparable_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        return_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\n        >>=? fun (aft, _) -> log loc stack_ty aft ; return_unit\n  in\n  let outer_return = return in\n  let return :\n      type bef.\n      context -> bef judgement -> (bef judgement * context) tzresult Lwt.t =\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          fail (Type_too_large (loc, type_size, maximum_type_size))\n        else return (judgement, ctxt)\n    | Failed _ ->\n        return (judgement, ctxt)\n  in\n  let typed ctxt loc instr aft =\n    log_stack ctxt loc stack_ty aft\n    >>=? fun () ->\n    Lwt.return @@ Gas.consume ctxt (Typecheck_costs.instr instr)\n    >>=? fun ctxt -> return ctxt (Typed {loc; instr; bef = stack_ty; aft})\n  in\n  Lwt.return @@ Gas.consume ctxt Typecheck_costs.cycle\n  >>=? fun ctxt ->\n  match (script_instr, stack_ty) with\n  (* stack ops *)\n  | (Prim (loc, I_DROP, [], annot), Item_t (_, rest, _)) ->\n      ( fail_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      Lwt.return (parse_int32 n)\n      >>=? fun whole_n ->\n      let rec make_proof_argument :\n          type tstk.\n          int -> tstk stack_ty -> tstk dropn_proof_argument tzresult Lwt.t =\n       fun n stk ->\n        match (Compare.Int.(n = 0), stk) with\n        | (true, rest) ->\n            outer_return @@ 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            outer_return\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            fail (Bad_stack (loc, I_DROP, whole_n, whole_stack))\n      in\n      fail_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      typed ctxt loc Dup (Item_t (v, Item_t (v, rest, stack_annot), annot))\n  | (Prim (loc, I_DIG, [n], result_annot), stack) ->\n      let rec make_proof_argument :\n          type tstk.\n          int -> tstk stack_ty -> tstk dig_proof_argument tzresult Lwt.t =\n       fun n stk ->\n        match (Compare.Int.(n = 0), stk) with\n        | (true, Item_t (v, rest, annot)) ->\n            outer_return @@ 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            outer_return\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            fail (Bad_stack (loc, I_DIG, 1, whole_stack))\n      in\n      Lwt.return (parse_int32 n)\n      >>=? fun n ->\n      fail_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      Lwt.return (parse_int32 n)\n      >>=? fun whole_n ->\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 Lwt.t =\n       fun n x stack_annot stk ->\n        match (Compare.Int.(n = 0), stk) with\n        | (true, rest) ->\n            outer_return\n            @@ 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            outer_return\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            fail (Bad_stack (loc, I_DUG, whole_n, whole_stack))\n      in\n      fail_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      fail_unexpected_annot loc result_annot\n      >>=? fun () ->\n      serialize_stack_for_error ctxt stack\n      >>=? fun (stack, _ctxt) -> fail (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      fail_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      Lwt.return @@ parse_packable_ty ctxt ~legacy t\n      >>=? fun (Ex_ty t, ctxt) ->\n      parse_data ?type_logger ctxt ~legacy t 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\n        ctxt\n        loc\n        Cons_some\n        (Item_t (Option_t (t, ty_name, has_big_map t), rest, annot))\n  | (Prim (loc, I_NONE, [t], annot), stack) ->\n      Lwt.return @@ 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, has_big_map t), 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      fail_unexpected_annot loc annot\n      >>=? fun () ->\n      let annot = gen_access_annot option_annot default_some_annot in\n      parse_instr ?type_logger tc_context ctxt ~legacy bt rest\n      >>=? fun (btr, ctxt) ->\n      parse_instr\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\n               ( (a, l_field, fst_annot),\n                 (b, r_field, snd_annot),\n                 ty_name,\n                 has_big_map a || has_big_map b ),\n             rest,\n             annot ))\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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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        Left\n        (Item_t\n           ( Union_t\n               ( (tl, l_field),\n                 (tr, r_field),\n                 tname,\n                 has_big_map tl || has_big_map tr ),\n             rest,\n             annot ))\n  | (Prim (loc, I_RIGHT, [tl], annot), Item_t (tr, rest, stack_annot)) ->\n      Lwt.return @@ 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        Right\n        (Item_t\n           ( Union_t\n               ( (tl, l_field),\n                 (tr, r_field),\n                 tname,\n                 has_big_map tl || has_big_map tr ),\n             rest,\n             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      fail_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      parse_instr\n        ?type_logger\n        tc_context\n        ctxt\n        ~legacy\n        bt\n        (Item_t (tl, rest, left_annot))\n      >>=? fun (btr, ctxt) ->\n      parse_instr\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      Lwt.return @@ 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        Nil\n        (Item_t (List_t (t, ty_name, has_big_map t), stack, annot))\n  | ( Prim (loc, I_CONS, [], annot),\n      Item_t (tv, Item_t (List_t (t, ty_name, has_big_map), 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\n        ctxt\n        loc\n        Cons_list\n        (Item_t (List_t (t, ty_name, has_big_map), rest, annot))\n  | ( Prim (loc, I_IF_CONS, [bt; bf], annot),\n      (Item_t (List_t (t, ty_name, has_big_map), rest, list_annot) as bef) ) ->\n      check_kind [Seq_kind] bt\n      >>=? fun () ->\n      check_kind [Seq_kind] bf\n      >>=? fun () ->\n      fail_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      parse_instr\n        ?type_logger\n        tc_context\n        ctxt\n        ~legacy\n        bt\n        (Item_t\n           ( t,\n             Item_t (List_t (t, ty_name, has_big_map), rest, tl_annot),\n             hd_annot ))\n      >>=? fun (btr, ctxt) ->\n      parse_instr ?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      parse_instr\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          trace_eval\n            invalid_map_body\n            ( Lwt.return @@ stack_ty_eq ctxt 1 rest starting_rest\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt rest starting_rest\n            >>=? fun (rest, ctxt) ->\n            typed\n              ctxt\n              loc\n              (List_map ibody)\n              (Item_t\n                 (List_t (ret, list_ty_name, has_big_map ret), rest, ret_annot))\n            )\n      | Typed {aft; _} ->\n          serialize_stack_for_error ctxt aft\n          >>=? fun (aft, _ctxt) -> fail (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      fail_unexpected_annot loc annot\n      >>=? fun () ->\n      let elt_annot = gen_access_annot list_annot default_elt_annot in\n      parse_instr\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          trace_eval\n            invalid_iter_body\n            ( Lwt.return @@ stack_ty_eq ctxt 1 aft rest\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt aft rest\n            >>=? fun (rest, ctxt) -> typed 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      Lwt.return @@ 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      fail_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      parse_instr\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          trace_eval\n            invalid_iter_body\n            ( Lwt.return @@ stack_ty_eq ctxt 1 aft rest\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt aft rest\n            >>=? fun (rest, ctxt) -> typed 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    match comparable_ty_of_ty v with\n    | None ->\n        unparse_ty ctxt v\n        >>=? fun (v, _ctxt) ->\n        fail (Comparable_type_expected (loc, Micheline.strip_locations v))\n    | Some v ->\n        parse_var_annot loc annot ~default:set_annot\n        >>=? fun annot ->\n        check_item_comparable_ty elt v loc I_UPDATE 1 3\n        >>=? fun (Eq, elt, ctxt) ->\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      Lwt.return @@ parse_comparable_ty ctxt tk\n      >>=? fun (Ex_comparable_ty tk, ctxt) ->\n      Lwt.return @@ 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, has_big_map tv), 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      parse_instr\n        ?type_logger\n        tc_context\n        ctxt\n        ~legacy\n        body\n        (Item_t\n           ( Pair_t\n               ((k, None, k_name), (elt, None, e_name), None, has_big_map elt),\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          trace_eval\n            invalid_map_body\n            ( Lwt.return @@ stack_ty_eq ctxt 1 rest starting_rest\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt rest starting_rest\n            >>=? fun (rest, ctxt) ->\n            typed\n              ctxt\n              loc\n              (Map_map ibody)\n              (Item_t\n                 (Map_t (ck, ret, ty_name, has_big_map ret), rest, ret_annot))\n            )\n      | Typed {aft; _} ->\n          serialize_stack_for_error ctxt aft\n          >>=? fun (aft, _ctxt) -> fail (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      fail_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      parse_instr\n        ?type_logger\n        tc_context\n        ctxt\n        ~legacy\n        body\n        (Item_t\n           ( Pair_t\n               ( (key, None, k_name),\n                 (element_ty, None, e_name),\n                 None,\n                 has_big_map element_ty ),\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          trace_eval\n            invalid_iter_body\n            ( Lwt.return @@ stack_ty_eq ctxt 1 aft rest\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt aft rest\n            >>=? fun (rest, ctxt) -> typed 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, _, has_big_map), 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\n        ctxt\n        loc\n        Map_get\n        (Item_t (Option_t (elt, None, has_big_map), 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, has_big_map), 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\n        ctxt\n        loc\n        Map_update\n        (Item_t (Map_t (ck, v, map_name, has_big_map), rest, 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      Lwt.return @@ parse_comparable_ty ctxt tk\n      >>=? fun (Ex_comparable_ty tk, ctxt) ->\n      Lwt.return @@ parse_packable_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\n        ctxt\n        loc\n        Big_map_get\n        (Item_t (Option_t (elt, None, has_big_map elt), 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  (* control *)\n  | (Seq (loc, []), stack) ->\n      typed ctxt loc Nop stack\n  | (Seq (loc, [single]), stack) -> (\n      parse_instr ?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      parse_instr ?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          parse_instr\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      fail_unexpected_annot loc annot\n      >>=? fun () ->\n      parse_instr ?type_logger tc_context ctxt ~legacy bt rest\n      >>=? fun (btr, ctxt) ->\n      parse_instr ?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      fail_unexpected_annot loc annot\n      >>=? fun () ->\n      parse_instr ?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          trace_eval\n            unmatched_branches\n            ( Lwt.return @@ stack_ty_eq ctxt 1 ibody.aft stack\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt ibody.aft stack\n            >>=? fun (_stack, ctxt) -> typed 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\n      stack ) ) -> (\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      parse_instr\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          trace_eval\n            unmatched_branches\n            ( Lwt.return @@ stack_ty_eq ctxt 1 ibody.aft stack\n            >>=? fun (Eq, ctxt) ->\n            Lwt.return @@ merge_stacks ~legacy loc ctxt ibody.aft stack\n            >>=? fun (_stack, ctxt) ->\n            typed ctxt loc (Loop_left ibody) (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      Lwt.return @@ parse_any_ty ctxt ~legacy arg\n      >>=? fun (Ex_ty arg, ctxt) ->\n      Lwt.return @@ 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        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, _),\n                  ret,\n                  _ ),\n              rest,\n              _ ),\n          _ ) ) ->\n      Lwt.return @@ 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      fail_unexpected_annot loc annot\n      >>=? fun () ->\n      check_kind [Seq_kind] code\n      >>=? fun () ->\n      parse_instr\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    when match parse_int32 n with Ok _ -> true | Error _ -> false ->\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            parse_instr ?type_logger inner_tc_context ctxt ~legacy code rest\n            >>=? fun (judgement, ctxt) ->\n            match judgement with\n            | Typed descr ->\n                outer_return\n                @@ Dipn_proof_argument (Rest, (ctxt, descr), descr.aft)\n            | Failed _ ->\n                fail (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            outer_return\n            @@ Dipn_proof_argument (Prefix n', descr, Item_t (v, aft', annot))\n        | (_, _) ->\n            serialize_stack_for_error ctxt stack\n            >>=? fun (whole_stack, _ctxt) ->\n            fail (Bad_stack (loc, I_DIP, 1, whole_stack))\n      in\n      Lwt.return (parse_int32 n)\n      >>=? fun n ->\n      fail_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      fail_unexpected_annot loc annot\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  (* 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      Lwt.return @@ 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      Lwt.return @@ 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, false), 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      Lwt.return @@ 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, false), 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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\n        ctxt\n        loc\n        Is_nat\n        (Item_t (Option_t (Nat_t None, None, false), 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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                     false ),\n                 None,\n                 false ),\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      Lwt.return @@ 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),\n                     (Mutez_t tname, None, None),\n                     None,\n                     false ),\n                 None,\n                 false ),\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      Lwt.return @@ 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),\n                     (Nat_t None, None, None),\n                     None,\n                     false ),\n                 None,\n                 false ),\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),\n                     (Nat_t None, None, None),\n                     None,\n                     false ),\n                 None,\n                 false ),\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),\n                     (Nat_t tname, None, None),\n                     None,\n                     false ),\n                 None,\n                 false ),\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      Lwt.return @@ 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),\n                     (Nat_t tname, None, None),\n                     None,\n                     false ),\n                 None,\n                 false ),\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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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      Lwt.return @@ 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    -> (\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      match comparable_ty_of_ty t with\n      | None ->\n          Lwt.return (serialize_ty_for_error ctxt t)\n          >>=? fun (t, _ctxt) -> fail (Comparable_type_expected (loc, t))\n      | Some key ->\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      Lwt.return @@ parse_any_ty ctxt ~legacy cast_t\n      >>=? fun (Ex_ty cast_t, ctxt) ->\n      Lwt.return @@ ty_eq ctxt cast_t t\n      >>=? fun (Eq, ctxt) ->\n      Lwt.return @@ merge_types ~legacy ctxt loc cast_t t\n      >>=? fun (_, ctxt) -> 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      Lwt.return\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      Lwt.return @@ 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\n        ctxt\n        loc\n        (Unpack t)\n        (Item_t\n           ( Option_t (t, ty_name, false) (* cannot unpack big_maps *),\n             rest,\n             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      Lwt.return @@ 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      ( Lwt.return\n      @@\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, false), 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 (loc, I_CREATE_ACCOUNT, [], annot),\n      Item_t\n        ( Key_hash_t _,\n          Item_t\n            ( Option_t (Key_hash_t _, _, _),\n              Item_t (Bool_t _, Item_t (Mutez_t _, rest, _), _),\n              _ ),\n          _ ) ) ->\n      if legacy then\n        (* For existing contracts, this instruction is still allowed *)\n        parse_two_var_annot loc annot\n        >>=? fun (op_annot, addr_annot) ->\n        typed\n          ctxt\n          loc\n          Create_account\n          (Item_t\n             ( Operation_t None,\n               Item_t (Address_t None, rest, addr_annot),\n               op_annot ))\n      else\n        (* For new contracts this instruction is not allowed anymore *)\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        ( Key_hash_t _,\n          Item_t\n            ( Option_t (Key_hash_t _, _, _),\n              Item_t\n                ( Bool_t _,\n                  Item_t\n                    ( Bool_t _,\n                      Item_t (Mutez_t _, Item_t (ginit, rest, _), _),\n                      _ ),\n                  _ ),\n              _ ),\n          _ ) ) ->\n      if legacy then\n        (* For existing contracts, this instruction is still allowed *)\n        parse_two_var_annot loc annot\n        >>=? fun (op_annot, addr_annot) ->\n        let cannonical_code = fst @@ Micheline.extract_locations code in\n        Lwt.return @@ parse_toplevel ~legacy cannonical_code\n        >>=? fun (arg_type, storage_type, code_field, root_name) ->\n        trace\n          (Ill_formed_type\n             (Some \"parameter\", cannonical_code, location arg_type))\n          (Lwt.return @@ parse_parameter_ty ctxt ~legacy arg_type)\n        >>=? fun (Ex_ty arg_type, ctxt) ->\n        ( if legacy then Error_monad.return ()\n        else Lwt.return (well_formed_entrypoints ~root_name arg_type) )\n        >>=? fun () ->\n        trace\n          (Ill_formed_type\n             (Some \"storage\", cannonical_code, location storage_type))\n          (Lwt.return @@ 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              has_big_map arg_type || has_big_map storage_type )\n        in\n        let ret_type_full =\n          Pair_t\n            ( (List_t (Operation_t None, None, false), None, None),\n              (storage_type, None, None),\n              None,\n              has_big_map storage_type )\n        in\n        trace\n          (Ill_typed_contract (cannonical_code, []))\n          (parse_returning\n             (Toplevel\n                {\n                  storage_type;\n                  param_type = arg_type;\n                  root_name;\n                  legacy_create_contract_literal = true;\n                })\n             ctxt\n             ~legacy\n             ?type_logger\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        Lwt.return @@ ty_eq ctxt arg arg_type_full\n        >>=? fun (Eq, ctxt) ->\n        Lwt.return @@ merge_types ~legacy ctxt loc arg arg_type_full\n        >>=? fun (_, ctxt) ->\n        Lwt.return @@ ty_eq ctxt ret ret_type_full\n        >>=? fun (Eq, ctxt) ->\n        Lwt.return @@ merge_types ~legacy ctxt loc ret ret_type_full\n        >>=? fun (_, ctxt) ->\n        Lwt.return @@ ty_eq ctxt storage_type ginit\n        >>=? fun (Eq, ctxt) ->\n        Lwt.return @@ merge_types ~legacy ctxt loc storage_type ginit\n        >>=? fun (_, 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      else\n        (* For new contracts this instruction is not allowed anymore *)\n        fail (Deprecated_instruction I_CREATE_CONTRACT)\n  | ( Prim (loc, I_CREATE_CONTRACT, [(Seq _ as code)], annot),\n      (* Removed the instruction's arguments manager, spendable and delegatable *)\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 cannonical_code = fst @@ Micheline.extract_locations code in\n      Lwt.return @@ parse_toplevel ~legacy cannonical_code\n      >>=? fun (arg_type, storage_type, code_field, root_name) ->\n      trace\n        (Ill_formed_type (Some \"parameter\", cannonical_code, location arg_type))\n        (Lwt.return @@ parse_parameter_ty ctxt ~legacy arg_type)\n      >>=? fun (Ex_ty arg_type, ctxt) ->\n      ( if legacy then Error_monad.return ()\n      else Lwt.return (well_formed_entrypoints ~root_name arg_type) )\n      >>=? fun () ->\n      trace\n        (Ill_formed_type\n           (Some \"storage\", cannonical_code, location storage_type))\n        (Lwt.return @@ 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            has_big_map arg_type || has_big_map storage_type )\n      in\n      let ret_type_full =\n        Pair_t\n          ( (List_t (Operation_t None, None, false), None, None),\n            (storage_type, None, None),\n            None,\n            has_big_map storage_type )\n      in\n      trace\n        (Ill_typed_contract (cannonical_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           (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      Lwt.return @@ ty_eq ctxt arg arg_type_full\n      >>=? fun (Eq, ctxt) ->\n      Lwt.return @@ merge_types ~legacy ctxt loc arg arg_type_full\n      >>=? fun (_, ctxt) ->\n      Lwt.return @@ ty_eq ctxt ret ret_type_full\n      >>=? fun (Eq, ctxt) ->\n      Lwt.return @@ merge_types ~legacy ctxt loc ret ret_type_full\n      >>=? fun (_, ctxt) ->\n      Lwt.return @@ ty_eq ctxt storage_type ginit\n      >>=? fun (Eq, ctxt) ->\n      Lwt.return @@ merge_types ~legacy ctxt loc storage_type ginit\n      >>=? fun (_, ctxt) ->\n      typed\n        ctxt\n        loc\n        (Create_contract_2 (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_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_STEPS_TO_QUOTA, [], annot), stack) ->\n      if legacy then\n        (* For existing contracts, this instruction is still allowed *)\n        parse_var_annot loc annot ~default:default_steps_annot\n        >>=? fun annot ->\n        typed ctxt loc Steps_to_quota (Item_t (Nat_t None, stack, annot))\n      else\n        (* For new contracts this instruction is not allowed anymore *)\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      parse_entrypoint_annot loc annot ~default:default_self_annot\n      >>=? fun (annot, entrypoint) ->\n      let entrypoint =\n        Option.unopt_map\n          ~f:(fun (`Field_annot annot) -> annot)\n          ~default:\"default\"\n          entrypoint\n      in\n      let rec get_toplevel_type :\n          tc_context -> (bef judgement * context) tzresult Lwt.t = function\n        | Lambda ->\n            fail (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            Lwt.return (find_entrypoint param_type ~root_name entrypoint)\n            >>=? fun (_, Ex_ty param_type) ->\n            typed\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\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  (* Primitive parsing errors *)\n  | ( Prim\n        ( loc,\n          ( ( I_DUP\n            | I_SWAP\n            | I_SOME\n            | I_UNIT\n            | I_PAIR\n            | I_CAR\n            | I_CDR\n            | I_CONS\n            | I_CONCAT\n            | I_SLICE\n            | I_MEM\n            | I_UPDATE\n            | I_MAP\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_CREATE_ACCOUNT\n            | I_SET_DELEGATE\n            | I_NOW\n            | I_IMPLICIT_ACCOUNT\n            | I_AMOUNT\n            | I_BALANCE\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_STEPS_TO_QUOTA\n            | I_ADDRESS ) 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_DIP\n            | I_LOOP\n            | I_LOOP_LEFT\n            | I_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 (loc, I_LAMBDA, (([] | [_] | _ :: _ :: _ :: _ :: _) as l), _), _) ->\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 ) as name ),\n          [],\n          _ ),\n      Item_t (ta, Item_t (tb, _, _), _) ) ->\n      Lwt.return @@ serialize_ty_for_error ctxt ta\n      >>=? fun (ta, ctxt) ->\n      Lwt.return @@ 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_CONCAT\n            | I_SIZE\n            | I_EQ\n            | I_NEQ\n            | I_LT\n            | I_GT\n            | I_LE\n            | I_GE ) as name ),\n          [],\n          _ ),\n      Item_t (t, _, _) ) ->\n      Lwt.return @@ 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      serialize_stack_for_error ctxt stack\n      >>=? fun (stack, _ctxt) -> fail (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_CREATE_ACCOUNT, [], _), stack) ->\n      serialize_stack_for_error ctxt stack\n      >>=? fun (stack, _ctxt) ->\n      fail (Bad_stack (loc, I_CREATE_ACCOUNT, 4, stack))\n  | (Prim (loc, I_TRANSFER_TOKENS, [], _), stack) ->\n      serialize_stack_for_error ctxt stack\n      >>=? fun (stack, _ctxt) ->\n      fail (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_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 ) as name ),\n          _,\n          _ ),\n      stack ) ->\n      serialize_stack_for_error ctxt stack\n      >>=? fun (stack, _ctxt) -> fail (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 ) as name ),\n          _,\n          _ ),\n      stack ) ->\n      serialize_stack_for_error ctxt stack\n      >>=? fun (stack, _ctxt) -> fail (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_CAR;\n             I_CDR;\n             I_CONS;\n             I_MEM;\n             I_UPDATE;\n             I_MAP;\n             I_ITER;\n             I_GET;\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_ACCOUNT;\n             I_CREATE_CONTRACT;\n             I_NOW;\n             I_AMOUNT;\n             I_BALANCE;\n             I_IMPLICIT_ACCOUNT;\n             I_CHECK_SIGNATURE;\n             I_BLAKE2B;\n             I_SHA256;\n             I_SHA512;\n             I_HASH_KEY;\n             I_STEPS_TO_QUOTA;\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_LAMBDA ]\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  Lwt.return @@ 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      Lwt.return @@ Gas.consume ctxt Typecheck_costs.get_script\n      >>=? fun ctxt ->\n      trace (Invalid_contract (loc, contract))\n      @@ Contract.get_script_code ctxt contract\n      >>=? fun (ctxt, code) ->\n      match code with\n      | None ->\n          Lwt.return\n            ( ty_eq ctxt 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 ctxt code\n          >>=? fun (code, ctxt) ->\n          Lwt.return\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            let return ctxt targ entrypoint =\n              merge_types ~legacy ctxt loc targ arg\n              >>? fun (arg, ctxt) ->\n              let contract : arg typed_contract =\n                (arg, (contract, entrypoint))\n              in\n              ok (ctxt, contract)\n            in\n            find_entrypoint_for_type\n              ~full:targ\n              ~expected:arg\n              ~root_name\n              entrypoint\n              ctxt\n            >>? fun (ctxt, entrypoint, targ) ->\n            merge_types ~legacy ctxt loc targ arg\n            >>? fun (targ, ctxt) -> return ctxt targ entrypoint ) )\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  Lwt.return @@ 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 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.cycle\n            >>? fun ctxt -> ok (ctxt, None) )\n  | (Some _, _) ->\n      Lwt.return @@ Gas.consume ctxt Typecheck_costs.cycle\n      >>=? fun ctxt ->\n      (* An implicit account on any other entrypoint is not a valid contract. *)\n      return (ctxt, None)\n  | (None, _) -> (\n      (* Originated account *)\n      Contract.exists ctxt contract\n      >>=? function\n      | false ->\n          return (ctxt, None)\n      | true -> (\n          Lwt.return @@ Gas.consume ctxt Typecheck_costs.get_script\n          >>=? fun ctxt ->\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              Script.force_decode ctxt code\n              >>=? fun (code, ctxt) ->\n              (* can only fail because of gas *)\n              Lwt.return\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                        ~full:targ\n                        ~expected:arg\n                        ~root_name\n                        entrypoint\n                        ctxt\n                      >>? fun (ctxt, entrypoint, targ) ->\n                      merge_types ~legacy ctxt loc targ arg\n                      >>? fun (targ, ctxt) ->\n                      merge_types ~legacy ctxt loc targ arg\n                      >>? fun (arg, ctxt) ->\n                      let contract : arg typed_contract =\n                        (arg, (contract, entrypoint))\n                      in\n                      ok (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                        ty_eq ctxt targ targ\n                        >>? fun (Eq, ctxt) ->\n                        merge_types ~legacy ctxt loc targ targ\n                        >>? fun (_, ctxt) -> ok (ctxt, None) ) ) ) ) )\n\nand parse_toplevel :\n    legacy:bool ->\n    Script.expr ->\n    (Script.node * Script.node * Script.node * string 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 (`Field_annot root_name) ->\n                ok (p, pannot, Some root_name)\n            | None -> (\n              match pannot with\n              | [single]\n                when Compare.Int.(String.length single > 0)\n                     && Compare.Char.(single.[0] = '%') ->\n                  ok\n                    ( p,\n                      [],\n                      Some (String.sub single 1 (String.length single - 1)) )\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_script :\n    ?type_logger:type_logger ->\n    context ->\n    legacy:bool ->\n    Script.t ->\n    (ex_script * context) tzresult Lwt.t =\n fun ?type_logger ctxt ~legacy {code; storage} ->\n  Script.force_decode ctxt code\n  >>=? fun (code, ctxt) ->\n  Script.force_decode ctxt storage\n  >>=? fun (storage, ctxt) ->\n  Lwt.return @@ parse_toplevel ~legacy code\n  >>=? fun (arg_type, storage_type, code_field, root_name) ->\n  trace\n    (Ill_formed_type (Some \"parameter\", code, location arg_type))\n    (Lwt.return (parse_parameter_ty ctxt ~legacy arg_type))\n  >>=? fun (Ex_ty arg_type, ctxt) ->\n  ( if legacy then return ()\n  else Lwt.return (well_formed_entrypoints ~root_name arg_type) )\n  >>=? fun () ->\n  trace\n    (Ill_formed_type (Some \"storage\", code, location storage_type))\n    (Lwt.return (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        has_big_map arg_type || has_big_map storage_type )\n  in\n  let ret_type_full =\n    Pair_t\n      ( (List_t (Operation_t None, None, false), None, None),\n        (storage_type, None, None),\n        None,\n        has_big_map storage_type )\n  in\n  trace_eval\n    (fun () ->\n      Lwt.return @@ serialize_ty_for_error ctxt storage_type\n      >>|? fun (storage_type, _ctxt) ->\n      Ill_typed_data (None, storage, storage_type))\n    (parse_data ?type_logger ctxt ~legacy storage_type (root storage))\n  >>=? fun (storage, ctxt) ->\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       ?type_logger\n       (arg_type_full, None)\n       ret_type_full\n       code_field)\n  >>=? fun (code, ctxt) ->\n  return (Ex_script {code; arg_type; storage; storage_type; root_name}, ctxt)\n\nlet typecheck_code :\n    context -> Script.expr -> (type_map * context) tzresult Lwt.t =\n fun ctxt code ->\n  let legacy = false in\n  Lwt.return @@ parse_toplevel ~legacy code\n  >>=? fun (arg_type, storage_type, code_field, root_name) ->\n  let type_map = ref [] in\n  trace\n    (Ill_formed_type (Some \"parameter\", code, location arg_type))\n    (Lwt.return (parse_parameter_ty ctxt ~legacy arg_type))\n  >>=? fun (Ex_ty arg_type, ctxt) ->\n  ( if legacy then return ()\n  else Lwt.return (well_formed_entrypoints ~root_name arg_type) )\n  >>=? fun () ->\n  trace\n    (Ill_formed_type (Some \"storage\", code, location storage_type))\n    (Lwt.return (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        has_big_map arg_type || has_big_map storage_type )\n  in\n  let ret_type_full =\n    Pair_t\n      ( (List_t (Operation_t None, None, false), None, None),\n        (storage_type, None, None),\n        None,\n        has_big_map storage_type )\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      ~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) -> return (!type_map, ctxt)\n\nlet typecheck_data :\n    ?type_logger:type_logger ->\n    context ->\n    Script.expr * Script.expr ->\n    context tzresult Lwt.t =\n fun ?type_logger ctxt (data, exp_ty) ->\n  let legacy = false in\n  trace\n    (Ill_formed_type (None, exp_ty, 0))\n    (Lwt.return @@ parse_parameter_ty ctxt ~legacy (root exp_ty))\n  >>=? fun (Ex_ty exp_ty, ctxt) ->\n  trace_eval\n    (fun () ->\n      Lwt.return @@ serialize_ty_for_error ctxt exp_ty\n      >>|? fun (exp_ty, _ctxt) -> Ill_typed_data (None, data, exp_ty))\n    (parse_data ?type_logger ctxt ~legacy exp_ty (root data))\n  >>=? fun (_, ctxt) -> return 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_no_lwt 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_no_lwt ctxt full\n  >>? fun (unparsed_full, _) ->\n  let (init, reachable) =\n    match root_name with\n    | None | Some \"\" ->\n        (Entrypoints_map.empty, false)\n    | Some 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\nlet rec unparse_data :\n    type a.\n    context ->\n    unparsing_mode ->\n    a ty ->\n    a ->\n    (Script.node * context) tzresult Lwt.t =\n fun ctxt mode ty a ->\n  Lwt.return (Gas.consume ctxt Unparse_costs.cycle)\n  >>=? fun ctxt ->\n  match (ty, a) with\n  | (Unit_t _, ()) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.unit)\n      >>=? fun ctxt -> return (Prim (-1, D_Unit, [], []), ctxt)\n  | (Int_t _, v) ->\n      Lwt.return (Gas.consume ctxt (Unparse_costs.int v))\n      >>=? fun ctxt -> return (Int (-1, Script_int.to_zint v), ctxt)\n  | (Nat_t _, v) ->\n      Lwt.return (Gas.consume ctxt (Unparse_costs.int v))\n      >>=? fun ctxt -> return (Int (-1, Script_int.to_zint v), ctxt)\n  | (String_t _, s) ->\n      Lwt.return (Gas.consume ctxt (Unparse_costs.string s))\n      >>=? fun ctxt -> return (String (-1, s), ctxt)\n  | (Bytes_t _, s) ->\n      Lwt.return (Gas.consume ctxt (Unparse_costs.bytes s))\n      >>=? fun ctxt -> return (Bytes (-1, s), ctxt)\n  | (Bool_t _, true) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.bool)\n      >>=? fun ctxt -> return (Prim (-1, D_True, [], []), ctxt)\n  | (Bool_t _, false) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.bool)\n      >>=? fun ctxt -> return (Prim (-1, D_False, [], []), ctxt)\n  | (Timestamp_t _, t) -> (\n      Lwt.return (Gas.consume ctxt (Unparse_costs.timestamp t))\n      >>=? fun ctxt ->\n      match mode with\n      | Optimized ->\n          return (Int (-1, Script_timestamp.to_zint t), ctxt)\n      | Readable -> (\n        match Script_timestamp.to_notation t with\n        | None ->\n            return (Int (-1, Script_timestamp.to_zint t), ctxt)\n        | Some s ->\n            return (String (-1, s), ctxt) ) )\n  | (Address_t _, (c, entrypoint)) -> (\n      Lwt.return (Gas.consume ctxt Unparse_costs.contract)\n      >>=? fun ctxt ->\n      match mode with\n      | Optimized ->\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          return (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          return (String (-1, notation), ctxt) )\n  | (Contract_t _, (_, (c, entrypoint))) -> (\n      Lwt.return (Gas.consume ctxt Unparse_costs.contract)\n      >>=? fun ctxt ->\n      match mode with\n      | Optimized ->\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          return (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          return (String (-1, notation), ctxt) )\n  | (Signature_t _, s) -> (\n      Lwt.return (Gas.consume ctxt Unparse_costs.signature)\n      >>=? fun ctxt ->\n      match mode with\n      | Optimized ->\n          let bytes = Data_encoding.Binary.to_bytes_exn Signature.encoding s in\n          return (Bytes (-1, bytes), ctxt)\n      | Readable ->\n          return (String (-1, Signature.to_b58check s), ctxt) )\n  | (Mutez_t _, v) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.tez)\n      >>=? fun ctxt -> return (Int (-1, Z.of_int64 (Tez.to_mutez v)), ctxt)\n  | (Key_t _, k) -> (\n      Lwt.return (Gas.consume ctxt Unparse_costs.key)\n      >>=? fun ctxt ->\n      match mode with\n      | Optimized ->\n          let bytes =\n            Data_encoding.Binary.to_bytes_exn Signature.Public_key.encoding k\n          in\n          return (Bytes (-1, bytes), ctxt)\n      | Readable ->\n          return (String (-1, Signature.Public_key.to_b58check k), ctxt) )\n  | (Key_hash_t _, k) -> (\n      Lwt.return (Gas.consume ctxt Unparse_costs.key_hash)\n      >>=? fun ctxt ->\n      match mode with\n      | Optimized ->\n          let bytes =\n            Data_encoding.Binary.to_bytes_exn\n              Signature.Public_key_hash.encoding\n              k\n          in\n          return (Bytes (-1, bytes), ctxt)\n      | Readable ->\n          return (String (-1, Signature.Public_key_hash.to_b58check k), ctxt) )\n  | (Operation_t _, (op, _big_map_diff)) ->\n      let bytes =\n        Data_encoding.Binary.to_bytes_exn\n          Operation.internal_operation_encoding\n          op\n      in\n      Lwt.return (Gas.consume ctxt (Unparse_costs.operation bytes))\n      >>=? fun ctxt -> return (Bytes (-1, bytes), ctxt)\n  | (Chain_id_t _, chain_id) ->\n      let bytes =\n        Data_encoding.Binary.to_bytes_exn Chain_id.encoding chain_id\n      in\n      Lwt.return (Gas.consume ctxt (Unparse_costs.chain_id bytes))\n      >>=? fun ctxt -> return (Bytes (-1, bytes), ctxt)\n  | (Pair_t ((tl, _, _), (tr, _, _), _, _), (l, r)) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.pair)\n      >>=? fun ctxt ->\n      unparse_data ctxt mode tl l\n      >>=? fun (l, ctxt) ->\n      unparse_data ctxt mode tr r\n      >>=? fun (r, ctxt) -> return (Prim (-1, D_Pair, [l; r], []), ctxt)\n  | (Union_t ((tl, _), _, _, _), L l) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.union)\n      >>=? fun ctxt ->\n      unparse_data ctxt mode tl l\n      >>=? fun (l, ctxt) -> return (Prim (-1, D_Left, [l], []), ctxt)\n  | (Union_t (_, (tr, _), _, _), R r) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.union)\n      >>=? fun ctxt ->\n      unparse_data ctxt mode tr r\n      >>=? fun (r, ctxt) -> return (Prim (-1, D_Right, [r], []), ctxt)\n  | (Option_t (t, _, _), Some v) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.some)\n      >>=? fun ctxt ->\n      unparse_data ctxt mode t v\n      >>=? fun (v, ctxt) -> return (Prim (-1, D_Some, [v], []), ctxt)\n  | (Option_t _, None) ->\n      Lwt.return (Gas.consume ctxt Unparse_costs.none)\n      >>=? fun ctxt -> return (Prim (-1, D_None, [], []), ctxt)\n  | (List_t (t, _, _), items) ->\n      fold_left_s\n        (fun (l, ctxt) element ->\n          Lwt.return (Gas.consume ctxt Unparse_costs.list_element)\n          >>=? fun ctxt ->\n          unparse_data ctxt mode t element\n          >>=? fun (unparsed, ctxt) -> return (unparsed :: l, ctxt))\n        ([], ctxt)\n        items\n      >>=? fun (items, ctxt) ->\n      return (Micheline.Seq (-1, List.rev items), ctxt)\n  | (Set_t (t, _), set) ->\n      let t = ty_of_comparable_ty t in\n      fold_left_s\n        (fun (l, ctxt) item ->\n          Lwt.return (Gas.consume ctxt Unparse_costs.set_element)\n          >>=? fun ctxt ->\n          unparse_data ctxt mode t item\n          >>=? fun (item, ctxt) -> return (item :: l, ctxt))\n        ([], ctxt)\n        (set_fold (fun e acc -> e :: acc) set [])\n      >>=? fun (items, ctxt) -> return (Micheline.Seq (-1, items), ctxt)\n  | (Map_t (kt, vt, _, _), map) ->\n      let kt = ty_of_comparable_ty kt in\n      fold_left_s\n        (fun (l, ctxt) (k, v) ->\n          Lwt.return (Gas.consume ctxt Unparse_costs.map_element)\n          >>=? fun ctxt ->\n          unparse_data ctxt mode kt k\n          >>=? fun (key, ctxt) ->\n          unparse_data ctxt mode vt v\n          >>=? fun (value, ctxt) ->\n          return (Prim (-1, D_Elt, [key; value], []) :: l, ctxt))\n        ([], ctxt)\n        (map_fold (fun k v acc -> (k, v) :: acc) map [])\n      >>=? fun (items, ctxt) -> return (Micheline.Seq (-1, items), ctxt)\n  | (Big_map_t (kt, vt, _), {id = None; diff = (module Diff); _}) ->\n      (* this branch is to allow roundtrip of big map literals *)\n      let kt = ty_of_comparable_ty kt in\n      fold_left_s\n        (fun (l, ctxt) (k, v) ->\n          Lwt.return (Gas.consume ctxt Unparse_costs.map_element)\n          >>=? fun ctxt ->\n          unparse_data ctxt mode kt k\n          >>=? fun (key, ctxt) ->\n          unparse_data ctxt mode vt v\n          >>=? fun (value, ctxt) ->\n          return (Prim (-1, D_Elt, [key; value], []) :: l, ctxt))\n        ([], ctxt)\n        (Diff.OPS.fold\n           (fun k v acc ->\n             match v with None -> acc | Some v -> (k, v) :: acc)\n           (fst Diff.boxed)\n           [])\n      >>=? fun (items, ctxt) -> return (Micheline.Seq (-1, items), ctxt)\n  | (Big_map_t (_kt, _kv, _), {id = Some id; diff = (module Diff); _}) ->\n      if Compare.Int.(Diff.OPS.cardinal (fst Diff.boxed) = 0) then\n        return (Micheline.Int (-1, id), ctxt)\n      else\n        (* this can only be the result of an execution and the map\n             must have been flushed at this point *)\n        assert false\n  | (Lambda_t _, Lam (_, original_code)) ->\n      unparse_code ctxt mode original_code\n\n(* Gas accounting may not be perfect in this function, as it is only called by RPCs. *)\nand unparse_code ctxt mode =\n  let legacy = true in\n  function\n  | Prim (loc, I_PUSH, [ty; data], annot) ->\n      Lwt.return (parse_packable_ty ctxt ~legacy ty)\n      >>=? fun (Ex_ty t, ctxt) ->\n      parse_data ctxt ~legacy t data\n      >>=? fun (data, ctxt) ->\n      unparse_data ctxt mode t data\n      >>=? fun (data, ctxt) ->\n      Lwt.return (Gas.consume ctxt (Unparse_costs.prim_cost 2 annot))\n      >>=? fun ctxt -> return (Prim (loc, I_PUSH, [ty; data], annot), ctxt)\n  | Seq (loc, items) ->\n      fold_left_s\n        (fun (l, ctxt) item ->\n          unparse_code ctxt mode item\n          >>=? fun (item, ctxt) -> return (item :: l, ctxt))\n        ([], ctxt)\n        items\n      >>=? fun (items, ctxt) ->\n      Lwt.return\n        (Gas.consume ctxt (Unparse_costs.seq_cost (List.length items)))\n      >>=? fun ctxt -> return (Micheline.Seq (loc, List.rev items), ctxt)\n  | Prim (loc, prim, items, annot) ->\n      fold_left_s\n        (fun (l, ctxt) item ->\n          unparse_code ctxt mode item\n          >>=? fun (item, ctxt) -> return (item :: l, ctxt))\n        ([], ctxt)\n        items\n      >>=? fun (items, ctxt) ->\n      Lwt.return (Gas.consume ctxt (Unparse_costs.prim_cost 3 annot))\n      >>=? fun ctxt -> 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 mode original_code\n  >>=? fun (code, ctxt) ->\n  unparse_data ctxt mode storage_type storage\n  >>=? fun (storage, ctxt) ->\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 =\n    add_field_annot\n      (Option.map ~f:(fun n -> `Field_annot n) root_name)\n      None\n      arg_type\n  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  Lwt.return\n    ( Gas.consume ctxt (Unparse_costs.seq_cost 3)\n    >>? fun ctxt ->\n    Gas.consume ctxt (Unparse_costs.prim_cost 1 [])\n    >>? fun ctxt ->\n    Gas.consume ctxt (Unparse_costs.prim_cost 1 [])\n    >>? fun ctxt -> Gas.consume ctxt (Unparse_costs.prim_cost 1 []) )\n  >>=? fun ctxt ->\n  return\n    ( {\n        code = lazy_expr (strip_locations code);\n        storage = lazy_expr (strip_locations storage);\n      },\n      ctxt )\n\nlet pack_data ctxt typ data =\n  unparse_data ctxt Optimized typ data\n  >>=? fun (unparsed, ctxt) ->\n  let bytes =\n    Data_encoding.Binary.to_bytes_exn\n      expr_encoding\n      (Micheline.strip_locations unparsed)\n  in\n  Lwt.return @@ Gas.consume ctxt (Script.serialized_cost bytes)\n  >>=? fun ctxt ->\n  let bytes = MBytes.concat \"\" [MBytes.of_string \"\\005\"; bytes] in\n  Lwt.return @@ Gas.consume ctxt (Script.serialized_cost bytes)\n  >>=? fun ctxt -> return (bytes, ctxt)\n\nlet hash_data ctxt typ data =\n  pack_data ctxt typ data\n  >>=? fun (bytes, ctxt) ->\n  Lwt.return\n  @@ Gas.consume\n       ctxt\n       (Michelson_v1_gas.Cost_of.Legacy.hash bytes Script_expr_hash.size)\n  >>=? fun ctxt -> return (Script_expr_hash.(hash_bytes [bytes]), ctxt)\n\n(* ---------------- Big map -------------------------------------------------*)\n\nlet empty_big_map tk tv =\n  {\n    id = None;\n    diff = empty_map tk;\n    key_type = ty_of_comparable_ty tk;\n    value_type = tv;\n  }\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_data ctxt key_type key\n      >>=? fun (hash, ctxt) ->\n      Alpha_context.Big_map.mem ctxt id hash\n      >>=? fun (ctxt, res) -> return (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_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 ctxt ~legacy:true value_type (Micheline.root value)\n          >>=? fun (x, ctxt) -> return (Some x, ctxt) )\n\nlet big_map_update key value ({diff; _} as map) =\n  {map with diff = map_set key value diff}\n\nmodule Ids = Set.Make (Compare.Z)\n\ntype big_map_ids = Ids.t\n\nlet no_big_map_id = Ids.empty\n\nlet diff_of_big_map ctxt fresh mode ~ids {id; key_type; value_type; diff} =\n  Lwt.return\n    (Gas.consume ctxt (Michelson_v1_gas.Cost_of.Legacy.map_to_list diff))\n  >>=? fun ctxt ->\n  ( match id with\n  | Some id ->\n      if Ids.mem id ids then\n        fresh ctxt\n        >>=? fun (ctxt, duplicate) ->\n        return (ctxt, [Contract.Copy (id, duplicate)], duplicate)\n      else\n        (* The first occurence 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_big_map_updates`, and this accumulator is not\n             reversed before being flattened. *)\n        return (ctxt, [], id)\n  | None ->\n      fresh ctxt\n      >>=? fun (ctxt, id) ->\n      unparse_ty ctxt key_type\n      >>=? fun (kt, ctxt) ->\n      unparse_ty ctxt value_type\n      >>=? fun (kv, ctxt) ->\n      return\n        ( ctxt,\n          [ Contract.Alloc\n              {\n                big_map = id;\n                key_type = Micheline.strip_locations kt;\n                value_type = Micheline.strip_locations kv;\n              } ],\n          id ) )\n  >>=? fun (ctxt, init, big_map) ->\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      Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n      >>=? fun ctxt ->\n      hash_data ctxt key_type key\n      >>=? fun (diff_key_hash, ctxt) ->\n      unparse_data ctxt mode key_type key\n      >>=? fun (key_node, ctxt) ->\n      let diff_key = Micheline.strip_locations key_node in\n      ( match value with\n      | None ->\n          return (None, ctxt)\n      | Some x ->\n          unparse_data ctxt mode value_type x\n          >>=? fun (node, ctxt) ->\n          return (Some (Micheline.strip_locations node), ctxt) )\n      >>=? fun (diff_value, ctxt) ->\n      let diff_item =\n        Contract.Update {big_map; diff_key; diff_key_hash; diff_value}\n      in\n      return (diff_item :: acc, ctxt))\n    ([], ctxt)\n    pairs\n  >>=? fun (diff, ctxt) -> return (init @ diff, big_map, ctxt)\n\nlet rec extract_big_map_updates :\n    type a.\n    context ->\n    (context -> (context * Big_map.id) tzresult Lwt.t) ->\n    unparsing_mode ->\n    Ids.t ->\n    Contract.big_map_diff list ->\n    a ty ->\n    a ->\n    (context * a * Ids.t * Contract.big_map_diff list) tzresult Lwt.t =\n fun ctxt fresh mode ids acc ty x ->\n  match (ty, x) with\n  | (Big_map_t (_, _, _), map) ->\n      diff_of_big_map ctxt fresh mode ids 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      return (ctxt, map, Ids.add id ids, diff :: acc)\n  | (Pair_t ((tyl, _, _), (tyr, _, _), _, true), (xl, xr)) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n      >>=? fun ctxt ->\n      extract_big_map_updates ctxt fresh mode ids acc tyl xl\n      >>=? fun (ctxt, xl, ids, acc) ->\n      extract_big_map_updates ctxt fresh mode ids acc tyr xr\n      >>=? fun (ctxt, xr, ids, acc) -> return (ctxt, (xl, xr), ids, acc)\n  | (Union_t ((ty, _), (_, _), _, true), L x) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n      >>=? fun ctxt ->\n      extract_big_map_updates ctxt fresh mode ids acc ty x\n      >>=? fun (ctxt, x, ids, acc) -> return (ctxt, L x, ids, acc)\n  | (Union_t ((_, _), (ty, _), _, true), R x) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n      >>=? fun ctxt ->\n      extract_big_map_updates ctxt fresh mode ids acc ty x\n      >>=? fun (ctxt, x, ids, acc) -> return (ctxt, R x, ids, acc)\n  | (Option_t (ty, _, true), Some x) ->\n      Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n      >>=? fun ctxt ->\n      extract_big_map_updates ctxt fresh mode ids acc ty x\n      >>=? fun (ctxt, x, ids, acc) -> return (ctxt, Some x, ids, acc)\n  | (List_t (ty, _, true), l) ->\n      fold_left_s\n        (fun (ctxt, l, ids, acc) x ->\n          Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n          >>=? fun ctxt ->\n          extract_big_map_updates ctxt fresh mode ids acc ty x\n          >>=? fun (ctxt, x, ids, acc) -> return (ctxt, x :: l, ids, acc))\n        (ctxt, [], ids, acc)\n        l\n      >>=? fun (ctxt, l, ids, acc) -> return (ctxt, List.rev l, ids, acc)\n  | (Map_t (_, ty, _, true), ((module M) as m)) ->\n      Lwt.return\n        (Gas.consume ctxt (Michelson_v1_gas.Cost_of.Legacy.map_to_list m))\n      >>=? fun ctxt ->\n      fold_left_s\n        (fun (ctxt, m, ids, acc) (k, x) ->\n          Lwt.return (Gas.consume ctxt Typecheck_costs.cycle)\n          >>=? fun ctxt ->\n          extract_big_map_updates ctxt fresh mode ids acc ty x\n          >>=? fun (ctxt, x, ids, acc) ->\n          return (ctxt, M.OPS.add k x m, ids, acc))\n        (ctxt, M.OPS.empty, ids, acc)\n        (M.OPS.bindings (fst M.boxed))\n      >>=? fun (ctxt, m, ids, 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      return\n        ( ctxt,\n          (module M : Boxed_map with type key = M.key and type value = M.value),\n          ids,\n          acc )\n  | (Option_t (_, _, true), None) ->\n      return (ctxt, None, ids, acc)\n  | (List_t (_, _, false), v) ->\n      return (ctxt, v, ids, acc)\n  | (Map_t (_, _, _, false), v) ->\n      return (ctxt, v, ids, acc)\n  | (Option_t (_, _, false), None) ->\n      return (ctxt, None, ids, acc)\n  | (Pair_t (_, _, _, false), v) ->\n      return (ctxt, v, ids, acc)\n  | (Union_t (_, _, _, false), v) ->\n      return (ctxt, v, ids, acc)\n  | (Option_t (_, _, false), v) ->\n      return (ctxt, v, ids, acc)\n  | (Chain_id_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Set_t (_, _), v) ->\n      return (ctxt, v, ids, acc)\n  | (Unit_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Int_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Nat_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Signature_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (String_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Bytes_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Mutez_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Key_hash_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Key_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Timestamp_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Address_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Bool_t _, v) ->\n      return (ctxt, v, ids, acc)\n  | (Lambda_t (_, _, _), v) ->\n      return (ctxt, v, ids, acc)\n  | (Contract_t (_, _), v) ->\n      return (ctxt, v, ids, acc)\n  | (Operation_t _, _) ->\n      assert false\n\n(* called only on parameters and storage, which cannot contain operations *)\n\nlet collect_big_maps ctxt ty x =\n  let rec collect :\n      type a. context -> a ty -> a -> Ids.t -> (Ids.t * context) tzresult =\n   fun ctxt ty x acc ->\n    match (ty, x) with\n    | (Big_map_t (_, _, _), {id = Some id}) ->\n        Gas.consume ctxt Typecheck_costs.cycle\n        >>? fun ctxt -> ok (Ids.add id acc, ctxt)\n    | (Pair_t ((tyl, _, _), (tyr, _, _), _, true), (xl, xr)) ->\n        collect ctxt tyl xl acc >>? fun (acc, ctxt) -> collect ctxt tyr xr acc\n    | (Union_t ((ty, _), (_, _), _, true), L x) ->\n        collect ctxt ty x acc\n    | (Union_t ((_, _), (ty, _), _, true), R x) ->\n        collect ctxt ty x acc\n    | (Option_t (ty, _, true), Some x) ->\n        collect ctxt ty x acc\n    | (List_t (ty, _, true), l) ->\n        List.fold_left\n          (fun acc x -> acc >>? fun (acc, ctxt) -> collect ctxt ty x acc)\n          (ok (acc, ctxt))\n          l\n    | (Map_t (_, ty, _, true), m) ->\n        map_fold\n          (fun _ v acc -> acc >>? fun (acc, ctxt) -> collect ctxt ty v acc)\n          m\n          (ok (acc, ctxt))\n    | (List_t (_, _, false), _) ->\n        ok (acc, ctxt)\n    | (Map_t (_, _, _, false), _) ->\n        ok (acc, ctxt)\n    | (Big_map_t (_, _, _), {id = None}) ->\n        ok (acc, ctxt)\n    | (Option_t (_, _, true), None) ->\n        ok (acc, ctxt)\n    | (Option_t (_, _, false), _) ->\n        ok (acc, ctxt)\n    | (Union_t (_, _, _, false), _) ->\n        ok (acc, ctxt)\n    | (Pair_t (_, _, _, false), _) ->\n        ok (acc, ctxt)\n    | (Chain_id_t _, _) ->\n        ok (acc, ctxt)\n    | (Set_t (_, _), _) ->\n        ok (acc, ctxt)\n    | (Unit_t _, _) ->\n        ok (acc, ctxt)\n    | (Int_t _, _) ->\n        ok (acc, ctxt)\n    | (Nat_t _, _) ->\n        ok (acc, ctxt)\n    | (Signature_t _, _) ->\n        ok (acc, ctxt)\n    | (String_t _, _) ->\n        ok (acc, ctxt)\n    | (Bytes_t _, _) ->\n        ok (acc, ctxt)\n    | (Mutez_t _, _) ->\n        ok (acc, ctxt)\n    | (Key_hash_t _, _) ->\n        ok (acc, ctxt)\n    | (Key_t _, _) ->\n        ok (acc, ctxt)\n    | (Timestamp_t _, _) ->\n        ok (acc, ctxt)\n    | (Address_t _, _) ->\n        ok (acc, ctxt)\n    | (Bool_t _, _) ->\n        ok (acc, ctxt)\n    | (Lambda_t (_, _, _), _) ->\n        ok (acc, ctxt)\n    | (Contract_t (_, _), _) ->\n        ok (acc, ctxt)\n    | (Operation_t _, _) ->\n        assert false\n   (* called only on parameters and storage, which cannot contain operations *)\n  in\n  Lwt.return (collect ctxt ty x no_big_map_id)\n\nlet extract_big_map_diff ctxt mode ~temporary ~to_duplicate ~to_update ty v =\n  let to_duplicate = Ids.diff to_duplicate to_update in\n  let fresh =\n    if temporary then fun c -> return (Big_map.fresh_temporary c)\n    else Big_map.fresh\n  in\n  extract_big_map_updates ctxt fresh mode to_duplicate [] ty v\n  >>=? fun (ctxt, v, alive, diffs) ->\n  let diffs =\n    if temporary then diffs\n    else\n      let dead = Ids.diff to_update alive in\n      Ids.fold (fun id acc -> Contract.Clear id :: acc) dead [] :: diffs\n  in\n  match diffs with\n  | [] ->\n      return (v, None, ctxt)\n  | diffs ->\n      return (v, Some (List.flatten diffs) (* do not reverse *), ctxt)\n\nlet list_of_big_map_ids ids = Ids.elements ids\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 three possible namespaces of primitive (data constructor, \\\n         type name or instruction).\"\n    @@ string_enum\n         [ (\"type\", Type_namespace);\n           (\"constant\", Constant_namespace);\n           (\"instruction\", Instr_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  (* 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  (* 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_bigmap\"\n    ~title:\"Big map in unauthorized position (type error)\"\n    ~description:\n      \"When parsing script, a big_map type was found in a position where it \\\n       could end up stored inside a big_map, which is forbidden for now.\"\n    (obj1 (req \"loc\" location_encoding))\n    (function Unexpected_big_map loc -> Some loc | _ -> None)\n    (fun loc -> Unexpected_big_map 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 duplicae 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 impropperly 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:\"invalidSyntacticConstantError\"\n    ~title:\"Invalid constant (parse error)\"\n    ~description:\"A compile-time constant was invalid for its expected form.\"\n    (located\n       (obj2\n          (req \"expectedForm\" Script.expr_encoding)\n          (req \"wrongExpression\" 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 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\" z)))\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  (* -- 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 propper 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  (* -- 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" ;
                } ;
                { 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_log\n\ntype error += Cannot_serialize_failure\n\ntype error += Cannot_serialize_storage\n\ntype execution_result = {\n  ctxt : context;\n  storage : Script.expr;\n  big_map_diff : Contract.big_map_diff 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\ntype 'tys stack =\n  | Item : 'ty * 'rest stack -> ('ty * 'rest) stack\n  | Empty : Script_typed_ir.end_of_stack stack\n\nval step :\n  ?log:execution_trace ref ->\n  context ->\n  step_constants ->\n  ('bef, 'aft) Script_typed_ir.descr ->\n  'bef stack ->\n  ('aft stack * context) tzresult Lwt.t\n\nval execute :\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  execution_result tzresult Lwt.t\n\nval trace :\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  (execution_result * execution_trace) 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\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_log\n\ntype error += Cannot_serialize_failure\n\ntype error += Cannot_serialize_storage\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 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  (* 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\n(* ---- interpreter ---------------------------------------------------------*)\n\ntype 'tys stack =\n  | Item : 'ty * 'rest stack -> ('ty * 'rest) stack\n  | Empty : end_of_stack stack\n\nlet 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 stack * a stack_ty -> (Script.expr * string option) list tzresult Lwt.t\n      = function\n    | (Empty, Empty_t) ->\n        return_nil\n    | (Item (v, rest), Item_t (ty, rest_ty, annot)) ->\n        unparse_data ctxt Readable ty v\n        >>=? fun (data, _ctxt) ->\n        unparse_stack (rest, rest_ty)\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        return ((data, annot) :: rest)\n  in\n  unparse_stack (stack, stack_ty)\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 stack -> (faft stack * result) tzresult Lwt.t) ->\n    (fbef, faft, bef, aft) stack_prefix_preservation_witness ->\n    bef stack ->\n    (aft stack * 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      Item\n        ( v0,\n          Item\n            ( v1,\n              Item\n                ( v2,\n                  Item\n                    ( v3,\n                      Item\n                        ( v4,\n                          Item\n                            ( v5,\n                              Item\n                                ( v6,\n                                  Item\n                                    ( v7,\n                                      Item\n                                        ( v8,\n                                          Item\n                                            ( v9,\n                                              Item\n                                                ( va,\n                                                  Item\n                                                    ( vb,\n                                                      Item\n                                                        ( vc,\n                                                          Item\n                                                            ( vd,\n                                                              Item\n                                                                ( ve,\n                                                                  Item\n                                                                    (vf, rest)\n                                                                ) ) ) ) ) ) )\n                                    ) ) ) ) ) ) ) ) ) ->\n      interp_stack_prefix_preserving_operation f n rest\n      >>=? fun (rest', result) ->\n      return\n        ( Item\n            ( v0,\n              Item\n                ( v1,\n                  Item\n                    ( v2,\n                      Item\n                        ( v3,\n                          Item\n                            ( v4,\n                              Item\n                                ( v5,\n                                  Item\n                                    ( v6,\n                                      Item\n                                        ( v7,\n                                          Item\n                                            ( v8,\n                                              Item\n                                                ( v9,\n                                                  Item\n                                                    ( va,\n                                                      Item\n                                                        ( vb,\n                                                          Item\n                                                            ( vc,\n                                                              Item\n                                                                ( vd,\n                                                                  Item\n                                                                    ( ve,\n                                                                      Item\n                                                                        ( vf,\n                                                                          rest'\n                                                                        ) ) )\n                                                            ) ) ) ) ) ) ) ) )\n                        ) ) ) ),\n          result )\n  | ( Prefix (Prefix (Prefix (Prefix n))),\n      Item (v0, Item (v1, Item (v2, Item (v3, rest)))) ) ->\n      interp_stack_prefix_preserving_operation f n rest\n      >>=? fun (rest', result) ->\n      return (Item (v0, Item (v1, Item (v2, Item (v3, rest')))), result)\n  | (Prefix n, Item (v, rest)) ->\n      interp_stack_prefix_preserving_operation f n rest\n      >>=? fun (rest', result) -> return (Item (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\nlet rec step :\n    type b a.\n    ?log:execution_trace ref ->\n    context ->\n    step_constants ->\n    (b, a) descr ->\n    b stack ->\n    (a stack * context) tzresult Lwt.t =\n fun ?log ctxt step_constants ({instr; loc; _} as descr) stack ->\n  Lwt.return (Gas.consume ctxt Interp_costs.cycle)\n  >>=? fun ctxt ->\n  let logged_return :\n      type a b.\n      (b, a) descr -> a stack * context -> (a stack * context) tzresult Lwt.t =\n   fun descr (ret, ctxt) ->\n    match log with\n    | None ->\n        return (ret, ctxt)\n    | Some log ->\n        trace Cannot_serialize_log (unparse_stack ctxt (ret, descr.aft))\n        >>=? fun stack ->\n        log := (descr.loc, Gas.level ctxt, stack) :: !log ;\n        return (ret, ctxt)\n  in\n  let get_log (log : execution_trace ref option) =\n    Option.map ~f:(fun l -> List.rev !l) log\n  in\n  let consume_gas_terop :\n      type ret arg1 arg2 arg3 rest.\n      (_ * (_ * (_ * rest)), ret * rest) descr ->\n      (arg1 -> arg2 -> arg3 -> ret) * arg1 * arg2 * arg3 ->\n      (arg1 -> arg2 -> arg3 -> Gas.cost) ->\n      rest stack ->\n      ((ret * rest) stack * context) tzresult Lwt.t =\n   fun descr (op, x1, x2, x3) cost_func rest ->\n    Lwt.return (Gas.consume ctxt (cost_func x1 x2 x3))\n    >>=? fun ctxt -> logged_return descr (Item (op x1 x2 x3, rest), ctxt)\n  in\n  let consume_gas_binop :\n      type ret arg1 arg2 rest.\n      (_ * (_ * rest), ret * rest) descr ->\n      (arg1 -> arg2 -> ret) * arg1 * arg2 ->\n      (arg1 -> arg2 -> Gas.cost) ->\n      rest stack ->\n      context ->\n      ((ret * rest) stack * context) tzresult Lwt.t =\n   fun descr (op, x1, x2) cost_func rest ctxt ->\n    Lwt.return (Gas.consume ctxt (cost_func x1 x2))\n    >>=? fun ctxt -> logged_return descr (Item (op x1 x2, rest), ctxt)\n  in\n  let consume_gas_unop :\n      type ret arg rest.\n      (_ * rest, ret * rest) descr ->\n      (arg -> ret) * arg ->\n      (arg -> Gas.cost) ->\n      rest stack ->\n      context ->\n      ((ret * rest) stack * context) tzresult Lwt.t =\n   fun descr (op, arg) cost_func rest ctxt ->\n    Lwt.return (Gas.consume ctxt (cost_func arg))\n    >>=? fun ctxt -> logged_return descr (Item (op arg, rest), ctxt)\n  in\n  let logged_return : a stack * context -> (a stack * context) tzresult Lwt.t =\n    logged_return descr\n  in\n  match (instr, stack) with\n  (* stack ops *)\n  | (Drop, Item (_, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.stack_op)\n      >>=? fun ctxt -> logged_return (rest, ctxt)\n  | (Dup, Item (v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.stack_op)\n      >>=? fun ctxt -> logged_return (Item (v, Item (v, rest)), ctxt)\n  | (Swap, Item (vi, Item (vo, rest))) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.stack_op)\n      >>=? fun ctxt -> logged_return (Item (vo, Item (vi, rest)), ctxt)\n  | (Const v, rest) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.push)\n      >>=? fun ctxt -> logged_return (Item (v, rest), ctxt)\n  (* options *)\n  | (Cons_some, Item (v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.wrap)\n      >>=? fun ctxt -> logged_return (Item (Some v, rest), ctxt)\n  | (Cons_none _, rest) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.variant_no_data)\n      >>=? fun ctxt -> logged_return (Item (None, rest), ctxt)\n  | (If_none (bt, _), Item (None, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.branch)\n      >>=? fun ctxt -> step ?log ctxt step_constants bt rest\n  | (If_none (_, bf), Item (Some v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.branch)\n      >>=? fun ctxt -> step ?log ctxt step_constants bf (Item (v, rest))\n  (* pairs *)\n  | (Cons_pair, Item (a, Item (b, rest))) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.pair)\n      >>=? fun ctxt -> logged_return (Item ((a, b), rest), ctxt)\n  | (Car, Item ((a, _), rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.pair_access)\n      >>=? fun ctxt -> logged_return (Item (a, rest), ctxt)\n  | (Cdr, Item ((_, b), rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.pair_access)\n      >>=? fun ctxt -> logged_return (Item (b, rest), ctxt)\n  (* unions *)\n  | (Left, Item (v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.wrap)\n      >>=? fun ctxt -> logged_return (Item (L v, rest), ctxt)\n  | (Right, Item (v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.wrap)\n      >>=? fun ctxt -> logged_return (Item (R v, rest), ctxt)\n  | (If_left (bt, _), Item (L v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.branch)\n      >>=? fun ctxt -> step ?log ctxt step_constants bt (Item (v, rest))\n  | (If_left (_, bf), Item (R v, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.branch)\n      >>=? fun ctxt -> step ?log ctxt step_constants bf (Item (v, rest))\n  (* lists *)\n  | (Cons_list, Item (hd, Item (tl, rest))) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.cons)\n      >>=? fun ctxt -> logged_return (Item (hd :: tl, rest), ctxt)\n  | (Nil, rest) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.variant_no_data)\n      >>=? fun ctxt -> logged_return (Item ([], rest), ctxt)\n  | (If_cons (_, bf), Item ([], rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.branch)\n      >>=? fun ctxt -> step ?log ctxt step_constants bf rest\n  | (If_cons (bt, _), Item (hd :: tl, rest)) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.branch)\n      >>=? fun ctxt ->\n      step ?log ctxt step_constants bt (Item (hd, Item (tl, rest)))\n  | (List_map body, Item (l, rest)) ->\n      let rec loop rest ctxt l acc =\n        Lwt.return (Gas.consume ctxt Interp_costs.loop_map)\n        >>=? fun ctxt ->\n        match l with\n        | [] ->\n            return (Item (List.rev acc, rest), ctxt)\n        | hd :: tl ->\n            step ?log ctxt step_constants body (Item (hd, rest))\n            >>=? fun (Item (hd, rest), ctxt) -> loop rest ctxt tl (hd :: acc)\n      in\n      loop rest ctxt l [] >>=? fun (res, ctxt) -> logged_return (res, ctxt)\n  | (List_size, Item (list, rest)) ->\n      Lwt.return\n        (List.fold_left\n           (fun acc _ ->\n             acc\n             >>? fun (size, ctxt) ->\n             Gas.consume ctxt Interp_costs.loop_size\n             >>? fun ctxt -> ok (size + 1 (* FIXME: overflow *), ctxt))\n           (ok (0, ctxt))\n           list)\n      >>=? fun (len, ctxt) ->\n      logged_return (Item (Script_int.(abs (of_int len)), rest), ctxt)\n  | (List_iter body, Item (l, init)) ->\n      let rec loop ctxt l stack =\n        Lwt.return (Gas.consume ctxt Interp_costs.loop_iter)\n        >>=? fun ctxt ->\n        match l with\n        | [] ->\n            return (stack, ctxt)\n        | hd :: tl ->\n            step ?log ctxt step_constants body (Item (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  (* sets *)\n  | (Empty_set t, rest) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.empty_set)\n      >>=? fun ctxt -> logged_return (Item (empty_set t, rest), ctxt)\n  | (Set_iter body, Item (set, init)) ->\n      Lwt.return (Gas.consume ctxt (Interp_costs.set_to_list set))\n      >>=? fun ctxt ->\n      let l = List.rev (set_fold (fun e acc -> e :: acc) set []) in\n      let rec loop ctxt l stack =\n        Lwt.return (Gas.consume ctxt Interp_costs.loop_iter)\n        >>=? fun ctxt ->\n        match l with\n        | [] ->\n            return (stack, ctxt)\n        | hd :: tl ->\n            step ?log ctxt step_constants body (Item (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, Item (v, Item (set, rest))) ->\n      consume_gas_binop descr (set_mem, v, set) Interp_costs.set_mem rest ctxt\n  | (Set_update, Item (v, Item (presence, Item (set, rest)))) ->\n      consume_gas_terop\n        descr\n        (set_update, v, presence, set)\n        Interp_costs.set_update\n        rest\n  | (Set_size, Item (set, rest)) ->\n      consume_gas_unop\n        descr\n        (set_size, set)\n        (fun _ -> Interp_costs.set_size)\n        rest\n        ctxt\n  (* maps *)\n  | (Empty_map (t, _), rest) ->\n      Lwt.return (Gas.consume ctxt Interp_costs.empty_map)\n      >>=? fun ctxt -> logged_return (Item (empty_map t, rest), ctxt)\n  | (Map_map body, Item (map, rest)) ->\n      Lwt.return (Gas.consume ctxt (Interp_costs.map_to_list map))\n      >>=? fun ctxt ->\n