Source file client_baking_denunciation.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
open Protocol
open Alpha_context
open Protocol_client_context
open Client_baking_blocks
module Events = Delegate_events.Denunciator
module B_Events = Delegate_events.Baking_scheduling
module HLevel = Hashtbl.Make (struct
type t = Chain_id.t * Raw_level.t * Round.t
let equal (c, l, r) (c', l', r') =
Chain_id.equal c c' && Raw_level.equal l l' && Round.equal r r'
let hash (c, lvl, r) = Hashtbl.hash (c, lvl, r)
end)
module Delegate_Map = Map.Make (Tezos_crypto.Signature.V0.Public_key_hash)
module Slot_Map = Slot.Map
type ops_stream =
((Operation_hash.t * packed_operation) * error trace option) list Lwt_stream.t
type 'a state = {
endorsements_table : Kind.endorsement operation Slot_Map.t HLevel.t;
preendorsements_table : Kind.preendorsement operation Slot_Map.t HLevel.t;
blocks_table : Block_hash.t Delegate_Map.t HLevel.t;
preserved_levels : int;
mutable highest_level_encountered : Raw_level.t;
clean_frequency : int;
mutable cleaning_countdown : int;
blocks_stream : (block_info, 'a) result Lwt_stream.t;
mutable ops_stream : ops_stream;
mutable ops_stream_stopper : unit -> unit;
}
let create_state ~preserved_levels blocks_stream ops_stream ops_stream_stopper =
let clean_frequency = max 1 (preserved_levels / 10) in
Lwt.return
{
endorsements_table = HLevel.create preserved_levels;
preendorsements_table = HLevel.create preserved_levels;
blocks_table = HLevel.create preserved_levels;
preserved_levels;
highest_level_encountered = Raw_level.root ;
clean_frequency;
cleaning_countdown = clean_frequency;
blocks_stream;
ops_stream;
ops_stream_stopper;
}
let get_block_offset level =
match Raw_level.of_int32 5l with
| Ok min_level ->
let offset = Raw_level.diff level min_level in
if Compare.Int32.(offset >= 0l) then Lwt.return (`Head 5)
else
let negative_offset = Int32.to_int offset in
Lwt.return (`Head (5 + negative_offset - 1))
| Error errs ->
Events.(emit invalid_level_conversion) (Environment.wrap_tztrace errs)
>>= fun () -> Lwt.return (`Head 0)
let get_payload_hash (type kind) (op_kind : kind consensus_operation_type)
(op : kind Operation.t) =
match (op_kind, op.protocol_data.contents) with
| Preendorsement, Single (Preendorsement consensus_content)
| Endorsement, Single (Endorsement consensus_content) ->
consensus_content.block_payload_hash
| _ -> .
let double_consensus_op_evidence (type kind) :
kind consensus_operation_type ->
#Protocol_client_context.full ->
'a ->
branch:Block_hash.t ->
op1:kind Alpha_context.operation ->
op2:kind Alpha_context.operation ->
unit ->
bytes Environment.Error_monad.shell_tzresult Lwt.t = function
| Endorsement -> Plugin.RPC.Forge.double_endorsement_evidence
| Preendorsement -> Plugin.RPC.Forge.double_preendorsement_evidence
let process_consensus_op (type kind) cctxt
(op_kind : kind consensus_operation_type) (new_op : kind Operation.t)
chain_id level round slot ops_table =
let map =
Option.value ~default:Slot_Map.empty
@@ HLevel.find ops_table (chain_id, level, round)
in
match Slot_Map.find slot map with
| None ->
return
@@ HLevel.add
ops_table
(chain_id, level, round)
(Slot_Map.add slot new_op map)
| Some existing_op
when Block_payload_hash.(
get_payload_hash op_kind existing_op
<> get_payload_hash op_kind new_op) ->
let new_op_hash, existing_op_hash =
(Operation.hash new_op, Operation.hash existing_op)
in
let op1, op2 =
if Operation_hash.(new_op_hash < existing_op_hash) then
(new_op, existing_op)
else (existing_op, new_op)
in
get_block_offset level >>= fun block ->
let chain = `Hash chain_id in
Alpha_block_services.hash cctxt ~chain ~block () >>=? fun block_hash ->
double_consensus_op_evidence
op_kind
cctxt
(`Hash chain_id, block)
~branch:block_hash
~op1
~op2
()
>>=? fun bytes ->
let bytes =
Tezos_crypto.Signature.V0.concat bytes Tezos_crypto.Signature.V0.zero
in
let double_op_detected, double_op_denounced =
Events.(
match op_kind with
| Endorsement ->
(double_endorsement_detected, double_endorsement_denounced)
| Preendorsement ->
(double_preendorsement_detected, double_preendorsement_denounced))
in
Events.(emit double_op_detected) (new_op_hash, existing_op_hash)
>>= fun () ->
HLevel.replace
ops_table
(chain_id, level, round)
(Slot_Map.add slot new_op map) ;
Shell_services.Injection.operation cctxt ~chain bytes >>=? fun op_hash ->
Events.(emit double_op_denounced) (op_hash, bytes) >>= fun () ->
return_unit
| _ -> return_unit
let process_operations (cctxt : #Protocol_client_context.full) state
(endorsements : 'a list) ~packed_op chain_id =
List.iter_es
(fun op ->
let {shell; protocol_data; _} = packed_op op in
match protocol_data with
| Operation_data
({contents = Single (Preendorsement {round; slot; level; _}); _} as
protocol_data) ->
let new_preendorsement : Kind.preendorsement Alpha_context.operation =
{shell; protocol_data}
in
process_consensus_op
cctxt
Preendorsement
new_preendorsement
chain_id
level
round
slot
state.preendorsements_table
| Operation_data
({contents = Single (Endorsement {round; slot; level; _}); _} as
protocol_data) ->
let new_endorsement : Kind.endorsement Alpha_context.operation =
{shell; protocol_data}
in
process_consensus_op
cctxt
Endorsement
new_endorsement
chain_id
level
round
slot
state.endorsements_table
| _ ->
return_unit)
endorsements
let cctxt ~chain b_hash =
Alpha_block_services.header cctxt ~chain ~block:(`Hash (b_hash, 0)) ()
>>=? fun ({shell; protocol_data; _} : Alpha_block_services.block_header) ->
return {Alpha_context.Block_header.shell; protocol_data}
let process_block (cctxt : #Protocol_client_context.full) state
( : Alpha_block_services.block_info) =
match header with
| {hash; metadata = None; _} ->
Events.(emit unexpected_pruned_block) hash >>= fun () -> return_unit
| {
Alpha_block_services.chain_id;
hash = new_hash;
metadata = Some {protocol_data = {baker; level_info = {level; _}; _}; _};
header = {shell = {fitness; _}; _};
_;
} -> (
let fitness = Fitness.from_raw fitness in
Lwt.return
(match fitness with
| Ok fitness -> Ok (Fitness.round fitness)
| Error errs -> Error (Environment.wrap_tztrace errs))
>>=? fun round ->
let chain = `Hash chain_id in
let map =
Option.value ~default:Delegate_Map.empty
@@ HLevel.find state.blocks_table (chain_id, level, round)
in
match Delegate_Map.find baker.delegate map with
| None ->
return
@@ HLevel.add
state.blocks_table
(chain_id, level, round)
(Delegate_Map.add baker.delegate new_hash map)
| Some existing_hash when Block_hash.(existing_hash = new_hash) ->
Events.(emit double_baking_but_not) () >>= fun () ->
return
@@ HLevel.replace
state.blocks_table
(chain_id, level, round)
(Delegate_Map.add baker.delegate new_hash map)
| Some existing_hash ->
context_block_header cctxt ~chain existing_hash >>=? fun bh1 ->
context_block_header cctxt ~chain new_hash >>=? fun bh2 ->
let hash1 = Block_header.hash bh1 in
let hash2 = Block_header.hash bh2 in
let bh1, bh2 =
if Block_hash.(hash1 < hash2) then (bh1, bh2) else (bh2, bh1)
in
get_block_offset level >>= fun block ->
Alpha_block_services.hash cctxt ~chain ~block ()
>>=? fun block_hash ->
Plugin.RPC.Forge.double_baking_evidence
cctxt
(chain, block)
~branch:block_hash
~bh1
~bh2
()
>>=? fun bytes ->
let bytes =
Tezos_crypto.Signature.V0.concat
bytes
Tezos_crypto.Signature.V0.zero
in
Events.(emit double_baking_detected) () >>= fun () ->
Shell_services.Injection.operation cctxt ~chain bytes
>>=? fun op_hash ->
Events.(emit double_baking_denounced) (op_hash, bytes) >>= fun () ->
return
@@ HLevel.replace
state.blocks_table
(chain_id, level, round)
(Delegate_Map.add baker.delegate new_hash map))
let cleanup_old_operations state =
state.cleaning_countdown <- state.cleaning_countdown - 1 ;
if state.cleaning_countdown < 0 then (
state.cleaning_countdown <- state.clean_frequency ;
let highest_level_encountered =
Int32.to_int (Raw_level.to_int32 state.highest_level_encountered)
in
let diff = highest_level_encountered - state.preserved_levels in
let threshold =
if diff < 0 then Raw_level.root
else
Raw_level.of_int32 (Int32.of_int diff) |> function
| Ok threshold -> threshold
| Error _ -> Raw_level.root
in
let filter hmap =
HLevel.filter_map_inplace
(fun (_, level, _) x ->
if Raw_level.(level < threshold) then None else Some x)
hmap
in
filter state.preendorsements_table ;
filter state.endorsements_table ;
filter state.blocks_table)
let process_new_block (cctxt : #Protocol_client_context.full) state
{hash; chain_id; level; protocol; next_protocol; _} =
if Protocol_hash.(protocol <> next_protocol) then
Events.(emit protocol_change_detected) () >>= fun () -> return_unit
else
Events.(emit accuser_saw_block) (level, hash) >>= fun () ->
let chain = `Hash chain_id in
let block = `Hash (hash, 0) in
state.highest_level_encountered <-
Raw_level.max level state.highest_level_encountered ;
(Alpha_block_services.info cctxt ~chain ~block () >>= function
| Ok block_info -> (
process_block cctxt state block_info >>=? fun () ->
match block_info.operations with
| consensus_ops :: _ ->
let packed_op {Alpha_block_services.shell; protocol_data; _} =
{shell; protocol_data}
in
process_operations cctxt state consensus_ops ~packed_op chain_id
| _ ->
Events.(emit fetch_operations_error hash) >>= fun () -> return_unit
)
| Error errs ->
Events.(emit accuser_block_error) (hash, errs) >>= fun () ->
return_unit)
>>=? fun () ->
cleanup_old_operations state ;
return_unit
let process_new_block cctxt state bi =
process_new_block cctxt state bi >>= function
| Ok () -> Events.(emit accuser_processed_block) bi.hash >>= Lwt.return
| Error errs ->
Events.(emit accuser_block_error) (bi.hash, errs) >>= Lwt.return
let rec wait_for_first_block ~name stream =
Lwt_stream.get stream >>= function
| None | Some (Error _) ->
B_Events.(emit cannot_fetch_event) name >>= fun () ->
wait_for_first_block ~name stream
| Some (Ok bi) -> Lwt.return bi
let log_errors_and_continue ~name p =
p >>= function
| Ok () -> Lwt.return_unit
| Error errs -> B_Events.(emit daemon_error) (name, errs)
let start_ops_monitor cctxt =
Alpha_block_services.Mempool.monitor_operations
cctxt
~chain:cctxt#chain
~applied:true
~branch_delayed:true
~branch_refused:true
~refused:true
~outdated:true
()
let create (cctxt : #Protocol_client_context.full) ?canceler ~preserved_levels
valid_blocks_stream =
B_Events.(emit daemon_setup) name >>= fun () ->
start_ops_monitor cctxt >>=? fun (ops_stream, ops_stream_stopper) ->
create_state
~preserved_levels
valid_blocks_stream
ops_stream
ops_stream_stopper
>>= fun state ->
Option.iter
(fun canceler ->
Lwt_canceler.on_cancel canceler (fun () ->
state.ops_stream_stopper () ;
Lwt.return_unit))
canceler ;
wait_for_first_block ~name state.blocks_stream >>= fun _first_event ->
let last_get_block = ref None in
let get_block () =
match !last_get_block with
| None ->
let t = Lwt_stream.get state.blocks_stream >|= fun e -> `Block e in
last_get_block := Some t ;
t
| Some t -> t
in
let last_get_ops = ref None in
let get_ops () =
match !last_get_ops with
| None ->
let t = Lwt_stream.get state.ops_stream >|= fun e -> `Operations e in
last_get_ops := Some t ;
t
| Some t -> t
in
Chain_services.chain_id cctxt () >>=? fun chain_id ->
let terminated = Lwt_exit.clean_up_starts >|= fun _ -> `Termination in
let rec worker_loop () =
Lwt.choose [terminated; get_block (); get_ops ()] >>= function
| `Termination -> return_unit
| `Block (None | Some (Error _)) ->
last_get_block := None ;
B_Events.(emit daemon_connection_lost) name >>= fun () ->
fail Baking_errors.Node_connection_lost
| `Block (Some (Ok bi)) ->
last_get_block := None ;
process_new_block cctxt state bi >>= fun () -> worker_loop ()
| `Operations None ->
last_get_ops := None ;
state.ops_stream_stopper () ;
start_ops_monitor cctxt >>=? fun (ops_stream, ops_stream_stopper) ->
state.ops_stream <- ops_stream ;
state.ops_stream_stopper <- ops_stream_stopper ;
worker_loop ()
| `Operations (Some ops) ->
last_get_ops := None ;
log_errors_and_continue ~name
@@ process_operations
cctxt
state
ops
~packed_op:(fun ((_h, op), _errl) -> op)
chain_id
>>= fun () -> worker_loop ()
in
B_Events.(emit daemon_start) name >>= fun () -> worker_loop ()