1use 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 rayon::ThreadPoolBuilder;
41use reth_chainspec::{Chain, EthChainSpec, EthereumHardforks};
42use reth_config::{config::EtlConfig, PruneConfig};
43use reth_consensus::noop::NoopConsensus;
44use reth_db_api::{database::Database, database_metrics::DatabaseMetrics};
45use reth_db_common::init::{
46 init_genesis_with_settings, init_genesis_with_settings_and_validate, InitStorageError,
47};
48use reth_downloaders::{bodies::noop::NoopBodiesDownloader, headers::noop::NoopHeaderDownloader};
49use reth_engine_local::MiningMode;
50use reth_evm::{noop::NoopEvmConfig, ConfigureEvm};
51use reth_exex::ExExManagerHandle;
52use reth_fs_util as fs;
53use reth_network_p2p::headers::client::HeadersClient;
54use reth_node_api::{FullNodeTypes, NodeTypes, NodeTypesWithDB, NodeTypesWithDBAdapter};
55use reth_node_core::{
56 args::{DefaultEraHost, PruneConfigKind},
57 dirs::{ChainPath, DataDirPath},
58 node_config::NodeConfig,
59 primitives::BlockHeader,
60 version::version_metadata,
61};
62use reth_node_metrics::{
63 chain::ChainSpecInfo,
64 hooks::Hooks,
65 recorder::install_prometheus_recorder,
66 server::{MetricServer, MetricServerConfig},
67 storage::StorageSettingsInfo,
68 version::VersionInfo,
69};
70use reth_provider::{
71 providers::{NodeTypesForProvider, ProviderNodeTypes, RocksDBProvider, StaticFileProvider},
72 BalConfig, BalStoreHandle, BlockHashReader, BlockNumReader, InMemoryBalStore, ProviderError,
73 ProviderFactory, ProviderResult, RocksDBProviderFactory, StageCheckpointReader,
74 StaticFileProviderBuilder, StaticFileProviderFactory, StorageSettingsCache,
75};
76use reth_prune::{PruneMode, PruneModes, PrunerBuilder};
77use reth_rpc_builder::config::RethRpcServerConfig;
78use reth_rpc_layer::JwtSecret;
79use reth_stages::{
80 sets::DefaultStages, stages::EraImportSource, MetricEvent, PipelineBuilder, PipelineTarget,
81 StageId, StageSet,
82};
83use reth_static_file::{blocks_per_file_for_prune_distance, StaticFileProducer, StaticFileSegment};
84use reth_tasks::TaskExecutor;
85use reth_tracing::{
86 throttle,
87 tracing::{debug, error, info, warn},
88};
89use reth_transaction_pool::TransactionPool;
90use reth_trie_db::ChangesetCache;
91use std::{num::NonZeroUsize, sync::Arc, thread::available_parallelism, time::Duration};
92use tokio::sync::{
93 mpsc::{unbounded_channel, UnboundedSender},
94 oneshot, watch,
95};
96
97use futures::{future::Either, stream, Stream, StreamExt};
98use reth_node_ethstats::EthStatsService;
99use reth_node_events::{cl::ConsensusLayerHealthEvents, node::NodeEvent};
100
101#[derive(Debug, Clone)]
120pub struct LaunchContext {
121 pub task_executor: TaskExecutor,
123 pub data_dir: ChainPath<DataDirPath>,
125}
126
127impl LaunchContext {
128 pub const fn new(task_executor: TaskExecutor, data_dir: ChainPath<DataDirPath>) -> Self {
130 Self { task_executor, data_dir }
131 }
132
133 pub const fn with<T>(self, attachment: T) -> LaunchContextWith<T> {
135 LaunchContextWith { inner: self, attachment }
136 }
137
138 pub fn with_loaded_toml_config<ChainSpec>(
143 self,
144 config: NodeConfig<ChainSpec>,
145 ) -> eyre::Result<LaunchContextWith<WithConfigs<ChainSpec>>>
146 where
147 ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
148 {
149 let toml_config = self.load_toml_config(&config)?;
150 Ok(self.with(WithConfigs { config, toml_config }))
151 }
152
153 pub fn load_toml_config<ChainSpec>(
158 &self,
159 config: &NodeConfig<ChainSpec>,
160 ) -> eyre::Result<reth_config::Config>
161 where
162 ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
163 {
164 let config_path = config.config.clone().unwrap_or_else(|| self.data_dir.config());
165
166 let mut toml_config = reth_config::Config::from_path(&config_path)
167 .wrap_err_with(|| format!("Could not load config file {config_path:?}"))?;
168
169 Self::save_pruning_config(&mut toml_config, config, &config_path)?;
170
171 info!(target: "reth::cli", path = ?config_path, "Configuration loaded");
172
173 toml_config.peers.trusted_nodes_only |= config.network.trusted_only;
176
177 toml_config.static_files =
179 config.static_files.merge_with_config(toml_config.static_files, config.pruning.minimal);
180
181 Ok(toml_config)
182 }
183
184 fn save_pruning_config<ChainSpec>(
187 reth_config: &mut reth_config::Config,
188 config: &NodeConfig<ChainSpec>,
189 config_path: impl AsRef<std::path::Path>,
190 ) -> eyre::Result<()>
191 where
192 ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
193 {
194 let mut should_save = reth_config.prune.segments.migrate();
195
196 if let Some(prune_config) = config.prune_config() {
197 if reth_config.prune != prune_config {
198 reth_config.set_prune_config(prune_config);
199 should_save = true;
200 }
201 } else if !reth_config.prune.is_default() {
202 info!(target: "reth::cli", "Pruning configuration is present in the config file, but no CLI arguments are provided. Using config from file.");
203 }
204
205 if should_save {
206 info!(target: "reth::cli", "Saving prune config to toml file");
207 reth_config.save(config_path.as_ref())?;
208 }
209
210 Ok(())
211 }
212
213 pub fn with_configured_globals(self, reserved_cpu_cores: usize) -> Self {
215 self.configure_globals(reserved_cpu_cores);
216 self
217 }
218
219 pub fn configure_globals(&self, reserved_cpu_cores: usize) {
224 match fdlimit::raise_fd_limit() {
227 Ok(fdlimit::Outcome::LimitRaised { from, to }) => {
228 debug!(from, to, "Raised file descriptor limit");
229 }
230 Ok(fdlimit::Outcome::Unsupported) => {}
231 Err(err) => warn!(%err, "Failed to raise file descriptor limit"),
232 }
233
234 let _ = reserved_cpu_cores;
238 let num_threads = available_parallelism().map_or(1, NonZeroUsize::get);
239 if let Err(err) = ThreadPoolBuilder::new()
240 .num_threads(num_threads)
241 .thread_name(|i| format!("rayon-{i:02}"))
242 .build_global()
243 {
244 warn!(%err, "Failed to build global thread pool")
245 }
246 }
247}
248
249#[derive(Debug, Clone)]
260pub struct LaunchContextWith<T> {
261 pub inner: LaunchContext,
263 pub attachment: T,
265}
266
267impl<T> LaunchContextWith<T> {
268 pub fn configure_globals(&self, reserved_cpu_cores: u64) {
273 self.inner.configure_globals(reserved_cpu_cores.try_into().unwrap());
274 }
275
276 pub const fn data_dir(&self) -> &ChainPath<DataDirPath> {
278 &self.inner.data_dir
279 }
280
281 pub const fn task_executor(&self) -> &TaskExecutor {
283 &self.inner.task_executor
284 }
285
286 pub fn attach<A>(self, attachment: A) -> LaunchContextWith<Attached<T, A>> {
288 LaunchContextWith {
289 inner: self.inner,
290 attachment: Attached::new(self.attachment, attachment),
291 }
292 }
293
294 pub fn inspect<F>(self, f: F) -> Self
297 where
298 F: FnOnce(&Self),
299 {
300 f(&self);
301 self
302 }
303}
304
305impl<ChainSpec> LaunchContextWith<WithConfigs<ChainSpec>> {
306 pub fn with_resolved_peers(mut self) -> eyre::Result<Self> {
308 if !self.attachment.config.network.trusted_peers.is_empty() {
309 info!(target: "reth::cli", "Adding trusted nodes");
310
311 self.attachment
312 .toml_config
313 .peers
314 .trusted_nodes
315 .extend(self.attachment.config.network.trusted_peers.clone());
316 }
317 Ok(self)
318 }
319}
320
321impl<L, R> LaunchContextWith<Attached<L, R>> {
322 pub const fn left(&self) -> &L {
324 &self.attachment.left
325 }
326
327 pub const fn right(&self) -> &R {
329 &self.attachment.right
330 }
331
332 pub const fn left_mut(&mut self) -> &mut L {
334 &mut self.attachment.left
335 }
336
337 pub const fn right_mut(&mut self) -> &mut R {
339 &mut self.attachment.right
340 }
341}
342impl<R, ChainSpec: EthChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpec>, R>> {
343 pub fn with_adjusted_configs(self) -> Self {
349 self.ensure_etl_datadir().with_adjusted_instance_ports()
350 }
351
352 pub fn ensure_etl_datadir(mut self) -> Self {
354 if self.toml_config_mut().stages.etl.dir.is_none() {
355 let etl_path = EtlConfig::from_datadir(self.data_dir().data_dir());
356 if etl_path.exists() {
357 if let Err(err) = fs::remove_dir_all(&etl_path) {
359 warn!(target: "reth::cli", ?etl_path, %err, "Failed to remove ETL path on launch");
360 }
361 }
362 self.toml_config_mut().stages.etl.dir = Some(etl_path);
363 }
364
365 self
366 }
367
368 pub fn with_adjusted_instance_ports(mut self) -> Self {
370 self.node_config_mut().adjust_instance_ports();
371 self
372 }
373
374 pub const fn configs(&self) -> &WithConfigs<ChainSpec> {
376 self.attachment.left()
377 }
378
379 pub const fn node_config(&self) -> &NodeConfig<ChainSpec> {
381 &self.left().config
382 }
383
384 pub const fn node_config_mut(&mut self) -> &mut NodeConfig<ChainSpec> {
386 &mut self.left_mut().config
387 }
388
389 pub const fn toml_config(&self) -> &reth_config::Config {
391 &self.left().toml_config
392 }
393
394 pub const fn toml_config_mut(&mut self) -> &mut reth_config::Config {
396 &mut self.left_mut().toml_config
397 }
398
399 pub fn chain_spec(&self) -> Arc<ChainSpec> {
401 self.node_config().chain.clone()
402 }
403
404 pub fn genesis_hash(&self) -> B256 {
406 self.node_config().chain.genesis_hash()
407 }
408
409 pub fn chain_id(&self) -> Chain {
411 self.node_config().chain.chain()
412 }
413
414 pub const fn is_dev(&self) -> bool {
416 self.node_config().dev.dev
417 }
418
419 pub fn prune_config(&self) -> PruneConfig
423 where
424 ChainSpec: reth_chainspec::EthereumHardforks,
425 {
426 let Some(mut node_prune_config) = self.node_config().prune_config() else {
427 return self.toml_config().prune.clone();
429 };
430
431 node_prune_config.merge(self.toml_config().prune.clone());
433 node_prune_config
434 }
435
436 pub fn prune_modes(&self) -> PruneModes
438 where
439 ChainSpec: reth_chainspec::EthereumHardforks,
440 {
441 self.prune_config().segments
442 }
443
444 pub fn pruner_builder(&self) -> PrunerBuilder
446 where
447 ChainSpec: reth_chainspec::EthereumHardforks,
448 {
449 PrunerBuilder::new(self.prune_config())
450 }
451
452 pub fn auth_jwt_secret(&self) -> eyre::Result<JwtSecret> {
454 let default_jwt_path = self.data_dir().jwt();
455 let secret = self.node_config().rpc.auth_jwt_secret(default_jwt_path)?;
456 Ok(secret)
457 }
458
459 pub fn dev_mining_mode<Pool>(&self, pool: Pool) -> MiningMode<Pool>
461 where
462 Pool: TransactionPool + Unpin,
463 {
464 self.node_config().dev_mining_mode(pool)
465 }
466}
467
468impl<DB, ChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpec>, DB>>
469where
470 DB: Database + Clone + 'static,
471 ChainSpec: EthChainSpec + EthereumHardforks + 'static,
472{
473 pub async fn create_provider_factory<N, Evm>(
477 &self,
478 changeset_cache: ChangesetCache,
479 rocksdb_provider: Option<RocksDBProvider>,
480 disabled_stages: &[StageId],
481 ) -> eyre::Result<ProviderFactory<N>>
482 where
483 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
484 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
485 {
486 let static_files_config = &self.toml_config().static_files;
488 static_files_config.validate()?;
489
490 let prune_config = self.prune_config();
491
492 let mut blocks_per_file = static_files_config.as_blocks_per_file_map();
493 if blocks_per_file.get(StaticFileSegment::Receipts).is_none() &&
498 let Some(PruneMode::Distance(distance)) = prune_config.segments.receipts
499 {
500 blocks_per_file
501 .insert(StaticFileSegment::Receipts, blocks_per_file_for_prune_distance(distance));
502 }
503
504 let static_file_provider =
506 StaticFileProviderBuilder::read_write(self.data_dir().static_files())
507 .with_metrics()
508 .with_blocks_per_file_for_segments(&blocks_per_file)
509 .with_genesis_block_number(self.chain_spec().genesis().number.unwrap_or_default())
510 .build()?;
511
512 let rocksdb_provider = if let Some(provider) = rocksdb_provider {
514 provider
515 } else {
516 RocksDBProvider::builder(self.data_dir().rocksdb())
517 .with_default_tables()
518 .with_metrics()
519 .with_statistics()
520 .build()?
521 };
522
523 let balstore_cache_size = self
524 .node_config()
525 .db
526 .balstore_cache_size
527 .unwrap_or(BalConfig::DEFAULT_IN_MEMORY_RETENTION_DISTANCE);
528 let bal_store = BalStoreHandle::new(InMemoryBalStore::new(
529 BalConfig::with_in_memory_retention_distance(balstore_cache_size),
530 ));
531 let factory = ProviderFactory::new(
532 self.right().clone(),
533 self.chain_spec(),
534 static_file_provider,
535 rocksdb_provider,
536 self.task_executor().clone(),
537 )?
538 .with_prune_modes(prune_config.segments)
539 .with_minimum_pruning_distance(prune_config.minimum_pruning_distance)
540 .with_changeset_cache(changeset_cache)
541 .with_bal_store(bal_store);
542
543 let (rocksdb_unwind, static_file_unwind) = factory.check_consistency()?;
547
548 let unwind_target = [rocksdb_unwind, static_file_unwind].into_iter().flatten().min();
550
551 if let Some(unwind_block) = unwind_target {
552 let inconsistency_source = match (rocksdb_unwind, static_file_unwind) {
555 (Some(_), Some(_)) => "RocksDB and static file",
556 (Some(_), None) => "RocksDB",
557 (None, Some(_)) => "static file",
558 (None, None) => unreachable!(),
559 };
560 assert_ne!(
561 unwind_block, 0,
562 "A {} inconsistency was found that would trigger an unwind to block 0",
563 inconsistency_source
564 );
565
566 let unwind_target = PipelineTarget::Unwind(unwind_block);
567
568 info!(target: "reth::cli", %unwind_target, %inconsistency_source, "Executing unwind after consistency check.");
569
570 let (_tip_tx, tip_rx) = watch::channel(B256::ZERO);
571
572 let pipeline = PipelineBuilder::default()
574 .add_stages(
575 DefaultStages::new(
576 factory.clone(),
577 tip_rx,
578 Arc::new(NoopConsensus::default()),
579 NoopHeaderDownloader::default(),
580 NoopBodiesDownloader::default(),
581 NoopEvmConfig::<Evm>::default(),
582 self.toml_config().stages.clone(),
583 self.prune_modes(),
584 None,
585 )
586 .builder()
587 .disable_all(disabled_stages),
588 )
589 .build(
590 factory.clone(),
591 StaticFileProducer::new(factory.clone(), self.prune_modes()),
592 );
593
594 let (tx, rx) = oneshot::channel();
596
597 self.task_executor().spawn_critical_blocking_task("pipeline task", async move {
599 let (_, result) = pipeline.run_as_fut(Some(unwind_target)).await;
600 let _ = tx.send(result);
601 });
602 rx.await?.inspect_err(|err| {
603 error!(target: "reth::cli", %unwind_target, %inconsistency_source, %err, "failed to run unwind")
604 })?;
605 }
606
607 Ok(factory)
608 }
609
610 pub async fn with_provider_factory<N, Evm>(
612 self,
613 changeset_cache: ChangesetCache,
614 rocksdb_provider: Option<RocksDBProvider>,
615 disabled_stages: &[StageId],
616 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>>>
617 where
618 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
619 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
620 {
621 let factory = self
622 .create_provider_factory::<N, Evm>(changeset_cache, rocksdb_provider, disabled_stages)
623 .await?;
624 let ctx = LaunchContextWith {
625 inner: self.inner,
626 attachment: self.attachment.map_right(|_| factory),
627 };
628
629 Ok(ctx)
630 }
631}
632
633impl<T> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, ProviderFactory<T>>>
634where
635 T: ProviderNodeTypes,
636{
637 pub const fn database(&self) -> &T::DB {
639 self.right().db_ref()
640 }
641
642 pub const fn provider_factory(&self) -> &ProviderFactory<T> {
644 self.right()
645 }
646
647 pub fn static_file_provider(&self) -> StaticFileProvider<T::Primitives> {
649 self.right().static_file_provider()
650 }
651
652 pub async fn with_prometheus_server(self) -> eyre::Result<Self>
656 where
657 T::ChainSpec: EthereumHardforks,
658 {
659 self.start_prometheus_endpoint().await?;
660 Ok(self)
661 }
662
663 pub async fn start_prometheus_endpoint(&self) -> eyre::Result<()>
665 where
666 T::ChainSpec: EthereumHardforks,
667 {
668 install_prometheus_recorder().spawn_upkeep();
670
671 let listen_addr = self.node_config().metrics.prometheus;
672 if let Some(addr) = listen_addr {
673 let prune_config = self.prune_config();
674 let pruning_mode =
675 PruneConfigKind::from_config(&prune_config, self.chain_spec().as_ref()).as_str();
676 let storage_settings =
680 if self.provider_factory().get_stage_checkpoint(StageId::Headers)?.is_some() {
681 self.provider_factory().cached_storage_settings()
682 } else {
683 self.node_config().storage_settings()
684 };
685 let config = MetricServerConfig::new(
686 addr,
687 VersionInfo {
688 version: version_metadata().cargo_pkg_version.as_ref(),
689 build_timestamp: version_metadata().vergen_build_timestamp.as_ref(),
690 cargo_features: version_metadata().vergen_cargo_features.as_ref(),
691 git_sha: version_metadata().vergen_git_sha.as_ref(),
692 target_triple: version_metadata().vergen_cargo_target_triple.as_ref(),
693 build_profile: version_metadata().build_profile_name.as_ref(),
694 },
695 ChainSpecInfo { name: self.chain_id().to_string() },
696 self.task_executor().clone(),
697 metrics_hooks(self.provider_factory()),
698 self.data_dir().pprof_dumps(),
699 )
700 .with_storage_settings_info(StorageSettingsInfo {
701 storage_v2: storage_settings.storage_v2,
702 pruning_mode,
703 prune_config: serde_json::to_string(&prune_config)
704 .expect("serializing PruneConfig should not fail"),
705 })
706 .with_push_gateway(
707 self.node_config().metrics.push_gateway_url.clone(),
708 self.node_config().metrics.push_gateway_interval,
709 );
710
711 MetricServer::new(config).serve().await?;
712 }
713
714 Ok(())
715 }
716
717 pub fn with_genesis(self) -> Result<Self, InitStorageError> {
719 init_genesis_with_settings_and_validate(
720 self.provider_factory(),
721 self.node_config().storage_settings(),
722 !self.node_config().debug.skip_genesis_validation,
723 )?;
724 Ok(self)
725 }
726
727 pub fn init_genesis(&self) -> Result<B256, InitStorageError> {
729 init_genesis_with_settings(self.provider_factory(), self.node_config().storage_settings())
730 }
731
732 pub fn with_metrics_task(
738 self,
739 ) -> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, WithMeteredProvider<T>>> {
740 let (metrics_sender, metrics_receiver) = unbounded_channel();
741
742 let with_metrics =
743 WithMeteredProvider { provider_factory: self.right().clone(), metrics_sender };
744
745 debug!(target: "reth::cli", "Spawning stages metrics listener task");
746 let sync_metrics_listener = reth_stages::MetricsListener::new(metrics_receiver);
747 self.task_executor()
748 .spawn_critical_task("stages metrics listener task", sync_metrics_listener);
749
750 LaunchContextWith {
751 inner: self.inner,
752 attachment: self.attachment.map_right(|_| with_metrics),
753 }
754 }
755}
756
757impl<N, DB>
758 LaunchContextWith<
759 Attached<WithConfigs<N::ChainSpec>, WithMeteredProvider<NodeTypesWithDBAdapter<N, DB>>>,
760 >
761where
762 N: NodeTypes,
763 DB: Database + DatabaseMetrics + Clone + Unpin + 'static,
764{
765 const fn provider_factory(&self) -> &ProviderFactory<NodeTypesWithDBAdapter<N, DB>> {
767 &self.right().provider_factory
768 }
769
770 fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
772 self.right().metrics_sender.clone()
773 }
774
775 #[expect(clippy::complexity)]
777 pub fn with_blockchain_db<T, F>(
778 self,
779 create_blockchain_provider: F,
780 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<N::ChainSpec>, WithMeteredProviders<T>>>>
781 where
782 T: FullNodeTypes<Types = N, DB = DB>,
783 F: FnOnce(ProviderFactory<NodeTypesWithDBAdapter<N, DB>>) -> eyre::Result<T::Provider>,
784 {
785 let blockchain_db = create_blockchain_provider(self.provider_factory().clone())?;
786
787 let metered_providers = WithMeteredProviders {
788 db_provider_container: WithMeteredProvider {
789 provider_factory: self.provider_factory().clone(),
790 metrics_sender: self.sync_metrics_tx(),
791 },
792 blockchain_db,
793 };
794
795 let ctx = LaunchContextWith {
796 inner: self.inner,
797 attachment: self.attachment.map_right(|_| metered_providers),
798 };
799
800 Ok(ctx)
801 }
802}
803
804impl<T>
805 LaunchContextWith<
806 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithMeteredProviders<T>>,
807 >
808where
809 T: FullNodeTypes<Types: NodeTypesForProvider>,
810{
811 pub const fn database(&self) -> &T::DB {
813 self.provider_factory().db_ref()
814 }
815
816 pub const fn provider_factory(
818 &self,
819 ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
820 &self.right().db_provider_container.provider_factory
821 }
822
823 pub fn lookup_head(&self) -> eyre::Result<Head> {
827 self.node_config()
828 .lookup_head(self.provider_factory())
829 .wrap_err("the head block is missing")
830 }
831
832 pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
834 self.right().db_provider_container.metrics_sender.clone()
835 }
836
837 pub const fn blockchain_db(&self) -> &T::Provider {
839 &self.right().blockchain_db
840 }
841
842 pub async fn with_components<CB>(
844 self,
845 components_builder: CB,
846 on_component_initialized: Box<
847 dyn OnComponentInitializedHook<NodeAdapter<T, CB::Components>>,
848 >,
849 ) -> eyre::Result<
850 LaunchContextWith<
851 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
852 >,
853 >
854 where
855 CB: NodeComponentsBuilder<T>,
856 {
857 let head = self.lookup_head()?;
859
860 let builder_ctx = BuilderContext::new(
861 head,
862 self.blockchain_db().clone(),
863 self.task_executor().clone(),
864 self.configs().clone(),
865 );
866
867 debug!(target: "reth::cli", "creating components");
868 let components = components_builder.build_components(&builder_ctx).await?;
869
870 let blockchain_db = self.blockchain_db().clone();
871
872 let node_adapter = NodeAdapter {
873 components,
874 task_executor: self.task_executor().clone(),
875 provider: blockchain_db,
876 };
877
878 debug!(target: "reth::cli", "calling on_component_initialized hook");
879 on_component_initialized.on_event(node_adapter.clone())?;
880
881 let components_container = WithComponents {
882 db_provider_container: WithMeteredProvider {
883 provider_factory: self.provider_factory().clone(),
884 metrics_sender: self.sync_metrics_tx(),
885 },
886 node_adapter,
887 head,
888 };
889
890 let ctx = LaunchContextWith {
891 inner: self.inner,
892 attachment: self.attachment.map_right(|_| components_container),
893 };
894
895 Ok(ctx)
896 }
897}
898
899impl<T, CB>
900 LaunchContextWith<
901 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
902 >
903where
904 T: FullNodeTypes<Types: NodeTypesForProvider>,
905 CB: NodeComponentsBuilder<T>,
906{
907 pub const fn provider_factory(
909 &self,
910 ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
911 &self.right().db_provider_container.provider_factory
912 }
913
914 pub async fn max_block<C>(&self, client: C) -> eyre::Result<Option<BlockNumber>>
917 where
918 C: HeadersClient<Header: BlockHeader>,
919 {
920 self.node_config().max_block(client, self.provider_factory().clone()).await
921 }
922
923 pub fn static_file_provider(&self) -> StaticFileProvider<<T::Types as NodeTypes>::Primitives> {
925 self.provider_factory().static_file_provider()
926 }
927
928 pub fn static_file_producer(
930 &self,
931 ) -> StaticFileProducer<ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>>> {
932 StaticFileProducer::new(self.provider_factory().clone(), self.prune_modes())
933 }
934
935 pub const fn head(&self) -> Head {
937 self.right().head
938 }
939
940 pub const fn node_adapter(&self) -> &NodeAdapter<T, CB::Components> {
942 &self.right().node_adapter
943 }
944
945 pub const fn node_adapter_mut(&mut self) -> &mut NodeAdapter<T, CB::Components> {
947 &mut self.right_mut().node_adapter
948 }
949
950 pub const fn blockchain_db(&self) -> &T::Provider {
952 &self.node_adapter().provider
953 }
954
955 pub fn initial_backfill_target(
961 &self,
962 disabled_stages: &[StageId],
963 ) -> ProviderResult<Option<B256>> {
964 let mut initial_target = self.node_config().debug.tip;
965
966 if initial_target.is_none() {
967 initial_target = self.check_pipeline_consistency(disabled_stages)?;
968 }
969
970 Ok(initial_target)
971 }
972
973 pub const fn terminate_after_initial_backfill(&self) -> bool {
979 self.node_config().debug.terminate || self.node_config().debug.max_block.is_some()
980 }
981
982 fn ensure_chain_specific_db_checks(&self) -> ProviderResult<()> {
987 if self.chain_spec().is_optimism() &&
988 !self.is_dev() &&
989 self.chain_id() == Chain::optimism_mainnet()
990 {
991 let latest = self.blockchain_db().last_block_number()?;
992 if latest < 105235063 {
994 error!(
995 "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"
996 );
997 return Err(ProviderError::BestBlockNotFound);
998 }
999 }
1000
1001 Ok(())
1002 }
1003
1004 pub fn check_pipeline_consistency(
1016 &self,
1017 disabled_stages: &[StageId],
1018 ) -> ProviderResult<Option<B256>> {
1019 let era_enabled = self.era_import_source().is_some();
1021 let mut all_stages = StageId::ALL
1022 .into_iter()
1023 .filter(|id| (era_enabled || id != &StageId::Era) && !disabled_stages.contains(id));
1024
1025 let first_stage = all_stages.next().expect("there must be at least one stage");
1027
1028 let first_stage_checkpoint = self
1031 .blockchain_db()
1032 .get_stage_checkpoint(first_stage)?
1033 .unwrap_or_default()
1034 .block_number;
1035
1036 for stage_id in all_stages {
1038 let stage_checkpoint = self
1039 .blockchain_db()
1040 .get_stage_checkpoint(stage_id)?
1041 .unwrap_or_default()
1042 .block_number;
1043
1044 debug!(
1047 target: "consensus::engine",
1048 first_stage_id = %first_stage,
1049 first_stage_checkpoint,
1050 stage_id = %stage_id,
1051 stage_checkpoint = stage_checkpoint,
1052 "Checking stage against first stage",
1053 );
1054 if stage_checkpoint < first_stage_checkpoint {
1055 debug!(
1056 target: "consensus::engine",
1057 first_stage_id = %first_stage,
1058 first_stage_checkpoint,
1059 inconsistent_stage_id = %stage_id,
1060 inconsistent_stage_checkpoint = stage_checkpoint,
1061 "Pipeline sync progress is inconsistent"
1062 );
1063 return self.blockchain_db().block_hash(first_stage_checkpoint);
1064 }
1065 }
1066
1067 self.ensure_chain_specific_db_checks()?;
1068
1069 Ok(None)
1070 }
1071
1072 pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
1074 self.right().db_provider_container.metrics_sender.clone()
1075 }
1076
1077 pub const fn components(&self) -> &CB::Components {
1079 &self.node_adapter().components
1080 }
1081
1082 #[expect(clippy::type_complexity)]
1084 pub async fn launch_exex(
1085 &self,
1086 installed_exex: Vec<(
1087 String,
1088 Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1089 )>,
1090 ) -> eyre::Result<Option<ExExManagerHandle<PrimitivesTy<T::Types>>>> {
1091 self.exex_launcher(installed_exex).launch().await
1092 }
1093
1094 #[expect(clippy::type_complexity)]
1106 pub fn exex_launcher(
1107 &self,
1108 installed_exex: Vec<(
1109 String,
1110 Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1111 )>,
1112 ) -> ExExLauncher<NodeAdapter<T, CB::Components>> {
1113 ExExLauncher::new(
1114 self.head(),
1115 self.node_adapter().clone(),
1116 installed_exex,
1117 self.configs().clone(),
1118 )
1119 }
1120
1121 pub fn era_import_source(&self) -> Option<EraImportSource> {
1125 let node_config = self.node_config();
1126 if !node_config.era.enabled {
1127 return None;
1128 }
1129
1130 EraImportSource::maybe_new(
1131 node_config.era.source.path.clone(),
1132 node_config.era.source.url.clone(),
1133 || node_config.chain.chain().kind().default_era_host(),
1134 || node_config.datadir().data_dir().join("era").into(),
1135 )
1136 }
1137
1138 pub fn consensus_layer_events(
1146 &self,
1147 ) -> impl Stream<Item = NodeEvent<PrimitivesTy<T::Types>>> + 'static
1148 where
1149 T::Provider: reth_provider::CanonChainTracker,
1150 {
1151 if self.node_config().debug.tip.is_none() && !self.is_dev() {
1152 Either::Left(
1153 ConsensusLayerHealthEvents::new(Box::new(self.blockchain_db().clone()))
1154 .map(Into::into),
1155 )
1156 } else {
1157 Either::Right(stream::empty())
1158 }
1159 }
1160
1161 pub async fn spawn_ethstats<St>(&self, mut engine_events: St) -> eyre::Result<()>
1163 where
1164 St: Stream<Item = reth_engine_primitives::ConsensusEngineEvent<PrimitivesTy<T::Types>>>
1165 + Send
1166 + Unpin
1167 + 'static,
1168 {
1169 let Some(url) = self.node_config().debug.ethstats.as_ref() else { return Ok(()) };
1170
1171 let network = self.components().network().clone();
1172 let pool = self.components().pool().clone();
1173 let provider = self.node_adapter().provider.clone();
1174
1175 info!(target: "reth::cli", "Starting EthStats service at {}", url);
1176
1177 let ethstats = EthStatsService::new(url, network, provider, pool).await?;
1178
1179 let ethstats_for_events = ethstats.clone();
1181 let task_executor = self.task_executor().clone();
1182 task_executor.spawn_task(async move {
1183 while let Some(event) = engine_events.next().await {
1184 use reth_engine_primitives::ConsensusEngineEvent;
1185 match event {
1186 ConsensusEngineEvent::ForkBlockAdded(executed, duration) |
1187 ConsensusEngineEvent::CanonicalBlockAdded(executed, duration) => {
1188 let block_hash = executed.recovered_block.num_hash().hash;
1189 let block_number = executed.recovered_block.num_hash().number;
1190 if let Err(e) = ethstats_for_events
1191 .report_new_payload(block_hash, block_number, duration)
1192 .await
1193 {
1194 debug!(
1195 target: "ethstats",
1196 "Failed to report new payload: {}", e
1197 );
1198 }
1199 }
1200 _ => {
1201 }
1203 }
1204 }
1205 });
1206
1207 task_executor.spawn_task(async move { ethstats.run().await });
1209
1210 Ok(())
1211 }
1212}
1213
1214#[derive(Clone, Copy, Debug)]
1220pub struct Attached<L, R> {
1221 left: L,
1222 right: R,
1223}
1224
1225impl<L, R> Attached<L, R> {
1226 pub const fn new(left: L, right: R) -> Self {
1228 Self { left, right }
1229 }
1230
1231 pub fn map_left<F, T>(self, f: F) -> Attached<T, R>
1233 where
1234 F: FnOnce(L) -> T,
1235 {
1236 Attached::new(f(self.left), self.right)
1237 }
1238
1239 pub fn map_right<F, T>(self, f: F) -> Attached<L, T>
1241 where
1242 F: FnOnce(R) -> T,
1243 {
1244 Attached::new(self.left, f(self.right))
1245 }
1246
1247 pub const fn left(&self) -> &L {
1249 &self.left
1250 }
1251
1252 pub const fn right(&self) -> &R {
1254 &self.right
1255 }
1256
1257 pub const fn left_mut(&mut self) -> &mut L {
1259 &mut self.left
1260 }
1261
1262 pub const fn right_mut(&mut self) -> &mut R {
1264 &mut self.right
1265 }
1266}
1267
1268#[derive(Debug)]
1271pub struct WithConfigs<ChainSpec> {
1272 pub config: NodeConfig<ChainSpec>,
1274 pub toml_config: reth_config::Config,
1276}
1277
1278impl<ChainSpec> Clone for WithConfigs<ChainSpec> {
1279 fn clone(&self) -> Self {
1280 Self { config: self.config.clone(), toml_config: self.toml_config.clone() }
1281 }
1282}
1283
1284#[derive(Debug, Clone)]
1287pub struct WithMeteredProvider<N: NodeTypesWithDB> {
1288 provider_factory: ProviderFactory<N>,
1289 metrics_sender: UnboundedSender<MetricEvent>,
1290}
1291
1292#[expect(missing_debug_implementations)]
1295pub struct WithMeteredProviders<T>
1296where
1297 T: FullNodeTypes,
1298{
1299 db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1300 blockchain_db: T::Provider,
1301}
1302
1303#[expect(missing_debug_implementations)]
1305pub struct WithComponents<T, CB>
1306where
1307 T: FullNodeTypes,
1308 CB: NodeComponentsBuilder<T>,
1309{
1310 db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1311 node_adapter: NodeAdapter<T, CB::Components>,
1312 head: Head,
1313}
1314
1315pub fn metrics_hooks<N: NodeTypesWithDB>(provider_factory: &ProviderFactory<N>) -> Hooks {
1317 Hooks::builder()
1318 .with_hook({
1319 let db = provider_factory.db_ref().clone();
1320 move || throttle!(Duration::from_secs(5 * 60), || db.report_metrics())
1321 })
1322 .with_hook({
1323 let sfp = provider_factory.static_file_provider();
1324 move || {
1325 throttle!(Duration::from_secs(5 * 60), || {
1326 if let Err(error) = sfp.report_metrics() {
1327 error!(%error, "Failed to report metrics from static file provider");
1328 }
1329 })
1330 }
1331 })
1332 .with_hook({
1333 let rocksdb = provider_factory.rocksdb_provider();
1334 move || throttle!(Duration::from_secs(5 * 60), || rocksdb.report_metrics())
1335 })
1336 .build()
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341 use super::{LaunchContext, NodeConfig};
1342 use reth_config::Config;
1343 use reth_node_core::args::PruningArgs;
1344
1345 const EXTENSION: &str = "toml";
1346
1347 fn with_tempdir(filename: &str, proc: fn(&std::path::Path)) {
1348 let temp_dir = tempfile::tempdir().unwrap();
1349 let config_path = temp_dir.path().join(filename).with_extension(EXTENSION);
1350 proc(&config_path);
1351 temp_dir.close().unwrap()
1352 }
1353
1354 #[test]
1355 fn test_save_prune_config() {
1356 with_tempdir("prune-store-test", |config_path| {
1357 let mut reth_config = Config::default();
1358 let node_config = NodeConfig {
1359 pruning: PruningArgs {
1360 full: true,
1361 minimal: false,
1362 block_interval: None,
1363 sender_recovery_full: false,
1364 sender_recovery_distance: None,
1365 sender_recovery_before: None,
1366 transaction_lookup_full: false,
1367 transaction_lookup_distance: None,
1368 transaction_lookup_before: None,
1369 receipts_full: false,
1370 receipts_pre_merge: false,
1371 receipts_distance: None,
1372 receipts_before: None,
1373 account_history_full: false,
1374 account_history_distance: None,
1375 account_history_before: None,
1376 storage_history_full: false,
1377 storage_history_distance: None,
1378 storage_history_before: None,
1379 bodies_pre_merge: false,
1380 bodies_distance: None,
1381 receipts_log_filter: None,
1382 bodies_before: None,
1383 minimum_distance: None,
1384 },
1385 ..NodeConfig::test()
1386 };
1387 LaunchContext::save_pruning_config(&mut reth_config, &node_config, config_path)
1388 .unwrap();
1389
1390 let loaded_config = Config::from_path(config_path).unwrap();
1391
1392 assert_eq!(reth_config, loaded_config);
1393 })
1394 }
1395}