11use std:: sync:: Arc ;
22
3- use anyhow:: bail;
3+ use anyhow:: { anyhow , bail} ;
44use ream_consensus_beacon:: {
55 attestation:: Attestation , attester_slashing:: AttesterSlashing ,
66 electra:: beacon_block:: SignedBeaconBlock ,
77} ;
8- use ream_consensus_misc:: constants:: beacon:: { FULU_FORK_EPOCH , genesis_validators_root} ;
8+ use ream_consensus_misc:: {
9+ constants:: beacon:: { FULU_FORK_EPOCH , genesis_validators_root} ,
10+ misc:: compute_epoch_at_slot,
11+ } ;
912use ream_events_beacon:: { BeaconEvent , BeaconEventSender , event:: chain:: BlockEvent } ;
1013use ream_execution_engine:: ExecutionEngine ;
1114use ream_fork_choice_beacon:: {
1215 handlers:: { on_attestation, on_attester_slashing, on_block, on_tick} ,
1316 store:: Store ,
1417} ;
18+ use ream_metrics:: { BEACON_HEAD_EPOCH , BEACON_HEAD_SLOT , BEACON_REORGS_TOTAL } ;
1519use ream_network_spec:: networks:: beacon_network_spec;
1620use ream_operation_pool:: OperationPool ;
1721use ream_req_resp:: beacon:: messages:: status:: Status ;
@@ -48,6 +52,7 @@ impl BeaconChain {
4852
4953 pub async fn process_block ( & self , signed_block : SignedBeaconBlock ) -> anyhow:: Result < ( ) > {
5054 let mut store = self . store . lock ( ) . await ;
55+ let previous_head = store. get_head ( ) . ok ( ) ;
5156
5257 on_block (
5358 & mut store,
@@ -57,7 +62,34 @@ impl BeaconChain {
5762 )
5863 . await ?;
5964
60- // Build and Emit Block event
65+ let new_head = store. get_head ( ) ?;
66+ let new_head_block = store
67+ . db
68+ . block_provider ( )
69+ . get ( new_head) ?
70+ . ok_or_else ( || anyhow ! ( "head block not found in store" ) ) ?;
71+ let new_head_slot = new_head_block. message . slot ;
72+
73+ BEACON_HEAD_SLOT . set ( new_head_slot as i64 ) ;
74+ BEACON_HEAD_EPOCH . set ( compute_epoch_at_slot ( new_head_slot) as i64 ) ;
75+
76+ // Detect canonical chain reorgs for beacon_reorgs_total.
77+ // A head change alone is insufficient because normal chain extensions
78+ // also change the head. We only count a reorg when the previous head
79+ // is no longer an ancestor of the new head.
80+ if let Some ( previous_head) = previous_head
81+ && previous_head != new_head
82+ && let Some ( previous_head_block) = store. db . block_provider ( ) . get ( previous_head) ?
83+ {
84+ let previous_head_slot = previous_head_block. message . slot ;
85+ let still_ancestor =
86+ store. get_ancestor ( new_head, previous_head_slot) . ok ( ) == Some ( previous_head) ;
87+
88+ if !still_ancestor {
89+ BEACON_REORGS_TOTAL . inc ( ) ;
90+ }
91+ }
92+
6193 let finalized_checkpoint = store. db . finalized_checkpoint_provider ( ) . get ( ) . ok ( ) ;
6294 let block_event =
6395 BlockEvent :: from_block ( & signed_block, finalized_checkpoint, |block_root, epoch| {
0 commit comments