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