package tezos-baking-015-PtLimaPt

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

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

open Protocol
open Alpha_context
open Client_baking_blocks
module Events = Baking_events.VDF
module D_Events = Delegate_events.Denunciator

type vdf_solution = Seed_repr.vdf_solution

type vdf_setup = Seed_repr.vdf_setup

type status =
  | Not_started
  | Started
  | Finished of vdf_solution
  | Injected
  | Invalid

type 'a state = {
  cctxt : Protocol_client_context.full;
  constants : Constants.t;
  mutable block_stream : (block_info, 'a) result Lwt_stream.t;
  mutable stream_stopper : Tezos_rpc.Context.stopper option;
  mutable cycle : Cycle.t option;
  mutable computation_status : status;
  mutable vdf_setup : vdf_setup option;
}

let init_block_stream_with_stopper cctxt chain =
  Client_baking_blocks.monitor_applied_blocks
    ~next_protocols:(Some [Protocol.hash])
    cctxt
    ~chains:[chain]
    ()

let stop_block_stream state =
  Option.iter
    (fun stopper ->
      stopper () ;
      state.stream_stopper <- None)
    state.stream_stopper

let restart_block_stream cctxt chain state =
  let open Lwt_result_syntax in
  stop_block_stream state ;
  let retries_on_failure = 10 in
  let rec try_start_block_stream retries_on_failure =
    let*! p = init_block_stream_with_stopper cctxt chain in
    match p with
    | Ok (block_stream, stream_stopper) ->
        state.block_stream <- block_stream ;
        state.stream_stopper <- Some stream_stopper ;
        return_unit
    | Error e ->
        if retries_on_failure > 0 then
          let*! () = Lwt_unix.sleep 10. in
          try_start_block_stream (retries_on_failure - 1)
        else fail e
  in
  let* () = try_start_block_stream retries_on_failure in
  return_unit

let log_errors_and_continue ~name p =
  let open Lwt_syntax in
  let* p = p in
  match p with
  | Ok () -> return_unit
  | Error errs -> Events.(emit vdf_daemon_error) (name, errs)

let get_seed_computation cctxt chain_id hash =
  let chain = `Hash chain_id in
  let block = `Hash (hash, 0) in
  Alpha_services.Seed_computation.get cctxt (chain, block)

