1use crate::cl::ConsensusLayerHealthEvent;
4use alloy_consensus::{
5 constants::{GWEI_TO_WEI, MGAS_TO_GAS},
6 BlockHeader,
7};
8use alloy_primitives::{BlockNumber, B256};
9use alloy_rpc_types_engine::ForkchoiceState;
10use futures::Stream;
11use reth_cli_util::parsers::format_duration;
12use reth_engine_primitives::{ConsensusEngineEvent, ForkchoiceStatus, SlowBlockInfo};
13use reth_network_api::PeersInfo;
14use reth_primitives_traits::{format_gas, format_gas_throughput, BlockBody, NodePrimitives};
15use reth_prune_types::PrunerEvent;
16use reth_stages::{EntitiesCheckpoint, ExecOutput, PipelineEvent, StageCheckpoint, StageId};
17use reth_static_file_types::StaticFileProducerEvent;
18use std::{
19 fmt::{Display, Formatter},
20 future::Future,
21 pin::Pin,
22 task::{Context, Poll},
23 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
24};
25use tokio::time::Interval;
26use tracing::{debug, info, warn};
27
28const INFO_MESSAGE_INTERVAL: Duration = Duration::from_secs(25);
30
31struct NodeState {
36 peers_info: Option<Box<dyn PeersInfo>>,
38 current_stage: Option<CurrentStage>,
40 latest_block: Option<BlockNumber>,
42 head_block_hash: Option<B256>,
44 safe_block_hash: Option<B256>,
46 finalized_block_hash: Option<B256>,
48 last_status_log_time: Option<u64>,
50}
51
52impl NodeState {
53 const fn new(
54 peers_info: Option<Box<dyn PeersInfo>>,
55 latest_block: Option<BlockNumber>,
56 ) -> Self {
57 Self {
58 peers_info,
59 current_stage: None,
60 latest_block,
61 head_block_hash: None,
62 safe_block_hash: None,
63 finalized_block_hash: None,
64 last_status_log_time: None,
65 }
66 }
67
68 fn num_connected_peers(&self) -> usize {
69 self.peers_info.as_ref().map(|info| info.num_connected_peers()).unwrap_or_default()
70 }
71
72 fn build_current_stage(
73 &self,
74 stage_id: StageId,
75 checkpoint: StageCheckpoint,
76 target: Option<BlockNumber>,
77 ) -> CurrentStage {
78 let (eta, entities_checkpoint) = self
79 .current_stage
80 .as_ref()
81 .filter(|current_stage| current_stage.stage_id == stage_id)
82 .map_or_else(
83 || (Eta::default(), None),
84 |current_stage| (current_stage.eta, current_stage.entities_checkpoint),
85 );
86
87 CurrentStage { stage_id, eta, checkpoint, entities_checkpoint, target }
88 }
89
90 fn handle_pipeline_event(&mut self, event: PipelineEvent) {
92 match event {
93 PipelineEvent::Prepare { pipeline_stages_progress, stage_id, checkpoint, target } => {
94 let checkpoint = checkpoint.unwrap_or_default();
95 let current_stage = self.build_current_stage(stage_id, checkpoint, target);
96
97 info!(
98 pipeline_stages = %pipeline_stages_progress,
99 stage = %stage_id,
100 checkpoint = %checkpoint.block_number,
101 target = %OptionalField(target),
102 "Preparing stage",
103 );
104
105 self.current_stage = Some(current_stage);
106 }
107 PipelineEvent::Run { pipeline_stages_progress, stage_id, checkpoint, target } => {
108 let checkpoint = checkpoint.unwrap_or_default();
109 let current_stage = self.build_current_stage(stage_id, checkpoint, target);
110
111 if let Some(stage_eta) = current_stage.eta.fmt_for_stage(stage_id) {
112 info!(
113 pipeline_stages = %pipeline_stages_progress,
114 stage = %stage_id,
115 checkpoint = %checkpoint.block_number,
116 target = %OptionalField(target),
117 %stage_eta,
118 "Executing stage",
119 );
120 } else {
121 info!(
122 pipeline_stages = %pipeline_stages_progress,
123 stage = %stage_id,
124 checkpoint = %checkpoint.block_number,
125 target = %OptionalField(target),
126 "Executing stage",
127 );
128 }
129
130 self.current_stage = Some(current_stage);
131 }
132 PipelineEvent::Ran {
133 pipeline_stages_progress,
134 stage_id,
135 result: ExecOutput { checkpoint, done },
136 } => {
137 if stage_id.is_finish() {
138 self.latest_block = Some(checkpoint.block_number);
139 }
140
141 if let Some(current_stage) = self.current_stage.as_mut() {
142 current_stage.checkpoint = checkpoint;
143 current_stage.entities_checkpoint = checkpoint.entities();
144 current_stage.eta.update(stage_id, checkpoint);
145
146 let target = OptionalField(current_stage.target);
147 let stage_progress = current_stage
148 .entities_checkpoint
149 .and_then(|entities| entities.fmt_percentage());
150 let stage_eta = current_stage.eta.fmt_for_stage(stage_id);
151
152 let message = if done { "Finished stage" } else { "Committed stage progress" };
153
154 match (stage_progress, stage_eta) {
155 (Some(stage_progress), Some(stage_eta)) => {
156 info!(
157 pipeline_stages = %pipeline_stages_progress,
158 stage = %stage_id,
159 checkpoint = %checkpoint.block_number,
160 %target,
161 %stage_progress,
162 %stage_eta,
163 "{message}",
164 )
165 }
166 (Some(stage_progress), None) => {
167 info!(
168 pipeline_stages = %pipeline_stages_progress,
169 stage = %stage_id,
170 checkpoint = %checkpoint.block_number,
171 %target,
172 %stage_progress,
173 "{message}",
174 )
175 }
176 (None, Some(stage_eta)) => {
177 info!(
178 pipeline_stages = %pipeline_stages_progress,
179 stage = %stage_id,
180 checkpoint = %checkpoint.block_number,
181 %target,
182 %stage_eta,
183 "{message}",
184 )
185 }
186 (None, None) => {
187 info!(
188 pipeline_stages = %pipeline_stages_progress,
189 stage = %stage_id,
190 checkpoint = %checkpoint.block_number,
191 %target,
192 "{message}",
193 )
194 }
195 }
196 }
197
198 if done {
199 self.current_stage = None;
200 }
201 }
202 PipelineEvent::Unwind { stage_id, input } => {
203 let current_stage = CurrentStage {
204 stage_id,
205 eta: Eta::default(),
206 checkpoint: input.checkpoint,
207 target: Some(input.unwind_to),
208 entities_checkpoint: input.checkpoint.entities(),
209 };
210
211 self.current_stage = Some(current_stage);
212 }
213 PipelineEvent::Unwound { stage_id, result } => {
214 info!(stage = %stage_id, checkpoint = %result.checkpoint.block_number, "Unwound stage");
215 self.current_stage = None;
216 }
217 _ => (),
218 }
219 }
220
221 fn handle_consensus_engine_event<N: NodePrimitives>(&mut self, event: ConsensusEngineEvent<N>) {
222 match event {
223 ConsensusEngineEvent::ForkchoiceUpdated(state, status) => {
224 let ForkchoiceState { head_block_hash, safe_block_hash, finalized_block_hash } =
225 state;
226 if self.safe_block_hash != Some(safe_block_hash) &&
227 self.finalized_block_hash != Some(finalized_block_hash)
228 {
229 let msg = match status {
230 ForkchoiceStatus::Valid => "Forkchoice updated",
231 ForkchoiceStatus::Invalid => "Received invalid forkchoice updated message",
232 ForkchoiceStatus::Syncing => {
233 "Received forkchoice updated message when syncing"
234 }
235 };
236 info!(?head_block_hash, ?safe_block_hash, ?finalized_block_hash, "{}", msg);
237 }
238 self.head_block_hash = Some(head_block_hash);
239 self.safe_block_hash = Some(safe_block_hash);
240 self.finalized_block_hash = Some(finalized_block_hash);
241 }
242 ConsensusEngineEvent::CanonicalBlockAdded(executed, elapsed) => {
243 let block = executed.sealed_block();
244 let mut full = block.gas_used() as f64 * 100.0 / block.gas_limit() as f64;
245 if full.is_nan() {
246 full = 0.0;
247 }
248 info!(
249 number=block.number(),
250 hash=?block.hash(),
251 peers=self.num_connected_peers(),
252 txs=block.body().transactions().len(),
253 gas_used=%format_gas(block.gas_used()),
254 gas_throughput=%format_gas_throughput(block.gas_used(), elapsed),
255 gas_limit=%format_gas(block.gas_limit()),
256 full=%format_args!("{:.1}%", full),
257 base_fee=%format_args!("{:.2}Gwei", block.base_fee_per_gas().unwrap_or(0) as f64 / GWEI_TO_WEI as f64),
258 blobs=block.blob_gas_used().unwrap_or(0) / alloy_eips::eip4844::DATA_GAS_PER_BLOB,
259 excess_blobs=block.excess_blob_gas().unwrap_or(0) / alloy_eips::eip4844::DATA_GAS_PER_BLOB,
260 ?elapsed,
261 "Block added to canonical chain"
262 );
263 }
264 ConsensusEngineEvent::CanonicalChainCommitted(head, elapsed) => {
265 self.latest_block = Some(head.number());
266 info!(number=head.number(), hash=?head.hash(), ?elapsed, "Canonical chain committed");
267 }
268 ConsensusEngineEvent::ForkBlockAdded(executed, elapsed) => {
269 let block = executed.sealed_block();
270 info!(number=block.number(), hash=?block.hash(), ?elapsed, "Block added to fork chain");
271 }
272 ConsensusEngineEvent::InvalidBlock { block, error } => {
273 warn!(number=block.number(), hash=?block.hash(), %error, "Encountered invalid block");
274 }
275 ConsensusEngineEvent::BlockReceived(num_hash) => {
276 info!(number=num_hash.number, hash=?num_hash.hash, "Received new payload from consensus engine");
277 }
278 ConsensusEngineEvent::SlowBlock(info) => {
279 Self::log_slow_block(&info);
280 }
281 }
282 }
283
284 fn log_slow_block(info: &SlowBlockInfo) {
285 fn hit_rate(hits: usize, misses: usize) -> f64 {
286 let total = hits + misses;
287 if total > 0 {
288 (hits as f64 / total as f64) * 100.0
289 } else {
290 0.0
291 }
292 }
293
294 let stats = &info.stats;
295 let processing_secs =
296 stats.execution_duration.as_secs_f64() + stats.state_hash_duration.as_secs_f64();
297 let mgas_per_sec = if processing_secs > 0.0 {
298 (stats.gas_used as f64 / MGAS_TO_GAS as f64) / processing_secs
299 } else {
300 0.0
301 };
302
303 macro_rules! log_slow_block_fields {
306 ($($commit_field:tt)*) => {
307 warn!(
308 target: "reth::slow_block",
309 message = "Slow block",
310 block.number = stats.block_number,
311 block.hash = ?stats.block_hash,
312 block.gas_used = stats.gas_used,
313 block.tx_count = stats.tx_count,
314 timing.execution_ms = stats.execution_duration.as_millis(),
315 timing.state_read_ms = stats.state_read_duration.as_millis(),
316 timing.state_hash_ms = stats.state_hash_duration.as_millis(),
317 $($commit_field)*
318 timing.total_ms = info.total_duration.as_millis(),
319 throughput.mgas_per_sec = format!("{:.2}", mgas_per_sec),
320 state_reads.accounts = stats.accounts_read,
321 state_reads.storage_slots = stats.storage_read,
322 state_reads.code = stats.code_read,
323 state_reads.code_bytes = stats.code_bytes_read,
324 state_writes.accounts = stats.accounts_changed,
325 state_writes.accounts_deleted = stats.accounts_deleted,
326 state_writes.storage_slots = stats.storage_slots_changed,
327 state_writes.storage_slots_deleted = stats.storage_slots_deleted,
328 state_writes.code = stats.bytecodes_changed,
329 state_writes.code_bytes = stats.code_bytes_written,
330 state_writes.eip7702_delegations_set = stats.eip7702_delegations_set,
331 state_writes.eip7702_delegations_cleared = stats.eip7702_delegations_cleared,
332 cache.account.hits = stats.account_cache_hits,
333 cache.account.misses = stats.account_cache_misses,
334 cache.account.hit_rate = format!("{:.2}", hit_rate(stats.account_cache_hits, stats.account_cache_misses)),
335 cache.storage.hits = stats.storage_cache_hits,
336 cache.storage.misses = stats.storage_cache_misses,
337 cache.storage.hit_rate = format!("{:.2}", hit_rate(stats.storage_cache_hits, stats.storage_cache_misses)),
338 cache.code.hits = stats.code_cache_hits,
339 cache.code.misses = stats.code_cache_misses,
340 cache.code.hit_rate = format!("{:.2}", hit_rate(stats.code_cache_hits, stats.code_cache_misses)),
341 cache.txpool_snapshot.account.hits = stats.txpool_snapshot_account_hits,
342 cache.txpool_snapshot.account.misses = stats.txpool_snapshot_account_misses,
343 cache.txpool_snapshot.account.hit_rate = format!("{:.2}", hit_rate(stats.txpool_snapshot_account_hits, stats.txpool_snapshot_account_misses)),
344 cache.txpool_snapshot.storage.hits = stats.txpool_snapshot_storage_hits,
345 cache.txpool_snapshot.storage.misses = stats.txpool_snapshot_storage_misses,
346 cache.txpool_snapshot.storage.hit_rate = format!("{:.2}", hit_rate(stats.txpool_snapshot_storage_hits, stats.txpool_snapshot_storage_misses)),
347 cache.txpool_snapshot.code.hits = stats.txpool_snapshot_code_hits,
348 cache.txpool_snapshot.code.misses = stats.txpool_snapshot_code_misses,
349 cache.txpool_snapshot.code.hit_rate = format!("{:.2}", hit_rate(stats.txpool_snapshot_code_hits, stats.txpool_snapshot_code_misses)),
350 );
351 }
352 }
353
354 if let Some(commit_dur) = info.commit_duration {
355 log_slow_block_fields!(timing.commit_ms = commit_dur.as_millis(),);
356 } else {
357 log_slow_block_fields!();
358 }
359 }
360
361 fn handle_consensus_layer_health_event(&self, event: ConsensusLayerHealthEvent) {
362 if self.current_stage.is_none() {
365 match event {
366 ConsensusLayerHealthEvent::NeverSeen => {
367 warn!(
368 "Post-merge network, but never seen beacon client. Please launch one to follow the chain!"
369 )
370 }
371 ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile(period) => {
372 warn!(
373 ?period,
374 "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!"
375 )
376 }
377 }
378 }
379 }
380
381 fn handle_pruner_event(&self, event: PrunerEvent) {
382 match event {
383 PrunerEvent::Started { tip_block_number } => {
384 debug!(tip_block_number, "Pruner started");
385 }
386 PrunerEvent::Finished { tip_block_number, elapsed, stats } => {
387 let stats = format!(
388 "[{}]",
389 stats.iter().map(|item| item.to_string()).collect::<Vec<_>>().join(", ")
390 );
391 debug!(tip_block_number, ?elapsed, pruned_segments = %stats, "Pruner finished");
392 }
393 }
394 }
395
396 fn handle_static_file_producer_event(&self, event: StaticFileProducerEvent) {
397 match event {
398 StaticFileProducerEvent::Started { targets } => {
399 debug!(?targets, "Static File Producer started");
400 }
401 StaticFileProducerEvent::Finished { targets, elapsed } => {
402 debug!(?targets, ?elapsed, "Static File Producer finished");
403 }
404 }
405 }
406}
407
408struct OptionalField<T: Display>(Option<T>);
412
413impl<T: Display> Display for OptionalField<T> {
414 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
415 if let Some(field) = &self.0 {
416 write!(f, "{field}")
417 } else {
418 write!(f, "None")
419 }
420 }
421}
422
423struct CurrentStage {
425 stage_id: StageId,
426 eta: Eta,
427 checkpoint: StageCheckpoint,
428 entities_checkpoint: Option<EntitiesCheckpoint>,
432 target: Option<BlockNumber>,
433}
434
435#[derive(Debug, derive_more::From)]
437pub enum NodeEvent<N: NodePrimitives> {
438 Pipeline(PipelineEvent),
440 ConsensusEngine(ConsensusEngineEvent<N>),
442 ConsensusLayerHealth(ConsensusLayerHealthEvent),
444 Pruner(PrunerEvent),
446 StaticFileProducer(StaticFileProducerEvent),
448 Other(String),
451}
452
453pub async fn handle_events<E, N: NodePrimitives>(
456 peers_info: Option<Box<dyn PeersInfo>>,
457 latest_block_number: Option<BlockNumber>,
458 events: E,
459) where
460 E: Stream<Item = NodeEvent<N>> + Unpin,
461{
462 let state = NodeState::new(peers_info, latest_block_number);
463
464 let start = tokio::time::Instant::now() + Duration::from_secs(3);
465 let mut info_interval = tokio::time::interval_at(start, INFO_MESSAGE_INTERVAL);
466 info_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
467
468 let handler = EventHandler { state, events, info_interval };
469 handler.await
470}
471
472#[pin_project::pin_project]
474struct EventHandler<E> {
475 state: NodeState,
476 #[pin]
477 events: E,
478 #[pin]
479 info_interval: Interval,
480}
481
482impl<E, N: NodePrimitives> Future for EventHandler<E>
483where
484 E: Stream<Item = NodeEvent<N>> + Unpin,
485{
486 type Output = ();
487
488 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
489 let mut this = self.project();
490
491 while this.info_interval.poll_tick(cx).is_ready() {
492 if let Some(CurrentStage { stage_id, eta, checkpoint, entities_checkpoint, target }) =
493 &this.state.current_stage
494 {
495 let stage_progress =
496 entities_checkpoint.and_then(|entities| entities.fmt_percentage());
497 let stage_eta = eta.fmt_for_stage(*stage_id);
498
499 match (stage_progress, stage_eta) {
500 (Some(stage_progress), Some(stage_eta)) => {
501 info!(
502 target: "reth::cli",
503 connected_peers = this.state.num_connected_peers(),
504 stage = %stage_id,
505 checkpoint = checkpoint.block_number,
506 target = %OptionalField(*target),
507 %stage_progress,
508 %stage_eta,
509 "Status"
510 )
511 }
512 (Some(stage_progress), None) => {
513 info!(
514 target: "reth::cli",
515 connected_peers = this.state.num_connected_peers(),
516 stage = %stage_id,
517 checkpoint = checkpoint.block_number,
518 target = %OptionalField(*target),
519 %stage_progress,
520 "Status"
521 )
522 }
523 (None, Some(stage_eta)) => {
524 info!(
525 target: "reth::cli",
526 connected_peers = this.state.num_connected_peers(),
527 stage = %stage_id,
528 checkpoint = checkpoint.block_number,
529 target = %OptionalField(*target),
530 %stage_eta,
531 "Status"
532 )
533 }
534 (None, None) => {
535 info!(
536 target: "reth::cli",
537 connected_peers = this.state.num_connected_peers(),
538 stage = %stage_id,
539 checkpoint = checkpoint.block_number,
540 target = %OptionalField(*target),
541 "Status"
542 )
543 }
544 }
545 } else {
546 let now =
547 SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
548
549 if now.saturating_sub(this.state.last_status_log_time.unwrap_or(0)) > 60 {
551 if let Some(latest_block) = this.state.latest_block {
552 info!(
553 target: "reth::cli",
554 connected_peers = this.state.num_connected_peers(),
555 %latest_block,
556 "Status"
557 );
558 } else {
559 info!(
560 target: "reth::cli",
561 connected_peers = this.state.num_connected_peers(),
562 "Status"
563 );
564 }
565 this.state.last_status_log_time = Some(now);
566 }
567 }
568 }
569
570 while let Poll::Ready(Some(event)) = this.events.as_mut().poll_next(cx) {
571 match event {
572 NodeEvent::Pipeline(event) => {
573 this.state.handle_pipeline_event(event);
574 }
575 NodeEvent::ConsensusEngine(event) => {
576 this.state.handle_consensus_engine_event(event);
577 }
578 NodeEvent::ConsensusLayerHealth(event) => {
579 this.state.handle_consensus_layer_health_event(event)
580 }
581 NodeEvent::Pruner(event) => {
582 this.state.handle_pruner_event(event);
583 }
584 NodeEvent::StaticFileProducer(event) => {
585 this.state.handle_static_file_producer_event(event);
586 }
587 NodeEvent::Other(event_description) => {
588 warn!("{event_description}");
589 }
590 }
591 }
592
593 Poll::Pending
594 }
595}
596
597#[derive(Default, Copy, Clone)]
602struct Eta {
603 last_checkpoint: EntitiesCheckpoint,
605 last_checkpoint_time: Option<Instant>,
607 eta: Option<Duration>,
609}
610
611impl Eta {
612 fn update(&mut self, stage: StageId, checkpoint: StageCheckpoint) {
614 let Some(current) = checkpoint.entities() else { return };
615
616 if let Some(last_checkpoint_time) = &self.last_checkpoint_time {
617 let Some(processed_since_last) =
618 current.processed.checked_sub(self.last_checkpoint.processed)
619 else {
620 self.eta = None;
621 debug!(target: "reth::cli", %stage, ?current, ?self.last_checkpoint, "Failed to calculate the ETA: processed entities is less than the last checkpoint");
622 return
623 };
624 let elapsed = last_checkpoint_time.elapsed();
625 let per_second = processed_since_last as f64 / elapsed.as_secs_f64();
626
627 let Some(remaining) = current.total.checked_sub(current.processed) else {
628 self.eta = None;
629 debug!(target: "reth::cli", %stage, ?current, "Failed to calculate the ETA: total entities is less than processed entities");
630 return
631 };
632
633 self.eta = Duration::try_from_secs_f64(remaining as f64 / per_second).ok();
634 }
635
636 self.last_checkpoint = current;
637 self.last_checkpoint_time = Some(Instant::now());
638 }
639
640 fn is_available(&self) -> bool {
642 self.eta.zip(self.last_checkpoint_time).is_some()
643 }
644
645 fn fmt_for_stage(&self, stage: StageId) -> Option<String> {
651 if !self.is_available() ||
652 matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution)
653 {
654 None
655 } else {
656 Some(self.to_string())
657 }
658 }
659}
660
661impl Display for Eta {
662 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
663 if let Some((eta, last_checkpoint_time)) = self.eta.zip(self.last_checkpoint_time) {
664 let remaining = eta.checked_sub(last_checkpoint_time.elapsed());
665
666 if let Some(remaining) = remaining {
667 return write!(
668 f,
669 "{}",
670 format_duration(Duration::from_secs(remaining.as_secs())).replace(' ', "")
671 )
672 }
673 }
674
675 write!(f, "unknown")
676 }
677}
678
679#[cfg(test)]
680mod tests {
681 use super::*;
682
683 #[test]
684 fn eta_display_no_milliseconds() {
685 let eta = Eta {
686 last_checkpoint_time: Some(Instant::now()),
687 eta: Some(Duration::from_millis(
688 13 * 60 * 1000 + 37 * 1000 + 999, )),
692 ..Default::default()
693 }
694 .to_string();
695
696 assert_eq!(eta, "13m37s");
697 }
698}