1pub use reth_primitives_traits::header::HeaderMut;
4
5use alloy_primitives::B256;
6use clap::Parser;
7use eyre::WrapErr;
8use reth_chainspec::EthChainSpec;
9use reth_cli::chainspec::ChainSpecParser;
10use reth_config::{config::EtlConfig, Config};
11use reth_consensus::noop::NoopConsensus;
12use reth_db::{init_db, open_db_read_only, DatabaseEnv};
13use reth_db_common::init::init_genesis_with_settings;
14use reth_downloaders::{bodies::noop::NoopBodiesDownloader, headers::noop::NoopHeaderDownloader};
15use reth_eth_wire::NetPrimitivesFor;
16use reth_evm::{noop::NoopEvmConfig, ConfigureEvm};
17use reth_network::NetworkEventListenerProvider;
18use reth_node_api::FullNodeTypesAdapter;
19use reth_node_builder::{
20 Node, NodeComponents, NodeComponentsBuilder, NodeTypes, NodeTypesWithDBAdapter,
21};
22use reth_node_core::{
23 args::{DatabaseArgs, DatadirArgs, StaticFilesArgs, StorageArgs},
24 dirs::{ChainPath, DataDirPath},
25};
26use reth_provider::{
27 providers::{
28 BlockchainProvider, NodeTypesForProvider, RocksDBProvider, StaticFileProvider,
29 StaticFileProviderBuilder,
30 },
31 BalStoreHandle, ProviderFactory, RocksDBBalStore, StaticFileProviderFactory, StorageSettings,
32};
33use reth_stages::{
34 sets::DefaultStages,
35 stages::{EraImportSource, EraStage},
36 Pipeline, PipelineTarget, StageId, StageSet,
37};
38use reth_static_file::StaticFileProducer;
39use reth_storage_overlay::OverlayManager;
40use std::{path::PathBuf, sync::Arc};
41use tokio::sync::watch;
42use tracing::{debug, info, warn};
43
44#[derive(Debug, Parser)]
46pub struct EnvironmentArgs<C: ChainSpecParser> {
47 #[command(flatten)]
49 pub datadir: DatadirArgs,
50
51 #[arg(long, value_name = "FILE")]
53 pub config: Option<PathBuf>,
54
55 #[arg(
59 long,
60 value_name = "CHAIN_OR_PATH",
61 long_help = C::help_message(),
62 default_value = C::default_value(),
63 value_parser = C::parser(),
64 global = true
65 )]
66 pub chain: Arc<C::ChainSpec>,
67
68 #[command(flatten)]
70 pub db: DatabaseArgs,
71
72 #[command(flatten)]
74 pub static_files: StaticFilesArgs,
75
76 #[command(flatten)]
78 pub storage: StorageArgs,
79}
80
81impl<C: ChainSpecParser> EnvironmentArgs<C> {
82 pub fn storage_settings(&self) -> StorageSettings {
88 if self.storage.v2 {
89 StorageSettings::v2()
90 } else {
91 StorageSettings::v1()
92 }
93 }
94
95 pub fn init<N: CliNodeTypes>(
100 &self,
101 access: AccessRights,
102 runtime: reth_tasks::Runtime,
103 ) -> eyre::Result<Environment<N>>
104 where
105 C: ChainSpecParser<ChainSpec = N::ChainSpec>,
106 {
107 let data_dir = self.datadir.clone().resolve_datadir(self.chain.chain());
108 let db_path = data_dir.db();
109 let sf_path = data_dir.static_files();
110 let rocksdb_path = data_dir.rocksdb();
111
112 if access.is_read_write() {
113 reth_fs_util::create_dir_all(&db_path)?;
114 reth_fs_util::create_dir_all(&sf_path)?;
115 reth_fs_util::create_dir_all(&rocksdb_path)?;
116 }
117
118 let config_path = self.config.clone().unwrap_or_else(|| data_dir.config());
119
120 let mut config = Config::from_path(&config_path)
121 .wrap_err_with(|| format!("Could not load config file {config_path:?}"))?;
122 config.static_files = self.static_files.merge_with_config(config.static_files, false);
123 config.static_files.validate()?;
124
125 if config.stages.etl.dir.is_none() {
127 config.stages.etl.dir = Some(EtlConfig::from_datadir(data_dir.data_dir()));
128 }
129 if config.stages.era.folder.is_none() {
130 config.stages.era = config.stages.era.with_datadir(data_dir.data_dir());
131 }
132
133 info!(target: "reth::cli", ?db_path, ?sf_path, "Opening storage");
134 let genesis_block_number = self.chain.genesis().number.unwrap_or_default();
135 let (db, sf_builder) = match access {
136 AccessRights::RW | AccessRights::RwInconsistent => (
137 init_db(db_path, self.db.database_args())?,
138 StaticFileProviderBuilder::read_write(sf_path),
139 ),
140 AccessRights::RO | AccessRights::RoInconsistent => (
141 open_db_read_only(&db_path, self.db.database_args())?,
142 StaticFileProviderBuilder::read_only(sf_path),
143 ),
144 };
145 let blocks_per_file = if access.is_read_write() {
146 config.static_files.blocks_per_file_with_pruning(config.prune.segments.receipts)
147 } else {
148 config.static_files.as_blocks_per_file_map()
149 };
150 let sfp = sf_builder
151 .with_metrics()
152 .with_blocks_per_file_for_segments(&blocks_per_file)
153 .with_genesis_block_number(genesis_block_number)
154 .build()?;
155 let rocksdb_provider = if !access.is_read_write() && !RocksDBProvider::exists(&rocksdb_path)
156 {
157 debug!(target: "reth::cli", ?rocksdb_path, "RocksDB not found, initializing empty database");
161 reth_fs_util::create_dir_all(&rocksdb_path)?;
162 let mut builder = RocksDBProvider::builder(data_dir.rocksdb())
163 .with_default_tables()
164 .with_database_log_level(self.db.log_level);
165 if let Some(cache_size) = self.db.rocksdb_block_cache_size {
166 builder = builder.with_block_cache_size(cache_size);
167 }
168 builder.build()?
169 } else {
170 let mut builder = RocksDBProvider::builder(data_dir.rocksdb())
171 .with_default_tables()
172 .with_database_log_level(self.db.log_level)
173 .with_read_only(!access.is_read_write());
174 if let Some(cache_size) = self.db.rocksdb_block_cache_size {
175 builder = builder.with_block_cache_size(cache_size);
176 }
177 builder.build()?
178 };
179
180 let provider_factory =
181 self.create_provider_factory(&config, db, sfp, rocksdb_provider, access, runtime)?;
182 if access.is_read_write() {
183 debug!(target: "reth::cli", chain=%self.chain.chain(), genesis=?self.chain.genesis_hash(), "Initializing genesis");
184 init_genesis_with_settings(&provider_factory, self.storage_settings())?;
185 }
186
187 Ok(Environment { config, provider_factory, data_dir })
188 }
189
190 fn create_provider_factory<N: CliNodeTypes>(
196 &self,
197 config: &Config,
198 db: DatabaseEnv,
199 static_file_provider: StaticFileProvider<N::Primitives>,
200 rocksdb_provider: RocksDBProvider,
201 access: AccessRights,
202 runtime: reth_tasks::Runtime,
203 ) -> eyre::Result<ProviderFactory<NodeTypesWithDBAdapter<N, DatabaseEnv>>>
204 where
205 C: ChainSpecParser<ChainSpec = N::ChainSpec>,
206 {
207 let bal_store = self
208 .db
209 .balstore_cache_size
210 .map(|distance| {
211 RocksDBBalStore::with_buffer_retention_distance(rocksdb_provider.clone(), distance)
212 })
213 .unwrap_or_else(|| RocksDBBalStore::new(rocksdb_provider.clone()));
214 let bal_store = BalStoreHandle::new(bal_store);
215 let factory = ProviderFactory::<NodeTypesWithDBAdapter<N, DatabaseEnv>>::new(
216 db,
217 self.chain.clone(),
218 static_file_provider,
219 rocksdb_provider,
220 OverlayManager::default(),
221 runtime,
222 )?
223 .with_prune_modes(config.prune.segments.clone())
224 .with_minimum_pruning_distance(config.prune.minimum_pruning_distance)
225 .with_bal_store(bal_store);
226
227 if !access.skips_consistency_check() &&
229 let Some(unwind_target) =
230 factory.static_file_provider().check_consistency(&factory.provider()?)?
231 {
232 if factory.db_ref().is_read_only()? {
233 warn!(target: "reth::cli", ?unwind_target, "Inconsistent storage. Restart node to heal.");
234 return Ok(factory)
235 }
236
237 assert_ne!(
240 unwind_target,
241 PipelineTarget::Unwind(0),
242 "A static file <> database inconsistency was found that would trigger an unwind to block 0"
243 );
244
245 info!(target: "reth::cli", unwind_target = %unwind_target, "Executing an unwind after a failed storage consistency check.");
246
247 let (_tip_tx, tip_rx) = watch::channel(B256::ZERO);
248
249 let mut pipeline = Pipeline::<NodeTypesWithDBAdapter<N, DatabaseEnv>>::builder()
251 .add_stages(
252 DefaultStages::new(
253 factory.clone(),
254 tip_rx,
255 Arc::new(NoopConsensus::default()),
256 NoopHeaderDownloader::default(),
257 NoopBodiesDownloader::default(),
258 NoopEvmConfig::<N::Evm>::default(),
259 config.stages.clone(),
260 config.prune.segments.clone(),
261 None,
262 )
263 .builder()
264 .add_before(
265 EraStage::new(None::<EraImportSource>, config.stages.etl.clone()),
266 StageId::Headers,
267 ),
268 )
269 .build(
270 factory.clone(),
271 StaticFileProducer::new(factory.clone(), config.prune.segments.clone()),
272 );
273
274 pipeline.move_to_static_files()?;
276 pipeline.unwind(unwind_target.unwind_target().expect("should exist"), None)?;
277 }
278
279 Ok(factory)
280 }
281}
282
283#[derive(Debug)]
285pub struct Environment<N: NodeTypes> {
286 pub config: Config,
288 pub provider_factory: ProviderFactory<NodeTypesWithDBAdapter<N, DatabaseEnv>>,
290 pub data_dir: ChainPath<DataDirPath>,
292}
293
294#[derive(Debug, Copy, Clone)]
296pub enum AccessRights {
297 RW,
299 RwInconsistent,
301 RO,
303 RoInconsistent,
305}
306
307impl AccessRights {
308 pub const fn is_read_write(&self) -> bool {
310 matches!(self, Self::RW | Self::RwInconsistent)
311 }
312
313 pub const fn is_read_only_inconsistent(&self) -> bool {
316 matches!(self, Self::RoInconsistent)
317 }
318
319 pub const fn skips_consistency_check(&self) -> bool {
321 matches!(self, Self::RwInconsistent | Self::RoInconsistent)
322 }
323}
324
325type FullTypesAdapter<T> = FullNodeTypesAdapter<
327 T,
328 DatabaseEnv,
329 BlockchainProvider<NodeTypesWithDBAdapter<T, DatabaseEnv>>,
330>;
331
332pub trait CliNodeTypes: Node<FullTypesAdapter<Self>> + NodeTypesForProvider {
335 type Evm: ConfigureEvm<Primitives = Self::Primitives>;
336 type NetworkPrimitives: NetPrimitivesFor<Self::Primitives>;
337}
338
339impl<N> CliNodeTypes for N
340where
341 N: Node<FullTypesAdapter<Self>> + NodeTypesForProvider,
342{
343 type Evm = <<N::ComponentsBuilder as NodeComponentsBuilder<FullTypesAdapter<Self>>>::Components as NodeComponents<FullTypesAdapter<Self>>>::Evm;
344 type NetworkPrimitives = <<<N::ComponentsBuilder as NodeComponentsBuilder<FullTypesAdapter<Self>>>::Components as NodeComponents<FullTypesAdapter<Self>>>::Network as NetworkEventListenerProvider>::Primitives;
345}
346
347type EvmFor<N> = <<<N as Node<FullTypesAdapter<N>>>::ComponentsBuilder as NodeComponentsBuilder<
348 FullTypesAdapter<N>,
349>>::Components as NodeComponents<FullTypesAdapter<N>>>::Evm;
350
351type ConsensusFor<N> =
352 <<<N as Node<FullTypesAdapter<N>>>::ComponentsBuilder as NodeComponentsBuilder<
353 FullTypesAdapter<N>,
354 >>::Components as NodeComponents<FullTypesAdapter<N>>>::Consensus;
355
356pub trait CliNodeComponents<N: CliNodeTypes>: Send + Sync + 'static {
358 fn evm_config(&self) -> &EvmFor<N>;
360 fn consensus(&self) -> &ConsensusFor<N>;
362}
363
364impl<N: CliNodeTypes> CliNodeComponents<N> for (EvmFor<N>, ConsensusFor<N>) {
365 fn evm_config(&self) -> &EvmFor<N> {
366 &self.0
367 }
368
369 fn consensus(&self) -> &ConsensusFor<N> {
370 &self.1
371 }
372}
373
374pub trait CliComponentsBuilder<N: CliNodeTypes>:
376 FnOnce(Arc<N::ChainSpec>) -> Self::Components + Send + Sync + 'static
377{
378 type Components: CliNodeComponents<N>;
379}
380
381impl<N: CliNodeTypes, F, Comp> CliComponentsBuilder<N> for F
382where
383 F: FnOnce(Arc<N::ChainSpec>) -> Comp + Send + Sync + 'static,
384 Comp: CliNodeComponents<N>,
385{
386 type Components = Comp;
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392
393 #[test]
394 fn inconsistent_access_rights_skip_consistency_checks() {
395 assert!(AccessRights::RwInconsistent.is_read_write());
396 assert!(AccessRights::RwInconsistent.skips_consistency_check());
397 assert!(!AccessRights::RW.skips_consistency_check());
398
399 assert!(!AccessRights::RoInconsistent.is_read_write());
400 assert!(AccessRights::RoInconsistent.is_read_only_inconsistent());
401 assert!(AccessRights::RoInconsistent.skips_consistency_check());
402 assert!(!AccessRights::RO.skips_consistency_check());
403 }
404}