Source file baking_nonces.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
open Protocol
open Alpha_context
open Baking_cache
module Events = Baking_events.Nonces
type state = {
cctxt : Protocol_client_context.full;
chain : Chain_services.chain;
constants : Constants.t;
config : Baking_configuration.nonce_config;
nonces_location : [`Nonce] Baking_files.location;
mutable last_predecessor : Block_hash.t;
cycle_cache : Block_hash.t list Cycle_cache.t;
(** This cache is used to avoid calling expensive RPCs at each
block. Still, this component's logic is very inefficient and
should be refactored. This cache is intended as "duct tape"
until a proper refactoring happens. *)
}
type t = state
type nonces = Nonce.t Block_hash.Map.t
let empty = Block_hash.Map.empty
let encoding =
let open Data_encoding in
def "seed_nonce"
@@ conv
(fun m ->
Block_hash.Map.fold (fun hash nonce acc -> (hash, nonce) :: acc) m [])
(fun l ->
List.fold_left
(fun map (hash, nonce) -> Block_hash.Map.add hash nonce map)
Block_hash.Map.empty
l)
@@ list (obj2 (req "block" Block_hash.encoding) (req "nonce" Nonce.encoding))
let may_migrate (wallet : Protocol_client_context.full) location =
let open Lwt_syntax in
let base_dir = wallet#get_base_dir in
let current_file =
Filename.Infix.((base_dir // Baking_files.filename location) ^ "s")
in
let* exists = Lwt_unix.file_exists current_file in
match exists with
| true ->
return_unit
| false -> (
let legacy_file = Filename.Infix.(base_dir // "nonces") in
let* exists = Lwt_unix.file_exists legacy_file in
match exists with
| false ->
return_unit
| true -> Lwt_utils_unix.copy_file ~src:legacy_file ~dst:current_file)
let load (wallet : #Client_context.wallet) location =
wallet#load (Baking_files.filename location) ~default:empty encoding
let save (wallet : #Client_context.wallet) location nonces =
wallet#write (Baking_files.filename location) nonces encoding
let mem nonces hash = Block_hash.Map.mem hash nonces
let find_opt nonces hash = Block_hash.Map.find hash nonces
let add nonces hash nonce = Block_hash.Map.add hash nonce nonces
let remove nonces hash = Block_hash.Map.remove hash nonces
let remove_all nonces nonces_to_remove =
Block_hash.Map.fold
(fun hash _ acc -> remove acc hash)
nonces_to_remove
nonces
let get_block_level_opt cctxt ~chain ~block =
let open Lwt_syntax in
let* result =
Shell_services.Blocks.Header.shell_header cctxt ~chain ~block ()
in
match result with
| Ok {level; _} -> return_some level
| Error errs ->
let* () =
Events.(
emit
cant_retrieve_block_header_for_nonce
(Block_services.to_string block, errs))
in
return_none
let get_outdated_nonces {cctxt; constants; chain; _} nonces =
let open Lwt_result_syntax in
let {Constants.parametric = {blocks_per_cycle; preserved_cycles; _}; _} =
constants
in
let*! current_level = get_block_level_opt cctxt ~chain ~block:(`Head 0) in
match current_level with
| None ->
let*! () = Events.(emit cannot_fetch_chain_head_level ()) in
return (empty, empty)
| Some current_level ->
let current_cycle = Int32.(div current_level blocks_per_cycle) in
let is_older_than_preserved_cycles block_level =
let block_cycle = Int32.(div block_level blocks_per_cycle) in
Int32.sub current_cycle block_cycle > Int32.of_int preserved_cycles
in
Block_hash.Map.fold
(fun hash nonce acc ->
let* orphans, outdated = acc in
let*! level =
get_block_level_opt cctxt ~chain ~block:(`Hash (hash, 0))
in
match level with
| Some level ->
if is_older_than_preserved_cycles level then
return (orphans, add outdated hash nonce)
else acc
| None -> return (add orphans hash nonce, outdated))
nonces
(return (empty, empty))
let filter_outdated_nonces state nonces =
let open Lwt_result_syntax in
let* orphans, outdated_nonces = get_outdated_nonces state nonces in
let* () =
when_
(Block_hash.Map.cardinal orphans >= 50)
(fun () ->
let*! () =
Events.(
emit
too_many_nonces
(Baking_files.filename state.nonces_location ^ "s"))
in
return_unit)
in
return (remove_all nonces outdated_nonces)
let blocks_from_previous_cycle {cctxt; chain; _} =
let open Lwt_result_syntax in
let block = `Head 0 in
let*! result =
Plugin.RPC.levels_in_current_cycle cctxt ~offset:(-1l) (chain, block)
in
match result with
| Error (Tezos_rpc.Context.Not_found _ :: _) -> return_nil
| Error _ as err -> Lwt.return err
| Ok (first, last) -> (
let* hash = Shell_services.Blocks.hash cctxt ~chain ~block () in
let* {level; _} =
Shell_services.Blocks.Header.shell_header cctxt ~chain ~block ()
in
let length = Int32.to_int (Int32.sub level (Raw_level.to_int32 first)) in
let* blocks_list =
Shell_services.Blocks.list cctxt ~chain ~heads:[hash] ~length ()
in
match blocks_list with
| [blocks] ->
if Int32.equal level (Raw_level.to_int32 last) then
return blocks
else
List.drop_n
(length - Int32.to_int (Raw_level.diff last first))
blocks
|> return
| l ->
failwith
"Baking_nonces.blocks_from_current_cycle: unexpected block list of \
size %d (expected 1)"
(List.length l))
let cached_blocks_from_previous_cycle ({cctxt; chain; cycle_cache; _} as state)
=
let open Lwt_result_syntax in
let* {cycle = current_cycle; _} =
Plugin.RPC.current_level cctxt (chain, `Head 0)
in
match Cycle.pred current_cycle with
| None ->
return_nil
| Some cycle_key -> (
match Cycle_cache.find_opt cycle_cache cycle_key with
| Some blocks -> return blocks
| None ->
let* blocks = blocks_from_previous_cycle state in
Cycle_cache.replace cycle_cache cycle_key blocks ;
return blocks)
let get_unrevealed_nonces ({cctxt; chain; _} as state) nonces =
let open Lwt_result_syntax in
let* blocks = cached_blocks_from_previous_cycle state in
List.filter_map_es
(fun hash ->
match find_opt nonces hash with
| None -> return_none
| Some nonce -> (
let*! level =
get_block_level_opt cctxt ~chain ~block:(`Hash (hash, 0))
in
match level with
| Some level -> (
let*? level =
Environment.wrap_tzresult (Raw_level.of_int32 level)
in
let* nonce_info =
Alpha_services.Nonce.get cctxt (chain, `Head 0) level
in
match nonce_info with
| Missing nonce_hash when Nonce.check_hash nonce nonce_hash ->
let*! () =
Events.(
emit found_nonce_to_reveal (hash, Raw_level.to_int32 level))
in
return_some (level, nonce)
| Missing _nonce_hash ->
let*! () =
Events.(emit incoherent_nonce (Raw_level.to_int32 level))
in
return_none
| Forgotten -> return_none
| Revealed _ -> return_none)
| None -> return_none))
blocks
let generate_seed_nonce (nonce_config : Baking_configuration.nonce_config)
(delegate : Baking_state.consensus_key) level =
let open Lwt_result_syntax in
let* nonce =
match nonce_config with
| Deterministic ->
let data = Data_encoding.Binary.to_bytes_exn Raw_level.encoding level in
let* nonce =
Client_keys.deterministic_nonce delegate.secret_key_uri data
in
return (Data_encoding.Binary.of_bytes_exn Nonce.encoding nonce)
| Random -> (
match
Nonce.of_bytes (Tezos_crypto.Rand.generate Constants.nonce_length)
with
| Error _errs -> assert false
| Ok nonce -> return nonce)
in
return (Nonce.hash nonce, nonce)
let register_nonce (cctxt : #Protocol_client_context.full) ~chain_id block_hash
nonce =
let open Lwt_result_syntax in
let*! () = Events.(emit registering_nonce block_hash) in
let nonces_location = Baking_files.resolve_location ~chain_id `Nonce in
cctxt#with_lock @@ fun () ->
let* nonces = load cctxt nonces_location in
let nonces = add nonces block_hash nonce in
let* () = save cctxt nonces_location nonces in
return_unit
let inject_seed_nonce_revelation (cctxt : #Protocol_client_context.full) ~chain
~block ~branch nonces =
let open Lwt_result_syntax in
match nonces with
| [] ->
let*! () = Events.(emit nothing_to_reveal branch) in
return_unit
| _ ->
List.iter_es
(fun (level, nonce) ->
let* bytes =
Plugin.RPC.Forge.seed_nonce_revelation
cctxt
(chain, block)
~branch
~level
~nonce
()
in
let bytes = Signature.concat bytes Signature.zero in
let* oph =
Shell_services.Injection.operation ~async:true cctxt ~chain bytes
in
let*! () =
Events.(
emit
revealing_nonce
(Raw_level.to_int32 level, Chain_services.to_string chain, oph))
in
return_unit)
nonces
(** [reveal_potential_nonces] reveal registered nonces *)
let reveal_potential_nonces state new_proposal =
let open Lwt_result_syntax in
let {cctxt; chain; nonces_location; last_predecessor; _} = state in
let new_predecessor_hash = new_proposal.Baking_state.predecessor.hash in
if
Block_hash.(last_predecessor <> new_predecessor_hash)
&& not (Baking_state.is_first_block_in_protocol new_proposal)
then (
state.last_predecessor <- new_predecessor_hash ;
let block = `Head 0 in
let branch = new_predecessor_hash in
cctxt#with_lock @@ fun () ->
let*! nonces = load cctxt nonces_location in
match nonces with
| Error err ->
let*! () = Events.(emit cannot_read_nonces err) in
return_unit
| Ok nonces -> (
let*! nonces_to_reveal = get_unrevealed_nonces state nonces in
match nonces_to_reveal with
| Error err ->
let*! () = Events.(emit cannot_retrieve_unrevealed_nonces err) in
return_unit
| Ok [] -> return_unit
| Ok nonces_to_reveal -> (
let*! result =
inject_seed_nonce_revelation
cctxt
~chain
~block
~branch
nonces_to_reveal
in
match result with
| Error err ->
let*! () = Events.(emit cannot_inject_nonces err) in
return_unit
| Ok () ->
let* live_nonces = filter_outdated_nonces state nonces in
let* () = save cctxt nonces_location live_nonces in
return_unit)))
else return_unit
let start_revelation_worker cctxt config chain_id constants block_stream =
let open Lwt_result_syntax in
let nonces_location = Baking_files.resolve_location ~chain_id `Nonce in
let*! () = may_migrate cctxt nonces_location in
let chain = `Hash chain_id in
let canceler = Lwt_canceler.create () in
let should_shutdown = ref false in
let state =
{
cctxt;
chain;
constants;
config;
nonces_location;
last_predecessor = Block_hash.zero;
cycle_cache = Cycle_cache.create 2;
}
in
let rec worker_loop () =
Lwt_canceler.on_cancel canceler (fun () ->
should_shutdown := true ;
Lwt.return_unit) ;
let*! new_proposal = Lwt_stream.get block_stream in
match new_proposal with
| None ->
return_unit
| Some new_proposal ->
if !should_shutdown then return_unit
else
let* () = reveal_potential_nonces state new_proposal in
worker_loop ()
in
Lwt.dont_wait
(fun () ->
Lwt.finalize
(fun () ->
let*! () = Events.(emit revelation_worker_started ()) in
let*! _ = worker_loop () in
Lwt.return_unit)
(fun () -> Lwt.return_unit))
(fun _exn -> ()) ;
Lwt.return canceler