Skip to main content

reth_node_builder/launch/
common.rs

1//! Helper types that can be used by launchers.
2//!
3//! ## Launch Context Type System
4//!
5//! The node launch process uses a type-state pattern to ensure correct initialization
6//! order at compile time. Methods are only available when their prerequisites are met.
7//!
8//! ### Core Types
9//!
10//! - [`LaunchContext`]: Base context with executor and data directory
11//! - [`LaunchContextWith<T>`]: Context with an attached value of type `T`
12//! - [`Attached<L, R>`]: Pairs values, preserving both previous (L) and new (R) state
13//!
14//! ### Helper Attachments
15//!
16//! - [`WithConfigs`]: Node config + TOML config
17//! - [`WithMeteredProvider`]: Provider factory with metrics
18//! - [`WithMeteredProviders`]: Provider factory + blockchain provider
19//! - [`WithComponents`]: Final form with all components
20//!
21//! ### Method Availability
22//!
23//! Methods are implemented on specific type combinations:
24//! - `impl<T> LaunchContextWith<T>`: Generic methods available for any attachment
25//! - `impl LaunchContextWith<WithConfigs>`: Config-specific methods
26//! - `impl LaunchContextWith<Attached<WithConfigs, DB>>`: Database operations
27//! - `impl LaunchContextWith<Attached<WithConfigs, ProviderFactory>>`: Provider operations
28//! - etc.
29//!
30//! This ensures correct initialization order without runtime checks.
31
32use crate::{
33    components::{NodeComponents, NodeComponentsBuilder},
34    hooks::OnComponentInitializedHook,
35    BuilderContext, ExExLauncher, NodeAdapter, PrimitivesTy,
36};
37use alloy_eips::eip2124::Head;
38use alloy_primitives::{BlockNumber, B256};
39use eyre::Context;
40use reth_chainspec::{Chain, EthChainSpec, EthereumHardforks};
41use reth_concurrency::sync::rayon::ThreadPoolBuilder;
42use reth_config::{config::EtlConfig, PruneConfig};
43use reth_consensus::noop::NoopConsensus;
44use reth_db_api::{
45    database::Database, database_metrics::DatabaseMetrics, models::PartialStateTrieUnwindMarker,
46};
47use reth_db_common::init::{
48    init_genesis_with_settings, init_genesis_with_settings_and_validate, InitStorageError,
49};
50use reth_downloaders::{bodies::noop::NoopBodiesDownloader, headers::noop::NoopHeaderDownloader};
51use reth_engine_local::MiningMode;
52use reth_evm::{noop::NoopEvmConfig, ConfigureEvm, SenderRecoveryCache};
53use reth_exex::ExExManagerHandle;
54use reth_fs_util as fs;
55use reth_network_p2p::headers::client::HeadersClient;
56use reth_node_api::{FullNodeTypes, NodeTypes, NodeTypesWithDB, NodeTypesWithDBAdapter};
57use reth_node_core::{
58    args::{DefaultEraHost, PruneConfigKind},
59    dirs::{ChainPath, DataDirPath},
60    node_config::NodeConfig,
61    primitives::BlockHeader,
62    version::version_metadata,
63};
64use reth_node_metrics::{
65    chain::ChainSpecInfo,
66    hooks::Hooks,
67    recorder::install_prometheus_recorder,
68    server::{MetricServer, MetricServerConfig},
69    storage::StorageSettingsInfo,
70    version::VersionInfo,
71};
72use reth_provider::{
73    providers::{NodeTypesForProvider, ProviderNodeTypes, RocksDBProvider, StaticFileProvider},
74    BalStoreHandle, BlockHashReader, BlockNumReader, DBProvider, DatabaseProviderFactory,
75    MetadataProvider, MetadataWriter, ProviderError, ProviderFactory, ProviderResult,
76    RocksDBBalStore, RocksDBProviderFactory, StageCheckpointReader, StaticFileProviderBuilder,
77    StaticFileProviderFactory, StorageSettingsCache,
78};
79use reth_prune::{PruneModes, PrunerBuilder};
80use reth_rpc_builder::config::RethRpcServerConfig;
81use reth_rpc_layer::JwtSecret;
82use reth_stages::{
83    sets::DefaultStages,
84    stages::{EraImportSource, EraStage, MerkleStage},
85    MetricEvent, PipelineBuilder, PipelineTarget, StageId, StageSet,
86};
87use reth_static_file::StaticFileProducer;
88use reth_storage_overlay::OverlayManager;
89use reth_tasks::TaskExecutor;
90use reth_tracing::tracing::{debug, error, info, warn};
91use reth_transaction_pool::TransactionPool;
92use std::{sync::Arc, time::Duration};
93use tokio::sync::{
94    mpsc::{unbounded_channel, UnboundedSender},
95    oneshot, watch,
96};
97
98use futures::{future::Either, stream, Stream, StreamExt};
99use reth_engine_primitives::ConsensusEngineEvent;
100use reth_node_ethstats::EthStatsService;
101use reth_node_events::{cl::ConsensusLayerHealthEvents, node::NodeEvent};
102
103/// Reusable setup for launching a node.
104///
105/// This is the entry point for the node launch process. It implements a builder
106/// pattern using type-state programming to enforce correct initialization order.
107///
108/// ## Type Evolution
109///
110/// Starting from `LaunchContext`, each method transforms the type to reflect
111/// accumulated state:
112///
113/// ```text
114/// LaunchContext
115///   └─> LaunchContextWith<WithConfigs>
116///       └─> LaunchContextWith<Attached<WithConfigs, DB>>
117///           └─> LaunchContextWith<Attached<WithConfigs, ProviderFactory>>
118///               └─> LaunchContextWith<Attached<WithConfigs, WithMeteredProviders>>
119///                   └─> LaunchContextWith<Attached<WithConfigs, WithComponents>>
120/// ```
121#[derive(Debug, Clone)]
122pub struct LaunchContext {
123    /// The task executor for the node.
124    pub task_executor: TaskExecutor,
125    /// The data directory for the node.
126    pub data_dir: ChainPath<DataDirPath>,
127}
128
129impl LaunchContext {
130    /// Create a new instance of the default node launcher.
131    pub const fn new(task_executor: TaskExecutor, data_dir: ChainPath<DataDirPath>) -> Self {
132        Self { task_executor, data_dir }
133    }
134
135    /// Create launch context with attachment.
136    pub const fn with<T>(self, attachment: T) -> LaunchContextWith<T> {
137        LaunchContextWith { inner: self, attachment }
138    }
139
140    /// Loads the reth config with the configured `data_dir` and overrides settings according to the
141    /// `config`.
142    ///
143    /// Attaches both the `NodeConfig` and the loaded `reth.toml` config to the launch context.
144    pub fn with_loaded_toml_config<ChainSpec>(
145        self,
146        config: NodeConfig<ChainSpec>,
147    ) -> eyre::Result<LaunchContextWith<WithConfigs<ChainSpec>>>
148    where
149        ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
150    {
151        let toml_config = self.load_toml_config(&config)?;
152        Ok(self.with(WithConfigs { config, toml_config }))
153    }
154
155    /// Loads the reth config with the configured `data_dir` and overrides settings according to the
156    /// `config`.
157    ///
158    /// This is async because the trusted peers may have to be resolved.
159    pub fn load_toml_config<ChainSpec>(
160        &self,
161        config: &NodeConfig<ChainSpec>,
162    ) -> eyre::Result<reth_config::Config>
163    where
164        ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
165    {
166        let config_path = config.config.clone().unwrap_or_else(|| self.data_dir.config());
167
168        let mut toml_config = reth_config::Config::from_path(&config_path)
169            .wrap_err_with(|| format!("Could not load config file {config_path:?}"))?;
170
171        Self::save_pruning_config(&mut toml_config, config, &config_path)?;
172
173        info!(target: "reth::cli", path = ?config_path, "Configuration loaded");
174
175        // Update the config with the command line arguments. Only override when the CLI flag is
176        // set, so the TOML value is preserved when the flag is not passed.
177        toml_config.peers.trusted_nodes_only |= config.network.trusted_only;
178
179        // Merge static file CLI arguments with config file, giving priority to CLI
180        toml_config.static_files =
181            config.static_files.merge_with_config(toml_config.static_files, config.pruning.minimal);
182
183        Ok(toml_config)
184    }
185
186    /// Save prune config to the toml file if node is a full node or has custom pruning CLI
187    /// arguments. Also migrates deprecated prune config values to new defaults.
188    fn save_pruning_config<ChainSpec>(
189        reth_config: &mut reth_config::Config,
190        config: &NodeConfig<ChainSpec>,
191        config_path: impl AsRef<std::path::Path>,
192    ) -> eyre::Result<()>
193    where
194        ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
195    {
196        let mut should_save = reth_config.prune.segments.migrate();
197
198        if let Some(prune_config) = config.prune_config() {
199            if reth_config.prune != prune_config {
200                reth_config.set_prune_config(prune_config);
201                should_save = true;
202            }
203        } else if !reth_config.prune.is_default() {
204            info!(target: "reth::cli", "Pruning configuration is present in the config file, but no CLI arguments are provided. Using config from file.");
205        }
206
207        if should_save {
208            info!(target: "reth::cli", "Saving prune config to toml file");
209            reth_config.save(config_path.as_ref())?;
210        }
211
212        Ok(())
213    }
214
215    /// Convenience function to [`Self::configure_globals`]
216    pub fn with_configured_globals(self, reserved_cpu_cores: usize) -> Self {
217        self.configure_globals(reserved_cpu_cores);
218        self
219    }
220
221    /// Configure global settings this includes:
222    ///
223    /// - Raising the file descriptor limit
224    /// - Configuring the global rayon thread pool for implicit `par_iter` usage
225    pub fn configure_globals(&self, reserved_cpu_cores: usize) {
226        // Raise the fd limit of the process.
227        // Does not do anything on windows.
228        match fdlimit::raise_fd_limit() {
229            Ok(fdlimit::Outcome::LimitRaised { from, to }) => {
230                debug!(from, to, "Raised file descriptor limit");
231            }
232            Ok(fdlimit::Outcome::Unsupported) => {}
233            Err(err) => warn!(%err, "Failed to raise file descriptor limit"),
234        }
235
236        // Configure the implicit global rayon pool for `par_iter` usage.
237        // TODO: reserved_cpu_cores is currently ignored because subtracting from thread pool
238        // sizes doesn't actually reserve CPU cores for other processes.
239        let _ = reserved_cpu_cores;
240        let num_threads = self.task_executor.cpu_pool().current_num_threads();
241        if let Err(err) = ThreadPoolBuilder::new()
242            .num_threads(num_threads)
243            .thread_name(|i| format!("rayon-{i:02}"))
244            .build_global()
245        {
246            warn!(%err, "Failed to build global thread pool")
247        }
248    }
249}
250
251/// A [`LaunchContext`] along with an additional value.
252///
253/// The type parameter `T` represents the current state of the launch process.
254/// Methods are conditionally implemented based on `T`, ensuring operations
255/// are only available when their prerequisites are met.
256///
257/// For example:
258/// - Config methods when `T = WithConfigs<ChainSpec>`
259/// - Database operations when `T = Attached<WithConfigs<ChainSpec>, DB>`
260/// - Provider operations when `T = Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>`
261#[derive(Debug, Clone)]
262pub struct LaunchContextWith<T> {
263    /// The wrapped launch context.
264    pub inner: LaunchContext,
265    /// The additional attached value.
266    pub attachment: T,
267}
268
269impl<T> LaunchContextWith<T> {
270    /// Configure global settings this includes:
271    ///
272    /// - Raising the file descriptor limit
273    /// - Configuring the global rayon thread pool
274    pub fn configure_globals(&self, reserved_cpu_cores: u64) {
275        self.inner.configure_globals(reserved_cpu_cores.try_into().unwrap());
276    }
277
278    /// Returns the data directory.
279    pub const fn data_dir(&self) -> &ChainPath<DataDirPath> {
280        &self.inner.data_dir
281    }
282
283    /// Returns the task executor.
284    pub const fn task_executor(&self) -> &TaskExecutor {
285        &self.inner.task_executor
286    }
287
288    /// Attaches another value to the launch context.
289    pub fn attach<A>(self, attachment: A) -> LaunchContextWith<Attached<T, A>> {
290        LaunchContextWith {
291            inner: self.inner,
292            attachment: Attached::new(self.attachment, attachment),
293        }
294    }
295
296    /// Consumes the type and calls a function with a reference to the context.
297    // Returns the context again
298    pub fn inspect<F>(self, f: F) -> Self
299    where
300        F: FnOnce(&Self),
301    {
302        f(&self);
303        self
304    }
305}
306
307impl<ChainSpec> LaunchContextWith<WithConfigs<ChainSpec>> {
308    /// Resolves the trusted peers and adds them to the toml config.
309    pub fn with_resolved_peers(mut self) -> eyre::Result<Self> {
310        if !self.attachment.config.network.trusted_peers.is_empty() {
311            info!(target: "reth::cli", "Adding trusted nodes");
312
313            self.attachment
314                .toml_config
315                .peers
316                .trusted_nodes
317                .extend(self.attachment.config.network.trusted_peers.clone());
318        }
319        Ok(self)
320    }
321}
322
323impl<L, R> LaunchContextWith<Attached<L, R>> {
324    /// Get a reference to the left value.
325    pub const fn left(&self) -> &L {
326        &self.attachment.left
327    }
328
329    /// Get a reference to the right value.
330    pub const fn right(&self) -> &R {
331        &self.attachment.right
332    }
333
334    /// Get a mutable reference to the left value.
335    pub const fn left_mut(&mut self) -> &mut L {
336        &mut self.attachment.left
337    }
338
339    /// Get a mutable reference to the right value.
340    pub const fn right_mut(&mut self) -> &mut R {
341        &mut self.attachment.right
342    }
343}
344impl<R, ChainSpec: EthChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpec>, R>> {
345    /// Adjust certain settings in the config to make sure they are set correctly
346    ///
347    /// This includes:
348    /// - Making sure the ETL dir is set to the datadir
349    /// - RPC settings are adjusted to the correct port
350    pub fn with_adjusted_configs(self) -> Self {
351        self.ensure_etl_datadir().with_adjusted_instance_ports()
352    }
353
354    /// Make sure ETL doesn't default to /tmp/, but to whatever datadir is set to
355    pub fn ensure_etl_datadir(mut self) -> Self {
356        if self.toml_config_mut().stages.etl.dir.is_none() {
357            let etl_path = EtlConfig::from_datadir(self.data_dir().data_dir());
358            if etl_path.exists() {
359                // Remove etl-path files on launch
360                if let Err(err) = fs::remove_dir_all(&etl_path) {
361                    warn!(target: "reth::cli", ?etl_path, %err, "Failed to remove ETL path on launch");
362                }
363            }
364            self.toml_config_mut().stages.etl.dir = Some(etl_path);
365        }
366
367        self
368    }
369
370    /// Change rpc port numbers based on the instance number.
371    pub fn with_adjusted_instance_ports(mut self) -> Self {
372        self.node_config_mut().adjust_instance_ports();
373        self
374    }
375
376    /// Returns the container for all config types
377    pub const fn configs(&self) -> &WithConfigs<ChainSpec> {
378        self.attachment.left()
379    }
380
381    /// Returns the attached [`NodeConfig`].
382    pub const fn node_config(&self) -> &NodeConfig<ChainSpec> {
383        &self.left().config
384    }
385
386    /// Returns the attached [`NodeConfig`].
387    pub const fn node_config_mut(&mut self) -> &mut NodeConfig<ChainSpec> {
388        &mut self.left_mut().config
389    }
390
391    /// Returns the attached toml config [`reth_config::Config`].
392    pub const fn toml_config(&self) -> &reth_config::Config {
393        &self.left().toml_config
394    }
395
396    /// Returns the attached toml config [`reth_config::Config`].
397    pub const fn toml_config_mut(&mut self) -> &mut reth_config::Config {
398        &mut self.left_mut().toml_config
399    }
400
401    /// Returns the configured chain spec.
402    pub fn chain_spec(&self) -> Arc<ChainSpec> {
403        self.node_config().chain.clone()
404    }
405
406    /// Get the hash of the genesis block.
407    pub fn genesis_hash(&self) -> B256 {
408        self.node_config().chain.genesis_hash()
409    }
410
411    /// Returns the chain identifier of the node.
412    pub fn chain_id(&self) -> Chain {
413        self.node_config().chain.chain()
414    }
415
416    /// Returns true if the node is configured as --dev
417    pub const fn is_dev(&self) -> bool {
418        self.node_config().dev.dev
419    }
420
421    /// Returns the configured [`PruneConfig`]
422    ///
423    /// Any configuration set in CLI will take precedence over those set in toml
424    pub fn prune_config(&self) -> PruneConfig
425    where
426        ChainSpec: reth_chainspec::EthereumHardforks,
427    {
428        let Some(mut node_prune_config) = self.node_config().prune_config() else {
429            // No CLI config is set, use the toml config.
430            return self.toml_config().prune.clone();
431        };
432
433        // Otherwise, use the CLI configuration and merge with toml config.
434        node_prune_config.merge(self.toml_config().prune.clone());
435        node_prune_config
436    }
437
438    /// Returns the configured [`PruneModes`], returning the default if no config was available.
439    pub fn prune_modes(&self) -> PruneModes
440    where
441        ChainSpec: reth_chainspec::EthereumHardforks,
442    {
443        self.prune_config().segments
444    }
445
446    /// Returns an initialized [`PrunerBuilder`] based on the configured [`PruneConfig`]
447    pub fn pruner_builder(&self) -> PrunerBuilder
448    where
449        ChainSpec: reth_chainspec::EthereumHardforks,
450    {
451        PrunerBuilder::new(self.prune_config())
452    }
453
454    /// Loads the JWT secret for the engine API
455    pub fn auth_jwt_secret(&self) -> eyre::Result<JwtSecret> {
456        let default_jwt_path = self.data_dir().jwt();
457        let secret = self.node_config().rpc.auth_jwt_secret(default_jwt_path)?;
458        Ok(secret)
459    }
460
461    /// Returns the [`MiningMode`] intended for --dev mode.
462    pub fn dev_mining_mode<Pool>(&self, pool: Pool) -> MiningMode<Pool>
463    where
464        Pool: TransactionPool + Unpin,
465    {
466        self.node_config().dev_mining_mode(pool)
467    }
468}
469
470impl<DB, ChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpec>, DB>>
471where
472    DB: Database + Clone + 'static,
473    ChainSpec: EthChainSpec + EthereumHardforks + 'static,
474{
475    /// Returns the [`ProviderFactory`] for the attached storage after executing a consistent check
476    /// between the database and static files. **It may execute a pipeline unwind if it fails this
477    /// check.**
478    pub async fn create_provider_factory<N, Evm>(
479        &self,
480        overlay_manager: OverlayManager<N::Primitives>,
481        rocksdb_provider: Option<RocksDBProvider>,
482        disabled_stages: &[StageId],
483    ) -> eyre::Result<ProviderFactory<N>>
484    where
485        N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
486        Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
487    {
488        self.create_provider_factory_with_recovery::<N, Evm>(
489            overlay_manager,
490            rocksdb_provider,
491            disabled_stages,
492            |_| Ok(()),
493        )
494        .await
495    }
496
497    /// Like [`Self::create_provider_factory`], but first runs `recover` to finish writes an earlier
498    /// run left half-committed, before the consistency check.
499    pub async fn create_provider_factory_with_recovery<N, Evm>(
500        &self,
501        overlay_manager: OverlayManager<N::Primitives>,
502        rocksdb_provider: Option<RocksDBProvider>,
503        disabled_stages: &[StageId],
504        recover: impl FnOnce(&ProviderFactory<N>) -> eyre::Result<()>,
505    ) -> eyre::Result<ProviderFactory<N>>
506    where
507        N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
508        Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
509    {
510        // Validate static files configuration
511        let static_files_config = &self.toml_config().static_files;
512        static_files_config.validate()?;
513
514        let prune_config = self.prune_config();
515
516        let blocks_per_file =
517            static_files_config.blocks_per_file_with_pruning(prune_config.segments.receipts);
518
519        // Apply per-segment blocks_per_file configuration
520        let static_file_provider =
521            StaticFileProviderBuilder::read_write(self.data_dir().static_files())
522                .with_metrics()
523                .with_blocks_per_file_for_segments(&blocks_per_file)
524                .with_genesis_block_number(self.chain_spec().genesis().number.unwrap_or_default())
525                .build()?;
526
527        // Use the provided RocksDB provider or create a new one
528        let rocksdb_provider = if let Some(provider) = rocksdb_provider {
529            provider
530        } else {
531            RocksDBProvider::builder(self.data_dir().rocksdb())
532                .with_default_tables()
533                .with_metrics()
534                .with_statistics()
535                .with_block_cache_size_opt(self.node_config().db.rocksdb_block_cache_size)
536                .build()?
537        };
538
539        let bal_store = self
540            .node_config()
541            .db
542            .balstore_cache_size
543            .map(|distance| {
544                RocksDBBalStore::with_buffer_retention_distance(rocksdb_provider.clone(), distance)
545            })
546            .unwrap_or_else(|| RocksDBBalStore::new(rocksdb_provider.clone()))
547            .with_bodies_prune_mode(
548                prune_config.segments.bodies_history,
549                prune_config.minimum_pruning_distance,
550            );
551        let bal_store = BalStoreHandle::new(bal_store);
552        let factory = ProviderFactory::new(
553            self.right().clone(),
554            self.chain_spec(),
555            static_file_provider,
556            rocksdb_provider,
557            overlay_manager,
558            self.task_executor().clone(),
559        )?
560        .with_prune_modes(prune_config.segments)
561        .with_minimum_pruning_distance(prune_config.minimum_pruning_distance)
562        .with_bal_store(bal_store);
563
564        recover(&factory)?;
565
566        // Check consistency between the database and static files, returning
567        // the unwind targets for each storage layer if inconsistencies are
568        // found.
569        let (rocksdb_unwind, static_file_unwind) = factory.check_consistency()?;
570        let provider_ro = factory.database_provider_ro()?;
571        // Finish is committed before Merkle during unwind, so this marker is authoritative when
572        // resuming an interrupted partial trie unwind.
573        let (partial_trie_unwind, has_persisted_partial_trie_unwind) =
574            get_partial_trie_unwind_marker(&provider_ro)?;
575        let pending_pipeline_unwind = provider_ro.pipeline_unwind()?;
576        drop(provider_ro);
577        let persist_partial_trie_unwind =
578            !has_persisted_partial_trie_unwind && partial_trie_unwind.is_some();
579        let partial_trie_unwind_target =
580            partial_trie_unwind.map(|marker| marker.partial_state_trie);
581        // Recover the partial state trie first. Its unwind enables
582        // `walk_all_changed_branch_children`, which is more expensive than a normal unwind, so
583        // it only runs to the partial trie target. A lower storage-layer target is then unwound
584        // normally.
585        let storage_unwind = [rocksdb_unwind, static_file_unwind].into_iter().flatten().min();
586        let storage_unwind = storage_unwind.filter(|unwind_block| {
587            partial_trie_unwind_target.is_none_or(|partial_trie| *unwind_block < partial_trie)
588        });
589
590        if partial_trie_unwind_target.is_some() ||
591            storage_unwind.is_some() ||
592            pending_pipeline_unwind.is_some()
593        {
594            let build_unwind_pipeline = |walk_all_changed_branch_children| {
595                let (_tip_tx, tip_rx) = watch::channel(B256::ZERO);
596                let mut stages = DefaultStages::new(
597                    factory.clone(),
598                    tip_rx,
599                    Arc::new(NoopConsensus::default()),
600                    NoopHeaderDownloader::default(),
601                    NoopBodiesDownloader::default(),
602                    NoopEvmConfig::<Evm>::default(),
603                    self.toml_config().stages.clone(),
604                    self.prune_modes(),
605                    None,
606                )
607                .builder()
608                // Recovery only moves the ERA checkpoint; it does not need an import source.
609                .add_before(
610                    EraStage::new(None::<EraImportSource>, self.toml_config().stages.etl.clone()),
611                    StageId::Headers,
612                )
613                .disable_all(disabled_stages);
614
615                if walk_all_changed_branch_children {
616                    // Partial trie recovery is not complete until Merkle has unwound.
617                    stages =
618                        stages.set(MerkleStage::new_unwind(true)).enable(StageId::MerkleUnwind);
619                }
620
621                PipelineBuilder::default().add_stages(stages).build(
622                    factory.clone(),
623                    StaticFileProducer::new(factory.clone(), self.prune_modes()),
624                )
625            };
626            let pending_unwind_target =
627                pending_pipeline_unwind.as_ref().map(|unwind| unwind.target);
628            let recovery_pipeline = pending_pipeline_unwind
629                .map(|_| build_unwind_pipeline(partial_trie_unwind_target.is_some()));
630            let mut unwinds = Vec::with_capacity(2);
631
632            if let Some(unwind_block) = partial_trie_unwind_target {
633                unwinds.push((
634                    PipelineTarget::Unwind(unwind_block),
635                    "partial state trie".to_owned(),
636                    build_unwind_pipeline(true),
637                    true,
638                ));
639            }
640
641            if let Some(unwind_block) = storage_unwind {
642                // Highly unlikely to happen, and given its destructive nature, it's better to
643                // panic instead. Unwinding to 0 would leave MDBX with a huge free list size.
644                let inconsistency_source = match (rocksdb_unwind, static_file_unwind) {
645                    (Some(_), Some(_)) => "RocksDB and static file",
646                    (Some(_), None) => "RocksDB",
647                    (None, Some(_)) => "static file",
648                    (None, None) => unreachable!(),
649                };
650                assert!(
651                    unwind_block != 0 || pending_unwind_target == Some(0),
652                    "A {inconsistency_source} inconsistency was found that would trigger an unwind to block 0"
653                );
654                unwinds.push((
655                    PipelineTarget::Unwind(unwind_block),
656                    inconsistency_source.to_owned(),
657                    build_unwind_pipeline(false),
658                    false,
659                ));
660            }
661
662            if persist_partial_trie_unwind {
663                // The marker must be durable before any unwind stage can commit.
664                let provider_rw = factory.database_provider_rw()?;
665                write_partial_trie_unwind_marker(
666                    &provider_rw,
667                    partial_trie_unwind.expect("partial trie unwind marker must exist"),
668                )?;
669                provider_rw.commit()?;
670            }
671
672            let (tx, rx) = oneshot::channel();
673            let factory = factory.clone();
674
675            // Pipeline should be run as blocking and panic if it fails.
676            self.task_executor().spawn_critical_blocking_task("pipeline task", async move {
677                let result: Result<(), reth_stages::PipelineError> = async {
678                    if let Some(mut pipeline) = recovery_pipeline {
679                        pipeline.resume_unwind()?;
680                    }
681                    for (unwind_target, inconsistency_source, pipeline, clear_partial_trie_unwind) in
682                        unwinds
683                    {
684                        info!(target: "reth::cli", %unwind_target, %inconsistency_source, "Executing unwind after consistency check.");
685                        let (_, result) = pipeline.run_as_fut(Some(unwind_target)).await;
686                        result.inspect_err(|err| {
687                            error!(target: "reth::cli", %unwind_target, %inconsistency_source, %err, "failed to run unwind");
688                        })?;
689
690                        if clear_partial_trie_unwind {
691                            let provider_rw = factory.database_provider_rw()?;
692                            delete_partial_trie_unwind_marker(&provider_rw)?;
693                            provider_rw.commit()?;
694                        }
695                    }
696                    Ok(())
697                }
698                .await;
699                let _ = tx.send(result);
700            });
701            rx.await??;
702        }
703
704        Ok(factory)
705    }
706
707    /// Creates a new [`ProviderFactory`] and attaches it to the launch context.
708    pub async fn with_provider_factory<N, Evm>(
709        self,
710        overlay_manager: OverlayManager<N::Primitives>,
711        rocksdb_provider: Option<RocksDBProvider>,
712        disabled_stages: &[StageId],
713    ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>>>
714    where
715        N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
716        Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
717    {
718        self.with_provider_factory_and_recovery::<N, Evm>(
719            overlay_manager,
720            rocksdb_provider,
721            disabled_stages,
722            |_| Ok(()),
723        )
724        .await
725    }
726
727    /// Like [`Self::with_provider_factory`], but first runs `recover` to finish writes an earlier
728    /// run left half-committed, before the consistency check.
729    pub async fn with_provider_factory_and_recovery<N, Evm>(
730        self,
731        overlay_manager: OverlayManager<N::Primitives>,
732        rocksdb_provider: Option<RocksDBProvider>,
733        disabled_stages: &[StageId],
734        recover: impl FnOnce(&ProviderFactory<N>) -> eyre::Result<()>,
735    ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>>>
736    where
737        N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
738        Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
739    {
740        let factory = self
741            .create_provider_factory_with_recovery::<N, Evm>(
742                overlay_manager,
743                rocksdb_provider,
744                disabled_stages,
745                recover,
746            )
747            .await?;
748        let ctx = LaunchContextWith {
749            inner: self.inner,
750            attachment: self.attachment.map_right(|_| factory),
751        };
752
753        Ok(ctx)
754    }
755}
756
757impl<T> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, ProviderFactory<T>>>
758where
759    T: ProviderNodeTypes,
760{
761    /// Returns access to the underlying database.
762    pub const fn database(&self) -> &T::DB {
763        self.right().db_ref()
764    }
765
766    /// Returns the configured `ProviderFactory`.
767    pub const fn provider_factory(&self) -> &ProviderFactory<T> {
768        self.right()
769    }
770
771    /// Returns the static file provider to interact with the static files.
772    pub fn static_file_provider(&self) -> StaticFileProvider<T::Primitives> {
773        self.right().static_file_provider()
774    }
775
776    /// This launches the prometheus endpoint.
777    ///
778    /// Convenience function to [`Self::start_prometheus_endpoint`]
779    pub async fn with_prometheus_server(self) -> eyre::Result<Self>
780    where
781        T::ChainSpec: EthereumHardforks,
782    {
783        self.start_prometheus_endpoint().await?;
784        Ok(self)
785    }
786
787    /// Starts the prometheus endpoint.
788    pub async fn start_prometheus_endpoint(&self) -> eyre::Result<()>
789    where
790        T::ChainSpec: EthereumHardforks,
791    {
792        // ensure recorder runs upkeep periodically
793        install_prometheus_recorder().spawn_upkeep();
794
795        let listen_addr = self.node_config().metrics.prometheus;
796        if let Some(addr) = listen_addr {
797            let prune_config = self.prune_config();
798            let pruning_mode =
799                PruneConfigKind::from_config(&prune_config, self.chain_spec().as_ref()).as_str();
800            // On existing databases, stored settings are authoritative and already cached by the
801            // provider factory. Fresh databases do not have storage metadata until genesis is
802            // initialized, so report the configured setting during this pre-genesis startup window.
803            let storage_settings =
804                if self.provider_factory().get_stage_checkpoint(StageId::Headers)?.is_some() {
805                    self.provider_factory().cached_storage_settings()
806                } else {
807                    self.node_config().storage_settings()
808                };
809            let config = MetricServerConfig::new(
810                addr,
811                VersionInfo {
812                    version: version_metadata().cargo_pkg_version.as_ref(),
813                    build_timestamp: version_metadata().vergen_build_timestamp.as_ref(),
814                    cargo_features: version_metadata().vergen_cargo_features.as_ref(),
815                    git_sha: version_metadata().vergen_git_sha.as_ref(),
816                    target_triple: version_metadata().vergen_cargo_target_triple.as_ref(),
817                    build_profile: version_metadata().build_profile_name.as_ref(),
818                },
819                ChainSpecInfo { name: self.chain_id().to_string() },
820                self.task_executor().clone(),
821                metrics_hooks(self.provider_factory()),
822                self.data_dir().pprof_dumps(),
823            )
824            .with_storage_settings_info(StorageSettingsInfo {
825                storage_v2: storage_settings.storage_v2,
826                pruning_mode,
827                prune_config: serde_json::to_string(&prune_config)
828                    .expect("serializing PruneConfig should not fail"),
829            })
830            .with_push_gateway(
831                self.node_config().metrics.push_gateway_url.clone(),
832                self.node_config().metrics.push_gateway_interval,
833            );
834
835            MetricServer::new(config).serve().await?;
836        }
837
838        Ok(())
839    }
840
841    /// Convenience function to [`Self::init_genesis`]
842    pub fn with_genesis(self) -> Result<Self, InitStorageError> {
843        init_genesis_with_settings_and_validate(
844            self.provider_factory(),
845            self.node_config().storage_settings(),
846            !self.node_config().debug.skip_genesis_validation,
847        )?;
848        Ok(self)
849    }
850
851    /// Write the genesis block and state if it has not already been written
852    pub fn init_genesis(&self) -> Result<B256, InitStorageError> {
853        init_genesis_with_settings(self.provider_factory(), self.node_config().storage_settings())
854    }
855
856    /// Creates a new `WithMeteredProvider` container and attaches it to the
857    /// launch context.
858    ///
859    /// This spawns a metrics task that listens for metrics related events and updates metrics for
860    /// prometheus.
861    pub fn with_metrics_task(
862        self,
863    ) -> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, WithMeteredProvider<T>>> {
864        let (metrics_sender, metrics_receiver) = unbounded_channel();
865
866        let with_metrics =
867            WithMeteredProvider { provider_factory: self.right().clone(), metrics_sender };
868
869        debug!(target: "reth::cli", "Spawning stages metrics listener task");
870        let sync_metrics_listener = reth_stages::MetricsListener::new(metrics_receiver);
871        self.task_executor()
872            .spawn_critical_task("stages metrics listener task", sync_metrics_listener);
873
874        LaunchContextWith {
875            inner: self.inner,
876            attachment: self.attachment.map_right(|_| with_metrics),
877        }
878    }
879}
880
881impl<N, DB>
882    LaunchContextWith<
883        Attached<WithConfigs<N::ChainSpec>, WithMeteredProvider<NodeTypesWithDBAdapter<N, DB>>>,
884    >
885where
886    N: NodeTypes,
887    DB: Database + DatabaseMetrics + Clone + Unpin + 'static,
888{
889    /// Returns the configured `ProviderFactory`.
890    pub const fn provider_factory(&self) -> &ProviderFactory<NodeTypesWithDBAdapter<N, DB>> {
891        &self.right().provider_factory
892    }
893
894    /// Returns the metrics sender.
895    fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
896        self.right().metrics_sender.clone()
897    }
898
899    /// Creates a `BlockchainProvider` and attaches it to the launch context.
900    #[expect(clippy::complexity)]
901    pub fn with_blockchain_db<T, F>(
902        self,
903        create_blockchain_provider: F,
904    ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<N::ChainSpec>, WithMeteredProviders<T>>>>
905    where
906        T: FullNodeTypes<Types = N, DB = DB>,
907        F: FnOnce(ProviderFactory<NodeTypesWithDBAdapter<N, DB>>) -> eyre::Result<T::Provider>,
908    {
909        let blockchain_db = create_blockchain_provider(self.provider_factory().clone())?;
910
911        let metered_providers = WithMeteredProviders {
912            db_provider_container: WithMeteredProvider {
913                provider_factory: self.provider_factory().clone(),
914                metrics_sender: self.sync_metrics_tx(),
915            },
916            blockchain_db,
917        };
918
919        let ctx = LaunchContextWith {
920            inner: self.inner,
921            attachment: self.attachment.map_right(|_| metered_providers),
922        };
923
924        Ok(ctx)
925    }
926}
927
928impl<T>
929    LaunchContextWith<
930        Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithMeteredProviders<T>>,
931    >
932where
933    T: FullNodeTypes<Types: NodeTypesForProvider>,
934{
935    /// Returns access to the underlying database.
936    pub const fn database(&self) -> &T::DB {
937        self.provider_factory().db_ref()
938    }
939
940    /// Returns the configured `ProviderFactory`.
941    pub const fn provider_factory(
942        &self,
943    ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
944        &self.right().db_provider_container.provider_factory
945    }
946
947    /// Fetches the head block from the database.
948    ///
949    /// If the database is empty, returns the genesis block.
950    pub fn lookup_head(&self) -> eyre::Result<Head> {
951        self.node_config()
952            .lookup_head(self.provider_factory())
953            .wrap_err("the head block is missing")
954    }
955
956    /// Returns the metrics sender.
957    pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
958        self.right().db_provider_container.metrics_sender.clone()
959    }
960
961    /// Returns a reference to the blockchain provider.
962    pub const fn blockchain_db(&self) -> &T::Provider {
963        &self.right().blockchain_db
964    }
965
966    /// Creates a `NodeAdapter` and attaches it to the launch context.
967    pub async fn with_components<CB>(
968        self,
969        components_builder: CB,
970        on_component_initialized: Box<
971            dyn OnComponentInitializedHook<NodeAdapter<T, CB::Components>>,
972        >,
973    ) -> eyre::Result<
974        LaunchContextWith<
975            Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
976        >,
977    >
978    where
979        CB: NodeComponentsBuilder<T>,
980    {
981        // fetch the head block from the database
982        let head = self.lookup_head()?;
983
984        let builder_ctx = BuilderContext::new(
985            head,
986            self.blockchain_db().clone(),
987            self.task_executor().clone(),
988            self.configs().clone(),
989        );
990
991        debug!(target: "reth::cli", "creating components");
992        let components = components_builder.build_components(&builder_ctx).await?;
993
994        let blockchain_db = self.blockchain_db().clone();
995
996        let node_adapter = NodeAdapter {
997            components,
998            task_executor: self.task_executor().clone(),
999            provider: blockchain_db,
1000        };
1001
1002        debug!(target: "reth::cli", "calling on_component_initialized hook");
1003        on_component_initialized.on_event(node_adapter.clone())?;
1004
1005        let components_container = WithComponents {
1006            db_provider_container: WithMeteredProvider {
1007                provider_factory: self.provider_factory().clone(),
1008                metrics_sender: self.sync_metrics_tx(),
1009            },
1010            node_adapter,
1011            head,
1012            sender_recovery_cache: builder_ctx.sender_recovery_cache().cloned(),
1013        };
1014
1015        let ctx = LaunchContextWith {
1016            inner: self.inner,
1017            attachment: self.attachment.map_right(|_| components_container),
1018        };
1019
1020        Ok(ctx)
1021    }
1022}
1023
1024impl<T, CB>
1025    LaunchContextWith<
1026        Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
1027    >
1028where
1029    T: FullNodeTypes<Types: NodeTypesForProvider>,
1030    CB: NodeComponentsBuilder<T>,
1031{
1032    /// Returns the configured `ProviderFactory`.
1033    pub const fn provider_factory(
1034        &self,
1035    ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
1036        &self.right().db_provider_container.provider_factory
1037    }
1038
1039    /// Returns the max block that the node should run to, looking it up from the network if
1040    /// necessary
1041    pub async fn max_block<C>(&self, client: C) -> eyre::Result<Option<BlockNumber>>
1042    where
1043        C: HeadersClient<Header: BlockHeader>,
1044    {
1045        self.node_config().max_block(client, self.provider_factory().clone()).await
1046    }
1047
1048    /// Returns the static file provider to interact with the static files.
1049    pub fn static_file_provider(&self) -> StaticFileProvider<<T::Types as NodeTypes>::Primitives> {
1050        self.provider_factory().static_file_provider()
1051    }
1052
1053    /// Creates a new [`StaticFileProducer`] with the attached database.
1054    pub fn static_file_producer(
1055        &self,
1056    ) -> StaticFileProducer<ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>>> {
1057        StaticFileProducer::new(self.provider_factory().clone(), self.prune_modes())
1058    }
1059
1060    /// Returns the current head block.
1061    pub const fn head(&self) -> Head {
1062        self.right().head
1063    }
1064
1065    /// Returns the configured `NodeAdapter`.
1066    pub const fn node_adapter(&self) -> &NodeAdapter<T, CB::Components> {
1067        &self.right().node_adapter
1068    }
1069
1070    /// Returns mutable reference to the configured `NodeAdapter`.
1071    pub const fn node_adapter_mut(&mut self) -> &mut NodeAdapter<T, CB::Components> {
1072        &mut self.right_mut().node_adapter
1073    }
1074
1075    /// Returns the cache of recovered transaction senders shared by node components, if enabled.
1076    pub const fn sender_recovery_cache(&self) -> Option<&SenderRecoveryCache> {
1077        self.right().sender_recovery_cache.as_ref()
1078    }
1079
1080    /// Returns a reference to the blockchain provider.
1081    pub const fn blockchain_db(&self) -> &T::Provider {
1082        &self.node_adapter().provider
1083    }
1084
1085    /// Returns the initial backfill to sync to at launch.
1086    ///
1087    /// This returns the configured `debug.tip` if set, otherwise it will check if backfill was
1088    /// previously interrupted and returns the block hash of the last checkpoint, see also
1089    /// [`Self::check_pipeline_consistency`]
1090    pub fn initial_backfill_target(
1091        &self,
1092        disabled_stages: &[StageId],
1093    ) -> ProviderResult<Option<B256>> {
1094        let mut initial_target = self.node_config().debug.tip;
1095
1096        if initial_target.is_none() {
1097            initial_target = self.check_pipeline_consistency(disabled_stages)?;
1098        }
1099
1100        Ok(initial_target)
1101    }
1102
1103    /// Returns true if the node should terminate after the initial backfill run.
1104    ///
1105    /// This is the case if any of these configs are set:
1106    ///  `--debug.max-block`
1107    ///  `--debug.terminate`
1108    pub const fn terminate_after_initial_backfill(&self) -> bool {
1109        self.node_config().debug.terminate || self.node_config().debug.max_block.is_some()
1110    }
1111
1112    /// Ensures that the database matches chain-specific requirements.
1113    ///
1114    /// This checks for OP-Mainnet and ensures we have all the necessary data to progress (past
1115    /// bedrock height)
1116    fn ensure_chain_specific_db_checks(&self) -> ProviderResult<()> {
1117        if self.chain_spec().is_optimism() &&
1118            !self.is_dev() &&
1119            self.chain_id() == Chain::optimism_mainnet()
1120        {
1121            let latest = self.blockchain_db().last_block_number()?;
1122            // bedrock height
1123            if latest < 105235063 {
1124                error!(
1125                    "Op-mainnet has been launched without importing the pre-Bedrock state. The chain can't progress without this. See also https://reth.rs/run/sync-op-mainnet.html?minimal-bootstrap-recommended"
1126                );
1127                return Err(ProviderError::BestBlockNotFound);
1128            }
1129        }
1130
1131        Ok(())
1132    }
1133
1134    /// Check if the pipeline is consistent (all stages have the checkpoint block numbers no less
1135    /// than the checkpoint of the first stage).
1136    ///
1137    /// This will return the pipeline target if:
1138    ///  * the pipeline was interrupted during its previous run
1139    ///  * a new stage was added
1140    ///  * stage data was dropped manually through `reth stage drop ...`
1141    ///
1142    /// # Returns
1143    ///
1144    /// A target block hash if the pipeline is inconsistent, otherwise `None`.
1145    pub fn check_pipeline_consistency(
1146        &self,
1147        disabled_stages: &[StageId],
1148    ) -> ProviderResult<Option<B256>> {
1149        // We skip the era stage if it's not enabled
1150        let era_enabled = self.era_import_source().is_some();
1151        let mut all_stages = StageId::ALL
1152            .into_iter()
1153            .filter(|id| (era_enabled || id != &StageId::Era) && !disabled_stages.contains(id));
1154
1155        // Get the expected first stage based on config.
1156        let first_stage = all_stages.next().expect("there must be at least one stage");
1157
1158        // If no target was provided, check if the stages are congruent - check if the
1159        // checkpoint of the last stage matches the checkpoint of the first.
1160        let first_stage_checkpoint = self
1161            .blockchain_db()
1162            .get_stage_checkpoint(first_stage)?
1163            .unwrap_or_default()
1164            .block_number;
1165
1166        // Compare all other stages against the first
1167        for stage_id in all_stages {
1168            let stage_checkpoint = self
1169                .blockchain_db()
1170                .get_stage_checkpoint(stage_id)?
1171                .unwrap_or_default()
1172                .block_number;
1173
1174            // If the checkpoint of any stage is less than the checkpoint of the first stage,
1175            // retrieve and return the block hash of the latest header and use it as the target.
1176            debug!(
1177                target: "consensus::engine",
1178                first_stage_id = %first_stage,
1179                first_stage_checkpoint,
1180                stage_id = %stage_id,
1181                stage_checkpoint = stage_checkpoint,
1182                "Checking stage against first stage",
1183            );
1184            if stage_checkpoint < first_stage_checkpoint {
1185                debug!(
1186                    target: "consensus::engine",
1187                    first_stage_id = %first_stage,
1188                    first_stage_checkpoint,
1189                    inconsistent_stage_id = %stage_id,
1190                    inconsistent_stage_checkpoint = stage_checkpoint,
1191                    "Pipeline sync progress is inconsistent"
1192                );
1193                return self.blockchain_db().block_hash(first_stage_checkpoint);
1194            }
1195        }
1196
1197        self.ensure_chain_specific_db_checks()?;
1198
1199        Ok(None)
1200    }
1201
1202    /// Returns the metrics sender.
1203    pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
1204        self.right().db_provider_container.metrics_sender.clone()
1205    }
1206
1207    /// Returns the node adapter components.
1208    pub const fn components(&self) -> &CB::Components {
1209        &self.node_adapter().components
1210    }
1211
1212    /// Launches ExEx (Execution Extensions) and returns the ExEx manager handle.
1213    #[expect(clippy::type_complexity)]
1214    pub async fn launch_exex(
1215        &self,
1216        installed_exex: Vec<(
1217            String,
1218            Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1219        )>,
1220    ) -> eyre::Result<Option<ExExManagerHandle<PrimitivesTy<T::Types>>>> {
1221        self.exex_launcher(installed_exex).launch().await
1222    }
1223
1224    /// Creates an [`ExExLauncher`] for the installed ExExes.
1225    ///
1226    /// This returns the launcher before calling `.launch()`, allowing custom configuration
1227    /// such as setting the WAL blocks warning threshold for L2 chains with faster block times:
1228    ///
1229    /// ```ignore
1230    /// ctx.exex_launcher(exexes)
1231    ///     .with_wal_blocks_warning(768)  // For 2-second block times
1232    ///     .launch()
1233    ///     .await
1234    /// ```
1235    #[expect(clippy::type_complexity)]
1236    pub fn exex_launcher(
1237        &self,
1238        installed_exex: Vec<(
1239            String,
1240            Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1241        )>,
1242    ) -> ExExLauncher<NodeAdapter<T, CB::Components>> {
1243        ExExLauncher::new(
1244            self.head(),
1245            self.node_adapter().clone(),
1246            installed_exex,
1247            self.configs().clone(),
1248        )
1249    }
1250
1251    /// Creates the ERA import source based on node configuration.
1252    ///
1253    /// Returns `Some(EraImportSource)` if ERA is enabled in the node config, otherwise `None`.
1254    pub fn era_import_source(&self) -> Option<EraImportSource> {
1255        let node_config = self.node_config();
1256        if !node_config.era.enabled {
1257            return None;
1258        }
1259
1260        EraImportSource::maybe_new(
1261            node_config.era.source.path.clone(),
1262            node_config.era.source.url.clone(),
1263            || node_config.chain.chain().kind().default_era_host(),
1264            || node_config.datadir().data_dir().join("era").into(),
1265        )
1266    }
1267
1268    /// Creates consensus layer health events stream based on node configuration.
1269    ///
1270    /// Returns a stream that monitors consensus layer health if:
1271    /// - No debug tip is configured
1272    /// - Not running in dev mode
1273    ///
1274    /// Otherwise returns an empty stream.
1275    pub fn consensus_layer_events(
1276        &self,
1277    ) -> impl Stream<Item = NodeEvent<PrimitivesTy<T::Types>>> + 'static
1278    where
1279        T::Provider: reth_provider::CanonChainTracker,
1280    {
1281        if self.node_config().debug.tip.is_none() && !self.is_dev() {
1282            Either::Left(
1283                ConsensusLayerHealthEvents::new(Box::new(self.blockchain_db().clone()))
1284                    .map(Into::into),
1285            )
1286        } else {
1287            Either::Right(stream::empty())
1288        }
1289    }
1290
1291    /// Spawns the [`EthStatsService`] service if configured.
1292    pub async fn spawn_ethstats<St>(&self, mut engine_events: St) -> eyre::Result<()>
1293    where
1294        St: Stream<Item = reth_engine_primitives::ConsensusEngineEvent<PrimitivesTy<T::Types>>>
1295            + Send
1296            + Unpin
1297            + 'static,
1298    {
1299        let Some(url) = self.node_config().debug.ethstats.as_ref() else { return Ok(()) };
1300
1301        let network = self.components().network().clone();
1302        let pool = self.components().pool().clone();
1303        let provider = self.node_adapter().provider.clone();
1304
1305        info!(target: "reth::cli", "Starting EthStats service at {}", url);
1306
1307        let ethstats = EthStatsService::new(url, network, provider, pool).await?;
1308
1309        // If engine events are provided, spawn listener for new payload reporting
1310        let ethstats_for_events = ethstats.clone();
1311        let task_executor = self.task_executor().clone();
1312        task_executor.spawn_task(async move {
1313            while let Some(event) = engine_events.next().await {
1314                match event {
1315                    ConsensusEngineEvent::ForkBlockAdded(executed, duration) |
1316                    ConsensusEngineEvent::CanonicalBlockAdded(executed, duration) => {
1317                        let block_hash = executed.recovered_block.num_hash().hash;
1318                        let block_number = executed.recovered_block.num_hash().number;
1319                        if let Err(e) = ethstats_for_events
1320                            .report_new_payload(block_hash, block_number, duration)
1321                            .await
1322                        {
1323                            debug!(
1324                                target: "ethstats",
1325                                "Failed to report new payload: {}", e
1326                            );
1327                        }
1328                    }
1329                    _ => {
1330                        // Ignore other event types for ethstats reporting
1331                    }
1332                }
1333            }
1334        });
1335
1336        // Spawn main ethstats service
1337        task_executor.spawn_task(async move { ethstats.run().await });
1338
1339        Ok(())
1340    }
1341}
1342
1343/// Joins two attachments together, preserving access to both values.
1344///
1345/// This type enables the launch process to accumulate state while maintaining
1346/// access to all previously attached components. The `left` field holds the
1347/// previous state, while `right` holds the newly attached component.
1348#[derive(Clone, Copy, Debug)]
1349pub struct Attached<L, R> {
1350    left: L,
1351    right: R,
1352}
1353
1354impl<L, R> Attached<L, R> {
1355    /// Creates a new `Attached` with the given values.
1356    pub const fn new(left: L, right: R) -> Self {
1357        Self { left, right }
1358    }
1359
1360    /// Maps the left value to a new value.
1361    pub fn map_left<F, T>(self, f: F) -> Attached<T, R>
1362    where
1363        F: FnOnce(L) -> T,
1364    {
1365        Attached::new(f(self.left), self.right)
1366    }
1367
1368    /// Maps the right value to a new value.
1369    pub fn map_right<F, T>(self, f: F) -> Attached<L, T>
1370    where
1371        F: FnOnce(R) -> T,
1372    {
1373        Attached::new(self.left, f(self.right))
1374    }
1375
1376    /// Get a reference to the left value.
1377    pub const fn left(&self) -> &L {
1378        &self.left
1379    }
1380
1381    /// Get a reference to the right value.
1382    pub const fn right(&self) -> &R {
1383        &self.right
1384    }
1385
1386    /// Get a mutable reference to the left value.
1387    pub const fn left_mut(&mut self) -> &mut L {
1388        &mut self.left
1389    }
1390
1391    /// Get a mutable reference to the right value.
1392    pub const fn right_mut(&mut self) -> &mut R {
1393        &mut self.right
1394    }
1395}
1396
1397/// Helper container type to bundle the initial [`NodeConfig`] and the loaded settings from the
1398/// reth.toml config
1399#[derive(Debug)]
1400pub struct WithConfigs<ChainSpec> {
1401    /// The configured, usually derived from the CLI.
1402    pub config: NodeConfig<ChainSpec>,
1403    /// The loaded reth.toml config.
1404    pub toml_config: reth_config::Config,
1405}
1406
1407impl<ChainSpec> Clone for WithConfigs<ChainSpec> {
1408    fn clone(&self) -> Self {
1409        Self { config: self.config.clone(), toml_config: self.toml_config.clone() }
1410    }
1411}
1412
1413/// Helper container type to bundle the [`ProviderFactory`] and the metrics
1414/// sender.
1415#[derive(Debug, Clone)]
1416pub struct WithMeteredProvider<N: NodeTypesWithDB> {
1417    provider_factory: ProviderFactory<N>,
1418    metrics_sender: UnboundedSender<MetricEvent>,
1419}
1420
1421/// Helper container to bundle the [`ProviderFactory`], [`FullNodeTypes::Provider`]
1422/// and a metrics sender.
1423#[expect(missing_debug_implementations)]
1424pub struct WithMeteredProviders<T>
1425where
1426    T: FullNodeTypes,
1427{
1428    db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1429    blockchain_db: T::Provider,
1430}
1431
1432/// Helper container to bundle the metered providers container and [`NodeAdapter`].
1433#[expect(missing_debug_implementations)]
1434pub struct WithComponents<T, CB>
1435where
1436    T: FullNodeTypes,
1437    CB: NodeComponentsBuilder<T>,
1438{
1439    db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1440    node_adapter: NodeAdapter<T, CB::Components>,
1441    head: Head,
1442    /// Cache of recovered transaction senders shared by node components, if enabled.
1443    sender_recovery_cache: Option<SenderRecoveryCache>,
1444}
1445
1446/// Returns the metrics hooks for the node.
1447///
1448/// The storage hooks walk their backing store, which scales with the dataset, so they are
1449/// registered as background hooks: metrics collection still refreshes them at most every 5
1450/// minutes, but renders the values of the previous refresh instead of waiting for the walk.
1451pub fn metrics_hooks<N: NodeTypesWithDB>(provider_factory: &ProviderFactory<N>) -> Hooks {
1452    Hooks::builder()
1453        .with_background_interval(Duration::from_secs(5 * 60))
1454        .with_background_hook({
1455            let db = provider_factory.db_ref().clone();
1456            move || db.report_metrics()
1457        })
1458        .with_background_hook({
1459            let sfp = provider_factory.static_file_provider();
1460            move || {
1461                if let Err(error) = sfp.report_metrics() {
1462                    error!(%error, "Failed to report metrics from static file provider");
1463                }
1464            }
1465        })
1466        .with_background_hook({
1467            let rocksdb = provider_factory.rocksdb_provider();
1468            move || rocksdb.report_metrics()
1469        })
1470        .build()
1471}
1472
1473fn get_partial_trie_unwind_marker(
1474    provider: &(impl MetadataProvider + StageCheckpointReader),
1475) -> ProviderResult<(Option<PartialStateTrieUnwindMarker>, bool)> {
1476    if let Some(marker) = provider.get_metadata(PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY)? {
1477        let marker = serde_json::from_slice::<PartialStateTrieUnwindMarker>(&marker)
1478            .map_err(ProviderError::other)?;
1479        if marker.partial_state_trie >= marker.finish_block_number {
1480            return Err(ProviderError::other(std::io::Error::other(format!(
1481                "partial state trie unwind target #{} is not below original Finish #{}",
1482                marker.partial_state_trie, marker.finish_block_number,
1483            ))))
1484        }
1485        return Ok((Some(marker), true))
1486    }
1487
1488    let Some(finish_checkpoint) = provider.get_stage_checkpoint(StageId::Finish)? else {
1489        return Ok((None, false))
1490    };
1491    let Some(partial_state_trie) =
1492        finish_checkpoint.finish_stage_checkpoint().and_then(|finish| finish.partial_state_trie())
1493    else {
1494        return Ok((None, false))
1495    };
1496
1497    if partial_state_trie > finish_checkpoint.block_number {
1498        return Err(ProviderError::other(std::io::Error::other(format!(
1499            "partial state trie frontier #{partial_state_trie} is ahead of Finish #{}",
1500            finish_checkpoint.block_number,
1501        ))))
1502    }
1503
1504    Ok((
1505        (partial_state_trie < finish_checkpoint.block_number).then_some(
1506            PartialStateTrieUnwindMarker {
1507                finish_block_number: finish_checkpoint.block_number,
1508                partial_state_trie,
1509            },
1510        ),
1511        false,
1512    ))
1513}
1514
1515/// Metadata key for a partial state trie unwind that has not completed yet.
1516const PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY: &str = "partial_state_trie_unwind";
1517
1518fn write_partial_trie_unwind_marker(
1519    provider: &impl MetadataWriter,
1520    marker: PartialStateTrieUnwindMarker,
1521) -> ProviderResult<()> {
1522    provider.write_metadata(
1523        PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY,
1524        serde_json::to_vec(&marker).map_err(ProviderError::other)?,
1525    )
1526}
1527
1528fn delete_partial_trie_unwind_marker(provider: &impl MetadataWriter) -> ProviderResult<()> {
1529    provider.delete_metadata(PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY)
1530}
1531
1532#[cfg(test)]
1533mod tests {
1534    use super::{get_partial_trie_unwind_marker, LaunchContext, NodeConfig};
1535    use reth_config::Config;
1536    use reth_db_api::models::PartialStateTrieUnwindMarker;
1537    use reth_node_core::args::PruningArgs;
1538    use reth_provider::{MetadataProvider, ProviderResult, StageCheckpointReader};
1539    use reth_stages::{FinishCheckpoint, StageCheckpoint, StageId};
1540
1541    const EXTENSION: &str = "toml";
1542
1543    struct MockProvider(Option<Vec<u8>>, Option<StageCheckpoint>);
1544
1545    impl MetadataProvider for MockProvider {
1546        fn get_metadata(&self, _: &str) -> ProviderResult<Option<Vec<u8>>> {
1547            Ok(self.0.clone())
1548        }
1549    }
1550
1551    impl StageCheckpointReader for MockProvider {
1552        fn get_stage_checkpoint(&self, id: StageId) -> ProviderResult<Option<StageCheckpoint>> {
1553            assert_eq!(id, StageId::Finish);
1554            Ok(self.1)
1555        }
1556
1557        fn get_stage_checkpoint_progress(&self, _: StageId) -> ProviderResult<Option<Vec<u8>>> {
1558            Ok(None)
1559        }
1560
1561        fn get_all_checkpoints(&self) -> ProviderResult<Vec<(String, StageCheckpoint)>> {
1562            Ok(Vec::new())
1563        }
1564    }
1565
1566    fn with_tempdir(filename: &str, proc: fn(&std::path::Path)) {
1567        let temp_dir = tempfile::tempdir().unwrap();
1568        let config_path = temp_dir.path().join(filename).with_extension(EXTENSION);
1569        proc(&config_path);
1570        temp_dir.close().unwrap()
1571    }
1572
1573    #[test]
1574    fn test_save_prune_config() {
1575        with_tempdir("prune-store-test", |config_path| {
1576            let mut reth_config = Config::default();
1577            let node_config = NodeConfig {
1578                pruning: PruningArgs {
1579                    full: true,
1580                    minimal: false,
1581                    block_interval: None,
1582                    sender_recovery_full: false,
1583                    sender_recovery_distance: None,
1584                    sender_recovery_before: None,
1585                    transaction_lookup_full: false,
1586                    transaction_lookup_distance: None,
1587                    transaction_lookup_before: None,
1588                    receipts_full: false,
1589                    receipts_pre_merge: false,
1590                    receipts_distance: None,
1591                    receipts_before: None,
1592                    account_history_full: false,
1593                    account_history_distance: None,
1594                    account_history_before: None,
1595                    storage_history_full: false,
1596                    storage_history_distance: None,
1597                    storage_history_before: None,
1598                    bodies_pre_merge: false,
1599                    bodies_distance: None,
1600                    receipts_log_filter: None,
1601                    bodies_before: None,
1602                    minimum_distance: None,
1603                },
1604                ..NodeConfig::test()
1605            };
1606            LaunchContext::save_pruning_config(&mut reth_config, &node_config, config_path)
1607                .unwrap();
1608
1609            let loaded_config = Config::from_path(config_path).unwrap();
1610
1611            assert_eq!(reth_config, loaded_config);
1612        })
1613    }
1614
1615    #[test]
1616    fn get_partial_trie_unwind_marker_uses_partial_finish_checkpoint() {
1617        let finish_checkpoint = StageCheckpoint::new(42)
1618            .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(21) });
1619        let expected =
1620            finish_checkpoint.finish_stage_checkpoint().unwrap().partial_state_trie().map(
1621                |partial_state_trie| PartialStateTrieUnwindMarker {
1622                    finish_block_number: finish_checkpoint.block_number,
1623                    partial_state_trie,
1624                },
1625            );
1626
1627        assert_eq!(
1628            get_partial_trie_unwind_marker(&MockProvider(None, Some(finish_checkpoint))).unwrap(),
1629            (expected, false)
1630        );
1631
1632        let genesis_checkpoint = StageCheckpoint::new(42)
1633            .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(0) });
1634        let expected =
1635            genesis_checkpoint.finish_stage_checkpoint().unwrap().partial_state_trie().map(
1636                |partial_state_trie| PartialStateTrieUnwindMarker {
1637                    finish_block_number: genesis_checkpoint.block_number,
1638                    partial_state_trie,
1639                },
1640            );
1641
1642        assert_eq!(
1643            get_partial_trie_unwind_marker(&MockProvider(None, Some(genesis_checkpoint))).unwrap(),
1644            (expected, false)
1645        );
1646    }
1647
1648    #[test]
1649    fn get_partial_trie_unwind_marker_resumes_persisted_unwind() {
1650        let marker =
1651            PartialStateTrieUnwindMarker { finish_block_number: 42, partial_state_trie: 21 };
1652
1653        assert_eq!(
1654            get_partial_trie_unwind_marker(&MockProvider(
1655                Some(serde_json::to_vec(&marker).unwrap()),
1656                Some(StageCheckpoint::new(21)),
1657            ),)
1658            .unwrap(),
1659            (Some(marker), true)
1660        );
1661        assert_eq!(
1662            get_partial_trie_unwind_marker(&MockProvider(
1663                Some(serde_json::to_vec(&marker).unwrap()),
1664                None
1665            ),)
1666            .unwrap(),
1667            (Some(marker), true)
1668        );
1669    }
1670
1671    #[test]
1672    fn get_partial_trie_unwind_marker_ignores_non_lagging_or_missing_partial_checkpoint() {
1673        let matching_finish_checkpoint = StageCheckpoint::new(42)
1674            .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(42) });
1675        let ahead_finish_checkpoint = StageCheckpoint::new(42)
1676            .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(43) });
1677        let missing_partial_finish_checkpoint = StageCheckpoint::new(42)
1678            .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: None });
1679
1680        assert_eq!(
1681            get_partial_trie_unwind_marker(&MockProvider(None, Some(matching_finish_checkpoint)),)
1682                .unwrap(),
1683            (None, false)
1684        );
1685        assert_eq!(
1686            get_partial_trie_unwind_marker(&MockProvider(
1687                None,
1688                Some(missing_partial_finish_checkpoint)
1689            ),)
1690            .unwrap(),
1691            (None, false)
1692        );
1693        assert_eq!(
1694            get_partial_trie_unwind_marker(&MockProvider(None, None)).unwrap(),
1695            (None, false)
1696        );
1697
1698        let partial_frontier = ahead_finish_checkpoint
1699            .finish_stage_checkpoint()
1700            .and_then(|finish| finish.partial_state_trie());
1701        let result =
1702            get_partial_trie_unwind_marker(&MockProvider(None, Some(ahead_finish_checkpoint)));
1703        if partial_frontier.is_some() {
1704            let error = result.unwrap_err();
1705            assert!(error.to_string().contains("ahead of Finish"), "unexpected error: {error}");
1706        } else {
1707            assert_eq!(result.unwrap(), (None, false));
1708        }
1709    }
1710
1711    #[test]
1712    fn get_partial_trie_unwind_marker_rejects_invalid_persisted_marker() {
1713        let marker =
1714            PartialStateTrieUnwindMarker { finish_block_number: 42, partial_state_trie: 42 };
1715        let error = get_partial_trie_unwind_marker(&MockProvider(
1716            Some(serde_json::to_vec(&marker).unwrap()),
1717            None,
1718        ))
1719        .unwrap_err();
1720
1721        assert!(error.to_string().contains("is not below original Finish"));
1722    }
1723
1724    #[test]
1725    fn get_partial_trie_unwind_marker_rejects_malformed_metadata() {
1726        assert!(get_partial_trie_unwind_marker(&MockProvider(Some(vec![0xff]), None)).is_err());
1727    }
1728}