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    ConsensusEngineEvent, 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>(&mut self, event: ConsensusEngineEvent<N>) {
216        match event {
217            ConsensusEngineEvent::ForkchoiceUpdated(state, status) => {
218                let ForkchoiceState { head_block_hash, safe_block_hash, finalized_block_hash } =
219                    state;
220                if self.safe_block_hash != Some(safe_block_hash) &&
221                    self.finalized_block_hash != Some(finalized_block_hash)
222                {
223                    let msg = match status {
224                        ForkchoiceStatus::Valid => "Forkchoice updated",
225                        ForkchoiceStatus::Invalid => "Received invalid forkchoice updated message",
226                        ForkchoiceStatus::Syncing => {
227                            "Received forkchoice updated message when syncing"
228                        }
229                    };
230                    info!(?head_block_hash, ?safe_block_hash, ?finalized_block_hash, "{}", msg);
231                }
232                self.head_block_hash = Some(head_block_hash);
233                self.safe_block_hash = Some(safe_block_hash);
234                self.finalized_block_hash = Some(finalized_block_hash);
235            }
236            ConsensusEngineEvent::LiveSyncProgress(live_sync_progress) => {
237                match live_sync_progress {
238                    ConsensusEngineLiveSyncProgress::DownloadingBlocks {
239                        remaining_blocks,
240                        target,
241                    } => {
242                        info!(
243                            remaining_blocks,
244                            target_block_hash=?target,
245                            "Live sync in progress, downloading blocks"
246                        );
247                    }
248                }
249            }
250            ConsensusEngineEvent::CanonicalBlockAdded(executed, elapsed) => {
251                let block = executed.sealed_block();
252                info!(
253                    number=block.number(),
254                    hash=?block.hash(),
255                    peers=self.num_connected_peers(),
256                    txs=block.body().transactions().len(),
257                    gas_used=%format_gas(block.gas_used()),
258                    gas_throughput=%format_gas_throughput(block.gas_used(), elapsed),
259                    gas_limit=%format_gas(block.gas_limit()),
260                    full=%format!("{:.1}%", block.gas_used() as f64 * 100.0 / block.gas_limit() as f64),
261                    base_fee=%format!("{:.2}Gwei", block.base_fee_per_gas().unwrap_or(0) as f64 / GWEI_TO_WEI as f64),
262                    blobs=block.blob_gas_used().unwrap_or(0) / alloy_eips::eip4844::DATA_GAS_PER_BLOB,
263                    excess_blobs=block.excess_blob_gas().unwrap_or(0) / alloy_eips::eip4844::DATA_GAS_PER_BLOB,
264                    ?elapsed,
265                    "Block added to canonical chain"
266                );
267            }
268            ConsensusEngineEvent::CanonicalChainCommitted(head, elapsed) => {
269                self.latest_block = Some(head.number());
270                self.latest_block_time = Some(head.timestamp());
271
272                info!(number=head.number(), hash=?head.hash(), ?elapsed, "Canonical chain committed");
273            }
274            ConsensusEngineEvent::ForkBlockAdded(executed, elapsed) => {
275                let block = executed.sealed_block();
276                info!(number=block.number(), hash=?block.hash(), ?elapsed, "Block added to fork chain");
277            }
278            ConsensusEngineEvent::InvalidBlock(block) => {
279                warn!(number=block.number(), hash=?block.hash(), "Encountered invalid block");
280            }
281            ConsensusEngineEvent::BlockReceived(num_hash) => {
282                info!(number=num_hash.number, hash=?num_hash.hash, "Received block from consensus engine");
283            }
284        }
285    }
286
287    fn handle_consensus_layer_health_event(&self, event: ConsensusLayerHealthEvent) {
288        // If pipeline is running, it's fine to not receive any messages from the CL.
289        // So we need to report about CL health only when pipeline is idle.
290        if self.current_stage.is_none() {
291            match event {
292                ConsensusLayerHealthEvent::NeverSeen => {
293                    warn!(
294                        "Post-merge network, but never seen beacon client. Please launch one to follow the chain!"
295                    )
296                }
297                ConsensusLayerHealthEvent::HasNotBeenSeenForAWhile(period) => {
298                    warn!(
299                        ?period,
300                        "Post-merge network, but no beacon client seen for a while. Please launch one to follow the chain!"
301                    )
302                }
303                ConsensusLayerHealthEvent::NeverReceivedUpdates => {
304                    warn!(
305                        "Beacon client online, but never received consensus updates. Please ensure your beacon client is operational to follow the chain!"
306                    )
307                }
308                ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile(period) => {
309                    warn!(
310                        ?period,
311                        "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!"
312                    )
313                }
314            }
315        }
316    }
317
318    fn handle_pruner_event(&self, event: PrunerEvent) {
319        match event {
320            PrunerEvent::Started { tip_block_number } => {
321                debug!(tip_block_number, "Pruner started");
322            }
323            PrunerEvent::Finished { tip_block_number, elapsed, stats } => {
324                let stats = format!(
325                    "[{}]",
326                    stats.iter().map(|item| item.to_string()).collect::<Vec<_>>().join(", ")
327                );
328                debug!(tip_block_number, ?elapsed, pruned_segments = %stats, "Pruner finished");
329            }
330        }
331    }
332
333    fn handle_static_file_producer_event(&self, event: StaticFileProducerEvent) {
334        match event {
335            StaticFileProducerEvent::Started { targets } => {
336                debug!(?targets, "Static File Producer started");
337            }
338            StaticFileProducerEvent::Finished { targets, elapsed } => {
339                debug!(?targets, ?elapsed, "Static File Producer finished");
340            }
341        }
342    }
343}
344
345/// Helper type for formatting of optional fields:
346/// - If [Some(x)], then `x` is written
347/// - If [None], then `None` is written
348struct OptionalField<T: Display>(Option<T>);
349
350impl<T: Display> Display for OptionalField<T> {
351    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
352        if let Some(field) = &self.0 {
353            write!(f, "{field}")
354        } else {
355            write!(f, "None")
356        }
357    }
358}
359
360/// The stage currently being executed.
361struct CurrentStage {
362    stage_id: StageId,
363    eta: Eta,
364    checkpoint: StageCheckpoint,
365    /// The entities checkpoint for reporting the progress. If `None`, then the progress is not
366    /// available, probably because the stage didn't finish running and didn't update its
367    /// checkpoint yet.
368    entities_checkpoint: Option<EntitiesCheckpoint>,
369    target: Option<BlockNumber>,
370}
371
372/// A node event.
373#[derive(Debug, derive_more::From)]
374pub enum NodeEvent<N: NodePrimitives> {
375    /// A sync pipeline event.
376    Pipeline(PipelineEvent),
377    /// A consensus engine event.
378    ConsensusEngine(ConsensusEngineEvent<N>),
379    /// A Consensus Layer health event.
380    ConsensusLayerHealth(ConsensusLayerHealthEvent),
381    /// A pruner event
382    Pruner(PrunerEvent),
383    /// A `static_file_producer` event
384    StaticFileProducer(StaticFileProducerEvent),
385    /// Used to encapsulate various conditions or situations that do not
386    /// naturally fit into the other more specific variants.
387    Other(String),
388}
389
390/// Displays relevant information to the user from components of the node, and periodically
391/// displays the high-level status of the node.
392pub async fn handle_events<E, N: NodePrimitives>(
393    peers_info: Option<Box<dyn PeersInfo>>,
394    latest_block_number: Option<BlockNumber>,
395    events: E,
396) where
397    E: Stream<Item = NodeEvent<N>> + Unpin,
398{
399    let state = NodeState::new(peers_info, latest_block_number);
400
401    let start = tokio::time::Instant::now() + Duration::from_secs(3);
402    let mut info_interval = tokio::time::interval_at(start, INFO_MESSAGE_INTERVAL);
403    info_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
404
405    let handler = EventHandler { state, events, info_interval };
406    handler.await
407}
408
409/// Handles events emitted by the node and logs them accordingly.
410#[pin_project::pin_project]
411struct EventHandler<E> {
412    state: NodeState,
413    #[pin]
414    events: E,
415    #[pin]
416    info_interval: Interval,
417}
418
419impl<E, N: NodePrimitives> Future for EventHandler<E>
420where
421    E: Stream<Item = NodeEvent<N>> + Unpin,
422{
423    type Output = ();
424
425    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
426        let mut this = self.project();
427
428        while this.info_interval.poll_tick(cx).is_ready() {
429            if let Some(CurrentStage { stage_id, eta, checkpoint, entities_checkpoint, target }) =
430                &this.state.current_stage
431            {
432                let stage_progress =
433                    entities_checkpoint.and_then(|entities| entities.fmt_percentage());
434                let stage_eta = eta.fmt_for_stage(*stage_id);
435
436                match (stage_progress, stage_eta) {
437                    (Some(stage_progress), Some(stage_eta)) => {
438                        info!(
439                            target: "reth::cli",
440                            connected_peers = this.state.num_connected_peers(),
441                            stage = %stage_id,
442                            checkpoint = checkpoint.block_number,
443                            target = %OptionalField(*target),
444                            %stage_progress,
445                            %stage_eta,
446                            "Status"
447                        )
448                    }
449                    (Some(stage_progress), None) => {
450                        info!(
451                            target: "reth::cli",
452                            connected_peers = this.state.num_connected_peers(),
453                            stage = %stage_id,
454                            checkpoint = checkpoint.block_number,
455                            target = %OptionalField(*target),
456                            %stage_progress,
457                            "Status"
458                        )
459                    }
460                    (None, Some(stage_eta)) => {
461                        info!(
462                            target: "reth::cli",
463                            connected_peers = this.state.num_connected_peers(),
464                            stage = %stage_id,
465                            checkpoint = checkpoint.block_number,
466                            target = %OptionalField(*target),
467                            %stage_eta,
468                            "Status"
469                        )
470                    }
471                    (None, None) => {
472                        info!(
473                            target: "reth::cli",
474                            connected_peers = this.state.num_connected_peers(),
475                            stage = %stage_id,
476                            checkpoint = checkpoint.block_number,
477                            target = %OptionalField(*target),
478                            "Status"
479                        )
480                    }
481                }
482            } else if let Some(latest_block) = this.state.latest_block {
483                let now =
484                    SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
485                if now.saturating_sub(this.state.latest_block_time.unwrap_or(0)) > 60 {
486                    // Once we start receiving consensus nodes, don't emit status unless stalled for
487                    // 1 minute
488                    info!(
489                        target: "reth::cli",
490                        connected_peers = this.state.num_connected_peers(),
491                        %latest_block,
492                        "Status"
493                    );
494                }
495            } else {
496                info!(
497                    target: "reth::cli",
498                    connected_peers = this.state.num_connected_peers(),
499                    "Status"
500                );
501            }
502        }
503
504        while let Poll::Ready(Some(event)) = this.events.as_mut().poll_next(cx) {
505            match event {
506                NodeEvent::Pipeline(event) => {
507                    this.state.handle_pipeline_event(event);
508                }
509                NodeEvent::ConsensusEngine(event) => {
510                    this.state.handle_consensus_engine_event(event);
511                }
512                NodeEvent::ConsensusLayerHealth(event) => {
513                    this.state.handle_consensus_layer_health_event(event)
514                }
515                NodeEvent::Pruner(event) => {
516                    this.state.handle_pruner_event(event);
517                }
518                NodeEvent::StaticFileProducer(event) => {
519                    this.state.handle_static_file_producer_event(event);
520                }
521                NodeEvent::Other(event_description) => {
522                    warn!("{event_description}");
523                }
524            }
525        }
526
527        Poll::Pending
528    }
529}
530
531/// A container calculating the estimated time that a stage will complete in, based on stage
532/// checkpoints reported by the pipeline.
533///
534/// One `Eta` is only valid for a single stage.
535#[derive(Default, Copy, Clone)]
536struct Eta {
537    /// The last stage checkpoint
538    last_checkpoint: EntitiesCheckpoint,
539    /// The last time the stage reported its checkpoint
540    last_checkpoint_time: Option<Instant>,
541    /// The current ETA
542    eta: Option<Duration>,
543}
544
545impl Eta {
546    /// Update the ETA given the checkpoint, if possible.
547    fn update(&mut self, stage: StageId, checkpoint: StageCheckpoint) {
548        let Some(current) = checkpoint.entities() else { return };
549
550        if let Some(last_checkpoint_time) = &self.last_checkpoint_time {
551            let Some(processed_since_last) =
552                current.processed.checked_sub(self.last_checkpoint.processed)
553            else {
554                self.eta = None;
555                debug!(target: "reth::cli", %stage, ?current, ?self.last_checkpoint, "Failed to calculate the ETA: processed entities is less than the last checkpoint");
556                return
557            };
558            let elapsed = last_checkpoint_time.elapsed();
559            let per_second = processed_since_last as f64 / elapsed.as_secs_f64();
560
561            let Some(remaining) = current.total.checked_sub(current.processed) else {
562                self.eta = None;
563                debug!(target: "reth::cli", %stage, ?current, "Failed to calculate the ETA: total entities is less than processed entities");
564                return
565            };
566
567            self.eta = Duration::try_from_secs_f64(remaining as f64 / per_second).ok();
568        }
569
570        self.last_checkpoint = current;
571        self.last_checkpoint_time = Some(Instant::now());
572    }
573
574    /// Returns `true` if the ETA is available, i.e. at least one checkpoint has been reported.
575    fn is_available(&self) -> bool {
576        self.eta.zip(self.last_checkpoint_time).is_some()
577    }
578
579    /// Format ETA for a given stage.
580    ///
581    /// NOTE: Currently ETA is enabled only for the stages that have predictable progress.
582    /// It's not the case for network-dependent ([`StageId::Headers`] and [`StageId::Bodies`]) and
583    /// [`StageId::Execution`] stages.
584    fn fmt_for_stage(&self, stage: StageId) -> Option<String> {
585        if !self.is_available() ||
586            matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution)
587        {
588            None
589        } else {
590            Some(self.to_string())
591        }
592    }
593}
594
595impl Display for Eta {
596    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
597        if let Some((eta, last_checkpoint_time)) = self.eta.zip(self.last_checkpoint_time) {
598            let remaining = eta.checked_sub(last_checkpoint_time.elapsed());
599
600            if let Some(remaining) = remaining {
601                return write!(
602                    f,
603                    "{}",
604                    humantime::format_duration(Duration::from_secs(remaining.as_secs()))
605                )
606            }
607        }
608
609        write!(f, "unknown")
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn eta_display_no_milliseconds() {
619        let eta = Eta {
620            last_checkpoint_time: Some(Instant::now()),
621            eta: Some(Duration::from_millis(
622                13 * 60 * 1000 + // Minutes
623                    37 * 1000 + // Seconds
624                    999, // Milliseconds
625            )),
626            ..Default::default()
627        }
628        .to_string();
629
630        assert_eq!(eta, "13m 37s");
631    }
632}