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};
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 BalConfig, BalStoreHandle, BlockHashReader, BlockNumReader, DBProvider,
75 DatabaseProviderFactory, InMemoryBalStore, MetadataProvider, MetadataWriter, ProviderError,
76 ProviderFactory, ProviderResult, RocksDBProviderFactory, StageCheckpointReader,
77 StaticFileProviderBuilder, 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::{num::NonZeroUsize, sync::Arc, thread::available_parallelism, 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 = available_parallelism().map_or(1, NonZeroUsize::get);
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 let static_files_config = &self.toml_config().static_files;
489 static_files_config.validate()?;
490
491 let prune_config = self.prune_config();
492
493 let mut blocks_per_file = static_files_config.as_blocks_per_file_map();
494 if blocks_per_file.get(StaticFileSegment::Receipts).is_none() &&
499 let Some(PruneMode::Distance(distance)) = prune_config.segments.receipts
500 {
501 blocks_per_file
502 .insert(StaticFileSegment::Receipts, blocks_per_file_for_prune_distance(distance));
503 }
504
505 let static_file_provider =
507 StaticFileProviderBuilder::read_write(self.data_dir().static_files())
508 .with_metrics()
509 .with_blocks_per_file_for_segments(&blocks_per_file)
510 .with_genesis_block_number(self.chain_spec().genesis().number.unwrap_or_default())
511 .build()?;
512
513 let rocksdb_provider = if let Some(provider) = rocksdb_provider {
515 provider
516 } else {
517 RocksDBProvider::builder(self.data_dir().rocksdb())
518 .with_default_tables()
519 .with_metrics()
520 .with_statistics()
521 .build()?
522 };
523
524 let balstore_cache_size = self
525 .node_config()
526 .db
527 .balstore_cache_size
528 .unwrap_or(BalConfig::DEFAULT_IN_MEMORY_RETENTION_DISTANCE);
529 let bal_store = BalStoreHandle::new(InMemoryBalStore::new(
530 BalConfig::with_in_memory_retention_distance(balstore_cache_size),
531 ));
532 let factory = ProviderFactory::new(
533 self.right().clone(),
534 self.chain_spec(),
535 static_file_provider,
536 rocksdb_provider,
537 self.task_executor().clone(),
538 )?
539 .with_prune_modes(prune_config.segments)
540 .with_minimum_pruning_distance(prune_config.minimum_pruning_distance)
541 .with_overlay_manager(overlay_manager)
542 .with_bal_store(bal_store);
543
544 let (rocksdb_unwind, static_file_unwind) = factory.check_consistency()?;
548 let provider_ro = factory.database_provider_ro()?;
549 let (partial_trie_unwind, has_persisted_partial_trie_unwind) =
552 get_partial_trie_unwind_marker(&provider_ro)?;
553 drop(provider_ro);
554 let persist_partial_trie_unwind =
555 !has_persisted_partial_trie_unwind && partial_trie_unwind.is_some();
556 let partial_trie_unwind_target =
557 partial_trie_unwind.map(|marker| marker.partial_state_trie);
558 let storage_unwind = [rocksdb_unwind, static_file_unwind].into_iter().flatten().min();
563 let storage_unwind = storage_unwind.filter(|unwind_block| {
564 partial_trie_unwind_target.is_none_or(|partial_trie| *unwind_block < partial_trie)
565 });
566
567 if partial_trie_unwind_target.is_some() || storage_unwind.is_some() {
568 let build_unwind_pipeline = |walk_all_changed_branch_children| {
569 let (_tip_tx, tip_rx) = watch::channel(B256::ZERO);
570 let mut stages = DefaultStages::new(
571 factory.clone(),
572 tip_rx,
573 Arc::new(NoopConsensus::default()),
574 NoopHeaderDownloader::default(),
575 NoopBodiesDownloader::default(),
576 NoopEvmConfig::<Evm>::default(),
577 self.toml_config().stages.clone(),
578 self.prune_modes(),
579 None,
580 )
581 .builder()
582 .disable_all(disabled_stages);
583
584 if walk_all_changed_branch_children {
585 stages =
587 stages.set(MerkleStage::new_unwind(true)).enable(StageId::MerkleUnwind);
588 }
589
590 PipelineBuilder::default().add_stages(stages).build(
591 factory.clone(),
592 StaticFileProducer::new(factory.clone(), self.prune_modes()),
593 )
594 };
595 let mut unwinds = Vec::with_capacity(2);
596
597 if let Some(unwind_block) = partial_trie_unwind_target {
598 unwinds.push((
599 PipelineTarget::Unwind(unwind_block),
600 "partial state trie".to_owned(),
601 build_unwind_pipeline(true),
602 true,
603 ));
604 }
605
606 if let Some(unwind_block) = storage_unwind {
607 let inconsistency_source = match (rocksdb_unwind, static_file_unwind) {
610 (Some(_), Some(_)) => "RocksDB and static file",
611 (Some(_), None) => "RocksDB",
612 (None, Some(_)) => "static file",
613 (None, None) => unreachable!(),
614 };
615 assert_ne!(
616 unwind_block, 0,
617 "A {inconsistency_source} inconsistency was found that would trigger an unwind to block 0"
618 );
619 unwinds.push((
620 PipelineTarget::Unwind(unwind_block),
621 inconsistency_source.to_owned(),
622 build_unwind_pipeline(false),
623 false,
624 ));
625 }
626
627 if persist_partial_trie_unwind {
628 let provider_rw = factory.database_provider_rw()?;
630 write_partial_trie_unwind_marker(
631 &provider_rw,
632 partial_trie_unwind.expect("partial trie unwind marker must exist"),
633 )?;
634 provider_rw.commit()?;
635 }
636
637 let (tx, rx) = oneshot::channel();
638 let factory = factory.clone();
639
640 self.task_executor().spawn_critical_blocking_task("pipeline task", async move {
642 let result: Result<(), reth_stages::PipelineError> = async {
643 for (unwind_target, inconsistency_source, pipeline, clear_partial_trie_unwind) in
644 unwinds
645 {
646 info!(target: "reth::cli", %unwind_target, %inconsistency_source, "Executing unwind after consistency check.");
647 let (_, result) = pipeline.run_as_fut(Some(unwind_target)).await;
648 result.inspect_err(|err| {
649 error!(target: "reth::cli", %unwind_target, %inconsistency_source, %err, "failed to run unwind");
650 })?;
651
652 if clear_partial_trie_unwind {
653 let provider_rw = factory.database_provider_rw()?;
654 delete_partial_trie_unwind_marker(&provider_rw)?;
655 provider_rw.commit()?;
656 }
657 }
658 Ok(())
659 }
660 .await;
661 let _ = tx.send(result);
662 });
663 rx.await??;
664 }
665
666 Ok(factory)
667 }
668
669 pub async fn with_provider_factory<N, Evm>(
671 self,
672 overlay_manager: OverlayManager<N::Primitives>,
673 rocksdb_provider: Option<RocksDBProvider>,
674 disabled_stages: &[StageId],
675 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<ChainSpec>, ProviderFactory<N>>>>
676 where
677 N: ProviderNodeTypes<DB = DB, ChainSpec = ChainSpec>,
678 Evm: ConfigureEvm<Primitives = N::Primitives> + 'static,
679 {
680 let factory = self
681 .create_provider_factory::<N, Evm>(overlay_manager, rocksdb_provider, disabled_stages)
682 .await?;
683 let ctx = LaunchContextWith {
684 inner: self.inner,
685 attachment: self.attachment.map_right(|_| factory),
686 };
687
688 Ok(ctx)
689 }
690}
691
692impl<T> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, ProviderFactory<T>>>
693where
694 T: ProviderNodeTypes,
695{
696 pub const fn database(&self) -> &T::DB {
698 self.right().db_ref()
699 }
700
701 pub const fn provider_factory(&self) -> &ProviderFactory<T> {
703 self.right()
704 }
705
706 pub fn static_file_provider(&self) -> StaticFileProvider<T::Primitives> {
708 self.right().static_file_provider()
709 }
710
711 pub async fn with_prometheus_server(self) -> eyre::Result<Self>
715 where
716 T::ChainSpec: EthereumHardforks,
717 {
718 self.start_prometheus_endpoint().await?;
719 Ok(self)
720 }
721
722 pub async fn start_prometheus_endpoint(&self) -> eyre::Result<()>
724 where
725 T::ChainSpec: EthereumHardforks,
726 {
727 install_prometheus_recorder().spawn_upkeep();
729
730 let listen_addr = self.node_config().metrics.prometheus;
731 if let Some(addr) = listen_addr {
732 let prune_config = self.prune_config();
733 let pruning_mode =
734 PruneConfigKind::from_config(&prune_config, self.chain_spec().as_ref()).as_str();
735 let storage_settings =
739 if self.provider_factory().get_stage_checkpoint(StageId::Headers)?.is_some() {
740 self.provider_factory().cached_storage_settings()
741 } else {
742 self.node_config().storage_settings()
743 };
744 let config = MetricServerConfig::new(
745 addr,
746 VersionInfo {
747 version: version_metadata().cargo_pkg_version.as_ref(),
748 build_timestamp: version_metadata().vergen_build_timestamp.as_ref(),
749 cargo_features: version_metadata().vergen_cargo_features.as_ref(),
750 git_sha: version_metadata().vergen_git_sha.as_ref(),
751 target_triple: version_metadata().vergen_cargo_target_triple.as_ref(),
752 build_profile: version_metadata().build_profile_name.as_ref(),
753 },
754 ChainSpecInfo { name: self.chain_id().to_string() },
755 self.task_executor().clone(),
756 metrics_hooks(self.provider_factory()),
757 self.data_dir().pprof_dumps(),
758 )
759 .with_storage_settings_info(StorageSettingsInfo {
760 storage_v2: storage_settings.storage_v2,
761 pruning_mode,
762 prune_config: serde_json::to_string(&prune_config)
763 .expect("serializing PruneConfig should not fail"),
764 })
765 .with_push_gateway(
766 self.node_config().metrics.push_gateway_url.clone(),
767 self.node_config().metrics.push_gateway_interval,
768 );
769
770 MetricServer::new(config).serve().await?;
771 }
772
773 Ok(())
774 }
775
776 pub fn with_genesis(self) -> Result<Self, InitStorageError> {
778 init_genesis_with_settings_and_validate(
779 self.provider_factory(),
780 self.node_config().storage_settings(),
781 !self.node_config().debug.skip_genesis_validation,
782 )?;
783 Ok(self)
784 }
785
786 pub fn init_genesis(&self) -> Result<B256, InitStorageError> {
788 init_genesis_with_settings(self.provider_factory(), self.node_config().storage_settings())
789 }
790
791 pub fn with_metrics_task(
797 self,
798 ) -> LaunchContextWith<Attached<WithConfigs<T::ChainSpec>, WithMeteredProvider<T>>> {
799 let (metrics_sender, metrics_receiver) = unbounded_channel();
800
801 let with_metrics =
802 WithMeteredProvider { provider_factory: self.right().clone(), metrics_sender };
803
804 debug!(target: "reth::cli", "Spawning stages metrics listener task");
805 let sync_metrics_listener = reth_stages::MetricsListener::new(metrics_receiver);
806 self.task_executor()
807 .spawn_critical_task("stages metrics listener task", sync_metrics_listener);
808
809 LaunchContextWith {
810 inner: self.inner,
811 attachment: self.attachment.map_right(|_| with_metrics),
812 }
813 }
814}
815
816impl<N, DB>
817 LaunchContextWith<
818 Attached<WithConfigs<N::ChainSpec>, WithMeteredProvider<NodeTypesWithDBAdapter<N, DB>>>,
819 >
820where
821 N: NodeTypes,
822 DB: Database + DatabaseMetrics + Clone + Unpin + 'static,
823{
824 const fn provider_factory(&self) -> &ProviderFactory<NodeTypesWithDBAdapter<N, DB>> {
826 &self.right().provider_factory
827 }
828
829 fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
831 self.right().metrics_sender.clone()
832 }
833
834 #[expect(clippy::complexity)]
836 pub fn with_blockchain_db<T, F>(
837 self,
838 create_blockchain_provider: F,
839 ) -> eyre::Result<LaunchContextWith<Attached<WithConfigs<N::ChainSpec>, WithMeteredProviders<T>>>>
840 where
841 T: FullNodeTypes<Types = N, DB = DB>,
842 F: FnOnce(ProviderFactory<NodeTypesWithDBAdapter<N, DB>>) -> eyre::Result<T::Provider>,
843 {
844 let blockchain_db = create_blockchain_provider(self.provider_factory().clone())?;
845
846 let metered_providers = WithMeteredProviders {
847 db_provider_container: WithMeteredProvider {
848 provider_factory: self.provider_factory().clone(),
849 metrics_sender: self.sync_metrics_tx(),
850 },
851 blockchain_db,
852 };
853
854 let ctx = LaunchContextWith {
855 inner: self.inner,
856 attachment: self.attachment.map_right(|_| metered_providers),
857 };
858
859 Ok(ctx)
860 }
861}
862
863impl<T>
864 LaunchContextWith<
865 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithMeteredProviders<T>>,
866 >
867where
868 T: FullNodeTypes<Types: NodeTypesForProvider>,
869{
870 pub const fn database(&self) -> &T::DB {
872 self.provider_factory().db_ref()
873 }
874
875 pub const fn provider_factory(
877 &self,
878 ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
879 &self.right().db_provider_container.provider_factory
880 }
881
882 pub fn lookup_head(&self) -> eyre::Result<Head> {
886 self.node_config()
887 .lookup_head(self.provider_factory())
888 .wrap_err("the head block is missing")
889 }
890
891 pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
893 self.right().db_provider_container.metrics_sender.clone()
894 }
895
896 pub const fn blockchain_db(&self) -> &T::Provider {
898 &self.right().blockchain_db
899 }
900
901 pub async fn with_components<CB>(
903 self,
904 components_builder: CB,
905 on_component_initialized: Box<
906 dyn OnComponentInitializedHook<NodeAdapter<T, CB::Components>>,
907 >,
908 ) -> eyre::Result<
909 LaunchContextWith<
910 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
911 >,
912 >
913 where
914 CB: NodeComponentsBuilder<T>,
915 {
916 let head = self.lookup_head()?;
918
919 let builder_ctx = BuilderContext::new(
920 head,
921 self.blockchain_db().clone(),
922 self.task_executor().clone(),
923 self.configs().clone(),
924 );
925
926 debug!(target: "reth::cli", "creating components");
927 let components = components_builder.build_components(&builder_ctx).await?;
928
929 let blockchain_db = self.blockchain_db().clone();
930
931 let node_adapter = NodeAdapter {
932 components,
933 task_executor: self.task_executor().clone(),
934 provider: blockchain_db,
935 };
936
937 debug!(target: "reth::cli", "calling on_component_initialized hook");
938 on_component_initialized.on_event(node_adapter.clone())?;
939
940 let components_container = WithComponents {
941 db_provider_container: WithMeteredProvider {
942 provider_factory: self.provider_factory().clone(),
943 metrics_sender: self.sync_metrics_tx(),
944 },
945 node_adapter,
946 head,
947 };
948
949 let ctx = LaunchContextWith {
950 inner: self.inner,
951 attachment: self.attachment.map_right(|_| components_container),
952 };
953
954 Ok(ctx)
955 }
956}
957
958impl<T, CB>
959 LaunchContextWith<
960 Attached<WithConfigs<<T::Types as NodeTypes>::ChainSpec>, WithComponents<T, CB>>,
961 >
962where
963 T: FullNodeTypes<Types: NodeTypesForProvider>,
964 CB: NodeComponentsBuilder<T>,
965{
966 pub const fn provider_factory(
968 &self,
969 ) -> &ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>> {
970 &self.right().db_provider_container.provider_factory
971 }
972
973 pub async fn max_block<C>(&self, client: C) -> eyre::Result<Option<BlockNumber>>
976 where
977 C: HeadersClient<Header: BlockHeader>,
978 {
979 self.node_config().max_block(client, self.provider_factory().clone()).await
980 }
981
982 pub fn static_file_provider(&self) -> StaticFileProvider<<T::Types as NodeTypes>::Primitives> {
984 self.provider_factory().static_file_provider()
985 }
986
987 pub fn static_file_producer(
989 &self,
990 ) -> StaticFileProducer<ProviderFactory<NodeTypesWithDBAdapter<T::Types, T::DB>>> {
991 StaticFileProducer::new(self.provider_factory().clone(), self.prune_modes())
992 }
993
994 pub const fn head(&self) -> Head {
996 self.right().head
997 }
998
999 pub const fn node_adapter(&self) -> &NodeAdapter<T, CB::Components> {
1001 &self.right().node_adapter
1002 }
1003
1004 pub const fn node_adapter_mut(&mut self) -> &mut NodeAdapter<T, CB::Components> {
1006 &mut self.right_mut().node_adapter
1007 }
1008
1009 pub const fn blockchain_db(&self) -> &T::Provider {
1011 &self.node_adapter().provider
1012 }
1013
1014 pub fn initial_backfill_target(
1020 &self,
1021 disabled_stages: &[StageId],
1022 ) -> ProviderResult<Option<B256>> {
1023 let mut initial_target = self.node_config().debug.tip;
1024
1025 if initial_target.is_none() {
1026 initial_target = self.check_pipeline_consistency(disabled_stages)?;
1027 }
1028
1029 Ok(initial_target)
1030 }
1031
1032 pub const fn terminate_after_initial_backfill(&self) -> bool {
1038 self.node_config().debug.terminate || self.node_config().debug.max_block.is_some()
1039 }
1040
1041 fn ensure_chain_specific_db_checks(&self) -> ProviderResult<()> {
1046 if self.chain_spec().is_optimism() &&
1047 !self.is_dev() &&
1048 self.chain_id() == Chain::optimism_mainnet()
1049 {
1050 let latest = self.blockchain_db().last_block_number()?;
1051 if latest < 105235063 {
1053 error!(
1054 "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"
1055 );
1056 return Err(ProviderError::BestBlockNotFound);
1057 }
1058 }
1059
1060 Ok(())
1061 }
1062
1063 pub fn check_pipeline_consistency(
1075 &self,
1076 disabled_stages: &[StageId],
1077 ) -> ProviderResult<Option<B256>> {
1078 let era_enabled = self.era_import_source().is_some();
1080 let mut all_stages = StageId::ALL
1081 .into_iter()
1082 .filter(|id| (era_enabled || id != &StageId::Era) && !disabled_stages.contains(id));
1083
1084 let first_stage = all_stages.next().expect("there must be at least one stage");
1086
1087 let first_stage_checkpoint = self
1090 .blockchain_db()
1091 .get_stage_checkpoint(first_stage)?
1092 .unwrap_or_default()
1093 .block_number;
1094
1095 for stage_id in all_stages {
1097 let stage_checkpoint = self
1098 .blockchain_db()
1099 .get_stage_checkpoint(stage_id)?
1100 .unwrap_or_default()
1101 .block_number;
1102
1103 debug!(
1106 target: "consensus::engine",
1107 first_stage_id = %first_stage,
1108 first_stage_checkpoint,
1109 stage_id = %stage_id,
1110 stage_checkpoint = stage_checkpoint,
1111 "Checking stage against first stage",
1112 );
1113 if stage_checkpoint < first_stage_checkpoint {
1114 debug!(
1115 target: "consensus::engine",
1116 first_stage_id = %first_stage,
1117 first_stage_checkpoint,
1118 inconsistent_stage_id = %stage_id,
1119 inconsistent_stage_checkpoint = stage_checkpoint,
1120 "Pipeline sync progress is inconsistent"
1121 );
1122 return self.blockchain_db().block_hash(first_stage_checkpoint);
1123 }
1124 }
1125
1126 self.ensure_chain_specific_db_checks()?;
1127
1128 Ok(None)
1129 }
1130
1131 pub fn sync_metrics_tx(&self) -> UnboundedSender<MetricEvent> {
1133 self.right().db_provider_container.metrics_sender.clone()
1134 }
1135
1136 pub const fn components(&self) -> &CB::Components {
1138 &self.node_adapter().components
1139 }
1140
1141 #[expect(clippy::type_complexity)]
1143 pub async fn launch_exex(
1144 &self,
1145 installed_exex: Vec<(
1146 String,
1147 Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1148 )>,
1149 ) -> eyre::Result<Option<ExExManagerHandle<PrimitivesTy<T::Types>>>> {
1150 self.exex_launcher(installed_exex).launch().await
1151 }
1152
1153 #[expect(clippy::type_complexity)]
1165 pub fn exex_launcher(
1166 &self,
1167 installed_exex: Vec<(
1168 String,
1169 Box<dyn crate::exex::BoxedLaunchExEx<NodeAdapter<T, CB::Components>>>,
1170 )>,
1171 ) -> ExExLauncher<NodeAdapter<T, CB::Components>> {
1172 ExExLauncher::new(
1173 self.head(),
1174 self.node_adapter().clone(),
1175 installed_exex,
1176 self.configs().clone(),
1177 )
1178 }
1179
1180 pub fn era_import_source(&self) -> Option<EraImportSource> {
1184 let node_config = self.node_config();
1185 if !node_config.era.enabled {
1186 return None;
1187 }
1188
1189 EraImportSource::maybe_new(
1190 node_config.era.source.path.clone(),
1191 node_config.era.source.url.clone(),
1192 || node_config.chain.chain().kind().default_era_host(),
1193 || node_config.datadir().data_dir().join("era").into(),
1194 )
1195 }
1196
1197 pub fn consensus_layer_events(
1205 &self,
1206 ) -> impl Stream<Item = NodeEvent<PrimitivesTy<T::Types>>> + 'static
1207 where
1208 T::Provider: reth_provider::CanonChainTracker,
1209 {
1210 if self.node_config().debug.tip.is_none() && !self.is_dev() {
1211 Either::Left(
1212 ConsensusLayerHealthEvents::new(Box::new(self.blockchain_db().clone()))
1213 .map(Into::into),
1214 )
1215 } else {
1216 Either::Right(stream::empty())
1217 }
1218 }
1219
1220 pub async fn spawn_ethstats<St>(&self, mut engine_events: St) -> eyre::Result<()>
1222 where
1223 St: Stream<Item = reth_engine_primitives::ConsensusEngineEvent<PrimitivesTy<T::Types>>>
1224 + Send
1225 + Unpin
1226 + 'static,
1227 {
1228 let Some(url) = self.node_config().debug.ethstats.as_ref() else { return Ok(()) };
1229
1230 let network = self.components().network().clone();
1231 let pool = self.components().pool().clone();
1232 let provider = self.node_adapter().provider.clone();
1233
1234 info!(target: "reth::cli", "Starting EthStats service at {}", url);
1235
1236 let ethstats = EthStatsService::new(url, network, provider, pool).await?;
1237
1238 let ethstats_for_events = ethstats.clone();
1240 let task_executor = self.task_executor().clone();
1241 task_executor.spawn_task(async move {
1242 while let Some(event) = engine_events.next().await {
1243 use reth_engine_primitives::ConsensusEngineEvent;
1244 match event {
1245 ConsensusEngineEvent::ForkBlockAdded(executed, duration) |
1246 ConsensusEngineEvent::CanonicalBlockAdded(executed, duration) => {
1247 let block_hash = executed.recovered_block.num_hash().hash;
1248 let block_number = executed.recovered_block.num_hash().number;
1249 if let Err(e) = ethstats_for_events
1250 .report_new_payload(block_hash, block_number, duration)
1251 .await
1252 {
1253 debug!(
1254 target: "ethstats",
1255 "Failed to report new payload: {}", e
1256 );
1257 }
1258 }
1259 _ => {
1260 }
1262 }
1263 }
1264 });
1265
1266 task_executor.spawn_task(async move { ethstats.run().await });
1268
1269 Ok(())
1270 }
1271}
1272
1273#[derive(Clone, Copy, Debug)]
1279pub struct Attached<L, R> {
1280 left: L,
1281 right: R,
1282}
1283
1284impl<L, R> Attached<L, R> {
1285 pub const fn new(left: L, right: R) -> Self {
1287 Self { left, right }
1288 }
1289
1290 pub fn map_left<F, T>(self, f: F) -> Attached<T, R>
1292 where
1293 F: FnOnce(L) -> T,
1294 {
1295 Attached::new(f(self.left), self.right)
1296 }
1297
1298 pub fn map_right<F, T>(self, f: F) -> Attached<L, T>
1300 where
1301 F: FnOnce(R) -> T,
1302 {
1303 Attached::new(self.left, f(self.right))
1304 }
1305
1306 pub const fn left(&self) -> &L {
1308 &self.left
1309 }
1310
1311 pub const fn right(&self) -> &R {
1313 &self.right
1314 }
1315
1316 pub const fn left_mut(&mut self) -> &mut L {
1318 &mut self.left
1319 }
1320
1321 pub const fn right_mut(&mut self) -> &mut R {
1323 &mut self.right
1324 }
1325}
1326
1327#[derive(Debug)]
1330pub struct WithConfigs<ChainSpec> {
1331 pub config: NodeConfig<ChainSpec>,
1333 pub toml_config: reth_config::Config,
1335}
1336
1337impl<ChainSpec> Clone for WithConfigs<ChainSpec> {
1338 fn clone(&self) -> Self {
1339 Self { config: self.config.clone(), toml_config: self.toml_config.clone() }
1340 }
1341}
1342
1343#[derive(Debug, Clone)]
1346pub struct WithMeteredProvider<N: NodeTypesWithDB> {
1347 provider_factory: ProviderFactory<N>,
1348 metrics_sender: UnboundedSender<MetricEvent>,
1349}
1350
1351#[expect(missing_debug_implementations)]
1354pub struct WithMeteredProviders<T>
1355where
1356 T: FullNodeTypes,
1357{
1358 db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1359 blockchain_db: T::Provider,
1360}
1361
1362#[expect(missing_debug_implementations)]
1364pub struct WithComponents<T, CB>
1365where
1366 T: FullNodeTypes,
1367 CB: NodeComponentsBuilder<T>,
1368{
1369 db_provider_container: WithMeteredProvider<NodeTypesWithDBAdapter<T::Types, T::DB>>,
1370 node_adapter: NodeAdapter<T, CB::Components>,
1371 head: Head,
1372}
1373
1374pub fn metrics_hooks<N: NodeTypesWithDB>(provider_factory: &ProviderFactory<N>) -> Hooks {
1380 Hooks::builder()
1381 .with_background_interval(Duration::from_secs(5 * 60))
1382 .with_background_hook({
1383 let db = provider_factory.db_ref().clone();
1384 move || db.report_metrics()
1385 })
1386 .with_background_hook({
1387 let sfp = provider_factory.static_file_provider();
1388 move || {
1389 if let Err(error) = sfp.report_metrics() {
1390 error!(%error, "Failed to report metrics from static file provider");
1391 }
1392 }
1393 })
1394 .with_background_hook({
1395 let rocksdb = provider_factory.rocksdb_provider();
1396 move || rocksdb.report_metrics()
1397 })
1398 .build()
1399}
1400
1401fn get_partial_trie_unwind_marker(
1402 provider: &(impl MetadataProvider + StageCheckpointReader),
1403) -> ProviderResult<(Option<PartialStateTrieUnwindMarker>, bool)> {
1404 if let Some(marker) = provider.get_metadata(PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY)? {
1405 let marker = serde_json::from_slice::<PartialStateTrieUnwindMarker>(&marker)
1406 .map_err(ProviderError::other)?;
1407 if marker.partial_state_trie >= marker.finish_block_number {
1408 return Err(ProviderError::other(std::io::Error::other(format!(
1409 "partial state trie unwind target #{} is not below original Finish #{}",
1410 marker.partial_state_trie, marker.finish_block_number,
1411 ))))
1412 }
1413 return Ok((Some(marker), true))
1414 }
1415
1416 let Some(finish_checkpoint) = provider.get_stage_checkpoint(StageId::Finish)? else {
1417 return Ok((None, false))
1418 };
1419 let Some(partial_state_trie) =
1420 finish_checkpoint.finish_stage_checkpoint().and_then(|finish| finish.partial_state_trie())
1421 else {
1422 return Ok((None, false))
1423 };
1424
1425 if partial_state_trie > finish_checkpoint.block_number {
1426 return Err(ProviderError::other(std::io::Error::other(format!(
1427 "partial state trie frontier #{partial_state_trie} is ahead of Finish #{}",
1428 finish_checkpoint.block_number,
1429 ))))
1430 }
1431
1432 Ok((
1433 (partial_state_trie < finish_checkpoint.block_number).then_some(
1434 PartialStateTrieUnwindMarker {
1435 finish_block_number: finish_checkpoint.block_number,
1436 partial_state_trie,
1437 },
1438 ),
1439 false,
1440 ))
1441}
1442
1443const PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY: &str = "partial_state_trie_unwind";
1445
1446fn write_partial_trie_unwind_marker(
1447 provider: &impl MetadataWriter,
1448 marker: PartialStateTrieUnwindMarker,
1449) -> ProviderResult<()> {
1450 provider.write_metadata(
1451 PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY,
1452 serde_json::to_vec(&marker).map_err(ProviderError::other)?,
1453 )
1454}
1455
1456fn delete_partial_trie_unwind_marker(provider: &impl MetadataWriter) -> ProviderResult<()> {
1457 provider.delete_metadata(PARTIAL_STATE_TRIE_UNWIND_METADATA_KEY)
1458}
1459
1460#[cfg(test)]
1461mod tests {
1462 use super::{get_partial_trie_unwind_marker, LaunchContext, NodeConfig};
1463 use reth_config::Config;
1464 use reth_db_api::models::PartialStateTrieUnwindMarker;
1465 use reth_node_core::args::PruningArgs;
1466 use reth_provider::{MetadataProvider, ProviderResult, StageCheckpointReader};
1467 use reth_stages::{FinishCheckpoint, StageCheckpoint, StageId};
1468
1469 const EXTENSION: &str = "toml";
1470
1471 struct MockProvider(Option<Vec<u8>>, Option<StageCheckpoint>);
1472
1473 impl MetadataProvider for MockProvider {
1474 fn get_metadata(&self, _: &str) -> ProviderResult<Option<Vec<u8>>> {
1475 Ok(self.0.clone())
1476 }
1477 }
1478
1479 impl StageCheckpointReader for MockProvider {
1480 fn get_stage_checkpoint(&self, id: StageId) -> ProviderResult<Option<StageCheckpoint>> {
1481 assert_eq!(id, StageId::Finish);
1482 Ok(self.1)
1483 }
1484
1485 fn get_stage_checkpoint_progress(&self, _: StageId) -> ProviderResult<Option<Vec<u8>>> {
1486 Ok(None)
1487 }
1488
1489 fn get_all_checkpoints(&self) -> ProviderResult<Vec<(String, StageCheckpoint)>> {
1490 Ok(Vec::new())
1491 }
1492 }
1493
1494 fn with_tempdir(filename: &str, proc: fn(&std::path::Path)) {
1495 let temp_dir = tempfile::tempdir().unwrap();
1496 let config_path = temp_dir.path().join(filename).with_extension(EXTENSION);
1497 proc(&config_path);
1498 temp_dir.close().unwrap()
1499 }
1500
1501 #[test]
1502 fn test_save_prune_config() {
1503 with_tempdir("prune-store-test", |config_path| {
1504 let mut reth_config = Config::default();
1505 let node_config = NodeConfig {
1506 pruning: PruningArgs {
1507 full: true,
1508 minimal: false,
1509 block_interval: None,
1510 sender_recovery_full: false,
1511 sender_recovery_distance: None,
1512 sender_recovery_before: None,
1513 transaction_lookup_full: false,
1514 transaction_lookup_distance: None,
1515 transaction_lookup_before: None,
1516 receipts_full: false,
1517 receipts_pre_merge: false,
1518 receipts_distance: None,
1519 receipts_before: None,
1520 account_history_full: false,
1521 account_history_distance: None,
1522 account_history_before: None,
1523 storage_history_full: false,
1524 storage_history_distance: None,
1525 storage_history_before: None,
1526 bodies_pre_merge: false,
1527 bodies_distance: None,
1528 receipts_log_filter: None,
1529 bodies_before: None,
1530 minimum_distance: None,
1531 },
1532 ..NodeConfig::test()
1533 };
1534 LaunchContext::save_pruning_config(&mut reth_config, &node_config, config_path)
1535 .unwrap();
1536
1537 let loaded_config = Config::from_path(config_path).unwrap();
1538
1539 assert_eq!(reth_config, loaded_config);
1540 })
1541 }
1542
1543 #[test]
1544 fn get_partial_trie_unwind_marker_uses_partial_finish_checkpoint() {
1545 let finish_checkpoint = StageCheckpoint::new(42)
1546 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(21) });
1547 let expected =
1548 finish_checkpoint.finish_stage_checkpoint().unwrap().partial_state_trie().map(
1549 |partial_state_trie| PartialStateTrieUnwindMarker {
1550 finish_block_number: finish_checkpoint.block_number,
1551 partial_state_trie,
1552 },
1553 );
1554
1555 assert_eq!(
1556 get_partial_trie_unwind_marker(&MockProvider(None, Some(finish_checkpoint))).unwrap(),
1557 (expected, false)
1558 );
1559
1560 let genesis_checkpoint = StageCheckpoint::new(42)
1561 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(0) });
1562 let expected =
1563 genesis_checkpoint.finish_stage_checkpoint().unwrap().partial_state_trie().map(
1564 |partial_state_trie| PartialStateTrieUnwindMarker {
1565 finish_block_number: genesis_checkpoint.block_number,
1566 partial_state_trie,
1567 },
1568 );
1569
1570 assert_eq!(
1571 get_partial_trie_unwind_marker(&MockProvider(None, Some(genesis_checkpoint))).unwrap(),
1572 (expected, false)
1573 );
1574 }
1575
1576 #[test]
1577 fn get_partial_trie_unwind_marker_resumes_persisted_unwind() {
1578 let marker =
1579 PartialStateTrieUnwindMarker { finish_block_number: 42, partial_state_trie: 21 };
1580
1581 assert_eq!(
1582 get_partial_trie_unwind_marker(&MockProvider(
1583 Some(serde_json::to_vec(&marker).unwrap()),
1584 Some(StageCheckpoint::new(21)),
1585 ),)
1586 .unwrap(),
1587 (Some(marker), true)
1588 );
1589 assert_eq!(
1590 get_partial_trie_unwind_marker(&MockProvider(
1591 Some(serde_json::to_vec(&marker).unwrap()),
1592 None
1593 ),)
1594 .unwrap(),
1595 (Some(marker), true)
1596 );
1597 }
1598
1599 #[test]
1600 fn get_partial_trie_unwind_marker_ignores_non_lagging_or_missing_partial_checkpoint() {
1601 let matching_finish_checkpoint = StageCheckpoint::new(42)
1602 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(42) });
1603 let ahead_finish_checkpoint = StageCheckpoint::new(42)
1604 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: Some(43) });
1605 let missing_partial_finish_checkpoint = StageCheckpoint::new(42)
1606 .with_finish_stage_checkpoint(FinishCheckpoint { partial_state_trie: None });
1607
1608 assert_eq!(
1609 get_partial_trie_unwind_marker(&MockProvider(None, Some(matching_finish_checkpoint)),)
1610 .unwrap(),
1611 (None, false)
1612 );
1613 assert_eq!(
1614 get_partial_trie_unwind_marker(&MockProvider(
1615 None,
1616 Some(missing_partial_finish_checkpoint)
1617 ),)
1618 .unwrap(),
1619 (None, false)
1620 );
1621 assert_eq!(
1622 get_partial_trie_unwind_marker(&MockProvider(None, None)).unwrap(),
1623 (None, false)
1624 );
1625
1626 let partial_frontier = ahead_finish_checkpoint
1627 .finish_stage_checkpoint()
1628 .and_then(|finish| finish.partial_state_trie());
1629 let result =
1630 get_partial_trie_unwind_marker(&MockProvider(None, Some(ahead_finish_checkpoint)));
1631 if partial_frontier.is_some() {
1632 let error = result.unwrap_err();
1633 assert!(error.to_string().contains("ahead of Finish"), "unexpected error: {error}");
1634 } else {
1635 assert_eq!(result.unwrap(), (None, false));
1636 }
1637 }
1638
1639 #[test]
1640 fn get_partial_trie_unwind_marker_rejects_invalid_persisted_marker() {
1641 let marker =
1642 PartialStateTrieUnwindMarker { finish_block_number: 42, partial_state_trie: 42 };
1643 let error = get_partial_trie_unwind_marker(&MockProvider(
1644 Some(serde_json::to_vec(&marker).unwrap()),
1645 None,
1646 ))
1647 .unwrap_err();
1648
1649 assert!(error.to_string().contains("is not below original Finish"));
1650 }
1651
1652 #[test]
1653 fn get_partial_trie_unwind_marker_rejects_malformed_metadata() {
1654 assert!(get_partial_trie_unwind_marker(&MockProvider(Some(vec![0xff]), None)).is_err());
1655 }
1656}