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::{
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::{PruneMode, PruneModes, PrunerBuilder};
80use reth_rpc_builder::config::RethRpcServerConfig;
81use reth_rpc_layer::JwtSecret;
82use reth_stages::{
83 sets::DefaultStages,
84 stages::{EraImportSource, MerkleStage},
85 MetricEvent, PipelineBuilder, PipelineTarget, StageId, StageSet,
86};
87use reth_static_file::{blocks_per_file_for_prune_distance, StaticFileProducer, StaticFileSegment};
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_node_ethstats::EthStatsService;
100use reth_node_events::{cl::ConsensusLayerHealthEvents, node::NodeEvent};
101
102#[derive(Debug, Clone)]
121pub struct LaunchContext {
122 pub task_executor: TaskExecutor,
124 pub data_dir: ChainPath<DataDirPath>,
126}
127
128impl LaunchContext {
129 pub const fn new(task_executor: TaskExecutor, data_dir: ChainPath<DataDirPath>) -> Self {
131 Self { task_executor, data_dir }
132 }
133
134 pub const fn with<T>(self, attachment: T) -> LaunchContextWith<T> {
136 LaunchContextWith { inner: self, attachment }
137 }
138
139 pub fn with_loaded_toml_config<ChainSpec>(
144 self,
145 config: NodeConfig<ChainSpec>,
146 ) -> eyre::Result<LaunchContextWith<WithConfigs<ChainSpec>>>
147 where
148 ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
149 {
150 let toml_config = self.load_toml_config(&config)?;
151 Ok(self.with(WithConfigs { config, toml_config }))
152 }
153
154 pub fn load_toml_config<ChainSpec>(
159 &self,
160 config: &NodeConfig<ChainSpec>,
161 ) -> eyre::Result<reth_config::Config>
162 where
163 ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
164 {
165 let config_path = config.config.clone().unwrap_or_else(|| self.data_dir.config());
166
167 let mut toml_config = reth_config::Config::from_path(&config_path)
168 .wrap_err_with(|| format!("Could not load config file {config_path:?}"))?;
169
170 Self::save_pruning_config(&mut toml_config, config, &config_path)?;
171
172 info!(target: "reth::cli", path = ?config_path, "Configuration loaded");
173
174 toml_config.peers.trusted_nodes_only |= config.network.trusted_only;
177
178 toml_config.static_files =
180 config.static_files.merge_with_config(toml_config.static_files, config.pruning.minimal);
181
182 Ok(toml_config)
183 }
184
185 fn save_pruning_config<ChainSpec>(
188 reth_config: &mut reth_config::Config,
189 config: &NodeConfig<ChainSpec>,
190 config_path: impl AsRef<std::path::Path>,
191 ) -> eyre::Result<()>
192 where
193 ChainSpec: EthChainSpec + reth_chainspec::EthereumHardforks,
194 {
195 let mut should_save = reth_config.prune.segments.migrate();
196
197 if let Some(prune_config) = config.prune_config() {
198 if reth_config.prune != prune_config {
199 reth_config.set_prune_config(prune_config);
200 should_save = true;
201 }
202 } else if !reth_config.prune.is_default() {
203 info!(target: "reth::cli", "Pruning configuration is present in the config file, but no CLI arguments are provided. Using config from file.");
204 }
205
206 if should_save {
207 info!(target: "reth::cli", "Saving prune config to toml file");
208 reth_config.save(config_path.as_ref())?;
209 }
210
211 Ok(())
212 }
213
214 pub fn with_configured_globals(self, reserved_cpu_cores: usize) -> Self {
216 self.configure_globals(reserved_cpu_cores);
217 self
218 }
219
220 pub fn configure_globals(&self, reserved_cpu_cores: usize) {
225 match fdlimit::raise_fd_limit() {
228 Ok(fdlimit::Outcome::LimitRaised { from, to }) => {
229 debug!(from, to, "Raised file descriptor limit");
230 }
231 Ok(fdlimit::Outcome::Unsupported) => {}
232 Err(err) => warn!(%err, "Failed to raise file descriptor limit"),
233 }
234
235 let _ = reserved_cpu_cores;
239 let num_threads = self.task_executor.cpu_pool().current_num_threads();
240 if let Err(err) = ThreadPoolBuilder::new()
241 .num_threads(num_threads)
242 .thread_name(|i| format!("rayon-{i:02}"))
243 .build_global()
244 {
245 warn!(%err, "Failed to build global thread pool")
246 }
247 }
248}
249
250#[derive(Debug, Clone)]
261pub struct LaunchContextWith<T> {
262 pub inner: LaunchContext,
264 pub attachment: T,
266}
267
268impl<T> LaunchContextWith<T> {
269 pub fn configure_globals(&self, reserved_cpu_cores: u64) {
274 self.inner.configure_globals(reserved_cpu_cores.try_into().unwrap());
275 }
276
277 pub const fn data_dir(&self) -> &ChainPath<DataDirPath> {
279 &self.inner.data_dir
280 }
281
282 pub const fn task_executor(&self) -> &TaskExecutor {
284 &self.inner.task_executor
285 }
286
287 pub fn attach<A>(self, attachment: A) -> LaunchContextWith<Attached<T, A>> {
289 LaunchContextWith {
290 inner: self.inner,
291 attachment: Attached::new(self.attachment, attachment),
292 }
293 }
294
295 pub fn inspect<F>(self, f: F) -> Self
298 where
299 F: FnOnce(&Self),
300 {
301 f(&self);
302 self
303 }
304}
305
306impl<ChainSpec> LaunchContextWith<WithConfigs<ChainSpec>> {
307 pub fn with_resolved_peers(mut self) -> eyre::Result<Self> {
309 if !self.attachment.config.network.trusted_peers.is_empty() {
310 info!(target: "reth::cli", "Adding trusted nodes");
311
312 self.attachment
313 .toml_config
314 .peers
315 .trusted_nodes
316 .extend(self.attachment.config.network.trusted_peers.clone());
317 }
318 Ok(self)
319 }
320}
321
322impl<L, R> LaunchContextWith<Attached<L, R>> {
323 pub const fn left(&self) -> &L {
325 &self.attachment.left
326 }
327
328 pub const fn right(&self) -> &R {
330 &self.attachment.right
331 }
332
333 pub const fn left_mut(&mut self) -> &mut L {
335 &mut self.attachment.left
336 }
337
338 pub const fn right_mut(&mut self) -> &mut R {
340 &mut self.attachment.right
341 }
342}
343impl<R, ChainSpec: EthChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpec>, R>> {
344 pub fn with_adjusted_configs(self) -> Self {
350 self.ensure_etl_datadir().with_adjusted_instance_ports()
351 }
352
353 pub fn ensure_etl_datadir(mut self) -> Self {
355 if self.toml_config_mut().stages.etl.dir.is_none() {
356 let etl_path = EtlConfig::from_datadir(self.data_dir().data_dir());
357 if etl_path.exists() {
358 if let Err(err) = fs::remove_dir_all(&etl_path) {
360 warn!(target: "reth::cli", ?etl_path, %err, "Failed to remove ETL path on launch");
361 }
362 }
363 self.toml_config_mut().stages.etl.dir = Some(etl_path);
364 }
365
366 self
367 }
368
369 pub fn with_adjusted_instance_ports(mut self) -> Self {
371 self.node_config_mut().adjust_instance_ports();
372 self
373 }
374
375 pub const fn configs(&self) -> &WithConfigs<ChainSpec> {
377 self.attachment.left()
378 }
379
380 pub const fn node_config(&self) -> &NodeConfig<ChainSpec> {
382 &self.left().config
383 }
384
385 pub const fn node_config_mut(&mut self) -> &mut NodeConfig<ChainSpec> {
387 &mut self.left_mut().config
388 }
389
390 pub const fn toml_config(&self) -> &reth_config::Config {
392 &self.left().toml_config
393 }
394
395 pub const fn toml_config_mut(&mut self) -> &mut reth_config::Config {
397 &mut self.left_mut().toml_config
398 }
399
400 pub fn chain_spec(&self) -> Arc<ChainSpec> {
402 self.node_config().chain.clone()
403 }
404
405 pub fn genesis_hash(&self) -> B256 {
407 self.node_config().chain.genesis_hash()
408 }
409
410 pub fn chain_id(&self) -> Chain {
412 self.node_config().chain.chain()
413 }
414
415 pub const fn is_dev(&self) -> bool {
417 self.node_config().dev.dev
418 }
419
420 pub fn prune_config(&self) -> PruneConfig
424 where
425 ChainSpec: reth_chainspec::EthereumHardforks,
426 {
427 let Some(mut node_prune_config) = self.node_config().prune_config() else {
428 return self.toml_config().prune.clone();
430 };
431
432 node_prune_config.merge(self.toml_config().prune.clone());
434 node_prune_config
435 }
436
437 pub fn prune_modes(&self) -> PruneModes
439 where
440 ChainSpec: reth_chainspec::EthereumHardforks,
441 {
442 self.prune_config().segments
443 }
444
445 pub fn pruner_builder(&self) -> PrunerBuilder
447 where
448 ChainSpec: reth_chainspec::EthereumHardforks,
449 {
450 PrunerBuilder::new(self.prune_config())
451 }
452
453 pub fn auth_jwt_secret(&self) -> eyre::Result<JwtSecret> {
455 let default_jwt_path = self.data_dir().jwt();
456 let secret = self.node_config().rpc.auth_jwt_secret(default_jwt_path)?;
457 Ok(secret)
458 }
459
460 pub fn dev_mining_mode<Pool>(&self, pool: Pool) -> MiningMode<Pool>
462 where
463 Pool: TransactionPool + Unpin,
464 {
465 self.node_config().dev_mining_mode(pool)
466 }
467}
468
469impl<DB, ChainSpec> LaunchContextWith<Attached<WithConfigs<ChainSpec>, DB>>
470where
471 DB: Database + Clone + 'static,
472 ChainSpec: EthChainSpec + EthereumHardforks + 'static,
473{
474 pub async fn create_provider_factory<N, Evm>(
478 &self,
479 overlay_manager: OverlayManager<N::Primitives>,
480 rocksdb_provider: Option<RocksDBProvider>,
481 disabled_stages: &[StageId],
482 ) -> eyre::Result<ProviderFactory<N>>
483 where
484 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
485 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
486 {
487 self.create_provider_factory_with_recovery::<N, Evm>(
488 overlay_manager,
489 rocksdb_provider,
490 disabled_stages,
491 |_| Ok(()),
492 )
493 .await
494 }
495
496 pub async fn create_provider_factory_with_recovery<N, Evm>(
499 &self,
500 overlay_manager: OverlayManager<N::Primitives>,
501 rocksdb_provider: Option<RocksDBProvider>,
502 disabled_stages: &[StageId],
503 recover: impl FnOnce(&ProviderFactory<N>) -> eyre::Result<()>,
504 ) -> eyre::Result<ProviderFactory<N>>
505 where
506 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
507 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
508 {
509 let static_files_config = &self.toml_config().static_files;
511 static_files_config.validate()?;
512
513 let prune_config = self.prune_config();
514
515 let mut blocks_per_file = static_files_config.as_blocks_per_file_map();
516 if blocks_per_file.get(StaticFileSegment::Receipts).is_none() &&
521 let Some(PruneMode::Distance(distance)) = prune_config.segments.receipts
522 {
523 blocks_per_file
524 .insert(StaticFileSegment::Receipts, blocks_per_file_for_prune_distance(distance));
525 }
526
527 let static_file_provider =
529 StaticFileProviderBuilder::read_write(self.data_dir().static_files())
530 .with_metrics()
531 .with_blocks_per_file_for_segments(&blocks_per_file)
532 .with_genesis_block_number(self.chain_spec().genesis().number.unwrap_or_default())
533 .build()?;
534
535 let rocksdb_provider = if let Some(provider) = rocksdb_provider {
537 provider
538 } else {
539 RocksDBProvider::builder(self.data_dir().rocksdb())
540 .with_default_tables()
541 .with_metrics()
542 .with_statistics()
543 .with_block_cache_size_opt(self.node_config().db.rocksdb_block_cache_size)
544 .build()?
545 };
546
547 let bal_store = self
548 .node_config()
549 .db
550 .balstore_cache_size
551 .map(|distance| {
552 RocksDBBalStore::with_buffer_retention_distance(rocksdb_provider.clone(), distance)
553 })
554 .unwrap_or_else(|| RocksDBBalStore::new(rocksdb_provider.clone()));
555 let bal_store = BalStoreHandle::new(bal_store);
556 let factory = ProviderFactory::new(
557 self.right().clone(),
558 self.chain_spec(),
559 static_file_provider,
560 rocksdb_provider,
561 self.task_executor().clone(),
562 )?
563 .with_prune_modes(prune_config.segments)
564 .with_minimum_pruning_distance(prune_config.minimum_pruning_distance)
565 .with_overlay_manager(overlay_manager)
566 .with_bal_store(bal_store);
567
568 recover(&factory)?;
569
570 let (rocksdb_unwind, static_file_unwind) = factory.check_consistency()?;
574 let provider_ro = factory.database_provider_ro()?;
575 let (partial_trie_unwind, has_persisted_partial_trie_unwind) =
578 get_partial_trie_unwind_marker(&provider_ro)?;
579 drop(provider_ro);
580 let persist_partial_trie_unwind =
581 !has_persisted_partial_trie_unwind && partial_trie_unwind.is_some();
582 let partial_trie_unwind_target =
583 partial_trie_unwind.map(|marker| marker.partial_state_trie);
584 let storage_unwind = [rocksdb_unwind, static_file_unwind].into_iter().flatten().min();
589 let storage_unwind = storage_unwind.filter(|unwind_block| {
590 partial_trie_unwind_target.is_none_or(|partial_trie| *unwind_block < partial_trie)
591 });
592
593 if partial_trie_unwind_target.is_some() || storage_unwind.is_some() {
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 .disable_all(disabled_stages);
609
610 if walk_all_changed_branch_children {
611 stages =
613 stages.set(MerkleStage::new_unwind(true)).enable(StageId::MerkleUnwind);
614 }
615
616 PipelineBuilder::default().add_stages(stages).build(
617 factory.clone(),
618 StaticFileProducer::new(factory.clone(), self.prune_modes()),
619 )
620 };
621 let mut unwinds = Vec::with_capacity(2);
622
623 if let Some(unwind_block) = partial_trie_unwind_target {
624 unwinds.push((
625 PipelineTarget::Unwind(unwind_block),
626 "partial state trie".to_owned(),
627 build_unwind_pipeline(true),
628 true,
629 ));
630 }
631
632 if let Some(unwind_block) = storage_unwind {
633 let inconsistency_source = match (rocksdb_unwind, static_file_unwind) {
636 (Some(_), Some(_)) => "RocksDB and static file",
637 (Some(_), None) => "RocksDB",
638 (None, Some(_)) => "static file",
639 (None, None) => unreachable!(),
640 };
641 assert_ne!(
642 unwind_block, 0,
643 "A {inconsistency_source} inconsistency was found that would trigger an unwind to block 0"
644 );
645 unwinds.push((
646 PipelineTarget::Unwind(unwind_block),
647 inconsistency_source.to_owned(),
648 build_unwind_pipeline(false),
649 false,
650 ));
651 }
652
653 if persist_partial_trie_unwind {
654 let provider_rw = factory.database_provider_rw()?;
656 write_partial_trie_unwind_marker(
657 &provider_rw,
658 partial_trie_unwind.expect("partial trie unwind marker must exist"),
659 )?;
660 provider_rw.commit()?;
661 }
662
663 let (tx, rx) = oneshot::channel();
664 let factory = factory.clone();
665
666 self.task_executor().spawn_critical_blocking_task("pipeline task", async move {
668 let result: Result<(), reth_stages::PipelineError> = async {
669 for (unwind_target, inconsistency_source, pipeline, clear_partial_trie_unwind) in
670 unwinds
671 {
672 info!(target: "reth::cli", %unwind_target, %inconsistency_source, "Executing unwind after consistency check.");
673 let (_, result) = pipeline.run_as_fut(Some(unwind_target)).await;
674 result.inspect_err(|err| {
675 error!(target: "reth::cli", %unwind_target, %inconsistency_source, %err, "failed to run unwind");
676 })?;
677
678 if clear_partial_trie_unwind {
679 let provider_rw = factory.database_provider_rw()?;
680 delete_partial_trie_unwind_marker(&provider_rw)?;
681 provider_rw.commit()?;
682 }
683 }
684 Ok(())
685 }
686 .await;
687 let _ = tx.send(result);
688 });
689 rx.await??;
690 }
691
692 Ok(factory)
693 }
694
695 pub async fn with_provider_factory<N, Evm>(
697 self,
698 overlay_manager: OverlayManager<N::Primitives>,
699 rocksdb_provider: Option<RocksDBProvider>,
700 disabled_stages: &[StageId],
701 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>>>
702 where
703 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
704 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
705 {
706 self.with_provider_factory_and_recovery::<N, Evm>(
707 overlay_manager,
708 rocksdb_provider,
709 disabled_stages,
710 |_| Ok(()),
711 )
712 .await
713 }
714
715 pub async fn with_provider_factory_and_recovery<N, Evm>(
718 self,
719 overlay_manager: OverlayManager<N::Primitives>,
720 rocksdb_provider: Option<RocksDBProvider>,
721 disabled_stages: &[StageId],
722 recover: impl FnOnce(&ProviderFactory<N>) -> eyre::Result<()>,
723 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>>>
724 where
725 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
726 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
727 {
728 let factory = self
729 .create_provider_factory_with_recovery::<N, Evm>(
730 overlay_manager,
731 rocksdb_provider,
732 disabled_stages,
733 recover,
734 )
735 .await?;
736 let ctx = LaunchContextWith {
737 inner: self.inner,
738 attachment: self.attachment.map_right(|_| factory),
739 };
740
741 Ok(ctx)
742 }
743}
744
745impl<T> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, ProviderFactory<T>>>
746where
747 T: ProviderNodeTypes,
748{
749 pub const fn database(&self) -> &T::DB {
751 self.right().db_ref()
752 }
753
754 pub const fn provider_factory(&self) -> &ProviderFactory<T> {
756 self.right()
757 }
758
759 pub fn static_file_provider(&self) -> StaticFileProvider<T::Primitives> {
761 self.right().static_file_provider()
762 }
763
764 pub async fn with_prometheus_server(self) -> eyre::Result<Self>
768 where
769 T::ChainSpec: EthereumHardforks,
770 {
771 self.start_prometheus_endpoint().await?;
772 Ok(self)
773 }
774
775 pub async fn start_prometheus_endpoint(&self) -> eyre::Result<()>
777 where
778 T::ChainSpec: EthereumHardforks,
779 {
780 install_prometheus_recorder().spawn_upkeep();
782
783 let listen_addr = self.node_config().metrics.prometheus;
784 if let Some(addr) = listen_addr {
785 let prune_config = self.prune_config();
786 let pruning_mode =
787 PruneConfigKind::from_config(&prune_config, self.chain_spec().as_ref()).as_str();
788 let storage_settings =
792 if self.provider_factory().get_stage_checkpoint(StageId::Headers)?.is_some() {
793 self.provider_factory().cached_storage_settings()
794 } else {
795 self.node_config().storage_settings()
796 };
797 let config = MetricServerConfig::new(
798 addr,
799 VersionInfo {
800 version: version_metadata().cargo_pkg_version.as_ref(),
801 build_timestamp: version_metadata().vergen_build_timestamp.as_ref(),
802 cargo_features: version_metadata().vergen_cargo_features.as_ref(),
803 git_sha: version_metadata().vergen_git_sha.as_ref(),
804 target_triple: version_metadata().vergen_cargo_target_triple.as_ref(),
805 build_profile: version_metadata().build_profile_name.as_ref(),
806 },
807 ChainSpecInfo { name: self.chain_id().to_string() },
808 self.task_executor().clone(),
809 metrics_hooks(self.provider_factory()),
810 self.data_dir().pprof_dumps(),
811 )
812 .with_storage_settings_info(StorageSettingsInfo {
813 storage_v2: storage_settings.storage_v2,
814 pruning_mode,
815 prune_config: serde_json::to_string(&prune_config)
816 .expect("serializing PruneConfig should not fail"),
817 })
818 .with_push_gateway(
819 self.node_config().metrics.push_gateway_url.clone(),
820 self.node_config().metrics.push_gateway_interval,
821 );
822
823 MetricServer::new(config).serve().await?;
824 }
825
826 Ok(())
827 }
828
829 pub fn with_genesis(self) -> Result<Self, InitStorageError> {
831 init_genesis_with_settings_and_validate(
832 self.provider_factory(),
833 self.node_config().storage_settings(),
834 !self.node_config().debug.skip_genesis_validation,
835 )?;
836 Ok(self)
837 }
838
839 pub fn init_genesis(&self) -> Result<B256, InitStorageError> {
841 init_genesis_with_settings(self.provider_factory(), self.node_config().storage_settings())
842 }
843
844 pub fn with_metrics_task(
850 self,
851 ) -> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, WithMeteredProvider<T>>> {
852 let (metrics_sender, metrics_receiver) = unbounded_channel();
853
854 let with_metrics =
855 WithMeteredProvider { provider_factory: self.right().clone(), metrics_sender };
856
857 debug!(target: "reth::cli", "Spawning stages metrics listener task");
858 let sync_metrics_listener = reth_stages::MetricsListener::new(metrics_receiver);
859 self.task_executor()
860 .spawn_critical_task("stages metrics listener task", sync_metrics_listener);
861
862 LaunchContextWith {
863 inner: self.inner,
864 attachment: self.attachment.map_right(|_| with_metrics),
865 }
866 }
867}
868
869impl<N, DB>
870 LaunchContextWith<
871 Attached<WithConfigs<N::ChainSpec>, WithMeteredProvider<NodeTypesWithDBAdapter<N, DB>>>,
872 >
873where
874 N: NodeTypes,
875 DB: Database + DatabaseMetrics + Clone + Unpin + 'static,
876{
877 const fn provider_factory(&self) -> &ProviderFactory<NodeTypesWithDBAdapter<N, DB>> {
879 &self.right().provider_factory
880 }
881
882 fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
884 self.right().metrics_sender.clone()
885 }
886
887 #[expect(clippy::complexity)]
889 pub fn with_blockchain_db<T, F>(
890 self,
891 create_blockchain_provider: F,
892 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<N::ChainSpec>, WithMeteredProviders<T>>>>
893 where
894 T: FullNodeTypes<Types = N, DB = DB>,
895 F: FnOnce(ProviderFactory<NodeTypesWithDBAdapter<N, DB>>) -> eyre::Result<T::Provider>,
896 {
897 let blockchain_db = create_blockchain_provider(self.provider_factory().clone())?;
898
899 let metered_providers = WithMeteredProviders {
900 db_provider_container: WithMeteredProvider {
901 provider_factory: self.provider_factory().clone(),
902 metrics_sender: self.sync_metrics_tx(),
903 },
904 blockchain_db,
905 };
906
907 let ctx = LaunchContextWith {
908 inner: self.inner,
909 attachment: self.attachment.map_right(|_| metered_providers),
910 };
911
912 Ok(ctx)
913 }
914}
915
916impl<T>
917 LaunchContextWith<
918 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithMeteredProviders<T>>,
919 >
920where
921 T: FullNodeTypes<Types: NodeTypesForProvider>,
922{
923 pub const fn database(&self) -> &T::DB {
925 self.provider_factory().db_ref()
926 }
927
928 pub const fn provider_factory(
930 &self,
931 ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
932 &self.right().db_provider_container.provider_factory
933 }
934
935 pub fn lookup_head(&self) -> eyre::Result<Head> {
939 self.node_config()
940 .lookup_head(self.provider_factory())
941 .wrap_err("the head block is missing")
942 }
943
944 pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
946 self.right().db_provider_container.metrics_sender.clone()
947 }
948
949 pub const fn blockchain_db(&self) -> &T::Provider {
951 &self.right().blockchain_db
952 }
953
954 pub async fn with_components<CB>(
956 self,
957 components_builder: CB,
958 on_component_initialized: Box<
959 dyn OnComponentInitializedHook<NodeAdapter<T, CB::Components>>,
960 >,
961 ) -> eyre::Result<
962 LaunchContextWith<
963 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
964 >,
965 >
966 where
967 CB: NodeComponentsBuilder<T>,
968 {
969 let head = self.lookup_head()?;
971
972 let builder_ctx = BuilderContext::new(
973 head,
974 self.blockchain_db().clone(),
975 self.task_executor().clone(),
976 self.configs().clone(),
977 );
978
979 debug!(target: "reth::cli", "creating components");
980 let components = components_builder.build_components(&builder_ctx).await?;
981
982 let blockchain_db = self.blockchain_db().clone();
983
984 let node_adapter = NodeAdapter {
985 components,
986 task_executor: self.task_executor().clone(),
987 provider: blockchain_db,
988 };
989
990 debug!(target: "reth::cli", "calling on_component_initialized hook");
991 on_component_initialized.on_event(node_adapter.clone())?;
992
993 let components_container = WithComponents {
994 db_provider_container: WithMeteredProvider {
995 provider_factory: self.provider_factory().clone(),
996 metrics_sender: self.sync_metrics_tx(),
997 },
998 node_adapter,
999 head,
1000 sender_recovery_cache: builder_ctx.sender_recovery_cache().cloned(),
1001 };
1002
1003 let ctx = LaunchContextWith {
1004 inner: self.inner,
1005 attachment: self.attachment.map_right(|_| components_container),
1006 };
1007
1008 Ok(ctx)
1009 }
1010}
1011
1012impl<T, CB>
1013 LaunchContextWith<
1014 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
1015 >
1016where
1017 T: FullNodeTypes<Types: NodeTypesForProvider>,
1018 CB: NodeComponentsBuilder<T>,
1019{
1020 pub const fn provider_factory(
1022 &self,
1023 ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
1024 &self.right().db_provider_container.provider_factory
1025 }
1026
1027 pub async fn max_block<C>(&self, client: C) -> eyre::Result<Option<BlockNumber>>
1030 where
1031 C: HeadersClient<Header: BlockHeader>,
1032 {
1033 self.node_config().max_block(client, self.provider_factory().clone()).await
1034 }
1035
1036 pub fn static_file_provider(&self) -> StaticFileProvider<<T::Types as NodeTypes>::Primitives> {
1038 self.provider_factory().static_file_provider()
1039 }
1040
1041 pub fn static_file_producer(
1043 &self,
1044 ) -> StaticFileProducer<ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>>> {
1045 StaticFileProducer::new(self.provider_factory().clone(), self.prune_modes())
1046 }
1047
1048 pub const fn head(&self) -> Head {
1050 self.right().head
1051 }
1052
1053 pub const fn node_adapter(&self) -> &NodeAdapter<T, CB::Components> {
1055 &self.right().node_adapter
1056 }
1057
1058 pub const fn node_adapter_mut(&mut self) -> &mut NodeAdapter<T, CB::Components> {
1060 &mut self.right_mut().node_adapter
1061 }
1062
1063 pub const fn sender_recovery_cache(&self) -> Option<&SenderRecoveryCache> {
1065 self.right().sender_recovery_cache.as_ref()
1066 }
1067
1068 pub const fn blockchain_db(&self) -> &T::Provider {
1070 &self.node_adapter().provider
1071 }
1072
1073 pub fn initial_backfill_target(
1079 &self,
1080 disabled_stages: &[StageId],
1081 ) -> ProviderResult<Option<B256>> {
1082 let mut initial_target = self.node_config().debug.tip;
1083
1084 if initial_target.is_none() {
1085 initial_target = self.check_pipeline_consistency(disabled_stages)?;
1086 }
1087
1088 Ok(initial_target)
1089 }
1090
1091 pub const fn terminate_after_initial_backfill(&self) -> bool {
1097 self.node_config().debug.terminate || self.node_config().debug.max_block.is_some()
1098 }
1099
1100 fn ensure_chain_specific_db_checks(&self) -> ProviderResult<()> {
1105 if self.chain_spec().is_optimism() &&
1106 !self.is_dev() &&
1107 self.chain_id() == Chain::optimism_mainnet()
1108 {
1109 let latest = self.blockchain_db().last_block_number()?;
1110 if latest < 105235063 {
1112 error!(
1113 "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"
1114 );
1115 return Err(ProviderError::BestBlockNotFound);
1116 }
1117 }
1118
1119 Ok(())
1120 }
1121
1122 pub fn check_pipeline_consistency(
1134 &self,
1135 disabled_stages: &[StageId],
1136 ) -> ProviderResult<Option<B256>> {
1137 let era_enabled = self.era_import_source().is_some();
1139 let mut all_stages = StageId::ALL
1140 .into_iter()
1141 .filter(|id| (era_enabled || id != &StageId::Era) && !disabled_stages.contains(id));
1142
1143 let first_stage = all_stages.next().expect("there must be at least one stage");
1145
1146 let first_stage_checkpoint = self
1149 .blockchain_db()
1150 .get_stage_checkpoint(first_stage)?
1151 .unwrap_or_default()
1152 .block_number;
1153
1154 for stage_id in all_stages {
1156 let stage_checkpoint = self
1157 .blockchain_db()
1158 .get_stage_checkpoint(stage_id)?
1159 .unwrap_or_default()
1160 .block_number;
1161
1162 debug!(
1165 target: "consensus::engine",
1166 first_stage_id = %first_stage,
1167 first_stage_checkpoint,
1168 stage_id = %stage_id,
1169 stage_checkpoint = stage_checkpoint,
1170 "Checking stage against first stage",
1171 );
1172 if stage_checkpoint < first_stage_checkpoint {
1173 debug!(
1174 target: "consensus::engine",
1175 first_stage_id = %first_stage,
1176 first_stage_checkpoint,
1177 inconsistent_stage_id = %stage_id,
1178 inconsistent_stage_checkpoint = stage_checkpoint,
1179 "Pipeline sync progress is inconsistent"
1180 );
1181 return self.blockchain_db().block_hash(first_stage_checkpoint);
1182 }
1183 }
1184
1185 self.ensure_chain_specific_db_checks()?;
1186
1187 Ok(None)
1188 }
1189
1190 pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
1192 self.right().db_provider_container.metrics_sender.clone()
1193 }
1194
1195 pub const fn components(&self) -> &CB::Components {
1197 &self.node_adapter().components
1198 }
1199
1200 #[expect(clippy::type_complexity)]
1202 pub async fn launch_exex(
1203 &self,
1204 installed_exex: Vec<(
1205 String,
1206 Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1207 )>,
1208 ) -> eyre::Result<Option<ExExManagerHandle<PrimitivesTy<T::Types>>>> {
1209 self.exex_launcher(installed_exex).launch().await
1210 }
1211
1212 #[expect(clippy::type_complexity)]
1224 pub fn exex_launcher(
1225 &self,
1226 installed_exex: Vec<(
1227 String,
1228 Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1229 )>,
1230 ) -> ExExLauncher<NodeAdapter<T, CB::Components>> {
1231 ExExLauncher::new(
1232 self.head(),
1233 self.node_adapter().clone(),
1234 installed_exex,
1235 self.configs().clone(),
1236 )
1237 }
1238
1239 pub fn era_import_source(&self) -> Option<EraImportSource> {
1243 let node_config = self.node_config();
1244 if !node_config.era.enabled {
1245 return None;
1246 }
1247
1248 EraImportSource::maybe_new(
1249 node_config.era.source.path.clone(),
1250 node_config.era.source.url.clone(),
1251 || node_config.chain.chain().kind().default_era_host(),
1252 || node_config.datadir().data_dir().join("era").into(),
1253 )
1254 }
1255
1256 pub fn consensus_layer_events(
1264 &self,
1265 ) -> impl Stream<Item = NodeEvent<PrimitivesTy<T::Types>>> + 'static
1266 where
1267 T::Provider: reth_provider::CanonChainTracker,
1268 {
1269 if self.node_config().debug.tip.is_none() && !self.is_dev() {
1270 Either::Left(
1271 ConsensusLayerHealthEvents::new(Box::new(self.blockchain_db().clone()))
1272 .map(Into::into),
1273 )
1274 } else {
1275 Either::Right(stream::empty())
1276 }
1277 }
1278
1279 pub async fn spawn_ethstats<St>(&self, mut engine_events: St) -> eyre::Result<()>
1281 where
1282 St: Stream<Item = reth_engine_primitives::ConsensusEngineEvent<PrimitivesTy<T::Types>>>
1283 + Send
1284 + Unpin
1285 + 'static,
1286 {
1287 let Some(url) = self.node_config().debug.ethstats.as_ref() else { return Ok(()) };
1288
1289 let network = self.components().network().clone();
1290 let pool = self.components().pool().clone();
1291 let provider = self.node_adapter().provider.clone();
1292
1293 info!(target: "reth::cli", "Starting EthStats service at {}", url);
1294
1295 let ethstats = EthStatsService::new(url, network, provider, pool).await?;
1296
1297 let ethstats_for_events = ethstats.clone();
1299 let task_executor = self.task_executor().clone();
1300 task_executor.spawn_task(async move {
1301 while let Some(event) = engine_events.next().await {
1302 use reth_engine_primitives::ConsensusEngineEvent;
1303 match event {
1304 ConsensusEngineEvent::ForkBlockAdded(executed, duration) |
1305 ConsensusEngineEvent::CanonicalBlockAdded(executed, duration) => {
1306 let block_hash = executed.recovered_block.num_hash().hash;
1307 let block_number = executed.recovered_block.num_hash().number;
1308 if let Err(e) = ethstats_for_events
1309 .report_new_payload(block_hash, block_number, duration)
1310 .await
1311 {
1312 debug!(
1313 target: "ethstats",
1314 "Failed to report new payload: {}", e
1315 );
1316 }
1317 }
1318 _ => {
1319 }
1321 }
1322 }
1323 });
1324
1325 task_executor.spawn_task(async move { ethstats.run().await });
1327
1328 Ok(())
1329 }
1330}
1331
1332#[derive(Clone, Copy, Debug)]
1338pub struct Attached<L, R> {
1339 left: L,
1340 right: R,
1341}
1342
1343impl<L, R> Attached<L, R> {
1344 pub const fn new(left: L, right: R) -> Self {
1346 Self { left, right }
1347 }
1348
1349 pub fn map_left<F, T>(self, f: F) -> Attached<T, R>
1351 where
1352 F: FnOnce(L) -> T,
1353 {
1354 Attached::new(f(self.left), self.right)
1355 }
1356
1357 pub fn map_right<F, T>(self, f: F) -> Attached<L, T>
1359 where
1360 F: FnOnce(R) -> T,
1361 {
1362 Attached::new(self.left, f(self.right))
1363 }
1364
1365 pub const fn left(&self) -> &L {
1367 &self.left
1368 }
1369
1370 pub const fn right(&self) -> &R {
1372 &self.right
1373 }
1374
1375 pub const fn left_mut(&mut self) -> &mut L {
1377 &mut self.left
1378 }
1379
1380 pub const fn right_mut(&mut self) -> &mut R {
1382 &mut self.right
1383 }
1384}
1385
1386#[derive(Debug)]
1389pub struct WithConfigs<ChainSpec> {
1390 pub config: NodeConfig<ChainSpec>,
1392 pub toml_config: reth_config::Config,
1394}
1395
1396impl<ChainSpec> Clone for WithConfigs<ChainSpec> {
1397 fn clone(&self) -> Self {
1398 Self { config: self.config.clone(), toml_config: self.toml_config.clone() }
1399 }
1400}
1401
1402#[derive(Debug, Clone)]
1405pub struct WithMeteredProvider<N: NodeTypesWithDB> {
1406 provider_factory: ProviderFactory<N>,
1407 metrics_sender: UnboundedSender<MetricEvent>,
1408}
1409
1410#[expect(missing_debug_implementations)]
1413pub struct WithMeteredProviders<T>
1414where
1415 T: FullNodeTypes,
1416{
1417 db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1418 blockchain_db: T::Provider,
1419}
1420
1421#[expect(missing_debug_implementations)]
1423pub struct WithComponents<T, CB>
1424where
1425 T: FullNodeTypes,
1426 CB: NodeComponentsBuilder<T>,
1427{
1428 db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1429 node_adapter: NodeAdapter<T, CB::Components>,
1430 head: Head,
1431 sender_recovery_cache: Option<SenderRecoveryCache>,
1433}
1434
1435pub fn metrics_hooks<N: NodeTypesWithDB>(provider_factory: &ProviderFactory<N>) -> Hooks {
1441 Hooks::builder()
1442 .with_background_interval(Duration::from_secs(5 * 60))
1443 .with_background_hook({
1444 let db = provider_factory.db_ref().clone();
1445 move || db.report_metrics()
1446 })
1447 .with_background_hook({
1448 let sfp = provider_factory.static_file_provider();
1449 move || {
1450 if let Err(error) = sfp.report_metrics() {
1451 error!(%error, "Failed to report metrics from static file provider");
1452 }
1453 }
1454 })
1455 .with_background_hook({
1456 let rocksdb = provider_factory.rocksdb_provider();
1457 move || rocksdb.report_metrics()
1458 })
1459 .build()
1460}
1461
1462fn get_partial_trie_unwind_marker(
1463 provider: &(impl MetadataProvider + StageCheckpointReader),
1464) -> ProviderResult<(Option<PartialStateTrieUnwindMarker>, bool)> {
1465 if let Some(marker) = provider.get_metadata(PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY)? {
1466 let marker = serde_json::from_slice::<PartialStateTrieUnwindMarker>(&marker)
1467 .map_err(ProviderError::other)?;
1468 if marker.partial_state_trie >= marker.finish_block_number {
1469 return Err(ProviderError::other(std::io::Error::other(format!(
1470 "partial state trie unwind target #{} is not below original Finish #{}",
1471 marker.partial_state_trie, marker.finish_block_number,
1472 ))))
1473 }
1474 return Ok((Some(marker), true))
1475 }
1476
1477 let Some(finish_checkpoint) = provider.get_stage_checkpoint(StageId::Finish)? else {
1478 return Ok((None, false))
1479 };
1480 let Some(partial_state_trie) =
1481 finish_checkpoint.finish_stage_checkpoint().and_then(|finish| finish.partial_state_trie())
1482 else {
1483 return Ok((None, false))
1484 };
1485
1486 if partial_state_trie > finish_checkpoint.block_number {
1487 return Err(ProviderError::other(std::io::Error::other(format!(
1488 "partial state trie frontier #{partial_state_trie} is ahead of Finish #{}",
1489 finish_checkpoint.block_number,
1490 ))))
1491 }
1492
1493 Ok((
1494 (partial_state_trie < finish_checkpoint.block_number).then_some(
1495 PartialStateTrieUnwindMarker {
1496 finish_block_number: finish_checkpoint.block_number,
1497 partial_state_trie,
1498 },
1499 ),
1500 false,
1501 ))
1502}
1503
1504const PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY: &str = "partial_state_trie_unwind";
1506
1507fn write_partial_trie_unwind_marker(
1508 provider: &impl MetadataWriter,
1509 marker: PartialStateTrieUnwindMarker,
1510) -> ProviderResult<()> {
1511 provider.write_metadata(
1512 PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY,
1513 serde_json::to_vec(&marker).map_err(ProviderError::other)?,
1514 )
1515}
1516
1517fn delete_partial_trie_unwind_marker(provider: &impl MetadataWriter) -> ProviderResult<()> {
1518 provider.delete_metadata(PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY)
1519}
1520
1521#[cfg(test)]
1522mod tests {
1523 use super::{get_partial_trie_unwind_marker, LaunchContext, NodeConfig};
1524 use reth_config::Config;
1525 use reth_db_api::models::PartialStateTrieUnwindMarker;
1526 use reth_node_core::args::PruningArgs;
1527 use reth_provider::{MetadataProvider, ProviderResult, StageCheckpointReader};
1528 use reth_stages::{FinishCheckpoint, StageCheckpoint, StageId};
1529
1530 const EXTENSION: &str = "toml";
1531
1532 struct MockProvider(Option<Vec<u8>>, Option<StageCheckpoint>);
1533
1534 impl MetadataProvider for MockProvider {
1535 fn get_metadata(&self, _: &str) -> ProviderResult<Option<Vec<u8>>> {
1536 Ok(self.0.clone())
1537 }
1538 }
1539
1540 impl StageCheckpointReader for MockProvider {
1541 fn get_stage_checkpoint(&self, id: StageId) -> ProviderResult<Option<StageCheckpoint>> {
1542 assert_eq!(id, StageId::Finish);
1543 Ok(self.1)
1544 }
1545
1546 fn get_stage_checkpoint_progress(&self, _: StageId) -> ProviderResult<Option<Vec<u8>>> {
1547 Ok(None)
1548 }
1549
1550 fn get_all_checkpoints(&self) -> ProviderResult<Vec<(String, StageCheckpoint)>> {
1551 Ok(Vec::new())
1552 }
1553 }
1554
1555 fn with_tempdir(filename: &str, proc: fn(&std::path::Path)) {
1556 let temp_dir = tempfile::tempdir().unwrap();
1557 let config_path = temp_dir.path().join(filename).with_extension(EXTENSION);
1558 proc(&config_path);
1559 temp_dir.close().unwrap()
1560 }
1561
1562 #[test]
1563 fn test_save_prune_config() {
1564 with_tempdir("prune-store-test", |config_path| {
1565 let mut reth_config = Config::default();
1566 let node_config = NodeConfig {
1567 pruning: PruningArgs {
1568 full: true,
1569 minimal: false,
1570 block_interval: None,
1571 sender_recovery_full: false,
1572 sender_recovery_distance: None,
1573 sender_recovery_before: None,
1574 transaction_lookup_full: false,
1575 transaction_lookup_distance: None,
1576 transaction_lookup_before: None,
1577 receipts_full: false,
1578 receipts_pre_merge: false,
1579 receipts_distance: None,
1580 receipts_before: None,
1581 account_history_full: false,
1582 account_history_distance: None,
1583 account_history_before: None,
1584 storage_history_full: false,
1585 storage_history_distance: None,
1586 storage_history_before: None,
1587 bodies_pre_merge: false,
1588 bodies_distance: None,
1589 receipts_log_filter: None,
1590 bodies_before: None,
1591 minimum_distance: None,
1592 },
1593 ..NodeConfig::test()
1594 };
1595 LaunchContext::save_pruning_config(&mut reth_config, &node_config, config_path)
1596 .unwrap();
1597
1598 let loaded_config = Config::from_path(config_path).unwrap();
1599
1600 assert_eq!(reth_config, loaded_config);
1601 })
1602 }
1603
1604 #[test]
1605 fn get_partial_trie_unwind_marker_uses_partial_finish_checkpoint() {
1606 let finish_checkpoint = StageCheckpoint::new(42)
1607 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(21) });
1608 let expected =
1609 finish_checkpoint.finish_stage_checkpoint().unwrap().partial_state_trie().map(
1610 |partial_state_trie| PartialStateTrieUnwindMarker {
1611 finish_block_number: finish_checkpoint.block_number,
1612 partial_state_trie,
1613 },
1614 );
1615
1616 assert_eq!(
1617 get_partial_trie_unwind_marker(&MockProvider(None, Some(finish_checkpoint))).unwrap(),
1618 (expected, false)
1619 );
1620
1621 let genesis_checkpoint = StageCheckpoint::new(42)
1622 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(0) });
1623 let expected =
1624 genesis_checkpoint.finish_stage_checkpoint().unwrap().partial_state_trie().map(
1625 |partial_state_trie| PartialStateTrieUnwindMarker {
1626 finish_block_number: genesis_checkpoint.block_number,
1627 partial_state_trie,
1628 },
1629 );
1630
1631 assert_eq!(
1632 get_partial_trie_unwind_marker(&MockProvider(None, Some(genesis_checkpoint))).unwrap(),
1633 (expected, false)
1634 );
1635 }
1636
1637 #[test]
1638 fn get_partial_trie_unwind_marker_resumes_persisted_unwind() {
1639 let marker =
1640 PartialStateTrieUnwindMarker { finish_block_number: 42, partial_state_trie: 21 };
1641
1642 assert_eq!(
1643 get_partial_trie_unwind_marker(&MockProvider(
1644 Some(serde_json::to_vec(&marker).unwrap()),
1645 Some(StageCheckpoint::new(21)),
1646 ),)
1647 .unwrap(),
1648 (Some(marker), true)
1649 );
1650 assert_eq!(
1651 get_partial_trie_unwind_marker(&MockProvider(
1652 Some(serde_json::to_vec(&marker).unwrap()),
1653 None
1654 ),)
1655 .unwrap(),
1656 (Some(marker), true)
1657 );
1658 }
1659
1660 #[test]
1661 fn get_partial_trie_unwind_marker_ignores_non_lagging_or_missing_partial_checkpoint() {
1662 let matching_finish_checkpoint = StageCheckpoint::new(42)
1663 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(42) });
1664 let ahead_finish_checkpoint = StageCheckpoint::new(42)
1665 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(43) });
1666 let missing_partial_finish_checkpoint = StageCheckpoint::new(42)
1667 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: None });
1668
1669 assert_eq!(
1670 get_partial_trie_unwind_marker(&MockProvider(None, Some(matching_finish_checkpoint)),)
1671 .unwrap(),
1672 (None, false)
1673 );
1674 assert_eq!(
1675 get_partial_trie_unwind_marker(&MockProvider(
1676 None,
1677 Some(missing_partial_finish_checkpoint)
1678 ),)
1679 .unwrap(),
1680 (None, false)
1681 );
1682 assert_eq!(
1683 get_partial_trie_unwind_marker(&MockProvider(None, None)).unwrap(),
1684 (None, false)
1685 );
1686
1687 let partial_frontier = ahead_finish_checkpoint
1688 .finish_stage_checkpoint()
1689 .and_then(|finish| finish.partial_state_trie());
1690 let result =
1691 get_partial_trie_unwind_marker(&MockProvider(None, Some(ahead_finish_checkpoint)));
1692 if partial_frontier.is_some() {
1693 let error = result.unwrap_err();
1694 assert!(error.to_string().contains("ahead of Finish"), "unexpected error: {error}");
1695 } else {
1696 assert_eq!(result.unwrap(), (None, false));
1697 }
1698 }
1699
1700 #[test]
1701 fn get_partial_trie_unwind_marker_rejects_invalid_persisted_marker() {
1702 let marker =
1703 PartialStateTrieUnwindMarker { finish_block_number: 42, partial_state_trie: 42 };
1704 let error = get_partial_trie_unwind_marker(&MockProvider(
1705 Some(serde_json::to_vec(&marker).unwrap()),
1706 None,
1707 ))
1708 .unwrap_err();
1709
1710 assert!(error.to_string().contains("is not below original Finish"));
1711 }
1712
1713 #[test]
1714 fn get_partial_trie_unwind_marker_rejects_malformed_metadata() {
1715 assert!(get_partial_trie_unwind_marker(&MockProvider(Some(vec![0xff]), None)).is_err());
1716 }
1717}