1mod archive;
87pub mod config_gen;
88mod extract;
89mod fetch;
90pub mod manifest;
91pub mod manifest_cmd;
92mod planning;
93mod progress;
94mod prune;
95mod session;
96mod source;
97mod tui;
98mod verify;
99
100pub use planning::{DownloadPlan, DownloadPlanArchive};
101
102use crate::common::EnvironmentArgs;
103use archive::run_modular_downloads;
104use clap::{builder::RangedU64ValueParser, Parser};
105use config_gen::config_for_selections;
106use extract::stream_and_extract;
107use eyre::Result;
108use manifest::{ComponentSelection, SnapshotComponentType, SnapshotManifest};
109use planning::{collect_planned_archives, PlannedDownloads};
110use progress::{DownloadProgress, DownloadRequestLimiter};
111use prune::prune_unlisted_outputs;
112use reth_chainspec::{EthChainSpec, EthereumHardfork, EthereumHardforks, MAINNET};
113use reth_cli::chainspec::ChainSpecParser;
114use reth_cli_util::cancellation::CancellationToken;
115use reth_config::config::Config;
116use reth_db::{init_db, Database};
117use reth_db_api::{tables, transaction::DbTx};
118use reth_fs_util as fs;
119use reth_node_api::NodeTypes;
120use reth_node_core::args::DefaultPruningValues;
121use reth_provider::{StaticFileProviderBuilder, StaticFileWriter};
122use reth_prune_types::{PruneMode, PruneModes, PruneSegment, MINIMUM_UNWIND_SAFE_DISTANCE};
123use reth_static_file_types::StaticFileSegment;
124use source::{
125 discover_manifest_url, fetch_manifest_from_source, fetch_snapshot_api_entries,
126 print_snapshot_listing, resolve_manifest_base_url,
127};
128use std::{
129 borrow::Cow,
130 collections::BTreeMap,
131 path::{Component, Path, PathBuf},
132 sync::{Arc, OnceLock},
133 time::Duration,
134};
135use tracing::info;
136use tui::{run_selector, SelectorOutput};
137
138const RETH_SNAPSHOTS_BASE_URL: &str = "https://snapshots-r2.reth.rs";
139const RETH_SNAPSHOTS_API_URL: &str = "https://snapshots.reth.rs/api/snapshots";
140const RETH_SNAPSHOTS_SOURCE: &str = "https://snapshots.reth.rs (default)";
141const SNAPSHOT_API_PATH: &str = "/api/snapshots";
142const MANAGED_DATADIR_PATHS: &[&str] = &["db", "rocksdb", "static_files", "reth.toml"];
143
144const MAX_CONCURRENT_DOWNLOADS: usize = 8;
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub(crate) enum SelectionPreset {
150 Minimal,
152 Full,
154 Archive,
156}
157
158struct ResolvedComponents {
159 selections: BTreeMap<SnapshotComponentType, ComponentSelection>,
160 preset: Option<SelectionPreset>,
161}
162
163static DOWNLOAD_DEFAULTS: OnceLock<DownloadDefaults> = OnceLock::new();
165
166#[derive(Debug, Clone)]
170pub struct DownloadDefaults {
171 pub available_snapshots: Vec<Cow<'static, str>>,
173 pub default_base_url: Cow<'static, str>,
175 pub default_chain_aware_base_url: Option<Cow<'static, str>>,
183 pub snapshot_api_url: Cow<'static, str>,
187 pub long_help: Option<String>,
189 pub full_preset_includes_rocksdb_indices: bool,
192}
193
194impl DownloadDefaults {
195 #[expect(clippy::result_large_err, reason = "returns the rejected defaults to the caller")]
197 pub fn try_init(self) -> Result<(), Self> {
198 DOWNLOAD_DEFAULTS.set(self)
199 }
200
201 pub fn get_global() -> &'static DownloadDefaults {
203 DOWNLOAD_DEFAULTS.get_or_init(DownloadDefaults::default_download_defaults)
204 }
205
206 pub fn default_download_defaults() -> Self {
208 Self {
209 available_snapshots: vec![
210 Cow::Borrowed(RETH_SNAPSHOTS_SOURCE),
211 Cow::Borrowed("https://publicnode.com/snapshots (full nodes & testnets)"),
212 ],
213 default_base_url: Cow::Borrowed(RETH_SNAPSHOTS_BASE_URL),
214 default_chain_aware_base_url: None,
215 snapshot_api_url: Cow::Borrowed(RETH_SNAPSHOTS_API_URL),
216 long_help: None,
217 full_preset_includes_rocksdb_indices: false,
218 }
219 }
220
221 pub fn long_help(&self) -> String {
226 if let Some(ref custom_help) = self.long_help {
227 return custom_help.clone();
228 }
229
230 let implicit_download_help = if self.mainnet_only_discovery() {
231 "\nIf no URL is provided, the latest archive snapshot will only be proposed\nfor Ethereum mainnet. For other chains, provide --manifest-url, --manifest-path,\nor -u explicitly."
232 } else {
233 "\nIf no URL is provided, the latest archive snapshot for the selected chain\nwill be proposed for download from "
234 };
235
236 let mut help = format!(
237 "Specify a snapshot URL or let the command propose a default one.\n\n\
238 Browse available snapshots at {}\n\
239 or use --list-snapshots to see them from the CLI.\n\nAvailable snapshot sources:\n",
240 self.snapshot_source_url(),
241 );
242
243 for source in &self.available_snapshots {
244 help.push_str("- ");
245 help.push_str(source);
246 help.push('\n');
247 }
248
249 help.push_str(implicit_download_help);
250 if !self.mainnet_only_discovery() {
251 help.push_str(
252 self.default_chain_aware_base_url.as_deref().unwrap_or(&self.default_base_url),
253 );
254 help.push('.');
255 }
256 help.push_str(
257 "\n\nLocal file:// URLs are also supported for extracting snapshots from disk.",
258 );
259 help
260 }
261
262 fn mainnet_only_discovery(&self) -> bool {
263 self.snapshot_api_url.trim_end_matches('/') == RETH_SNAPSHOTS_API_URL
264 }
265
266 fn snapshot_source_url(&self) -> &str {
267 snapshot_source_url_from_api(&self.snapshot_api_url)
268 }
269
270 pub fn with_snapshot(mut self, source: impl Into<Cow<'static, str>>) -> Self {
272 self.available_snapshots.push(source.into());
273 self
274 }
275
276 pub fn with_snapshots(mut self, sources: Vec<Cow<'static, str>>) -> Self {
278 self.available_snapshots = sources;
279 self
280 }
281
282 pub fn with_base_url(mut self, url: impl Into<Cow<'static, str>>) -> Self {
284 self.default_base_url = url.into();
285 self
286 }
287
288 pub fn with_chain_aware_base_url(mut self, url: impl Into<Cow<'static, str>>) -> Self {
290 self.default_chain_aware_base_url = Some(url.into());
291 self
292 }
293
294 pub fn with_snapshot_api_url(mut self, url: impl Into<Cow<'static, str>>) -> Self {
299 self.snapshot_api_url = url.into();
300
301 let source_url = self.snapshot_source_url().to_string();
302 if self.default_chain_aware_base_url.is_none() {
303 self.default_chain_aware_base_url = Some(Cow::Owned(source_url.clone()));
304 }
305 for source in &mut self.available_snapshots {
306 if source.as_ref() == RETH_SNAPSHOTS_SOURCE {
307 *source = Cow::Owned(format!("{source_url} (default)"));
308 }
309 }
310
311 self
312 }
313
314 pub fn with_snapshot_source_url(mut self, url: impl Into<Cow<'static, str>>) -> Self {
319 let source_url = normalize_snapshot_source_url(url.into());
320 self.available_snapshots = vec![Cow::Owned(format!("{} (default)", source_url.as_ref()))];
321 self.default_base_url = source_url.clone();
322 self.default_chain_aware_base_url = Some(source_url.clone());
323 self.snapshot_api_url = Cow::Owned(format!("{}{SNAPSHOT_API_PATH}", source_url.as_ref()));
324 self
325 }
326
327 pub const fn with_full_preset_rocksdb_indices(mut self) -> Self {
329 self.full_preset_includes_rocksdb_indices = true;
330 self
331 }
332
333 pub fn with_long_help(mut self, help: impl Into<String>) -> Self {
335 self.long_help = Some(help.into());
336 self
337 }
338}
339
340fn snapshot_source_url_from_api(api_url: &str) -> &str {
341 api_url.trim_end_matches('/').trim_end_matches(SNAPSHOT_API_PATH)
342}
343
344fn normalize_snapshot_source_url(url: Cow<'static, str>) -> Cow<'static, str> {
345 match url {
346 Cow::Borrowed(url) => Cow::Borrowed(snapshot_source_url_from_api(url)),
347 Cow::Owned(url) => Cow::Owned(snapshot_source_url_from_api(&url).to_string()),
348 }
349}
350
351impl Default for DownloadDefaults {
352 fn default() -> Self {
354 Self::default_download_defaults()
355 }
356}
357
358#[derive(Debug, Parser)]
360pub struct DownloadCommand<C: ChainSpecParser> {
361 #[command(flatten)]
362 env: EnvironmentArgs<C>,
363
364 #[arg(long, short, long_help = DownloadDefaults::get_global().long_help())]
369 url: Option<String>,
370
371 #[arg(long, value_name = "URL", conflicts_with = "url")]
376 manifest_url: Option<String>,
377
378 #[arg(long, value_name = "PATH", conflicts_with_all = ["url", "manifest_url"])]
380 manifest_path: Option<PathBuf>,
381
382 #[arg(long, conflicts_with_all = ["with_txs_since", "with_txs_distance", "minimal", "full", "archive"])]
384 with_txs: bool,
385
386 #[arg(long, value_name = "BLOCK_NUMBER", conflicts_with_all = ["with_txs", "with_txs_distance", "minimal", "full", "archive"])]
388 with_txs_since: Option<u64>,
389
390 #[arg(long, value_name = "BLOCKS", value_parser = RangedU64ValueParser::<u64>::new().range(1..), conflicts_with_all = ["with_txs", "with_txs_since", "minimal", "full", "archive"])]
392 with_txs_distance: Option<u64>,
393
394 #[arg(long, conflicts_with_all = ["with_receipts_since", "with_receipts_distance", "minimal", "full", "archive"])]
396 with_receipts: bool,
397
398 #[arg(long, value_name = "BLOCK_NUMBER", conflicts_with_all = ["with_receipts", "with_receipts_distance", "minimal", "full", "archive"])]
400 with_receipts_since: Option<u64>,
401
402 #[arg(long, value_name = "BLOCKS", value_parser = RangedU64ValueParser::<u64>::new().range(1..), conflicts_with_all = ["with_receipts", "with_receipts_since", "minimal", "full", "archive"])]
404 with_receipts_distance: Option<u64>,
405
406 #[arg(long, alias = "with-changesets", conflicts_with_all = ["with_state_history_since", "with_state_history_distance", "minimal", "full", "archive"])]
408 with_state_history: bool,
409
410 #[arg(long, value_name = "BLOCK_NUMBER", conflicts_with_all = ["with_state_history", "with_state_history_distance", "minimal", "full", "archive"])]
412 with_state_history_since: Option<u64>,
413
414 #[arg(long, value_name = "BLOCKS", value_parser = RangedU64ValueParser::<u64>::new().range(1..), conflicts_with_all = ["with_state_history", "with_state_history_since", "minimal", "full", "archive"])]
416 with_state_history_distance: Option<u64>,
417
418 #[arg(long, requires = "with_txs", conflicts_with_all = ["minimal", "full", "archive"])]
420 with_senders: bool,
421
422 #[arg(long, conflicts_with_all = ["minimal", "full", "archive", "without_rocksdb"])]
424 with_rocksdb: bool,
425
426 #[arg(long, alias = "all", conflicts_with_all = ["with_txs", "with_txs_since", "with_txs_distance", "with_receipts", "with_receipts_since", "with_receipts_distance", "with_state_history", "with_state_history_since", "with_state_history_distance", "with_senders", "with_rocksdb", "minimal", "full"])]
428 archive: bool,
429
430 #[arg(long, conflicts_with_all = ["with_txs", "with_txs_since", "with_txs_distance", "with_receipts", "with_receipts_since", "with_receipts_distance", "with_state_history", "with_state_history_since", "with_state_history_distance", "with_senders", "with_rocksdb", "archive", "full"])]
432 minimal: bool,
433
434 #[arg(long, conflicts_with_all = ["with_txs", "with_txs_since", "with_txs_distance", "with_receipts", "with_receipts_since", "with_receipts_distance", "with_state_history", "with_state_history_since", "with_state_history_distance", "with_senders", "with_rocksdb", "archive", "minimal"])]
436 full: bool,
437
438 #[arg(long, conflicts_with_all = ["url", "with_rocksdb"])]
443 without_rocksdb: bool,
444
445 #[arg(long, short = 'y')]
448 non_interactive: bool,
449
450 #[arg(long, conflicts_with = "list")]
452 force: bool,
453
454 #[arg(long, conflicts_with_all = ["force", "list", "url"])]
468 prune_unlisted: bool,
469
470 #[arg(long, default_value_t = true, num_args = 0..=1, default_missing_value = "true")]
477 resumable: bool,
478
479 #[arg(long, default_value_t = MAX_CONCURRENT_DOWNLOADS)]
484 download_concurrency: usize,
485
486 #[arg(long, value_name = "DURATION", value_parser = reth_cli_util::parse_duration_from_secs_or_ms)]
492 retry_backoff: Option<Duration>,
493
494 #[arg(long, alias = "list-snapshots", conflicts_with_all = ["url", "manifest_url", "manifest_path"])]
499 list: bool,
500
501 #[arg(long, conflicts_with_all = ["url", "list"])]
503 print_plan_json: bool,
504}
505
506impl<C: ChainSpecParser<ChainSpec: EthChainSpec + EthereumHardforks>> DownloadCommand<C> {
507 pub async fn execute<N: NodeTypes>(self) -> Result<Option<PreparedSnapshotDownload>> {
509 let chain = self.env.chain.chain();
510
511 if self.list {
513 let entries = fetch_snapshot_api_entries(chain.id()).await?;
514 print_snapshot_listing(&entries, chain.id());
515 return Ok(None);
516 }
517
518 let data_dir = self.env.datadir.clone().resolve_datadir(chain);
519 let static_files_dir = data_dir.static_files();
520 let static_files_dir = (static_files_dir != data_dir.data_dir().join("static_files"))
521 .then_some(static_files_dir);
522
523 if let Some(ref url) = self.url {
525 let cancel_token = CancellationToken::new();
526 let _cancel_guard = cancel_token.drop_guard();
527 let data_dir = self.env.datadir.clone().resolve_datadir(chain);
528 let target_dir = data_dir.data_dir();
529 if self.force {
530 clear_existing_datadir(target_dir, static_files_dir.as_deref())?;
531 }
532 fs::create_dir_all(target_dir)?;
533
534 let request_limiter = DownloadRequestLimiter::new(self.download_concurrency.max(1));
535 info!(target: "reth::cli",
536 dir = ?data_dir.data_dir(),
537 url = %url,
538 "Starting snapshot download and extraction"
539 );
540
541 stream_and_extract(
542 url,
543 data_dir.data_dir(),
544 static_files_dir.as_deref(),
545 self.resumable,
546 Some(request_limiter),
547 cancel_token.clone(),
548 self.retry_backoff,
549 )
550 .await?;
551 info!(target: "reth::cli", "Snapshot downloaded and extracted successfully");
552
553 return Ok(None);
554 }
555
556 let ResolvedDownload { manifest, selections, preset, planned, transaction_jars } =
557 self.resolve_download(chain.id()).await?;
558 let config_path = self.env.config.clone().unwrap_or_else(|| data_dir.config());
559 let data_dir = data_dir.data_dir().to_path_buf();
560 let prepared = PreparedSnapshotDownload { manifest, data_dir };
561 if self.print_plan_json {
562 DownloadPlan::from_planned(&prepared.manifest, &planned)
563 .write_json(std::io::stdout().lock())?;
564 return Ok(Some(prepared))
565 }
566
567 let target_dir = prepared.data_dir.as_path();
568 let cancel_token = CancellationToken::new();
569 let _cancel_guard = cancel_token.drop_guard();
570 let (downloads, config_path) = {
571 let target_dir = std::path::absolute(target_dir)?;
572 let static_files_dir =
573 static_files_dir.as_deref().map(std::path::absolute).transpose()?;
574 reth_tasks::spawn_blocking(move || -> Result<_> {
575 let static_files_dir = static_files_dir.as_deref();
576 let config_path = planned.validated_config_path(
577 std::path::absolute(config_path)?,
578 &target_dir,
579 static_files_dir,
580 self.force || self.prune_unlisted,
581 )?;
582 if self.force {
583 clear_existing_datadir(&target_dir, static_files_dir)?;
584 } else if self.prune_unlisted {
585 prune_unlisted_outputs(&planned.archives, &target_dir, static_files_dir)?;
586 }
587 fs::create_dir_all(&target_dir)?;
588 let downloads = planned.partition_reusable(&target_dir, static_files_dir)?;
589 Ok((downloads, config_path))
590 })
591 .await??
592 };
593 info!(target: "reth::cli",
594 reusable = downloads.reused.len(),
595 needs_download = downloads.pending.len(),
596 "Startup integrity summary (plain output files)"
597 );
598
599 info!(target: "reth::cli",
600 archives = downloads.total_archives(),
601 download_total = %DownloadProgress::format_size(downloads.total_download_size),
602 output_total = %DownloadProgress::format_size(downloads.total_output_size),
603 "Downloading all archives"
604 );
605
606 run_modular_downloads(
607 downloads,
608 target_dir,
609 static_files_dir.as_deref(),
610 self.download_concurrency.max(1),
611 cancel_token,
612 self.retry_backoff,
613 )
614 .await?;
615
616 reth_tasks::spawn_blocking(move || {
617 self.finalize_modular_download::<N>(
618 &selections,
619 &prepared,
620 preset,
621 &config_path,
622 &transaction_jars,
623 )?;
624 Ok(Some(prepared))
625 })
626 .await?
627 }
628
629 pub async fn plan(&self) -> Result<(DownloadPlan, PreparedSnapshotDownload)> {
632 let chain = self.env.chain.chain();
633 let resolved = self.resolve_download(chain.id()).await?;
634 let plan = DownloadPlan::from_planned(&resolved.manifest, &resolved.planned);
635 let prepared = PreparedSnapshotDownload {
636 manifest: resolved.manifest,
637 data_dir: self.env.datadir.clone().resolve_datadir(chain).data_dir().to_path_buf(),
638 };
639 Ok((plan, prepared))
640 }
641
642 async fn resolve_download(&self, chain_id: u64) -> Result<ResolvedDownload> {
643 let manifest = self.load_manifest(chain_id).await?;
644 let ResolvedComponents { mut selections, preset } = self.resolve_components(&manifest)?;
645
646 match preset {
647 Some(SelectionPreset::Archive) => {
648 inject_archive_only_components(&mut selections, &manifest, !self.without_rocksdb)
649 }
650 Some(SelectionPreset::Full)
651 if DownloadDefaults::get_global().full_preset_includes_rocksdb_indices &&
652 !self.without_rocksdb =>
653 {
654 inject_rocksdb_indices(&mut selections, &manifest)
655 }
656 _ => {}
657 }
658
659 let planned = collect_planned_archives(&manifest, &selections)?;
660 let transaction_jars = planned.transaction_jars()?;
661 let selected = selections.get(&SnapshotComponentType::Transactions);
662 eyre::ensure!(
663 !transaction_jars.is_empty() ||
664 matches!(
665 selected,
666 None | Some(ComponentSelection::None | ComponentSelection::Distance(0))
667 ),
668 "Selected transaction files do not cover snapshot block {}",
669 manifest.block
670 );
671 Ok(ResolvedDownload { manifest, selections, preset, planned, transaction_jars })
672 }
673
674 async fn load_manifest(&self, chain_id: u64) -> Result<SnapshotManifest> {
676 let manifest_source = self.resolve_manifest_source(chain_id).await?;
677
678 info!(target: "reth::cli", source = %manifest_source, "Fetching snapshot manifest");
679 let mut manifest = fetch_manifest_from_source(&manifest_source).await?;
680 if self.env.datadir.datadir.as_ref().is_none() ||
681 (self.manifest_url.is_none() && self.manifest_path.is_none())
682 {
683 self.validate_manifest_chain(&manifest)?;
684 }
685 manifest.base_url = Some(resolve_manifest_base_url(&manifest, &manifest_source)?);
686
687 info!(target: "reth::cli",
688 block = manifest.block,
689 chain_id = manifest.chain_id,
690 storage_version = %manifest.storage_version,
691 components = manifest.components.len(),
692 "Loaded snapshot manifest"
693 );
694
695 Ok(manifest)
696 }
697
698 fn download_config(
699 &self,
700 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
701 manifest: &SnapshotManifest,
702 preset: Option<SelectionPreset>,
703 ) -> Config {
704 let mut config =
705 config_for_selections(selections, manifest, preset, Some(self.env.chain.as_ref()));
706 if let Some(selection) =
708 explicit_component_selection(self.with_txs, self.with_txs_since, self.with_txs_distance)
709 {
710 config.prune.segments.bodies_history =
711 config_gen::selection_to_prune_mode(selection, Some(MINIMUM_UNWIND_SAFE_DISTANCE));
712 }
713 if let Some(selection) = self.explicit_history_selection() {
714 let mode =
715 config_gen::selection_to_prune_mode(selection, Some(MINIMUM_UNWIND_SAFE_DISTANCE));
716 config.prune.segments.account_history = mode;
717 config.prune.segments.storage_history = mode;
718 }
719 config
720 }
721
722 fn finalize_modular_download<N: NodeTypes>(
724 self,
725 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
726 prepared: &PreparedSnapshotDownload,
727 preset: Option<SelectionPreset>,
728 config_path: &Path,
729 transaction_jars: &[String],
730 ) -> Result<()> {
731 let PreparedSnapshotDownload { manifest, data_dir: target_dir } = prepared;
732 let mut config = self.download_config(selections, manifest, preset);
733 let static_files = self.env.datadir.resolve_datadir(self.env.chain.chain()).static_files();
734 let boundary =
735 planning::restored_bodies_boundary(&static_files, transaction_jars, manifest.block)?;
736 if config_path.try_exists()? {
737 let retained = Config::from_path(config_path)?;
738 retained.static_files.validate()?;
739 config.static_files = retained.static_files;
740 }
741 let db = init_db(target_dir.join("db"), self.env.db.database_args())?;
742 let tx = db.tx_mut()?;
743 let is_v2 = config_gen::snapshot_uses_v2(&tx, selections)?;
744 let mut source_bodies = tx.get::<tables::PruneCheckpoints>(PruneSegment::Bodies)?;
745 if let Some(source) = source_bodies &&
746 boundary < source.block_number &&
747 source.block_number <= Some(manifest.block)
748 {
749 let files =
750 StaticFileProviderBuilder::read_only(&static_files).build::<N::Primitives>()?;
751 let first = boundary.map_or(0, |block| block + 1);
752 source_bodies =
753 Some(files.snapshot_bodies_checkpoint(&tx, source, first, manifest.block)?);
754 }
755 config_gen::write_prune_checkpoints_tx(
756 &tx,
757 &config,
758 selections,
759 manifest,
760 is_v2,
761 boundary,
762 source_bodies,
763 )?;
764 if is_v2 && rocksdb_indices_missing(selections) {
765 config_gen::reset_index_stage_checkpoints_tx(&tx)?;
766 }
767 if boundary == Some(manifest.block) {
768 let segment = StaticFileSegment::Transactions;
771 let provider = StaticFileProviderBuilder::read_write(static_files)
772 .with_blocks_per_file_for_segments(&config.static_files.as_blocks_per_file_map())
773 .build::<N::Primitives>()?;
774 if provider.get_highest_static_file_block(segment) < Some(manifest.block) {
775 eyre::ensure!(provider.get_highest_static_file_tx(segment).is_none(),
776 "Local transaction files end before the snapshot tip; use --prune-unlisted to remove unselected files");
777 let mut writer = provider.get_writer(manifest.block, segment)?;
778 if writer.current_block_number().is_none() {
779 writer.initialize_pruned_anchor(manifest.block)?;
780 } else {
781 writer.user_header_mut().set_block_range(manifest.block, manifest.block);
783 }
784 writer.commit()?;
785 }
786 }
787 if config_gen::write_config_to_path(&config, config_path)? {
788 let desc = config_gen::describe_prune_config(&config);
789 info!(target: "reth::cli", "{}", desc.join(", "));
790 }
791 tx.commit()?;
792
793 if self.env.chain.chain().id() == manifest.chain_id {
794 let config = self.env.config.as_ref().map(|_| config_path);
795 let start_command = startup_node_command::<C>(self.env.chain.as_ref(), config);
796 info!(target: "reth::cli", "Snapshot download complete. Run `{}` to start syncing.", start_command);
797 } else {
798 info!(target: "reth::cli", "Snapshot download complete.");
799 }
800
801 Ok(())
802 }
803
804 fn resolve_components(&self, manifest: &SnapshotManifest) -> Result<ResolvedComponents> {
806 let available = |ty: SnapshotComponentType| manifest.component(ty).is_some();
807
808 if self.archive {
810 return Ok(ResolvedComponents {
811 selections: SnapshotComponentType::ALL
812 .iter()
813 .copied()
814 .filter(|ty| available(*ty))
815 .filter(|ty| {
816 !self.without_rocksdb || *ty != SnapshotComponentType::RocksdbIndices
817 })
818 .map(|ty| (ty, ComponentSelection::All))
819 .collect(),
820 preset: Some(SelectionPreset::Archive),
821 });
822 }
823
824 if self.full {
825 return Ok(ResolvedComponents {
826 selections: self.full_preset_selections(manifest)?,
827 preset: Some(SelectionPreset::Full),
828 });
829 }
830
831 if self.minimal {
832 return Ok(ResolvedComponents {
833 selections: self.minimal_preset_selections(manifest),
834 preset: Some(SelectionPreset::Minimal),
835 });
836 }
837
838 let has_explicit_flags = self.with_txs ||
839 self.with_txs_since.is_some() ||
840 self.with_txs_distance.is_some() ||
841 self.with_receipts ||
842 self.with_receipts_since.is_some() ||
843 self.with_receipts_distance.is_some() ||
844 self.with_state_history ||
845 self.with_state_history_since.is_some() ||
846 self.with_state_history_distance.is_some() ||
847 self.with_senders ||
848 self.with_rocksdb;
849
850 if has_explicit_flags {
851 let mut selections = BTreeMap::new();
852 let tx_selection = explicit_component_selection(
853 self.with_txs,
854 self.with_txs_since,
855 self.with_txs_distance,
856 );
857 let receipt_selection = explicit_component_selection(
858 self.with_receipts,
859 self.with_receipts_since,
860 self.with_receipts_distance,
861 );
862 let history_selection = self.explicit_history_selection();
863 if available(SnapshotComponentType::State) {
865 selections.insert(SnapshotComponentType::State, ComponentSelection::All);
866 }
867 if available(SnapshotComponentType::Headers) {
868 selections.insert(SnapshotComponentType::Headers, ComponentSelection::All);
869 }
870 for (ty, selection) in [
871 (SnapshotComponentType::Transactions, tx_selection),
872 (SnapshotComponentType::Receipts, receipt_selection),
873 (SnapshotComponentType::AccountChangesets, history_selection),
874 (SnapshotComponentType::StorageChangesets, history_selection),
875 ] {
876 if let Some(selection) = selection &&
877 available(ty) &&
878 !matches!(selection, ComponentSelection::Since(block) if block > manifest.block)
879 {
880 selections.insert(ty, selection);
881 }
882 }
883 if self.with_senders && available(SnapshotComponentType::TransactionSenders) {
884 selections
885 .insert(SnapshotComponentType::TransactionSenders, ComponentSelection::All);
886 }
887 if self.with_rocksdb && available(SnapshotComponentType::RocksdbIndices) {
888 selections.insert(SnapshotComponentType::RocksdbIndices, ComponentSelection::All);
889 }
890 return Ok(ResolvedComponents { selections, preset: None });
891 }
892
893 if self.non_interactive {
894 eyre::ensure!(
897 !self.prune_unlisted,
898 "--prune-unlisted with --non-interactive requires an explicit component selection: \
899 --minimal, --full, --archive, or --with-* flags"
900 );
901 return Ok(ResolvedComponents {
902 selections: self.minimal_preset_selections(manifest),
903 preset: Some(SelectionPreset::Minimal),
904 });
905 }
906
907 let minimal_preset = self.minimal_preset_selections(manifest);
909 let full_preset = self.full_preset_selections(manifest)?;
910 let SelectorOutput { selections, preset } =
911 run_selector(manifest.clone(), &minimal_preset, &full_preset)?;
912 let selected =
913 selections.into_iter().filter(|(_, sel)| *sel != ComponentSelection::None).collect();
914
915 Ok(ResolvedComponents { selections: selected, preset })
916 }
917
918 fn explicit_history_selection(&self) -> Option<ComponentSelection> {
919 explicit_component_selection(
920 self.with_state_history,
921 self.with_state_history_since,
922 self.with_state_history_distance,
923 )
924 }
925
926 fn minimal_preset_selections(
928 &self,
929 manifest: &SnapshotManifest,
930 ) -> BTreeMap<SnapshotComponentType, ComponentSelection> {
931 self.pruning_preset_selections(manifest, SelectionPreset::Minimal)
932 }
933
934 fn full_preset_selections(
936 &self,
937 manifest: &SnapshotManifest,
938 ) -> Result<BTreeMap<SnapshotComponentType, ComponentSelection>> {
939 if DefaultPruningValues::get_global().full_bodies_history_use_pre_merge {
940 self.validate_manifest_chain(manifest)?;
941 }
942 Ok(self.pruning_preset_selections(manifest, SelectionPreset::Full))
943 }
944
945 fn pruning_preset_selections(
947 &self,
948 manifest: &SnapshotManifest,
949 preset: SelectionPreset,
950 ) -> BTreeMap<SnapshotComponentType, ComponentSelection> {
951 let defaults = DefaultPruningValues::get_global();
952 let (prune_modes, bodies_history_use_pre_merge) = match preset {
953 SelectionPreset::Minimal => (&defaults.minimal_prune_modes, false),
954 SelectionPreset::Full => {
955 (&defaults.full_prune_modes, defaults.full_bodies_history_use_pre_merge)
956 }
957 SelectionPreset::Archive => unreachable!("archive selects every component"),
958 };
959 let mut selections = BTreeMap::new();
960
961 for &ty in &SnapshotComponentType::ALL {
962 if manifest.component(ty).is_none() {
963 continue;
964 }
965
966 let selection = self.pruning_selection_for_component(
967 ty,
968 manifest.block,
969 prune_modes,
970 bodies_history_use_pre_merge,
971 );
972 if selection != ComponentSelection::None {
973 selections.insert(ty, selection);
974 }
975 }
976
977 selections
978 }
979
980 fn pruning_selection_for_component(
982 &self,
983 ty: SnapshotComponentType,
984 snapshot_block: u64,
985 prune_modes: &PruneModes,
986 bodies_history_use_pre_merge: bool,
987 ) -> ComponentSelection {
988 if ty == SnapshotComponentType::Transactions && bodies_history_use_pre_merge {
989 return match self
990 .env
991 .chain
992 .ethereum_fork_activation(EthereumHardfork::Paris)
993 .block_number()
994 {
995 Some(paris) if snapshot_block >= paris => ComponentSelection::Since(paris),
996 Some(_) => ComponentSelection::None,
997 None => ComponentSelection::All,
998 }
999 }
1000
1001 let mode = match ty {
1002 SnapshotComponentType::State | SnapshotComponentType::Headers => {
1003 return ComponentSelection::All
1004 }
1005 SnapshotComponentType::Transactions => prune_modes.bodies_history,
1006 SnapshotComponentType::TransactionSenders => prune_modes.sender_recovery,
1007 SnapshotComponentType::Receipts => prune_modes.receipts,
1008 SnapshotComponentType::AccountChangesets => prune_modes.account_history,
1009 SnapshotComponentType::StorageChangesets => prune_modes.storage_history,
1010 SnapshotComponentType::RocksdbIndices => return ComponentSelection::None,
1011 };
1012
1013 selection_from_prune_mode(mode, snapshot_block)
1014 }
1015
1016 async fn resolve_manifest_source(&self, chain_id: u64) -> Result<String> {
1018 if let Some(path) = &self.manifest_path {
1019 return Ok(path.display().to_string());
1020 }
1021
1022 match &self.manifest_url {
1023 Some(url) => Ok(url.clone()),
1024 None => {
1025 let defaults = DownloadDefaults::get_global();
1026 if defaults.mainnet_only_discovery() && chain_id != MAINNET.chain.id() {
1027 eyre::bail!(
1028 "Snapshots are only auto-discovered for Ethereum mainnet.\n\n\
1029 Chain {chain_id} requires an explicit source:\n\
1030 \t--manifest-url <URL>\n\
1031 \t--manifest-path <PATH>\n\
1032 \t-u <SNAPSHOT-URL>\n\n\
1033 Use --list to inspect snapshots exposed by {}.",
1034 defaults.snapshot_source_url(),
1035 );
1036 }
1037
1038 discover_manifest_url(chain_id).await
1039 }
1040 }
1041 }
1042
1043 fn validate_manifest_chain(&self, manifest: &SnapshotManifest) -> Result<()> {
1044 let chain_id = self.env.chain.chain().id();
1045 eyre::ensure!(
1046 manifest.chain_id == chain_id,
1047 "Snapshot chain ID {} does not match selected chain ID {chain_id}",
1048 manifest.chain_id
1049 );
1050 Ok(())
1051 }
1052}
1053
1054fn explicit_component_selection(
1057 all: bool,
1058 since: Option<u64>,
1059 distance: Option<u64>,
1060) -> Option<ComponentSelection> {
1061 if all {
1062 Some(ComponentSelection::All)
1063 } else if let Some(block) = since {
1064 Some(ComponentSelection::Since(block))
1065 } else {
1066 distance.map(ComponentSelection::Distance)
1067 }
1068}
1069
1070fn selection_from_prune_mode(mode: Option<PruneMode>, snapshot_block: u64) -> ComponentSelection {
1072 match mode {
1073 None => ComponentSelection::All,
1074 Some(PruneMode::Full) => ComponentSelection::None,
1075 Some(PruneMode::Distance(d)) => ComponentSelection::Distance(d),
1076 Some(PruneMode::Before(block)) => {
1077 if snapshot_block >= block {
1078 ComponentSelection::Since(block)
1079 } else {
1080 ComponentSelection::None
1081 }
1082 }
1083 }
1084}
1085
1086fn clear_existing_datadir(target_dir: &Path, static_files_dir: Option<&Path>) -> Result<()> {
1088 info!(target: "reth::cli", dir = ?target_dir, "Clearing existing snapshot data");
1089 for entry in MANAGED_DATADIR_PATHS {
1090 let path = managed_datadir_path(entry, target_dir, static_files_dir);
1091 let file_type = match path.symlink_metadata() {
1092 Ok(metadata) => metadata.file_type(),
1093 Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue,
1094 Err(err) => return Err(fs::FsPathError::metadata(err, path).into()),
1095 };
1096 let is_dir = file_type.is_dir();
1097 #[cfg(windows)]
1098 let is_dir = is_dir || std::os::windows::fs::FileTypeExt::is_symlink_dir(&file_type);
1099 if is_dir {
1100 fs::remove_dir_all(&path)?;
1101 } else if file_type.is_file() || file_type.is_symlink() {
1102 fs::remove_file(&path)?;
1103 }
1104 }
1105
1106 Ok(())
1107}
1108
1109fn is_managed_snapshot_path(path: &Path, directory: bool) -> bool {
1111 let mut components = path.components().peekable();
1112 if components.peek() == Some(&Component::CurDir) {
1113 components.next();
1114 }
1115 let Some(Component::Normal(root)) = components.next() else { return false };
1116 if !MANAGED_DATADIR_PATHS.iter().any(|name| root == *name) {
1117 return false
1118 }
1119 if root == "reth.toml" {
1120 return !directory && components.next().is_none()
1121 }
1122 (directory || components.peek().is_some()) &&
1123 components.all(|part| matches!(part, Component::Normal(_)))
1124}
1125
1126fn managed_datadir_path(
1128 entry: &str,
1129 target_dir: &Path,
1130 static_files_dir: Option<&Path>,
1131) -> PathBuf {
1132 if entry == "static_files" {
1133 static_files_dir.map_or_else(|| target_dir.join(entry), Path::to_path_buf)
1134 } else {
1135 target_dir.join(entry)
1136 }
1137}
1138
1139fn inject_archive_only_components(
1142 selections: &mut BTreeMap<SnapshotComponentType, ComponentSelection>,
1143 manifest: &SnapshotManifest,
1144 include_rocksdb: bool,
1145) {
1146 let is_all =
1147 |ty: SnapshotComponentType| selections.get(&ty).copied() == Some(ComponentSelection::All);
1148
1149 let is_archive = is_all(SnapshotComponentType::Transactions) &&
1150 is_all(SnapshotComponentType::Receipts) &&
1151 is_all(SnapshotComponentType::AccountChangesets) &&
1152 is_all(SnapshotComponentType::StorageChangesets);
1153
1154 if !is_archive {
1155 return;
1156 }
1157
1158 for component in
1159 [SnapshotComponentType::TransactionSenders, SnapshotComponentType::RocksdbIndices]
1160 {
1161 if component == SnapshotComponentType::RocksdbIndices && !include_rocksdb {
1162 continue;
1163 }
1164
1165 if manifest.component(component).is_some() {
1166 selections.insert(component, ComponentSelection::All);
1167 }
1168 }
1169}
1170
1171fn inject_rocksdb_indices(
1173 selections: &mut BTreeMap<SnapshotComponentType, ComponentSelection>,
1174 manifest: &SnapshotManifest,
1175) {
1176 if manifest.component(SnapshotComponentType::RocksdbIndices).is_some() {
1177 selections.insert(SnapshotComponentType::RocksdbIndices, ComponentSelection::All);
1178 }
1179}
1180
1181fn rocksdb_indices_missing(
1183 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
1184) -> bool {
1185 !matches!(selections.get(&SnapshotComponentType::RocksdbIndices), Some(ComponentSelection::All))
1186}
1187
1188fn startup_node_command<C>(chain_spec: &C::ChainSpec, config: Option<&Path>) -> String
1189where
1190 C: ChainSpecParser,
1191 C::ChainSpec: EthChainSpec,
1192{
1193 let command = startup_node_command_for_binary::<C>(¤t_binary_name(), chain_spec);
1194 let Some(path) = config else { return command };
1195 let quote = if cfg!(windows) { "''" } else { "'\\''" };
1196 let path = path.to_string_lossy().replace('\'', quote);
1197 format!("{command} --config '{path}'")
1198}
1199
1200fn startup_node_command_for_binary<C>(binary_name: &str, chain_spec: &C::ChainSpec) -> String
1201where
1202 C: ChainSpecParser,
1203 C::ChainSpec: EthChainSpec,
1204{
1205 let mut command = format!("{binary_name} node");
1206
1207 if let Some(chain_arg) = startup_chain_arg::<C>(chain_spec) {
1208 command.push_str(" --chain ");
1209 command.push_str(&chain_arg);
1210 }
1211
1212 command
1213}
1214
1215fn current_binary_name() -> String {
1216 std::env::args_os()
1217 .next()
1218 .map(PathBuf::from)
1219 .and_then(|path| path.file_stem().map(|name| name.to_owned()))
1220 .and_then(|name| name.into_string().ok())
1221 .filter(|name| !name.is_empty())
1222 .unwrap_or_else(|| "reth".to_string())
1223}
1224
1225fn download_command() -> String {
1226 download_command_for_binary(¤t_binary_name())
1227}
1228
1229fn download_command_for_binary(binary_name: &str) -> String {
1230 format!("{binary_name} download")
1231}
1232
1233fn startup_chain_arg<C>(chain_spec: &C::ChainSpec) -> Option<String>
1234where
1235 C: ChainSpecParser,
1236 C::ChainSpec: EthChainSpec,
1237{
1238 let current_chain = chain_spec.chain();
1239 let current_genesis_hash = chain_spec.genesis_hash();
1240 let default_chain = C::default_value().and_then(|chain_name| C::parse(chain_name).ok());
1241
1242 if default_chain.as_ref().is_some_and(|default_chain| {
1243 default_chain.chain() == current_chain &&
1244 default_chain.genesis_hash() == current_genesis_hash
1245 }) {
1246 return None;
1247 }
1248
1249 C::SUPPORTED_CHAINS
1250 .iter()
1251 .find_map(|chain_name| {
1252 let parsed_chain = C::parse(chain_name).ok()?;
1253 (parsed_chain.chain() == current_chain &&
1254 parsed_chain.genesis_hash() == current_genesis_hash)
1255 .then(|| (*chain_name).to_string())
1256 })
1257 .or_else(|| Some("<chain-or-chainspec>".to_string()))
1258}
1259
1260impl<C: ChainSpecParser> DownloadCommand<C> {
1261 pub const fn env(&self) -> &EnvironmentArgs<C> {
1263 &self.env
1264 }
1265
1266 pub fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
1268 Some(&self.env.chain)
1269 }
1270
1271 pub const fn prints_plan_json(&self) -> bool {
1273 self.print_plan_json
1274 }
1275}
1276
1277#[derive(Debug)]
1279pub struct PreparedSnapshotDownload {
1280 pub manifest: SnapshotManifest,
1282 pub data_dir: PathBuf,
1284}
1285
1286struct ResolvedDownload {
1287 manifest: SnapshotManifest,
1288 selections: BTreeMap<SnapshotComponentType, ComponentSelection>,
1289 preset: Option<SelectionPreset>,
1290 planned: PlannedDownloads,
1291 transaction_jars: Vec<String>,
1292}
1293
1294const MAX_DOWNLOAD_RETRIES: u32 = 10;
1295const RETRY_BACKOFF_SECS: u64 = 5;
1296
1297#[cfg(test)]
1298mod tests {
1299 use super::*;
1300 use alloy_consensus::{Block, Header, SignableTransaction, TxLegacy};
1301 use alloy_primitives::Signature;
1302 use clap::{Args, Parser};
1303 use extract::CompressionFormat;
1304 use manifest::{generate_manifest, ComponentManifest, OutputFileChecksum, SingleArchive};
1305 use reth_chainspec::{HOLESKY, MAINNET};
1306 use reth_db::{
1307 mdbx::DatabaseArguments,
1308 models::StorageSettings,
1309 static_file::{iter_static_files, CONFIG_FILE_EXTENSION, OFFSETS_FILE_EXTENSION},
1310 DatabaseEnv,
1311 };
1312 use reth_db_api::transaction::DbTxMut;
1313 use reth_ethereum_cli::chainspec::EthereumChainSpecParser;
1314 use reth_primitives_traits::Block as _;
1315 use reth_provider::{
1316 providers::RocksDBProvider,
1317 test_utils::{MockNodeTypes, MockNodeTypesWithDB},
1318 BlockNumReader, BlockReader, BlockWriter, ProviderError, ProviderFactory,
1319 PruneCheckpointReader,
1320 };
1321 use reth_prune::PrunerBuilder;
1322 use reth_prune_types::PruneCheckpoint;
1323 use reth_stages_types::{StageCheckpoint, StageId};
1324 use reth_storage_api::metadata::keys;
1325 use std::ops::RangeInclusive;
1326 use tempfile::{tempdir, TempDir};
1327
1328 #[derive(Parser)]
1329 struct CommandParser<T: Args> {
1330 #[command(flatten)]
1331 args: T,
1332 }
1333
1334 pub(super) fn empty_manifest() -> SnapshotManifest {
1335 SnapshotManifest {
1336 block: 0,
1337 chain_id: 1,
1338 storage_version: 2,
1339 timestamp: 0,
1340 base_url: None,
1341 reth_version: None,
1342 components: BTreeMap::new(),
1343 extensions: Default::default(),
1344 }
1345 }
1346
1347 fn single_archive(
1348 component: SnapshotComponentType,
1349 output_path: &str,
1350 ) -> (String, ComponentManifest) {
1351 let key = component.key();
1352 let archive = SingleArchive {
1353 file: format!("{key}.tar.zst"),
1354 size: 1,
1355 decompressed_size: 1,
1356 blake3: None,
1357 output_files: vec![OutputFileChecksum {
1358 path: output_path.to_owned(),
1359 size: 1,
1360 blake3: blake3::hash(b"x").to_hex().to_string(),
1361 }],
1362 };
1363 (key.to_owned(), ComponentManifest::Single(archive))
1364 }
1365
1366 fn manifest_with_archive_only_components() -> SnapshotManifest {
1367 SnapshotManifest {
1368 base_url: Some("https://example.com".to_string()),
1369 components: BTreeMap::from([
1370 single_archive(
1371 SnapshotComponentType::TransactionSenders,
1372 "static_files/static_file_transaction_senders_0_0",
1373 ),
1374 single_archive(SnapshotComponentType::RocksdbIndices, "rocksdb/000001.sst"),
1375 ]),
1376 ..empty_manifest()
1377 }
1378 }
1379
1380 #[cfg(unix)]
1381 #[test]
1382 fn clear_existing_datadir_removes_managed_links_without_following_them() {
1383 let dir = tempfile::tempdir().unwrap();
1384 let datadir = dir.path().join("datadir");
1385 let existing = dir.path().join("storage");
1386 let missing = dir.path().join("old-config.toml");
1387 fs::create_dir_all(&datadir).unwrap();
1388 fs::create_dir_all(&existing).unwrap();
1389 fs::write(existing.join("data"), b"keep").unwrap();
1390 std::os::unix::fs::symlink(&existing, datadir.join("db")).unwrap();
1391 std::os::unix::fs::symlink(&missing, datadir.join("reth.toml")).unwrap();
1392
1393 clear_existing_datadir(&datadir, None).unwrap();
1394
1395 for entry in ["db", "reth.toml"] {
1396 let err = datadir.join(entry).symlink_metadata().unwrap_err();
1397 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
1398 }
1399 assert_eq!(fs::read(existing.join("data")).unwrap(), b"keep");
1400 assert!(!missing.exists());
1401 }
1402
1403 #[test]
1404 fn managed_snapshot_paths_match_output_types() {
1405 assert!(is_managed_snapshot_path(Path::new("./db/data"), false));
1406 assert!(is_managed_snapshot_path(Path::new("static_files"), true));
1407 assert!(is_managed_snapshot_path(Path::new("reth.toml"), false));
1408 assert!(!is_managed_snapshot_path(Path::new("db"), false));
1409 assert!(!is_managed_snapshot_path(Path::new("reth.toml/settings"), false));
1410 assert!(!is_managed_snapshot_path(Path::new("reth.toml"), true));
1411 assert!(!is_managed_snapshot_path(Path::new("logs/restore.log"), false));
1412 }
1413
1414 #[test]
1415 fn test_download_defaults_builder() {
1416 let defaults = DownloadDefaults::default()
1417 .with_snapshot("https://example.com/snapshots (example)")
1418 .with_base_url("https://example.com");
1419
1420 assert_eq!(defaults.default_base_url, "https://example.com");
1421 assert_eq!(defaults.available_snapshots.len(), 3); }
1423
1424 #[test]
1425 fn test_download_defaults_replace_snapshots() {
1426 let defaults = DownloadDefaults::default().with_snapshots(vec![
1427 Cow::Borrowed("https://custom1.com"),
1428 Cow::Borrowed("https://custom2.com"),
1429 ]);
1430
1431 assert_eq!(defaults.available_snapshots.len(), 2);
1432 assert_eq!(defaults.available_snapshots[0], "https://custom1.com");
1433 }
1434
1435 #[test]
1436 fn test_long_help_generation() {
1437 let defaults = DownloadDefaults::default();
1438 let help = defaults.long_help();
1439
1440 assert!(help.contains("Available snapshot sources:"));
1441 assert!(help.contains("Ethereum mainnet"));
1442 assert!(help.contains("snapshots.reth.rs"));
1443 assert!(help.contains("publicnode.com"));
1444 assert!(help.contains("file://"));
1445 }
1446
1447 #[test]
1448 fn test_custom_snapshot_api_keeps_selected_chain_help() {
1449 let defaults = DownloadDefaults::default()
1450 .with_snapshot_api_url("https://snapshots.tempoxyz.dev/api/snapshots");
1451 let help = defaults.long_help();
1452
1453 assert_eq!(
1454 defaults.default_chain_aware_base_url.as_deref(),
1455 Some("https://snapshots.tempoxyz.dev")
1456 );
1457 assert!(help.contains("Browse available snapshots at https://snapshots.tempoxyz.dev"));
1458 assert!(help.contains("- https://snapshots.tempoxyz.dev (default)"));
1459 assert!(help.contains("selected chain"));
1460 assert!(!help.contains("Ethereum mainnet"));
1461 assert!(!help.contains("snapshots.reth.rs"));
1462 }
1463
1464 #[test]
1465 fn test_snapshot_source_url_sets_generated_references() {
1466 let defaults =
1467 DownloadDefaults::default().with_snapshot_source_url("https://snapshots.tempoxyz.dev/");
1468 let help = defaults.long_help();
1469
1470 assert_eq!(defaults.snapshot_api_url, "https://snapshots.tempoxyz.dev/api/snapshots");
1471 assert_eq!(defaults.default_base_url, "https://snapshots.tempoxyz.dev");
1472 assert_eq!(
1473 defaults.default_chain_aware_base_url.as_deref(),
1474 Some("https://snapshots.tempoxyz.dev")
1475 );
1476 assert_eq!(
1477 defaults.available_snapshots.iter().map(|source| source.as_ref()).collect::<Vec<_>>(),
1478 vec!["https://snapshots.tempoxyz.dev (default)"]
1479 );
1480 assert!(!defaults.mainnet_only_discovery());
1481 assert!(help.contains("Browse available snapshots at https://snapshots.tempoxyz.dev"));
1482 assert!(help.contains("from https://snapshots.tempoxyz.dev."));
1483 }
1484
1485 #[test]
1486 fn test_snapshot_api_url_trailing_slash_sets_source_url() {
1487 let defaults = DownloadDefaults::default()
1488 .with_snapshot_api_url("https://snapshots.tempoxyz.dev/api/snapshots/");
1489 let help = defaults.long_help();
1490
1491 assert_eq!(
1492 defaults.default_chain_aware_base_url.as_deref(),
1493 Some("https://snapshots.tempoxyz.dev")
1494 );
1495 assert!(help.contains("Browse available snapshots at https://snapshots.tempoxyz.dev"));
1496 assert!(help.contains("- https://snapshots.tempoxyz.dev (default)"));
1497 }
1498
1499 #[test]
1500 fn test_long_help_override() {
1501 let custom_help = "This is custom help text for downloading snapshots.";
1502 let defaults = DownloadDefaults::default().with_long_help(custom_help);
1503
1504 let help = defaults.long_help();
1505 assert_eq!(help, custom_help);
1506 assert!(!help.contains("Available snapshot sources:"));
1507 }
1508
1509 #[test]
1510 fn test_builder_chaining() {
1511 let defaults = DownloadDefaults::default()
1512 .with_base_url("https://custom.example.com")
1513 .with_snapshot("https://snapshot1.com")
1514 .with_snapshot("https://snapshot2.com")
1515 .with_long_help("Custom help for snapshots");
1516
1517 assert_eq!(defaults.default_base_url, "https://custom.example.com");
1518 assert_eq!(defaults.available_snapshots.len(), 4); assert_eq!(defaults.long_help, Some("Custom help for snapshots".to_string()));
1520 }
1521
1522 #[test]
1523 fn test_download_prune_unlisted_conflicts_with_force_list_and_url() {
1524 let parse = |args: &[&str]| {
1525 CommandParser::<DownloadCommand<EthereumChainSpecParser>>::try_parse_from(args)
1526 };
1527
1528 assert!(parse(&["reth", "--prune-unlisted"]).unwrap().args.prune_unlisted);
1529 assert!(parse(&["reth", "--prune-unlisted", "--force"]).is_err());
1530 assert!(parse(&["reth", "--prune-unlisted", "--list"]).is_err());
1531 assert!(
1532 parse(&["reth", "--prune-unlisted", "--url", "https://example.com/a.tar.zst"]).is_err()
1533 );
1534 }
1535
1536 #[test]
1537 fn test_download_resumable_defaults_to_true() {
1538 let args =
1539 CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from(["reth"]).args;
1540
1541 assert!(args.resumable);
1542 }
1543
1544 #[test]
1545 fn test_download_resumable_implicit_true() {
1546 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1547 "reth",
1548 "--resumable",
1549 ])
1550 .args;
1551
1552 assert!(args.resumable);
1553 }
1554
1555 #[test]
1556 fn test_download_resumable_explicit_false() {
1557 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1558 "reth",
1559 "--resumable=false",
1560 ])
1561 .args;
1562
1563 assert!(!args.resumable);
1564 }
1565
1566 #[test]
1567 fn test_download_print_plan_json_parses() {
1568 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1569 "reth",
1570 "--manifest-path",
1571 "manifest.json",
1572 "--minimal",
1573 "--print-plan-json",
1574 ])
1575 .args;
1576
1577 assert!(args.prints_plan_json());
1578 }
1579
1580 #[test]
1581 fn test_download_print_plan_json_rejects_single_archive() {
1582 let result = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::try_parse_from([
1583 "reth",
1584 "--url",
1585 "https://example.com/snapshot.tar.zst",
1586 "--print-plan-json",
1587 ]);
1588
1589 assert!(result.is_err());
1590 }
1591
1592 #[test]
1593 fn minimal_component_selection_uses_configured_prune_modes() {
1594 let args =
1595 CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from(["reth"]).args;
1596 let history_distance = 64_864;
1597 let modes = PruneModes {
1598 sender_recovery: Some(PruneMode::Full),
1599 receipts: Some(PruneMode::Distance(128)),
1600 account_history: Some(PruneMode::Distance(history_distance)),
1601 storage_history: Some(PruneMode::Distance(history_distance)),
1602 bodies_history: Some(PruneMode::Distance(history_distance)),
1603 ..Default::default()
1604 };
1605
1606 assert_eq!(
1607 args.pruning_selection_for_component(
1608 SnapshotComponentType::Transactions,
1609 1_000_000,
1610 &modes,
1611 false,
1612 ),
1613 ComponentSelection::Distance(history_distance)
1614 );
1615 assert_eq!(
1616 args.pruning_selection_for_component(
1617 SnapshotComponentType::Receipts,
1618 1_000_000,
1619 &modes,
1620 false,
1621 ),
1622 ComponentSelection::Distance(128)
1623 );
1624 assert_eq!(
1625 args.pruning_selection_for_component(
1626 SnapshotComponentType::AccountChangesets,
1627 1_000_000,
1628 &modes,
1629 false,
1630 ),
1631 ComponentSelection::Distance(history_distance)
1632 );
1633 assert_eq!(
1634 args.pruning_selection_for_component(
1635 SnapshotComponentType::StorageChangesets,
1636 1_000_000,
1637 &modes,
1638 false,
1639 ),
1640 ComponentSelection::Distance(history_distance)
1641 );
1642 assert_eq!(
1643 args.pruning_selection_for_component(
1644 SnapshotComponentType::TransactionSenders,
1645 1_000_000,
1646 &modes,
1647 false,
1648 ),
1649 ComponentSelection::None
1650 );
1651 }
1652
1653 #[test]
1654 fn resolve_manifest_source_requires_explicit_source_for_non_mainnet_defaults() {
1655 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1656 "reth", "--chain", "holesky",
1657 ])
1658 .args;
1659
1660 let err = tokio::runtime::Runtime::new()
1661 .unwrap()
1662 .block_on(args.resolve_manifest_source(HOLESKY.chain.id()))
1663 .unwrap_err();
1664
1665 let message = err.to_string();
1666 assert!(message.contains("only auto-discovered for Ethereum mainnet"));
1667 assert!(message.contains("--manifest-url <URL>"));
1668 assert!(message.contains("-u <SNAPSHOT-URL>"));
1669 }
1670
1671 #[test]
1672 fn resolve_manifest_source_allows_manifest_path_for_non_mainnet_defaults() {
1673 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1674 "reth",
1675 "--chain",
1676 "holesky",
1677 "--manifest-path",
1678 "./manifest.json",
1679 ])
1680 .args;
1681
1682 let source = tokio::runtime::Runtime::new()
1683 .unwrap()
1684 .block_on(args.resolve_manifest_source(HOLESKY.chain.id()))
1685 .unwrap();
1686
1687 assert_eq!(source, "./manifest.json");
1688 }
1689
1690 #[test]
1691 fn test_compression_format_detection() {
1692 assert!(matches!(
1693 CompressionFormat::from_url("https://example.com/snapshot.tar.lz4"),
1694 Ok(CompressionFormat::Lz4)
1695 ));
1696 assert!(matches!(
1697 CompressionFormat::from_url("https://example.com/snapshot.tar.zst"),
1698 Ok(CompressionFormat::Zstd)
1699 ));
1700 assert!(matches!(
1701 CompressionFormat::from_url("file:///path/to/snapshot.tar.lz4"),
1702 Ok(CompressionFormat::Lz4)
1703 ));
1704 assert!(matches!(
1705 CompressionFormat::from_url("file:///path/to/snapshot.tar.zst"),
1706 Ok(CompressionFormat::Zstd)
1707 ));
1708 assert!(CompressionFormat::from_url("https://example.com/snapshot.tar.gz").is_err());
1709 }
1710
1711 #[test]
1712 fn inject_archive_only_components_for_archive_selection() {
1713 let manifest = manifest_with_archive_only_components();
1714 let mut selections = BTreeMap::new();
1715 selections.insert(SnapshotComponentType::Transactions, ComponentSelection::All);
1716 selections.insert(SnapshotComponentType::Receipts, ComponentSelection::All);
1717 selections.insert(SnapshotComponentType::AccountChangesets, ComponentSelection::All);
1718 selections.insert(SnapshotComponentType::StorageChangesets, ComponentSelection::All);
1719
1720 inject_archive_only_components(&mut selections, &manifest, true);
1721
1722 assert_eq!(
1723 selections.get(&SnapshotComponentType::TransactionSenders),
1724 Some(&ComponentSelection::All)
1725 );
1726 assert_eq!(
1727 selections.get(&SnapshotComponentType::RocksdbIndices),
1728 Some(&ComponentSelection::All)
1729 );
1730 }
1731
1732 #[test]
1733 fn inject_archive_only_components_without_rocksdb() {
1734 let manifest = manifest_with_archive_only_components();
1735 let mut selections = BTreeMap::new();
1736 selections.insert(SnapshotComponentType::Transactions, ComponentSelection::All);
1737 selections.insert(SnapshotComponentType::Receipts, ComponentSelection::All);
1738 selections.insert(SnapshotComponentType::AccountChangesets, ComponentSelection::All);
1739 selections.insert(SnapshotComponentType::StorageChangesets, ComponentSelection::All);
1740
1741 inject_archive_only_components(&mut selections, &manifest, false);
1742
1743 assert_eq!(
1744 selections.get(&SnapshotComponentType::TransactionSenders),
1745 Some(&ComponentSelection::All)
1746 );
1747 assert_eq!(selections.get(&SnapshotComponentType::RocksdbIndices), None);
1748 }
1749
1750 #[test]
1751 fn inject_rocksdb_indices_keeps_index_stages() {
1752 let manifest = manifest_with_archive_only_components();
1753 let mut selections = BTreeMap::new();
1754 selections
1755 .insert(SnapshotComponentType::AccountChangesets, ComponentSelection::Distance(10));
1756
1757 inject_rocksdb_indices(&mut selections, &manifest);
1758
1759 assert_eq!(
1760 selections.get(&SnapshotComponentType::RocksdbIndices),
1761 Some(&ComponentSelection::All)
1762 );
1763 assert_eq!(selections.get(&SnapshotComponentType::TransactionSenders), None);
1764 }
1765
1766 #[test]
1767 fn inject_rocksdb_indices_skips_manifest_without_indices() {
1768 let mut manifest = manifest_with_archive_only_components();
1769 manifest.components.clear();
1770 let mut selections = BTreeMap::new();
1771
1772 inject_rocksdb_indices(&mut selections, &manifest);
1773
1774 assert!(selections.is_empty());
1775 }
1776
1777 #[test]
1778 fn startup_node_command_omits_default_chain_arg() {
1779 let command =
1780 startup_node_command_for_binary::<EthereumChainSpecParser>("reth", MAINNET.as_ref());
1781
1782 assert_eq!(command, "reth node");
1783 }
1784
1785 #[test]
1786 fn startup_node_command_includes_non_default_chain_arg() {
1787 let command =
1788 startup_node_command_for_binary::<EthereumChainSpecParser>("reth", HOLESKY.as_ref());
1789
1790 assert_eq!(command, "reth node --chain holesky");
1791 }
1792
1793 #[test]
1794 fn startup_node_command_uses_running_binary_name() {
1795 let command =
1796 startup_node_command_for_binary::<EthereumChainSpecParser>("tempo", HOLESKY.as_ref());
1797
1798 assert_eq!(command, "tempo node --chain holesky");
1799 }
1800
1801 #[test]
1802 fn startup_node_command_includes_config() {
1803 let command = startup_node_command::<EthereumChainSpecParser>(
1804 MAINNET.as_ref(),
1805 Some(Path::new("node configs/mainnet.toml")),
1806 );
1807 assert_eq!(
1808 command,
1809 format!("{} node --config 'node configs/mainnet.toml'", current_binary_name())
1810 );
1811 }
1812
1813 #[test]
1814 fn download_command_uses_binary_name() {
1815 assert_eq!(download_command_for_binary("tempo"), "tempo download");
1816 }
1817
1818 #[tokio::test]
1819 async fn restore_rejects_incompatible_layout_at_finalization() -> Result<()> {
1820 let source = tempdir()?;
1821 snapshot_db(&source)?.update(|tx| {
1822 set_layout(tx, serde_json::json!({"account_changesets_in_static_files": true}));
1823 })?;
1824 let error = restore_history(&source, "--archive", None).await.unwrap_err();
1825 assert_eq!(error.to_string(), "Unsupported legacy snapshot setting for this download: account_changesets_in_static_files=true");
1826 Ok(())
1827 }
1828
1829 #[tokio::test]
1830 async fn test_download_explicit_source_and_datadir_allow_other_chains() {
1831 let dir = tempfile::tempdir().unwrap();
1832 let manifest_path = dir.path().join("manifest.json");
1833 let mut manifest = manifest_with_archive_only_components();
1834 manifest.chain_id = 42431;
1835 fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
1836 let manifest_url = format!("file://{}", manifest_path.display());
1837 let target = dir.path().join("download");
1838
1839 for source in ["--manifest-url", "--manifest-path"] {
1840 let location = if source == "--manifest-url" {
1841 manifest_url.as_str()
1842 } else {
1843 manifest_path.to_str().unwrap()
1844 };
1845 for selection in ["--archive", "--minimal", "--non-interactive", "--with-txs"] {
1846 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1847 "reth",
1848 source,
1849 location,
1850 "--datadir",
1851 target.to_str().unwrap(),
1852 selection,
1853 ])
1854 .args;
1855 let (plan, prepared) = args.plan().await.unwrap();
1856 assert_eq!(plan.chain_id, 42431);
1857 assert_eq!(prepared.manifest.chain_id, 42431);
1858 assert_eq!(prepared.data_dir, target);
1859 assert!(!target.exists());
1860 }
1861 }
1862 }
1863
1864 #[tokio::test]
1865 async fn test_download_chain_derived_datadir_rejects_other_chains() {
1866 let dir = tempfile::tempdir().unwrap();
1867 let manifest_path = dir.path().join("manifest.json");
1868 let mut manifest = manifest_with_archive_only_components();
1869 manifest.chain_id = 42431;
1870 fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
1871
1872 for datadir in [vec![], vec!["--datadir", "default"]] {
1873 let mut cli_args =
1874 vec!["reth", "--manifest-path", manifest_path.to_str().unwrap(), "--archive"];
1875 cli_args.extend(datadir);
1876 let args =
1877 CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from(cli_args)
1878 .args;
1879 assert_eq!(
1880 args.plan().await.unwrap_err().to_string(),
1881 "Snapshot chain ID 42431 does not match selected chain ID 1"
1882 );
1883 }
1884 }
1885
1886 #[test]
1887 fn test_download_full_chain_derived_pruning_rejects_other_chains() {
1888 let args = CommandParser::<DownloadCommand<EthereumChainSpecParser>>::parse_from([
1889 "reth",
1890 "--datadir",
1891 "download",
1892 "--manifest-url",
1893 "https://example.com/manifest.json",
1894 "--full",
1895 ])
1896 .args;
1897 let mut manifest = manifest_with_archive_only_components();
1898 manifest.chain_id = 42431;
1899 assert_eq!(
1900 args.full_preset_selections(&manifest).unwrap_err().to_string(),
1901 "Snapshot chain ID 42431 does not match selected chain ID 1"
1902 );
1903 manifest.chain_id = 1;
1904 assert!(args.full_preset_selections(&manifest).is_ok());
1905 }
1906
1907 const SNAPSHOT_TIP: u64 = 10;
1908
1909 const INDEX_STAGES: [StageId; 3] =
1910 [StageId::TransactionLookup, StageId::IndexAccountHistory, StageId::IndexStorageHistory];
1911
1912 const SOURCE_BOUNDARY: PruneCheckpoint = PruneCheckpoint::pruned_through(3);
1913 const SOURCE_HISTORY: PruneCheckpoint =
1914 PruneCheckpoint { prune_mode: PruneMode::Distance(30_000), ..SOURCE_BOUNDARY };
1915
1916 fn snapshot_db(dir: &TempDir) -> Result<DatabaseEnv> {
1917 init_db(dir.path().join("db"), DatabaseArguments::test())
1918 }
1919
1920 pub(super) fn history_checkpoints(tx: &impl DbTx) -> Result<[Option<PruneCheckpoint>; 2]> {
1921 Ok([
1922 tx.get::<tables::PruneCheckpoints>(PruneSegment::AccountHistory)?,
1923 tx.get::<tables::PruneCheckpoints>(PruneSegment::StorageHistory)?,
1924 ])
1925 }
1926
1927 pub(super) fn set_history_checkpoints(
1928 tx: &impl DbTxMut,
1929 account: PruneCheckpoint,
1930 storage: PruneCheckpoint,
1931 ) {
1932 tx.put::<tables::PruneCheckpoints>(PruneSegment::AccountHistory, account).unwrap();
1933 tx.put::<tables::PruneCheckpoints>(PruneSegment::StorageHistory, storage).unwrap();
1934 }
1935
1936 async fn restore_history(
1937 source: &TempDir,
1938 flag: &str,
1939 expected_mode: Option<PruneMode>,
1940 ) -> Result<TempDir> {
1941 let target = tempdir()?;
1942 restore_snapshot(source, &target, SNAPSHOT_TIP, &[flag]).await?;
1943 let modes = Config::from_path(target.path().join("reth.toml"))?.prune.segments;
1944 assert_eq!(modes.account_history, expected_mode);
1945 assert_eq!(modes.storage_history, expected_mode);
1946 Ok(target)
1947 }
1948
1949 async fn restore_snapshot(
1950 source: &TempDir,
1951 target: &TempDir,
1952 tip: u64,
1953 flags: &[&str],
1954 ) -> Result<()> {
1955 let archives = tempdir()?;
1956 let output = archives.path();
1957 let manifest = generate_manifest(source.path(), output, None, tip, 1, 10, None, false)?;
1958 let path = output.join("manifest.json");
1959 fs::write(&path, serde_json::to_vec(&manifest)?)?;
1960 let args = [
1961 "reth",
1962 "--manifest-path",
1963 path.to_str().unwrap(),
1964 "--datadir",
1965 target.path().to_str().unwrap(),
1966 ];
1967 DownloadCommand::<EthereumChainSpecParser>::parse_from(args.iter().chain(flags))
1968 .execute::<MockNodeTypes>()
1969 .await?;
1970 Ok(())
1971 }
1972
1973 #[tokio::test]
1974 async fn restore_bundled_v1_history() -> Result<()> {
1975 for (setting, flag, mode) in [
1976 ("receipts_in_static_files", "--with-state-history", None),
1977 (
1978 "transaction_senders_in_static_files",
1979 "--minimal",
1980 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE)),
1981 ),
1982 ] {
1983 let source = tempdir()?;
1984 let indexed = StageCheckpoint::new(SNAPSHOT_TIP);
1985 {
1986 let db = snapshot_db(&source)?;
1987 let tx = db.tx_mut()?;
1988 set_layout(&tx, serde_json::json!({(setting): true}));
1990 for stage in INDEX_STAGES {
1991 tx.put::<tables::StageCheckpoints>(stage.to_string(), indexed)?;
1992 tx.put::<tables::StageCheckpointProgresses>(stage.to_string(), vec![1, 2, 3])?;
1993 }
1994 for segment in [PruneSegment::StorageHistory, PruneSegment::TransactionLookup] {
1995 tx.put::<tables::PruneCheckpoints>(segment, SOURCE_HISTORY)?;
1996 }
1997 tx.commit()?;
1998 }
1999 let target = restore_history(&source, flag, mode).await?;
2000 let db = snapshot_db(&target)?;
2001 let tx = db.tx()?;
2002 assert_eq!(history_checkpoints(&tx)?, [None, Some(SOURCE_HISTORY)]);
2003 assert_eq!(
2004 tx.get::<tables::PruneCheckpoints>(PruneSegment::TransactionLookup)?,
2005 Some(SOURCE_HISTORY)
2006 );
2007 for stage in INDEX_STAGES {
2008 assert_eq!(tx.get::<tables::StageCheckpoints>(stage.to_string())?, Some(indexed));
2009 assert_eq!(
2010 tx.get::<tables::StageCheckpointProgresses>(stage.to_string())?,
2011 Some(vec![1, 2, 3])
2012 );
2013 }
2014 }
2015 Ok(())
2016 }
2017
2018 #[tokio::test]
2019 async fn future_history_keeps_v1_checkpoint_progress() -> Result<()> {
2020 let source = tempdir()?;
2021 let interrupted = PruneCheckpoint {
2022 block_number: Some(4),
2023 tx_number: None,
2024 prune_mode: PruneMode::Before(SNAPSHOT_TIP),
2025 };
2026 let unstarted = PruneCheckpoint { block_number: None, ..SOURCE_HISTORY };
2027 snapshot_db(&source)?.update(|tx| set_history_checkpoints(tx, interrupted, unstarted))?;
2028 let mode = PruneMode::Before(20);
2029 let target = restore_history(&source, "--with-state-history-since=20", Some(mode)).await?;
2030 assert_eq!(
2031 history_checkpoints(&snapshot_db(&target)?.tx()?)?,
2032 [Some(interrupted), Some(unstarted)]
2033 );
2034 Ok(())
2035 }
2036
2037 #[tokio::test]
2038 async fn restore_v2_history_uses_selected_range_and_retention() -> Result<()> {
2039 let source = tempdir()?;
2040 snapshot_db(&source)?.update(|tx| {
2041 set_layout(tx, StorageSettings::v2());
2042 set_history_checkpoints(tx, SOURCE_HISTORY, SOURCE_HISTORY);
2043 })?;
2044 for segment in [StaticFileSegment::AccountChangeSets, StaticFileSegment::StorageChangeSets]
2045 {
2046 manifest::tests::write_test_static_files(source.path(), segment, SNAPSHOT_TIP);
2047 }
2048 let future = PruneMode::Before(20);
2049 let tip = PruneCheckpoint::pruned_through(SNAPSHOT_TIP);
2050 for (flag, mode, checkpoint, segment_count) in [
2051 (
2052 "--with-state-history-since=20",
2053 Some(future),
2054 PruneCheckpoint { prune_mode: future, ..tip },
2055 0,
2056 ),
2057 ("--with-state-history", None, SOURCE_BOUNDARY, 2),
2058 ] {
2059 let target = restore_history(&source, flag, mode).await?;
2060 let files = iter_static_files(&target.path().join("static_files"))?;
2061 assert_eq!(
2062 files.keys().filter(|segment| segment.is_change_based()).count(),
2063 segment_count,
2064 "{flag}"
2065 );
2066 let db = snapshot_db(&target)?;
2067 let tx = db.tx()?;
2068 assert_eq!(history_checkpoints(&tx)?, [Some(checkpoint); 2]);
2069 }
2070 Ok(())
2071 }
2072
2073 #[tokio::test]
2074 async fn restore_v2_without_history_or_indices() -> Result<()> {
2075 let source = tempdir()?;
2076 let indexed = StageCheckpoint::new(SNAPSHOT_TIP);
2077 let tip = PruneCheckpoint::pruned_through(SNAPSHOT_TIP);
2078 let source_prune = PruneCheckpoint { prune_mode: PruneMode::Full, ..tip };
2079 {
2080 let db = snapshot_db(&source)?;
2081 let tx = db.tx_mut()?;
2082 set_layout(&tx, StorageSettings::v2());
2083 for stage in INDEX_STAGES.into_iter().chain([StageId::SenderRecovery]) {
2084 tx.put::<tables::StageCheckpoints>(stage.to_string(), indexed)?;
2085 }
2086 for segment in [PruneSegment::TransactionLookup, PruneSegment::SenderRecovery] {
2087 tx.put::<tables::PruneCheckpoints>(segment, source_prune)?;
2088 }
2089 tx.commit()?;
2090 }
2091 let target = restore_history(&source, "--with-state-history", None).await?;
2092 let db = snapshot_db(&target)?;
2093 let tx = db.tx()?;
2094 assert_eq!(history_checkpoints(&tx)?, [Some(tip); 2]);
2095 for stage in INDEX_STAGES {
2096 assert_eq!(
2097 tx.get::<tables::StageCheckpoints>(stage.to_string())?,
2098 Some(StageCheckpoint::default()),
2099 "{stage}"
2100 );
2101 }
2102 assert_eq!(tx.get::<tables::PruneCheckpoints>(PruneSegment::TransactionLookup)?, None);
2103 assert_eq!(
2104 tx.get::<tables::StageCheckpoints>(StageId::SenderRecovery.to_string())?,
2105 Some(indexed)
2106 );
2107 assert_eq!(
2108 tx.get::<tables::PruneCheckpoints>(PruneSegment::SenderRecovery)?,
2109 Some(source_prune)
2110 );
2111 Ok(())
2112 }
2113
2114 pub(super) fn snapshot_source(bodies: Option<RangeInclusive<u64>>) -> Result<TempDir> {
2115 let source = tempdir()?;
2116 snapshot_db(&source)?;
2117 let Some(bodies) = bodies else { return Ok(source) };
2118 let (start, tip) = bodies.into_inner();
2119 let provider = StaticFileProviderBuilder::read_write(source.path().join("static_files"))
2120 .with_blocks_per_file(10)
2121 .build::<<MockNodeTypes as NodeTypes>::Primitives>()?;
2122 let mut writer = provider.get_writer(start, StaticFileSegment::Transactions)?;
2123 writer.initialize_pruned_anchor(start)?;
2124 writer.ensure_at_block(tip)?;
2125 writer.commit()?;
2126 Ok(source)
2127 }
2128
2129 fn bodies_checkpoint(target: &TempDir) -> Result<Option<PruneCheckpoint>> {
2130 Ok(snapshot_db(target)?.tx()?.get::<tables::PruneCheckpoints>(PruneSegment::Bodies)?)
2131 }
2132
2133 fn open_snapshot(dir: &TempDir) -> Result<ProviderFactory<MockNodeTypesWithDB<DatabaseEnv>>> {
2134 Ok(ProviderFactory::new(
2135 snapshot_db(dir)?,
2136 MAINNET.clone(),
2137 StaticFileProviderBuilder::read_write(dir.path().join("static_files"))
2138 .with_blocks_per_file(10)
2139 .build()?,
2140 RocksDBProvider::builder(dir.path().join("rocksdb")).with_default_tables().build()?,
2141 Default::default(),
2142 reth_tasks::Runtime::test(),
2143 )?)
2144 }
2145
2146 fn source_with_transactions() -> Result<TempDir> {
2147 let source = tempdir()?;
2148 {
2149 let factory = open_snapshot(&source)?;
2150 let provider = factory.provider_rw()?;
2151 for number in 0..=24 {
2152 let mut block =
2153 Block { header: Header { number, ..Default::default() }, ..Default::default() };
2154 let tx = TxLegacy { nonce: number, ..Default::default() };
2155 block.body.transactions.push(tx.into_signed(Signature::test_signature()).into());
2156 provider.insert_block(&block.try_into_recovered()?)?;
2157 }
2158 provider.commit()?;
2159 }
2160 Ok(source)
2161 }
2162
2163 #[tokio::test]
2164 async fn retry_repairs_repackaged_transaction_history() -> Result<()> {
2165 let source = source_with_transactions()?;
2166 let old_tip = PruneCheckpoint {
2167 block_number: Some(15),
2168 tx_number: Some(15),
2169 prune_mode: PruneMode::Before(13),
2170 };
2171 snapshot_db(&source)?.update(|tx| {
2172 tx.put::<tables::PruneCheckpoints>(
2173 PruneSegment::Bodies,
2174 PruneCheckpoint { block_number: Some(24), tx_number: Some(24), ..old_tip },
2175 )
2176 .unwrap();
2177 tx.put::<tables::PruneCheckpoints>(
2178 PruneSegment::SenderRecovery,
2179 PruneCheckpoint { prune_mode: PruneMode::Full, ..old_tip },
2180 )
2181 .unwrap();
2182 })?;
2183 let target = tempdir()?;
2184 restore_snapshot(&source, &target, 24, &["--with-txs-since=21"]).await?;
2185 let mode = PruneMode::Before(21);
2186 assert_eq!(
2187 bodies_checkpoint(&target)?,
2188 Some(PruneCheckpoint { block_number: Some(19), tx_number: Some(19), prune_mode: mode })
2189 );
2190 let header = target.path().join("static_files/static_file_transactions_20_29.conf");
2191 let expected = fs::read(&header)?;
2192 let mut corrupt = expected.clone();
2193 corrupt[0] ^= 1;
2194 fs::write(&header, corrupt)?;
2195
2196 snapshot_db(&source)?
2198 .update(|tx| tx.put::<tables::PruneCheckpoints>(PruneSegment::Bodies, old_tip))??;
2199 restore_snapshot(&source, &target, 24, &["--with-txs-since=13"]).await?;
2200 assert_eq!(fs::read(header)?, expected);
2201 let factory = open_snapshot(&target)?;
2202 let mode = PruneMode::Before(13);
2203 assert_eq!(
2204 factory.get_prune_checkpoint(PruneSegment::Bodies)?,
2205 Some(PruneCheckpoint { block_number: Some(9), tx_number: Some(9), prune_mode: mode })
2206 );
2207 assert_eq!(factory.earliest_block_number()?, 10);
2208 Ok(())
2209 }
2210
2211 #[tokio::test]
2212 async fn restored_bodies_survive_pruning_and_reopen() -> Result<()> {
2213 let source = source_with_transactions()?;
2214 let target = tempdir()?;
2215 restore_snapshot(&source, &target, 24, &["--with-txs"]).await?;
2216 assert_eq!(bodies_checkpoint(&target)?, None);
2217 restore_snapshot(&source, &target, 24, &["--with-txs-since=21"]).await?;
2218 let files = target.path().join("static_files");
2219 for ext in ["", CONFIG_FILE_EXTENSION, OFFSETS_FILE_EXTENSION] {
2220 fs::remove_file(files.join("static_file_transactions_10_19").with_extension(ext))?;
2221 }
2222 let factory = open_snapshot(&target)?;
2223 let mode = PruneMode::Before(20);
2224 PrunerBuilder::default()
2225 .segments(PruneModes { bodies_history: Some(mode), ..Default::default() })
2226 .build_with_provider_factory(factory)
2227 .with_minimum_pruning_distance(0)
2228 .run(24)?;
2229 assert!(!files.join("static_file_transactions_0_9").exists());
2230 let factory = open_snapshot(&target)?;
2231 let advertised = factory
2232 .get_prune_checkpoints_for_availability()?
2233 .into_iter()
2234 .find(|(segment, _)| *segment == PruneSegment::Bodies)
2235 .unwrap()
2236 .1;
2237 assert_eq!(
2238 advertised,
2239 PruneCheckpoint { block_number: Some(19), tx_number: Some(19), prune_mode: mode }
2240 );
2241 assert_eq!(factory.earliest_block_number()?, 20);
2242 assert!(matches!(
2243 factory.block(19.into()),
2244 Err(ProviderError::BlockExpired { requested: 19, earliest_available: 20 })
2245 ));
2246 assert_eq!(factory.block(20.into())?.unwrap().body.transactions.len(), 1);
2247 drop(factory);
2248
2249 let repackaged = tempdir()?;
2250 restore_snapshot(&target, &repackaged, 24, &["--with-txs"]).await?;
2251 let factory = open_snapshot(&repackaged)?;
2252 assert_eq!(factory.earliest_block_number()?, 20);
2253 let progress = factory.get_prune_checkpoint(PruneSegment::Bodies)?.unwrap();
2254 assert_eq!((progress.block_number, progress.tx_number), (Some(19), Some(19)));
2255 assert_eq!(factory.block(20.into())?.unwrap().body.transactions.len(), 1);
2256 Ok(())
2257 }
2258
2259 #[tokio::test]
2260 async fn restore_transaction_bodies_and_retention() -> Result<()> {
2261 for (bodies, boundary) in [(Some(3..=3), 2), (None, 3)] {
2262 let source = snapshot_source(bodies)?;
2263 let target = tempdir()?;
2264 let files = tempdir()?;
2265 let flags = ["--with-txs", "--datadir.static-files", files.path().to_str().unwrap()];
2266 restore_snapshot(&source, &target, 3, &flags).await?;
2267 let config = Config::from_path(target.path().join("reth.toml"))?;
2268 assert_eq!(config.prune.segments.bodies_history, None);
2269 assert_eq!(
2270 bodies_checkpoint(&target)?,
2271 Some(PruneCheckpoint::pruned_through(boundary))
2272 );
2273 }
2274 Ok(())
2275 }
2276
2277 #[tokio::test]
2278 async fn restore_uses_explicit_config_for_bodies() -> Result<()> {
2279 let source = snapshot_source(None)?;
2280 let target = tempdir()?;
2281 fs::write(target.path().join("reth.toml"), "[invalid")?;
2282 let path = target.path().join("configs/custom.toml");
2283 let restore = async |flags: &[&str]| restore_snapshot(&source, &target, 24, flags).await;
2284 let mode = PruneMode::Distance(30000);
2285 let expected =
2286 Some(PruneCheckpoint { prune_mode: mode, ..PruneCheckpoint::pruned_through(24) });
2287 restore(&["--config", path.to_str().unwrap(), "--with-txs-distance=30000"]).await?;
2288 assert_eq!(Config::from_path(&path)?.prune.segments.bodies_history, Some(mode));
2289 assert_eq!(bodies_checkpoint(&target)?, expected);
2290
2291 let subdir = target.path().join("db/subdir");
2293 fs::create_dir_all(&subdir)?;
2294 let alias = subdir.join("../../configs/custom.toml");
2295 let alias = alias.to_str().unwrap();
2296 let marker = target.path().join("static_files/local");
2297 fs::write(&marker, "local")?;
2298 fs::write(&path, "[invalid")?;
2299 let error = Config::from_path(&path).unwrap_err().to_string();
2300 assert_eq!(
2301 restore(&["--force", "--minimal", "--config", alias]).await.unwrap_err().to_string(),
2302 error
2303 );
2304 assert_eq!(fs::read_to_string(&marker)?, "local");
2305
2306 let flags = ["--prune-unlisted", "--minimal", "--config", alias];
2307 fs::write(&path, "[static_files.blocks_per_file]\ntransactions = 0")?;
2308 assert_eq!(
2309 restore(&flags).await.unwrap_err().to_string(),
2310 "Transactions segment blocks per file must be greater than 0"
2311 );
2312 assert_eq!(fs::read_to_string(&marker)?, "local");
2313
2314 fs::write(&path, "[prune.segments]\nbodies_history = { distance = 30000 }\n[static_files.blocks_per_file]\ntransactions = 10\n")?;
2315 restore(&flags).await?;
2316 assert!(target.path().join("static_files/static_file_transactions_20_29").exists());
2317 let mode = PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE);
2319 assert_eq!(
2320 bodies_checkpoint(&target)?,
2321 Some(PruneCheckpoint { prune_mode: mode, ..PruneCheckpoint::pruned_through(24) })
2322 );
2323 assert!(!subdir.exists());
2324 Ok(())
2325 }
2326
2327 #[tokio::test]
2328 async fn restore_rejects_a_requested_range_past_the_transaction_files() -> Result<()> {
2329 let source = snapshot_source(Some(0..=19))?;
2330 let target = tempdir()?;
2331 let marker = target.path().join("reth.toml");
2332 fs::write(&marker, "# retained")?;
2333 let err = restore_snapshot(&source, &target, 24, &["--with-txs-since=21", "--force"])
2334 .await
2335 .unwrap_err();
2336 assert_eq!(err.to_string(), "Selected transaction files do not cover snapshot block 24");
2337 assert_eq!(fs::read_to_string(marker)?, "# retained");
2338 Ok(())
2339 }
2340
2341 #[tokio::test]
2342 async fn retry_advances_an_empty_transaction_anchor() -> Result<()> {
2343 let source = snapshot_source(None)?;
2344 let target = tempdir()?;
2345 let segment = StaticFileSegment::Transactions;
2346 let open = || {
2347 StaticFileProviderBuilder::read_write(target.path().join("static_files"))
2348 .build::<<MockNodeTypes as NodeTypes>::Primitives>()
2349 };
2350 let restore =
2351 async |tip, flags: &[&str]| restore_snapshot(&source, &target, tip, flags).await;
2352 let check_anchor = |tip| -> Result<()> {
2353 let provider = open()?;
2354 assert_eq!(provider.get_highest_static_file_block(segment), Some(tip));
2355 assert_eq!(provider.get_highest_static_file_tx(segment), None);
2356 assert_eq!(provider.latest_writer(segment)?.next_block_number(), tip + 1);
2357 Ok(())
2358 };
2359 for tip in [21, 24] {
2360 restore(tip, &["--with-txs-since=30"]).await?;
2361 check_anchor(tip)?;
2362 }
2363 {
2364 let provider = open()?;
2365 let mut writer = provider.latest_writer(segment)?;
2366 writer.increment_block(25)?;
2367 writer.append_transaction(
2368 0,
2369 &TxLegacy::default().into_signed(Signature::test_signature()).into(),
2370 )?;
2371 writer.commit()?;
2372 }
2373 restore(25, &["--with-txs-since=30"]).await?;
2374 let err = restore(26, &["--with-txs-since=30"]).await.unwrap_err();
2375 assert_eq!(err.to_string(), "Local transaction files end before the snapshot tip; use --prune-unlisted to remove unselected files");
2376 assert_eq!(open()?.latest_writer(segment)?.user_header().tx_len(), Some(1));
2377 restore(26, &["--with-txs-since=30", "--prune-unlisted"]).await?;
2378 check_anchor(26)
2379 }
2380
2381 #[tokio::test]
2382 async fn restore_rejects_incomplete_transaction_jar() -> Result<()> {
2383 for extension in ["", CONFIG_FILE_EXTENSION, OFFSETS_FILE_EXTENSION] {
2384 let source = snapshot_source(Some(0..=24))?;
2385 let missing =
2386 Path::new("static_files/static_file_transactions_10_19").with_extension(extension);
2387 fs::remove_file(source.path().join(&missing))?;
2388
2389 let target = tempdir()?;
2390 let err =
2391 restore_snapshot(&source, &target, 24, &["--with-txs-since=13"]).await.unwrap_err();
2392 assert_eq!(
2393 err.to_string(),
2394 format!("Incomplete transaction static file: missing {}", missing.display())
2395 );
2396 assert!(!target.path().join("db").exists());
2397 }
2398 Ok(())
2399 }
2400
2401 #[tokio::test]
2402 async fn minimal_restore_with_existing_archive_config() -> Result<()> {
2403 let source = tempdir()?;
2404 snapshot_db(&source)?.update(|tx| set_layout(tx, StorageSettings::v2()))?;
2405 let target = tempdir()?;
2406 let config_path = target.path().join("reth.toml");
2407 let archive_config = "[prune.segments]\n";
2408 fs::write(&config_path, archive_config)?;
2409
2410 restore_snapshot(&source, &target, SNAPSHOT_TIP, &["--minimal"]).await?;
2411
2412 assert_eq!(fs::read_to_string(config_path)?, archive_config);
2413 let db = snapshot_db(&target)?;
2414 let tx = db.tx()?;
2415 for (segment, prune_mode) in [
2416 (PruneSegment::SenderRecovery, PruneMode::Full),
2417 (PruneSegment::Bodies, PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE)),
2418 ] {
2419 assert_eq!(
2420 tx.get::<tables::PruneCheckpoints>(segment)?,
2421 Some(PruneCheckpoint {
2422 prune_mode,
2423 ..PruneCheckpoint::pruned_through(SNAPSHOT_TIP)
2424 }),
2425 "{segment}"
2426 );
2427 }
2428 Ok(())
2429 }
2430
2431 pub(super) fn set_layout(tx: &impl DbTxMut, settings: impl serde::Serialize) {
2432 let bytes = serde_json::to_vec(&settings).unwrap();
2433 tx.put::<tables::Metadata>(keys::STORAGE_SETTINGS.to_owned(), bytes).unwrap();
2434 }
2435}