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