Skip to main content

reth_cli_commands/
common.rs

1//! Contains common `reth` arguments
2
3pub use reth_primitives_traits::header::HeaderMut;
4
5use alloy_primitives::B256;
6use clap::Parser;
7use reth_chainspec::EthChainSpec;
8use reth_cli::chainspec::ChainSpecParser;
9use reth_config::{config::EtlConfig, Config};
10use reth_consensus::noop::NoopConsensus;
11use reth_db::{init_db, open_db_read_only, DatabaseEnv};
12use reth_db_common::init::init_genesis_with_settings;
13use reth_downloaders::{bodies::noop::NoopBodiesDownloader, headers::noop::NoopHeaderDownloader};
14use reth_eth_wire::NetPrimitivesFor;
15use reth_evm::{noop::NoopEvmConfig, ConfigureEvm};
16use reth_network::NetworkEventListenerProvider;
17use reth_node_api::FullNodeTypesAdapter;
18use reth_node_builder::{
19    Node, NodeComponents, NodeComponentsBuilder, NodeTypes, NodeTypesWithDBAdapter,
20};
21use reth_node_core::{
22    args::{DatabaseArgs, DatadirArgs, StaticFilesArgs, StorageArgs},
23    dirs::{ChainPath, DataDirPath},
24};
25use reth_provider::{
26    providers::{
27        BlockchainProvider, NodeTypesForProvider, RocksDBProvider, StaticFileProvider,
28        StaticFileProviderBuilder,
29    },
30    ProviderFactory, StaticFileProviderFactory, StorageSettings,
31};
32use reth_stages::{sets::DefaultStages, Pipeline, PipelineTarget};
33use reth_static_file::StaticFileProducer;
34use std::{path::PathBuf, sync::Arc};
35use tokio::sync::watch;
36use tracing::{debug, info, warn};
37
38/// Struct to hold config and datadir paths
39#[derive(Debug, Parser)]
40pub struct EnvironmentArgs<C: ChainSpecParser> {
41    /// Parameters for datadir configuration
42    #[command(flatten)]
43    pub datadir: DatadirArgs,
44
45    /// The path to the configuration file to use.
46    #[arg(long, value_name = "FILE")]
47    pub config: Option<PathBuf>,
48
49    /// The chain this node is running.
50    ///
51    /// Possible values are either a built-in chain or the path to a chain specification file.
52    #[arg(
53        long,
54        value_name = "CHAIN_OR_PATH",
55        long_help = C::help_message(),
56        default_value = C::default_value(),
57        value_parser = C::parser(),
58        global = true
59    )]
60    pub chain: Arc<C::ChainSpec>,
61
62    /// All database related arguments
63    #[command(flatten)]
64    pub db: DatabaseArgs,
65
66    /// All static files related arguments
67    #[command(flatten)]
68    pub static_files: StaticFilesArgs,
69
70    /// Storage mode configuration (v2 vs v1/legacy)
71    #[command(flatten)]
72    pub storage: StorageArgs,
73}
74
75impl<C: ChainSpecParser> EnvironmentArgs<C> {
76    /// Returns the effective storage settings derived from `--storage.v2`.
77    ///
78    /// The base storage mode is determined by `--storage.v2`:
79    /// - When `--storage.v2` is set: uses [`StorageSettings::v2()`] defaults
80    /// - Otherwise: uses [`StorageSettings::base()`] defaults
81    pub fn storage_settings(&self) -> StorageSettings {
82        if self.storage.v2 {
83            StorageSettings::v2()
84        } else {
85            StorageSettings::base()
86        }
87    }
88
89    /// Initializes environment according to [`AccessRights`] and returns an instance of
90    /// [`Environment`].
91    ///
92    /// Internally builds a [`reth_tasks::Runtime`] attached to the current tokio handle for
93    /// parallel storage I/O.
94    pub fn init<N: CliNodeTypes>(&self, access: AccessRights) -> eyre::Result<Environment<N>>
95    where
96        C: ChainSpecParser<ChainSpec = N::ChainSpec>,
97    {
98        let runtime = reth_tasks::Runtime::with_existing_handle(tokio::runtime::Handle::current())?;
99        let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain());
100        let db_path = data_dir.db();
101        let sf_path = data_dir.static_files();
102        let rocksdb_path = data_dir.rocksdb();
103
104        if access.is_read_write() {
105            reth_fs_util::create_dir_all(&db_path)?;
106            reth_fs_util::create_dir_all(&sf_path)?;
107            reth_fs_util::create_dir_all(&rocksdb_path)?;
108        }
109
110        let config_path = self.config.clone().unwrap_or_else(|| data_dir.config());
111
112        let mut config = Config::from_path(config_path)
113            .inspect_err(
114                |err| warn!(target: "reth::cli", %err, "Failed to load config file, using default"),
115            )
116            .unwrap_or_default();
117
118        // Make sure ETL doesn't default to /tmp/, but to whatever datadir is set to
119        if config.stages.etl.dir.is_none() {
120            config.stages.etl.dir = Some(EtlConfig::from_datadir(data_dir.data_dir()));
121        }
122        if config.stages.era.folder.is_none() {
123            config.stages.era = config.stages.era.with_datadir(data_dir.data_dir());
124        }
125
126        info!(target: "reth::cli", ?db_path, ?sf_path, "Opening storage");
127        let genesis_block_number = self.chain.genesis().number.unwrap_or_default();
128        let (db, sfp) = match access {
129            AccessRights::RW => (
130                init_db(db_path, self.db.database_args())?,
131                StaticFileProviderBuilder::read_write(sf_path)
132                    .with_metrics()
133                    .with_genesis_block_number(genesis_block_number)
134                    .build()?,
135            ),
136            AccessRights::RO | AccessRights::RoInconsistent => {
137                (open_db_read_only(&db_path, self.db.database_args())?, {
138                    let provider = StaticFileProviderBuilder::read_only(sf_path)
139                        .with_metrics()
140                        .with_genesis_block_number(genesis_block_number)
141                        .build()?;
142                    provider.watch_directory();
143                    provider
144                })
145            }
146        };
147        let rocksdb_provider = RocksDBProvider::builder(data_dir.rocksdb())
148            .with_default_tables()
149            .with_database_log_level(self.db.log_level)
150            .with_read_only(!access.is_read_write())
151            .build()?;
152
153        let provider_factory =
154            self.create_provider_factory(&config, db, sfp, rocksdb_provider, access, runtime)?;
155        if access.is_read_write() {
156            debug!(target: "reth::cli", chain=%self.chain.chain(), genesis=?self.chain.genesis_hash(), "Initializing genesis");
157            init_genesis_with_settings(&provider_factory, self.storage_settings())?;
158        }
159
160        Ok(Environment { config, provider_factory, data_dir })
161    }
162
163    /// Returns a [`ProviderFactory`] after executing consistency checks.
164    ///
165    /// If it's a read-write environment and an issue is found, it will attempt to heal (including a
166    /// pipeline unwind). Otherwise, it will print out a warning, advising the user to restart the
167    /// node to heal.
168    fn create_provider_factory<N: CliNodeTypes>(
169        &self,
170        config: &Config,
171        db: DatabaseEnv,
172        static_file_provider: StaticFileProvider<N::Primitives>,
173        rocksdb_provider: RocksDBProvider,
174        access: AccessRights,
175        runtime: reth_tasks::Runtime,
176    ) -> eyre::Result<ProviderFactory<NodeTypesWithDBAdapter<N, DatabaseEnv>>>
177    where
178        C: ChainSpecParser<ChainSpec = N::ChainSpec>,
179    {
180        let prune_modes = config.prune.segments.clone();
181        let factory = ProviderFactory::<NodeTypesWithDBAdapter<N, DatabaseEnv>>::new(
182            db,
183            self.chain.clone(),
184            static_file_provider,
185            rocksdb_provider,
186            runtime,
187        )?
188        .with_prune_modes(prune_modes.clone());
189
190        // Check for consistency between database and static files.
191        if !access.is_read_only_inconsistent() &&
192            let Some(unwind_target) =
193                factory.static_file_provider().check_consistency(&factory.provider()?)?
194        {
195            if factory.db_ref().is_read_only()? {
196                warn!(target: "reth::cli", ?unwind_target, "Inconsistent storage. Restart node to heal.");
197                return Ok(factory)
198            }
199
200            // Highly unlikely to happen, and given its destructive nature, it's better to panic
201            // instead.
202            assert_ne!(
203                unwind_target,
204                PipelineTarget::Unwind(0),
205                "A static file <> database inconsistency was found that would trigger an unwind to block 0"
206            );
207
208            info!(target: "reth::cli", unwind_target = %unwind_target, "Executing an unwind after a failed storage consistency check.");
209
210            let (_tip_tx, tip_rx) = watch::channel(B256::ZERO);
211
212            // Builds and executes an unwind-only pipeline
213            let mut pipeline = Pipeline::<NodeTypesWithDBAdapter<N, DatabaseEnv>>::builder()
214                .add_stages(DefaultStages::new(
215                    factory.clone(),
216                    tip_rx,
217                    Arc::new(NoopConsensus::default()),
218                    NoopHeaderDownloader::default(),
219                    NoopBodiesDownloader::default(),
220                    NoopEvmConfig::<N::Evm>::default(),
221                    config.stages.clone(),
222                    prune_modes.clone(),
223                    None,
224                ))
225                .build(factory.clone(), StaticFileProducer::new(factory.clone(), prune_modes));
226
227            // Move all applicable data from database to static files.
228            pipeline.move_to_static_files()?;
229            pipeline.unwind(unwind_target.unwind_target().expect("should exist"), None)?;
230        }
231
232        Ok(factory)
233    }
234}
235
236/// Environment built from [`EnvironmentArgs`].
237#[derive(Debug)]
238pub struct Environment<N: NodeTypes> {
239    /// Configuration for reth node
240    pub config: Config,
241    /// Provider factory.
242    pub provider_factory: ProviderFactory<NodeTypesWithDBAdapter<N, DatabaseEnv>>,
243    /// Datadir path.
244    pub data_dir: ChainPath<DataDirPath>,
245}
246
247/// Environment access rights.
248#[derive(Debug, Copy, Clone)]
249pub enum AccessRights {
250    /// Read-write access
251    RW,
252    /// Read-only access
253    RO,
254    /// Read-only access with possibly inconsistent data
255    RoInconsistent,
256}
257
258impl AccessRights {
259    /// Returns `true` if it requires read-write access to the environment.
260    pub const fn is_read_write(&self) -> bool {
261        matches!(self, Self::RW)
262    }
263
264    /// Returns `true` if it requires read-only access to the environment with possibly inconsistent
265    /// data.
266    pub const fn is_read_only_inconsistent(&self) -> bool {
267        matches!(self, Self::RoInconsistent)
268    }
269}
270
271/// Helper alias to satisfy `FullNodeTypes` bound on [`Node`] trait generic.
272type FullTypesAdapter<T> = FullNodeTypesAdapter<
273    T,
274    DatabaseEnv,
275    BlockchainProvider<NodeTypesWithDBAdapter<T, DatabaseEnv>>,
276>;
277
278/// Helper trait with a common set of requirements for the
279/// [`NodeTypes`] in CLI.
280pub trait CliNodeTypes: Node<FullTypesAdapter<Self>> + NodeTypesForProvider {
281    type Evm: ConfigureEvm<Primitives = Self::Primitives>;
282    type NetworkPrimitives: NetPrimitivesFor<Self::Primitives>;
283}
284
285impl<N> CliNodeTypes for N
286where
287    N: Node<FullTypesAdapter<Self>> + NodeTypesForProvider,
288{
289    type Evm = <<N::ComponentsBuilder as NodeComponentsBuilder<FullTypesAdapter<Self>>>::Components as NodeComponents<FullTypesAdapter<Self>>>::Evm;
290    type NetworkPrimitives = <<<N::ComponentsBuilder as NodeComponentsBuilder<FullTypesAdapter<Self>>>::Components as NodeComponents<FullTypesAdapter<Self>>>::Network as NetworkEventListenerProvider>::Primitives;
291}
292
293type EvmFor<N> = <<<N as Node<FullTypesAdapter<N>>>::ComponentsBuilder as NodeComponentsBuilder<
294    FullTypesAdapter<N>,
295>>::Components as NodeComponents<FullTypesAdapter<N>>>::Evm;
296
297type ConsensusFor<N> =
298    <<<N as Node<FullTypesAdapter<N>>>::ComponentsBuilder as NodeComponentsBuilder<
299        FullTypesAdapter<N>,
300    >>::Components as NodeComponents<FullTypesAdapter<N>>>::Consensus;
301
302/// Helper trait aggregating components required for the CLI.
303pub trait CliNodeComponents<N: CliNodeTypes>: Send + Sync + 'static {
304    /// Returns the configured EVM.
305    fn evm_config(&self) -> &EvmFor<N>;
306    /// Returns the consensus implementation.
307    fn consensus(&self) -> &ConsensusFor<N>;
308}
309
310impl<N: CliNodeTypes> CliNodeComponents<N> for (EvmFor<N>, ConsensusFor<N>) {
311    fn evm_config(&self) -> &EvmFor<N> {
312        &self.0
313    }
314
315    fn consensus(&self) -> &ConsensusFor<N> {
316        &self.1
317    }
318}
319
320/// Helper trait alias for an [`FnOnce`] producing [`CliNodeComponents`].
321pub trait CliComponentsBuilder<N: CliNodeTypes>:
322    FnOnce(Arc<N::ChainSpec>) -> Self::Components + Send + Sync + 'static
323{
324    type Components: CliNodeComponents<N>;
325}
326
327impl<N: CliNodeTypes, F, Comp> CliComponentsBuilder<N> for F
328where
329    F: FnOnce(Arc<N::ChainSpec>) -> Comp + Send + Sync + 'static,
330    Comp: CliNodeComponents<N>,
331{
332    type Components = Comp;
333}