Source file wasm_pvm.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
open Wasm_pvm_state.Internal_state
module Wasm = Tezos_webassembly_interpreter
module Parsing = Binary_parser_encodings
open Tezos_lazy_containers
let durable_scope = ["durable"]
let tick_state_encoding =
  let open Tezos_tree_encoding in
  tagged_union
    ~default:(fun () -> Collect)
    (value [] Data_encoding.string)
    [
      case
        "snapshot"
        (return ())
        (function Snapshot -> Some () | _ -> None)
        (fun () -> Snapshot);
      case
        "decode"
        Parsing.Decode.encoding
        (function Decode m -> Some m | _ -> None)
        (fun m -> Decode m);
      case
        "link"
        (tup3
           ~flatten:true
           (scope ["ast_module"]
           @@ Parsing.(no_region_encoding Module.module_encoding))
           (scope
              ["externs"]
              (Lazy_vector.Int32Vector.encoding
                 (value [] Data_encoding.int32)
                 Wasm_encoding.extern_encoding))
           (value ["imports_offset"] Data_encoding.int32))
        (function
          | Link {ast_module; externs; imports_offset} ->
              Some (ast_module, externs, imports_offset)
          | _ -> None)
        (fun (ast_module, externs, imports_offset) ->
          Link {ast_module; externs; imports_offset});
      case
        "init"
        (tup4
           ~flatten:true
           (scope ["self"] Wasm_encoding.module_key_encoding)
           (scope ["ast_module"]
           @@ Parsing.(no_region_encoding Module.module_encoding))
           (scope ["init_kont"] Init_encodings.init_kont_encoding)
           (scope ["modules"] Wasm_encoding.module_instances_encoding))
        (function
          | Init {self; ast_module; init_kont; module_reg} ->
              Some (self, ast_module, init_kont, module_reg)
          | _ -> None)
        (fun (self, ast_module, init_kont, module_reg) ->
          Init {self; ast_module; init_kont; module_reg});
      case
        "eval"
        (tup2
           ~flatten:true
           (scope ["config"] @@ Wasm_encoding.config_encoding)
           (scope ["modules"] Wasm_encoding.module_instances_encoding))
        (function
          | Eval {config; module_reg} -> Some (config, module_reg) | _ -> None)
        (fun (config, module_reg) -> Eval {config; module_reg});
      case
        "stuck"
        (value [] Wasm_pvm_errors.encoding)
        (function Stuck err -> Some err | _ -> None)
        (fun err -> Stuck err);
      case
        "collect"
        (return ())
        (function Collect -> Some () | _ -> None)
        (fun () -> Collect);
      case
        "padding"
        (return ())
        (function Padding -> Some () | _ -> None)
        (fun () -> Padding);
    ]
let durable_buffers_encoding =
  Tezos_tree_encoding.(scope ["pvm"; "buffers"] Wasm_encoding.buffers_encoding)
let durable_storage_encoding =
  Tezos_tree_encoding.(scope durable_scope Durable.encoding)
let default_buffers validity_period message_limit () =
  Tezos_webassembly_interpreter.Eval.
    {
      input = Tezos_webassembly_interpreter.Input_buffer.alloc ();
      output =
        Tezos_webassembly_interpreter.Output_buffer.alloc
          ~validity_period
          ~message_limit
          ~last_level:None;
    }
let output_buffer_parameters_encoding =
  Tezos_tree_encoding.(
    conv
      (fun (validity_period, message_limit) -> {validity_period; message_limit})
      (fun {validity_period; message_limit} -> (validity_period, message_limit))
      (tup2
         ~flatten:true
         (value ["pvm"; "outbox_validity_period"] Data_encoding.int32)
         (value ["pvm"; "outbox_message_limit"] Data_encoding.z)))