let get_level_info cctxt level =
  let open Lwt_result_syntax in
  let level = Raw_level.to_int32 level in
  let* {protocol_data = {level_info; _}; _} =
    Protocol_client_context.Alpha_block_services.metadata
      cctxt
      ~chain:cctxt#chain
      ~block:(`Level level)
      ()
  in
  return level_info

let is_in_nonce_revelation_period state (level_info : Level.t) =
  let open Lwt_result_syntax in
  let {Constants.parametric = {nonce_revelation_threshold; _}; _} =
    state.constants
  in
  let position_in_cycle = level_info.cycle_position in
  return (Int32.compare position_in_cycle nonce_revelation_threshold < 0)

let check_new_cycle state (level_info : Level.t) =
  let open Lwt_result_syntax in
  let current_cycle = level_info.cycle in
  match state.cycle with
  | None ->
      state.cycle <- Some current_cycle ;
      return_unit
  | Some cycle ->
      if Cycle.(succ cycle <= current_cycle) then (
        (* The cycle of this block is different from the cycle of the last
         * processed block. Emit an event if the VDF for the previous cycle
         * has not been injected and reset the computation status. *)
        let* () =
          match state.computation_status with
          | Injected -> return_unit
          | _ ->
              let cycle_str = Int32.to_string (Cycle.to_int32 cycle) in
              let*! () =
                Events.(emit vdf_info)
                  ("VDF revelation was NOT injected for cycle " ^ cycle_str)
              in
              return_unit
        in
        state.cycle <- Some current_cycle ;
        state.computation_status <- Not_started ;
        return_unit)
      else return_unit

let inject_vdf_revelation cctxt hash chain_id solution =
  let open Lwt_result_syntax in
  let chain = `Hash chain_id in
  let block = `Hash (hash, 0) in
  let* bytes =
    Plugin.RPC.Forge.vdf_revelation
      cctxt
      (chain, block)
      ~branch:hash
      ~solution
      ()
  in
  let bytes =
    Tezos_crypto.Signature.V0.concat bytes Tezos_crypto.Signature.V0.zero
  in
  Shell_services.Injection.operation cctxt ~chain bytes

(* Checks if the VDF setup saved in the state is equal to the one computed
   from a seed *)
let eq_vdf_setup state seed_discriminant seed_challenge =
  let open Environment.Vdf in
  match state.vdf_setup with
  | None -> assert false
  | Some (saved_discriminant, saved_challenge) ->
      let discriminant, challenge =
        Seed.generate_vdf_setup ~seed_discriminant ~seed_challenge
      in
      Bytes.equal
        (discriminant_to_bytes discriminant)
        (discriminant_to_bytes saved_discriminant)
      && Bytes.equal
           (challenge_to_bytes challenge)
           (challenge_to_bytes saved_challenge)

let process_new_block (cctxt : #Protocol_client_context.full) state
    {hash; chain_id; protocol; next_protocol; level; _} =
  let open Lwt_result_syntax in
  let* level_info = get_level_info cctxt level in
  let level_str = Int32.to_string (Raw_level.to_int32 level) in
  let* () = check_new_cycle state level_info in
  if Protocol_hash.(protocol <> next_protocol) then
    let*! () = D_Events.(emit protocol_change_detected) () in
    return_unit
  else
    let* out = is_in_nonce_revelation_period state level_info in
    if out then
      let*! () =
        Events.(emit vdf_info)
          ("Skipping, still in nonce revelation period (level " ^ level_str
         ^ ")")
      in
      return_unit
      (* enter main loop if we are not in the nonce revelation period and
         the expected protocol has been activated *)
    else
      match state.computation_status with
      | Started ->
          let*! () =
            Events.(emit vdf_info)
              ("Skipping, already started VDF (level " ^ level_str ^ ")")
          in
          return_unit
      | Not_started -> (
          let chain = `Hash chain_id in
          let* seed_computation = get_seed_computation cctxt chain_id hash in
          match seed_computation with
          | Vdf_revelation_stage {seed_discriminant; seed_challenge} ->
              state.computation_status <- Started ;
              let*! () =
                Events.(emit vdf_info)
                  ("Started to compute VDF (level " ^ level_str ^ ")")
              in
              let vdf_setup =
                Seed.generate_vdf_setup ~seed_discriminant ~seed_challenge
              in
              state.vdf_setup <- Some vdf_setup ;
              stop_block_stream state ;
              let* () =
                Lwt.catch
                  (fun () ->
                    let discriminant, challenge = vdf_setup in
                    (* `Vdf.prove` is a long computation. We reset the block
                     * stream in order to not process all the blocks added
                     * to the chain during this time and skip straight to
                     * the current head. *)
                    let solution =
                      Environment.Vdf.prove
                        discriminant
                        challenge
                        state.constants.parametric.vdf_difficulty
                    in
                    state.computation_status <- Finished solution ;
                    let*! () = Events.(emit vdf_info) "VDF solution computed" in
                    return_unit)
                  (fun _ ->
                    (* VDF computation failed with an error thrown by the external
                     * library. We set the status back to Not_started in order to
                     * retry computing it if still possible. *)
                    state.computation_status <- Not_started ;
                    let*! () =
                      Events.(emit vdf_info)
                        ("Failed to compute VDF solution (level " ^ level_str
                       ^ ")")
                    in
                    return_unit)
              in
              restart_block_stream cctxt chain state
          | Nonce_revelation_stage | Computation_finished ->
              (* Daemon started too early or too late in a cycle, skipping. *)
              return_unit)
      | Finished solution -> (
          let*! () =
            Events.(emit vdf_info) ("Finished VDF (level " ^ level_str ^ ")")
          in
          let chain = `Hash chain_id in
          let* seed_computation = get_seed_computation cctxt chain_id hash in
          match seed_computation with
          | Vdf_revelation_stage {seed_discriminant; seed_challenge} ->
              (* If a solution has been computed that is consistent with the VDF
               * setup for the current cycle and we are still in the VDF
               * revelation stage, inject the operation. *)
              if eq_vdf_setup state seed_discriminant seed_challenge then (
                let* op_hash =
                  inject_vdf_revelation cctxt hash chain_id solution
                in
                state.computation_status <- Injected ;
                let*! () =
                  Events.(emit vdf_revelation_injected)
                    ( Cycle.to_int32 level_info.cycle,
                      Chain_services.to_string chain,
                      op_hash )
                in
                return_unit)
              else (
                state.computation_status <- Invalid ;
                let*! () =
                  Events.(emit vdf_info)
                    ("Error injecting VDF: setup has been updated (level "
                   ^ level_str ^ ")")
                in
                return_unit)
          | Nonce_revelation_stage ->
              state.computation_status <- Not_started ;
              let*! () =
                Events.(emit vdf_info)
                  ("Error injecting VDF: new cycle started (level " ^ level_str
                 ^ ")")
              in
              return_unit
          | Computation_finished ->
              state.computation_status <- Injected ;
              let*! () =
                Events.(emit vdf_info)
                  ("Error injecting VDF: already injected (level " ^ level_str
                 ^ ")")
              in
              return_unit)
      | Injected ->
          let*! () =
            Events.(emit vdf_info)
              ("Skipping, already injected VDF (level " ^ level_str ^ ")")
          in
          return_unit
      | Invalid ->
          let*! () =
            Events.(emit vdf_info)
              ("Skipping, failed to compute VDF (level " ^ level_str ^ ")")
          in
          return_unit

let start_vdf_worker (cctxt : Protocol_client_context.full) ~canceler constants
    chain =
  let open Lwt_result_syntax in
  let* block_stream, stream_stopper =
    init_block_stream_with_stopper cctxt chain
  in
  let state =
    {
      cctxt;
      constants;
      block_stream;
      stream_stopper = Some stream_stopper;
      cycle = None;
      computation_status = Not_started;
      vdf_setup = None;
    }
  in
  Lwt_canceler.on_cancel canceler (fun () ->
      stop_block_stream state ;
      Lwt.return_unit) ;
  let rec worker_loop () =
    let*! b =
      Lwt.choose
        [
          (Lwt_exit.clean_up_starts >|= fun _ -> `Termination);
          (Lwt_stream.get state.block_stream >|= fun e -> `Block e);
        ]
    in
    match b with
    | `Termination -> return_unit
    | `Block (None | Some (Error _)) ->
        (* exit when the node is unavailable *)
        stop_block_stream state ;
        let*! () = Events.(emit vdf_daemon_connection_lost) name in
        tzfail Baking_errors.Node_connection_lost
    | `Block (Some (Ok bi)) ->
        let*! () =
          log_errors_and_continue ~name @@ process_new_block cctxt state bi
        in
        worker_loop ()
  in
  let*! () = Events.(emit vdf_daemon_start) name in
  worker_loop ()
OCaml

Innovation. Community. Security.