reth_node_events/
node.rs

1//! Support for handling events emitted by node components.
2
3use crate::cl::ConsensusLayerHealthEvent;
4use alloy_consensus::{constants::GWEI_TO_WEI, BlockHeader};
5use alloy_primitives::{BlockNumber, B256};
6use alloy_rpc_types_engine::ForkchoiceState;
7use futures::Stream;
8use reth_engine_primitives::{ConsensusEngineEvent, ForkchoiceStatus};
9use reth_network_api::PeersInfo;
10use reth_primitives_traits::{format_gas, format_gas_throughput, BlockBody, NodePrimitives};
11use reth_prune_types::PrunerEvent;
12use reth_stages::{EntitiesCheckpoint, ExecOutput, PipelineEvent, StageCheckpoint, StageId};
13use reth_static_file_types::StaticFileProducerEvent;
14use std::{
15    fmt::{Display, Formatter},
16    future::Future,
17    pin::Pin,
18    task::{Context, Poll},
19    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
20};
21use tokio::time::Interval;
22use tracing::{debug, info, warn};
23
24/// Interval of reporting node state.
25const INFO_MESSAGE_INTERVAL: Duration = Duration::from_secs(25);
26
27/// The current high-level state of the node, including the node's database environment, network
28/// connections, current processing stage, and the latest block information. It provides
29/// methods to handle different types of events that affect the node's state, such as pipeline
30/// events, network events, and consensus engine events.
31struct NodeState {
32    /// Information about connected peers.
33    peers_info: Option<Box<dyn PeersInfo>>,
34    /// The stage currently being executed.
35    current_stage: Option<CurrentStage>,
36    /// The latest block reached by either pipeline or consensus engine.
37    latest_block: Option<BlockNumber>,
38    /// Hash of the head block last set by fork choice update
39    head_block_hash: Option<B256>,
40    /// Hash of the safe block last set by fork choice update
41    safe_block_hash: Option<B256>,
42    /// Hash of finalized block last set by fork choice update
43    finalized_block_hash: Option<B256>,
44    /// The time when we last logged a status message
45    last_status_log_time: Option<u64>,
46}
47
48impl NodeState {
49    const fn new(
50        peers_info: Option<Box<dyn PeersInfo>>,
51        latest_block: Option<BlockNumber>,
52    ) -> Self {
53        Self {
54            peers_info,
55            current_stage: None,
56            latest_block,
57            head_block_hash: None,
58            safe_block_hash: None,
59            finalized_block_hash: None,
60            last_status_log_time: None,
61        }
62    }
63
64    fn num_connected_peers(&self) -> usize {
65        self.peers_info.as_ref().map(|info| info.num_connected_peers()).unwrap_or_default()
66    }
67
68    fn build_current_stage(
69        &self,
70        stage_id: StageId,
71        checkpoint: StageCheckpoint,
72        target: Option<BlockNumber>,
73    ) -> CurrentStage {
74        let (eta, entities_checkpoint) = self
75            .current_stage
76            .as_ref()
77            .filter(|current_stage| current_stage.stage_id == stage_id)
78            .map_or_else(
79                || (Eta::default(), None),
80                |current_stage| (current_stage.eta, current_stage.entities_checkpoint),
81            );
82
83        CurrentStage { stage_id, eta, checkpoint, entities_checkpoint, target }
84    }
85
86    /// Processes an event emitted by the pipeline
87    fn handle_pipeline_event(&mut self, event: PipelineEvent) {
88        match event {
89            PipelineEvent::Prepare { pipeline_stages_progress, stage_id, checkpoint, target } => {
90                let checkpoint = checkpoint.unwrap_or_default();
91                let current_stage = self.build_current_stage(stage_id, checkpoint, target);
92
93                info!(
94                    pipeline_stages = %pipeline_stages_progress,
95                    stage = %stage_id,
96                    checkpoint = %checkpoint.block_number,
97                    target = %OptionalField(target),
98                    "Preparing stage",
99                );
100
101                self.current_stage = Some(current_stage);
102            }
103            PipelineEvent::Run { pipeline_stages_progress, stage_id, checkpoint, target } => {
104                let checkpoint = checkpoint.unwrap_or_default();
105                let current_stage = self.build_current_stage(stage_id, checkpoint, target);
106
107                if let Some(stage_eta) = current_stage.eta.fmt_for_stage(stage_id) {
108                    info!(
109                        pipeline_stages = %pipeline_stages_progress,
110                        stage = %stage_id,
111                        checkpoint = %checkpoint.block_number,
112                        target = %OptionalField(target),
113                        %stage_eta,
114                        "Executing stage",
115                    );
116                } else {
117                    info!(
118                        pipeline_stages = %pipeline_stages_progress,
119                        stage = %stage_id,
120                        checkpoint = %checkpoint.block_number,
121                        target = %OptionalField(target),
122                        "Executing stage",
123                    );
124                }
125
126                self.current_stage = Some(current_stage);
127            }
128            PipelineEvent::Ran {
129                pipeline_stages_progress,
130                stage_id,
131                result: ExecOutput { checkpoint, done },
132            } => {
133                if stage_id.is_finish() {
134                    self.latest_block = Some(checkpoint.block_number);
135                }
136
137                if let Some(current_stage) = self.current_stage.as_mut() {
138                    current_stage.checkpoint = checkpoint;
139                    current_stage.entities_checkpoint = checkpoint.entities();
140                    current_stage.eta.update(stage_id, checkpoint);
141
142                    let target = OptionalField(current_stage.target);
143                    let stage_progress = current_stage
144                        .entities_checkpoint
145                        .and_then(|entities| entities.fmt_percentage());
146                    let stage_eta = current_stage.eta.fmt_for_stage(stage_id);
147
148                    let message = if done { "Finished stage" } else { "Committed stage progress" };
149
150                    match (stage_progress, stage_eta) {
151                        (Some(stage_progress), Some(stage_eta)) => {
152                            info!(
153                                pipeline_stages = %pipeline_stages_progress,
154                                stage = %stage_id,
155                                checkpoint = %checkpoint.block_number,
156                                %target,
157                                %stage_progress,
158                                %stage_eta,
159                                "{message}",
160                            )
161                        }
162                        (Some(stage_progress), None) => {
163                            info!(
164                                pipeline_stages = %pipeline_stages_progress,
165                                stage = %stage_id,
166                                checkpoint = %checkpoint.block_number,
167                                %target,
168                                %stage_progress,
169                                "{message}",
170                            )
171                        }
172                        (None, Some(stage_eta)) => {
173                            info!(
174                                pipeline_stages = %pipeline_stages_progress,
175                                stage = %stage_id,
176                                checkpoint = %checkpoint.block_number,
177                                %target,
178                                %stage_eta,
179                                "{message}",
180                            )
181                        }
182                        (None, None) => {
183                            info!(
184                                pipeline_stages = %pipeline_stages_progress,
185                                stage = %stage_id,
186                                checkpoint = %checkpoint.block_number,
187                                %target,
188                                "{message}",
189                            )
190                        }
191                    }
192                }
193
194                if done {
195                    self.current_stage = None;
196                }
197            }
198            PipelineEvent::Unwind { stage_id, input } => {
199                let current_stage = CurrentStage {
200                    stage_id,
201                    eta: Eta::default(),
202                    checkpoint: input.checkpoint,
203                    target: Some(input.unwind_to),
204                    entities_checkpoint: input.checkpoint.entities(),
205                };
206
207                self.current_stage = Some(current_stage);
208            }
209            _ => (),
210        }
211    }
212
213    fn handle_consensus_engine_event<N: NodePrimitives>(&mut self, event: ConsensusEngineEvent<N>) {
214        match event {
215            ConsensusEngineEvent::ForkchoiceUpdated(state, status) => {
216                let ForkchoiceState { head_block_hash, safe_block_hash, finalized_block_hash } =
217                    state;
218                if self.safe_block_hash != Some(safe_block_hash) &&
219                    self.finalized_block_hash != Some(finalized_block_hash)
220                {
221                    let msg = match status {
222                        ForkchoiceStatus::Valid => "Forkchoice updated",
223                        ForkchoiceStatus::Invalid => "Received invalid forkchoice updated message",
224                        ForkchoiceStatus::Syncing => {
225                            "Received forkchoice updated message when syncing"
226                        }
227                    };
228                    info!(?head_block_hash, ?safe_block_hash, ?finalized_block_hash, "{}", msg);
229                }
230                self.head_block_hash = Some(head_block_hash);
231                self.safe_block_hash = Some(safe_block_hash);
232                self.finalized_block_hash = Some(finalized_block_hash);
233            }
234            ConsensusEngineEvent::CanonicalBlockAdded(executed, elapsed) => {
235                let block = executed.sealed_block();
236                let mut full = block.gas_used() as f64 * 100.0 / block.gas_limit() as f64;
237                if full.is_nan() {
238                    full = 0.0;
239                }
240                info!(
241                    number=block.number(),
242                    hash=?block.hash(),
243                    peers=self.num_connected_peers(),
244                    txs=block.body().transactions().len(),
245                    gas_used=%format_gas(block.gas_used()),
246                    gas_throughput=%format_gas_throughput(block.gas_used(), elapsed),
247                    gas_limit=%format_gas(block.gas_limit()),
248                    full=%format!("{:.1}%", full),
249                    base_fee=%format!("{:.2}Gwei", block.base_fee_per_gas().unwrap_or(0) as f64 / GWEI_TO_WEI as f64),
250                    blobs=block.blob_gas_used().unwrap_or(0) / alloy_eips::eip4844::DATA_GAS_PER_BLOB,
251                    excess_blobs=block.excess_blob_gas().unwrap_or(0) / alloy_eips::eip4844::DATA_GAS_PER_BLOB,
252                    ?elapsed,
253                    "Block added to canonical chain"
254                );
255            }
256            ConsensusEngineEvent::CanonicalChainCommitted(head, elapsed) => {
257                self.latest_block = Some(head.number());
258                info!(number=head.number(), hash=?head.hash(), ?elapsed, "Canonical chain committed");
259            }
260            ConsensusEngineEvent::ForkBlockAdded(executed, elapsed) => {
261                let block = executed.sealed_block();
262                info!(number=block.number(), hash=?block.hash(), ?elapsed, "Block added to fork chain");
263            }
264            ConsensusEngineEvent::InvalidBlock(block) => {
265                warn!(number=block.number(), hash=?block.hash(), "Encountered invalid block");
266            }
267            ConsensusEngineEvent::BlockReceived(num_hash) => {
268                info!(number=num_hash.number, hash=?num_hash.hash, "Received block from consensus engine");
269            }
270        }
271    }
272
273    fn handle_consensus_layer_health_event(&self, event: ConsensusLayerHealthEvent) {
274        // If pipeline is running, it's fine to not receive any messages from the CL.
275        // So we need to report about CL health only when pipeline is idle.
276        if self.current_stage.is_none() {
277            match event {
278                ConsensusLayerHealthEvent::NeverSeen => {
279                    warn!(
280                        "Post-merge network, but never seen beacon client. Please launch one to follow the chain!"
281                    )
282                }
283                ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile(period) => {
284                    warn!(
285                        ?period,
286                        "Beacon client online, but no consensus updates received for a while. This may be because of a reth error, or an error in the beacon client! Please investigate reth and beacon client logs!"
287                    )
288                }
289            }
290        }
291    }
292
293    fn handle_pruner_event(&self, event: PrunerEvent) {
294        match event {
295            PrunerEvent::Started { tip_block_number } => {
296                debug!(tip_block_number, "Pruner started");
297            }
298            PrunerEvent::Finished { tip_block_number, elapsed, stats } => {
299                let stats = format!(
300                    "[{}]",
301                    stats.iter().map(|item| item.to_string()).collect::<Vec<_>>().join(", ")
302                );
303                debug!(tip_block_number, ?elapsed, pruned_segments = %stats, "Pruner finished");
304            }
305        }
306    }
307
308    fn handle_static_file_producer_event(&self, event: StaticFileProducerEvent) {
309        match event {
310            StaticFileProducerEvent::Started { targets } => {
311                debug!(?targets, "Static File Producer started");
312            }
313            StaticFileProducerEvent::Finished { targets, elapsed } => {
314                debug!(?targets, ?elapsed, "Static File Producer finished");
315            }
316        }
317    }
318}
319
320/// Helper type for formatting of optional fields:
321/// - If [Some(x)], then `x` is written
322/// - If [None], then `None` is written
323struct OptionalField<T: Display>(Option<T>);
324
325impl<T: Display> Display for OptionalField<T> {
326    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
327        if let Some(field) = &self.0 {
328            write!(f, "{field}")
329        } else {
330            write!(f, "None")
331        }
332    }
333}
334
335/// The stage currently being executed.
336struct CurrentStage {
337    stage_id: StageId,
338    eta: Eta,
339    checkpoint: StageCheckpoint,
340    /// The entities checkpoint for reporting the progress. If `None`, then the progress is not
341    /// available, probably because the stage didn't finish running and didn't update its
342    /// checkpoint yet.
343    entities_checkpoint: Option<EntitiesCheckpoint>,
344    target: Option<BlockNumber>,
345}
346
347/// A node event.
348#[derive(Debug, derive_more::From)]
349pub enum NodeEvent<N: NodePrimitives> {
350    /// A sync pipeline event.
351    Pipeline(PipelineEvent),
352    /// A consensus engine event.
353    ConsensusEngine(ConsensusEngineEvent<N>),
354    /// A Consensus Layer health event.
355    ConsensusLayerHealth(ConsensusLayerHealthEvent),
356    /// A pruner event
357    Pruner(PrunerEvent),
358    /// A `static_file_producer` event
359    StaticFileProducer(StaticFileProducerEvent),
360    /// Used to encapsulate various conditions or situations that do not
361    /// naturally fit into the other more specific variants.
362    Other(String),
363}
364
365/// Displays relevant information to the user from components of the node, and periodically
366/// displays the high-level status of the node.
367pub async fn handle_events<E, N: NodePrimitives>(
368    peers_info: Option<Box<dyn PeersInfo>>,
369    latest_block_number: Option<BlockNumber>,
370    events: E,
371) where
372    E: Stream<Item = NodeEvent<N>> + Unpin,
373{
374    let state = NodeState::new(peers_info, latest_block_number);
375
376    let start = tokio::time::Instant::now() + Duration::from_secs(3);
377    let mut info_interval = tokio::time::interval_at(start, INFO_MESSAGE_INTERVAL);
378    info_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
379
380    let handler = EventHandler { state, events, info_interval };
381    handler.await
382}
383
384/// Handles events emitted by the node and logs them accordingly.
385#[pin_project::pin_project]
386struct EventHandler<E> {
387    state: NodeState,
388    #[pin]
389    events: E,
390    #[pin]
391    info_interval: Interval,
392}
393
394impl<E, N: NodePrimitives> Future for EventHandler<E>
395where
396    E: Stream<Item = NodeEvent<N>> + Unpin,
397{
398    type Output = ();
399
400    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
401        let mut this = self.project();
402
403        while this.info_interval.poll_tick(cx).is_ready() {
404            if let Some(CurrentStage { stage_id, eta, checkpoint, entities_checkpoint, target }) =
405                &this.state.current_stage
406            {
407                let stage_progress =
408                    entities_checkpoint.and_then(|entities| entities.fmt_percentage());
409                let stage_eta = eta.fmt_for_stage(*stage_id);
410
411                match (stage_progress, stage_eta) {
412                    (Some(stage_progress), Some(stage_eta)) => {
413                        info!(
414                            target: "reth::cli",
415                            connected_peers = this.state.num_connected_peers(),
416                            stage = %stage_id,
417                            checkpoint = checkpoint.block_number,
418                            target = %OptionalField(*target),
419                            %stage_progress,
420                            %stage_eta,
421                            "Status"
422                        )
423                    }
424                    (Some(stage_progress), None) => {
425                        info!(
426                            target: "reth::cli",
427                            connected_peers = this.state.num_connected_peers(),
428                            stage = %stage_id,
429                            checkpoint = checkpoint.block_number,
430                            target = %OptionalField(*target),
431                            %stage_progress,
432                            "Status"
433                        )
434                    }
435                    (None, Some(stage_eta)) => {
436                        info!(
437                            target: "reth::cli",
438                            connected_peers = this.state.num_connected_peers(),
439                            stage = %stage_id,
440                            checkpoint = checkpoint.block_number,
441                            target = %OptionalField(*target),
442                            %stage_eta,
443                            "Status"
444                        )
445                    }
446                    (None, None) => {
447                        info!(
448                            target: "reth::cli",
449                            connected_peers = this.state.num_connected_peers(),
450                            stage = %stage_id,
451                            checkpoint = checkpoint.block_number,
452                            target = %OptionalField(*target),
453                            "Status"
454                        )
455                    }
456                }
457            } else {
458                let now =
459                    SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
460
461                // Only log status if we haven't logged recently
462                if now.saturating_sub(this.state.last_status_log_time.unwrap_or(0)) > 60 {
463                    if let Some(latest_block) = this.state.latest_block {
464                        info!(
465                            target: "reth::cli",
466                            connected_peers = this.state.num_connected_peers(),
467                            %latest_block,
468                            "Status"
469                        );
470                    } else {
471                        info!(
472                            target: "reth::cli",
473                            connected_peers = this.state.num_connected_peers(),
474                            "Status"
475                        );
476                    }
477                    this.state.last_status_log_time = Some(now);
478                }
479            }
480        }
481
482        while let Poll::Ready(Some(event)) = this.events.as_mut().poll_next(cx) {
483            match event {
484                NodeEvent::Pipeline(event) => {
485                    this.state.handle_pipeline_event(event);
486                }
487                NodeEvent::ConsensusEngine(event) => {
488                    this.state.handle_consensus_engine_event(event);
489                }
490                NodeEvent::ConsensusLayerHealth(event) => {
491                    this.state.handle_consensus_layer_health_event(event)
492                }
493                NodeEvent::Pruner(event) => {
494                    this.state.handle_pruner_event(event);
495                }
496                NodeEvent::StaticFileProducer(event) => {
497                    this.state.handle_static_file_producer_event(event);
498                }
499                NodeEvent::Other(event_description) => {
500                    warn!("{event_description}");
501                }
502            }
503        }
504
505        Poll::Pending
506    }
507}
508
509/// A container calculating the estimated time that a stage will complete in, based on stage
510/// checkpoints reported by the pipeline.
511///
512/// One `Eta` is only valid for a single stage.
513#[derive(Default, Copy, Clone)]
514struct Eta {
515    /// The last stage checkpoint
516    last_checkpoint: EntitiesCheckpoint,
517    /// The last time the stage reported its checkpoint
518    last_checkpoint_time: Option<Instant>,
519    /// The current ETA
520    eta: Option<Duration>,
521}
522
523impl Eta {
524    /// Update the ETA given the checkpoint, if possible.
525    fn update(&mut self, stage: StageId, checkpoint: StageCheckpoint) {
526        let Some(current) = checkpoint.entities() else { return };
527
528        if let Some(last_checkpoint_time) = &self.last_checkpoint_time {
529            let Some(processed_since_last) =
530                current.processed.checked_sub(self.last_checkpoint.processed)
531            else {
532                self.eta = None;
533                debug!(target: "reth::cli", %stage, ?current, ?self.last_checkpoint, "Failed to calculate the ETA: processed entities is less than the last checkpoint");
534                return
535            };
536            let elapsed = last_checkpoint_time.elapsed();
537            let per_second = processed_since_last as f64 / elapsed.as_secs_f64();
538
539            let Some(remaining) = current.total.checked_sub(current.processed) else {
540                self.eta = None;
541                debug!(target: "reth::cli", %stage, ?current, "Failed to calculate the ETA: total entities is less than processed entities");
542                return
543            };
544
545            self.eta = Duration::try_from_secs_f64(remaining as f64 / per_second).ok();
546        }
547
548        self.last_checkpoint = current;
549        self.last_checkpoint_time = Some(Instant::now());
550    }
551
552    /// Returns `true` if the ETA is available, i.e. at least one checkpoint has been reported.
553    fn is_available(&self) -> bool {
554        self.eta.zip(self.last_checkpoint_time).is_some()
555    }
556
557    /// Format ETA for a given stage.
558    ///
559    /// NOTE: Currently ETA is enabled only for the stages that have predictable progress.
560    /// It's not the case for network-dependent ([`StageId::Headers`] and [`StageId::Bodies`]) and
561    /// [`StageId::Execution`] stages.
562    fn fmt_for_stage(&self, stage: StageId) -> Option<String> {
563        if !self.is_available() ||
564            matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution)
565        {
566            None
567        } else {
568            Some(self.to_string())
569        }
570    }
571}
572
573impl Display for Eta {
574    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
575        if let Some((eta, last_checkpoint_time)) = self.eta.zip(self.last_checkpoint_time) {
576            let remaining = eta.checked_sub(last_checkpoint_time.elapsed());
577
578            if let Some(remaining) = remaining {
579                return write!(
580                    f,
581                    "{}",
582                    humantime::format_duration(Duration::from_secs(remaining.as_secs()))
583                        .to_string()
584                        .replace(' ', "")
585                )
586            }
587        }
588
589        write!(f, "unknown")
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596
597    #[test]
598    fn eta_display_no_milliseconds() {
599        let eta = Eta {
600            last_checkpoint_time: Some(Instant::now()),
601            eta: Some(Duration::from_millis(
602                13 * 60 * 1000 + // Minutes
603                    37 * 1000 + // Seconds
604                    999, // Milliseconds
605            )),
606            ..Default::default()
607        }
608        .to_string();
609
610        assert_eq!(eta, "13m37s");
611    }
612}