let pvm_state_encoding =
  let open Tezos_tree_encoding in
  conv
    (fun ( last_input_info,
           current_tick,
           reboot_counter,
           durable,
           buffers,
           tick_state,
           last_top_level_call,
           max_nb_ticks,
           maximum_reboots_per_input,
           output_buffer_parameters ) ->
      {
        last_input_info;
        current_tick;
        reboot_counter =
          Option.value
            ~default:(Z.succ maximum_reboots_per_input)
            
            reboot_counter;
        durable;
        buffers =
          
          Option.value_f
            ~default:
              (default_buffers
                 output_buffer_parameters.validity_period
                 output_buffer_parameters.message_limit)
            buffers;
        tick_state;
        last_top_level_call;
        max_nb_ticks;
        maximum_reboots_per_input;
        output_buffer_parameters;
      })
    (fun {
           last_input_info;
           current_tick;
           reboot_counter;
           durable;
           buffers;
           tick_state;
           last_top_level_call;
           max_nb_ticks;
           maximum_reboots_per_input;
           output_buffer_parameters;
         } ->
      ( last_input_info,
        current_tick,
        Some reboot_counter,
        durable,
        Some buffers,
        tick_state,
        last_top_level_call,
        max_nb_ticks,
        maximum_reboots_per_input,
        output_buffer_parameters ))
    (tup10
       ~flatten:true
       (value_option ["wasm"; "input"] Wasm_pvm_sig.input_info_encoding)
       (value ~default:Z.zero ["wasm"; "current_tick"] Data_encoding.n)
       (value_option ["wasm"; "reboot_counter"] Data_encoding.n)
       durable_storage_encoding
       (option durable_buffers_encoding)
       (scope ["wasm"] tick_state_encoding)
       (value ~default:Z.zero ["pvm"; "last_top_level_call"] Data_encoding.n)
       (value ["pvm"; "max_nb_ticks"] Data_encoding.n)
       (value
          ~default:Constants.maximum_reboots_per_input
          ["pvm"; "maximum_reboots_per_input"]
          Data_encoding.n)
       output_buffer_parameters_encoding)
module Make_pvm (Wasm_vm : Wasm_vm_sig.S) (T : Tezos_tree_encoding.TREE) :
  Wasm_pvm_sig.S with type tree = T.tree = struct
  type tree = T.tree
  module Tree_encoding_runner = Tezos_tree_encoding.Runner.Make (T)
  let decode tree = Tree_encoding_runner.decode pvm_state_encoding tree
  let encode pvm_state tree =
    let open Lwt.Syntax in
    
    let* tree = T.remove tree ["wasm"] in
    Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
  let initial_state version empty_tree =
    let open Lwt.Syntax in
    let* durable =
      Tree_encoding_runner.decode durable_storage_encoding empty_tree
    in
    let version_str =
      Data_encoding.Binary.to_string_exn Wasm_pvm_state.version_encoding version
    in
    let* durable =
      Durable.set_value_exn
        ~edit_readonly:true
        durable
        Constants.version_key
        version_str
    in
    Tree_encoding_runner.encode durable_storage_encoding durable empty_tree
  let install_boot_sector ~ticks_per_snapshot ~outbox_validity_period
      ~outbox_message_limit bs tree =
    let open Lwt_syntax in
    let open Tezos_tree_encoding in
    let* durable =
      Tree_encoding_runner.decode (scope durable_scope Durable.encoding) tree
    in
    let reboot_flag_key = Durable.key_of_string_exn "/kernel/env/reboot" in
    let kernel_key = Durable.key_of_string_exn "/kernel/boot.wasm" in
    let* durable = Durable.set_value_exn durable reboot_flag_key "" in
    let* durable = Durable.set_value_exn durable kernel_key bs in
    let pvm : pvm_state =
      {
        last_input_info = None;
        current_tick = Z.zero;
        reboot_counter = Z.succ Constants.maximum_reboots_per_input;
        durable;
        buffers = default_buffers outbox_validity_period outbox_message_limit ();
        tick_state = Collect;
        last_top_level_call = Z.zero;
        max_nb_ticks = ticks_per_snapshot;
        maximum_reboots_per_input = Constants.maximum_reboots_per_input;
        output_buffer_parameters =
          {
            validity_period = outbox_validity_period;
            message_limit = outbox_message_limit;
          };
      }
    in
    encode pvm tree
  let compute_step_many ?reveal_builtins ?write_debug ?stop_at_snapshot
      ~max_steps tree =
    let open Lwt.Syntax in
    let* pvm_state = decode tree in
    let* pvm_state, executed_ticks =
      Wasm_vm.compute_step_many
        ?reveal_builtins
        ?write_debug
        ?stop_at_snapshot
        ~max_steps
        pvm_state
    in
    let+ tree = encode pvm_state tree in
    (tree, executed_ticks)
  let compute_step_with_debug ~write_debug tree =
    let open Lwt.Syntax in
    let* initial_state = decode tree in
    let* final_state =
      Wasm_vm.compute_step_with_debug ~write_debug initial_state
    in
    encode final_state tree
  let compute_step tree = compute_step_with_debug tree ~write_debug:Noop
  let get_output output_info tree =
    let open Lwt_syntax in
    let* candidate =
      Tree_encoding_runner.decode
        (Tezos_tree_encoding.option durable_buffers_encoding)
        tree
    in
    Lwt.catch
      (fun () ->
        match candidate with
        | Some {output; _} ->
            let+ result = Wasm_vm.get_output output_info output in
            Some result
        | None -> Lwt.return None)
      (fun _ -> Lwt.return None)
  let get_info tree =
    let open Lwt_syntax in
    let* pvm_state = decode tree in
    Wasm_vm.get_info pvm_state
  let set_input_step input_info message tree =
    let open Lwt_syntax in
    let* pvm_state = decode tree in
    let* pvm_state = Wasm_vm.set_input_step input_info message pvm_state in
    encode pvm_state tree
  let reveal_step payload tree =
    let open Lwt_syntax in
    let* pvm_state = decode tree in
    let* pvm_state = Wasm_vm.reveal_step payload pvm_state in
    encode pvm_state tree
  let get_wasm_version tree =
    let open Lwt.Syntax in
    let* pvm = Tree_encoding_runner.decode pvm_state_encoding tree in
    Wasm_vm.get_wasm_version pvm
  module Internal_for_tests = struct
    let get_tick_state tree =
      let open Lwt_syntax in
      let+ pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      pvm_state.tick_state
    let get_module_instance_exn tree =
      let open Lwt_syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      match pvm_state.tick_state with
      | Eval {module_reg; _} | Init {module_reg; _} ->
          Wasm.Instance.ModuleMap.get Constants.wasm_main_module_name module_reg
      | _ -> raise (Invalid_argument "get_module_instance")
    let is_stuck tree =
      let open Lwt.Syntax in
      let* pvm = Tree_encoding_runner.decode pvm_state_encoding tree in
      match pvm.tick_state with
      | Stuck error -> Lwt.return_some error
      | _ -> Lwt.return_none
    let set_max_nb_ticks n tree =
      let open Lwt_syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      let pvm_state = {pvm_state with max_nb_ticks = n} in
      Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
    let set_maximum_reboots_per_input n tree =
      let open Lwt_syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      let pvm_state =
        {
          pvm_state with
          maximum_reboots_per_input = n;
          reboot_counter = Z.(min (succ n) pvm_state.reboot_counter);
        }
      in
      Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
    let decr_reboot_counter tree =
      let open Lwt_syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      let pvm_state =
        {pvm_state with reboot_counter = Z.pred pvm_state.reboot_counter}
      in
      Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
    let reset_reboot_counter tree =
      let open Lwt_syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      let pvm_state =
        {
          pvm_state with
          reboot_counter = Z.succ pvm_state.maximum_reboots_per_input;
        }
      in
      Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
    let get_output_buffer tree =
      let open Lwt.Syntax in
      let+ pvm = Tree_encoding_runner.decode pvm_state_encoding tree in
      pvm.buffers.output
    let get_input_buffer tree =
      let open Lwt.Syntax in
      let+ pvm = Tree_encoding_runner.decode pvm_state_encoding tree in
      pvm.buffers.input
    let compute_step_many_with_hooks ?reveal_builtins ?write_debug
        ?after_fast_exec ?stop_at_snapshot ~max_steps tree =
      let open Lwt.Syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      let* pvm_state, ticks =
        Wasm_vm.Internal_for_tests.compute_step_many_with_hooks
          ?reveal_builtins
          ?write_debug
          ?after_fast_exec
          ?stop_at_snapshot
          ~max_steps
          pvm_state
      in
      let+ tree =
        Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
      in
      (tree, ticks)
    let compute_step_many_until ?max_steps ?reveal_builtins ?write_debug
        should_compute tree =
      let open Lwt.Syntax in
      let* pvm_state = Tree_encoding_runner.decode pvm_state_encoding tree in
      let* pvm_state, ticks =
        Wasm_vm.compute_step_many_until
          ?max_steps
          ?reveal_builtins
          ?write_debug
          should_compute
          pvm_state
      in
      let+ tree =
        Tree_encoding_runner.encode pvm_state_encoding pvm_state tree
      in
      (tree, ticks)
  end
end
module Make = Make_pvm (Wasm_vm)