Skip to main content

reth_cli_commands/download/
planning.rs

1use super::{
2    is_managed_snapshot_path, managed_datadir_path, manifest::*, verify::OutputVerifier,
3    MANAGED_DATADIR_PATHS,
4};
5use eyre::Result;
6use reth_concurrency::sync::rayon::prelude::*;
7use reth_config::config::Config;
8use reth_db::static_file::{
9    last_missing_block, read_static_file_header, CONFIG_FILE_EXTENSION, OFFSETS_FILE_EXTENSION,
10};
11use reth_static_file_types::StaticFileSegment;
12use serde::Serialize;
13use std::{
14    collections::{BTreeMap, HashSet},
15    io::Write,
16    path::{Path, PathBuf},
17};
18use tracing::info;
19
20/// Machine-readable description of the archives selected for a modular snapshot download.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22#[serde(rename_all = "camelCase")]
23pub struct DownloadPlan {
24    /// Version of this JSON schema.
25    pub schema_version: u8,
26    /// Chain ID declared by the snapshot manifest.
27    pub chain_id: u64,
28    /// Block declared by the snapshot manifest.
29    pub block: u64,
30    /// Total compressed bytes for all selected archives.
31    pub total_download_size: u64,
32    /// Total extracted bytes for all selected archives.
33    pub total_output_size: u64,
34    /// Archives selected by the command's component and range flags.
35    pub archives: Vec<DownloadPlanArchive>,
36}
37
38impl DownloadPlan {
39    const SCHEMA_VERSION: u8 = 1;
40
41    pub(crate) fn from_planned(manifest: &SnapshotManifest, planned: &PlannedDownloads) -> Self {
42        Self {
43            schema_version: Self::SCHEMA_VERSION,
44            chain_id: manifest.chain_id,
45            block: manifest.block,
46            total_download_size: planned.total_download_size,
47            total_output_size: planned.total_output_size,
48            archives: planned.archives.iter().map(DownloadPlanArchive::from_planned).collect(),
49        }
50    }
51
52    /// Adds an archive supplied by a command that extends the base Reth snapshot format.
53    pub fn push_archive(&mut self, archive: DownloadPlanArchive) {
54        self.total_download_size = self.total_download_size.saturating_add(archive.download_size);
55        self.total_output_size = self.total_output_size.saturating_add(archive.output_size);
56        self.archives.push(archive);
57    }
58
59    /// Writes the plan as pretty-printed JSON followed by a newline.
60    pub fn write_json(&self, mut writer: impl Write) -> Result<()> {
61        serde_json::to_writer_pretty(&mut writer, self)?;
62        writeln!(writer)?;
63        Ok(())
64    }
65}
66
67/// One concrete archive in a [`DownloadPlan`].
68#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
69#[serde(rename_all = "camelCase")]
70pub struct DownloadPlanArchive {
71    /// Stable manifest component key, such as `state` or `transactions`.
72    pub component: String,
73    /// Archive file name relative to the manifest's base URL.
74    pub file_name: String,
75    /// Resolved archive source URL.
76    pub url: String,
77    /// Compressed bytes fetched for this archive.
78    pub download_size: u64,
79    /// Extracted bytes produced by this archive.
80    pub output_size: u64,
81    /// Optional checksum of the compressed archive.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub blake3: Option<String>,
84}
85
86impl DownloadPlanArchive {
87    /// Creates an archive entry for a download-command extension.
88    pub fn new(
89        component: impl Into<String>,
90        file_name: impl Into<String>,
91        url: impl Into<String>,
92        download_size: u64,
93        output_size: u64,
94        blake3: Option<String>,
95    ) -> Self {
96        Self {
97            component: component.into(),
98            file_name: file_name.into(),
99            url: url.into(),
100            download_size,
101            output_size,
102            blake3,
103        }
104    }
105
106    fn from_planned(planned: &PlannedArchive) -> Self {
107        Self::new(
108            planned.ty.key(),
109            planned.archive.file_name.clone(),
110            planned.archive.url.clone(),
111            planned.archive.size.unwrap_or_default(),
112            planned.archive.output_size(),
113            planned.archive.blake3.clone(),
114        )
115    }
116}
117
118/// One archive selected from the manifest, along with its component name.
119#[derive(Debug, Clone)]
120pub(crate) struct PlannedArchive {
121    /// Snapshot component type this archive belongs to.
122    pub(crate) ty: SnapshotComponentType,
123    /// User-facing component name used in logs.
124    pub(crate) component: String,
125    /// Concrete snapshot archive metadata resolved from the manifest.
126    pub(crate) archive: SnapshotArchive,
127}
128
129/// The archive list for a modular snapshot download.
130#[derive(Debug)]
131pub(crate) struct PlannedDownloads {
132    /// Concrete archives that still need reuse checks or processing.
133    pub(crate) archives: Vec<PlannedArchive>,
134    /// Total compressed download size of all planned archives.
135    pub(crate) total_download_size: u64,
136    /// Total extracted plain-output size of all planned archives.
137    pub(crate) total_output_size: u64,
138}
139
140impl PlannedDownloads {
141    /// Collects transaction jars from the selected archives after all manifest formats have
142    /// been expanded. A jar's members can be distributed across archives.
143    pub(super) fn transaction_jars(&self) -> Result<Vec<String>> {
144        let files: HashSet<_> = self
145            .archives
146            .iter()
147            .filter(|planned| planned.ty == SnapshotComponentType::Transactions)
148            .flat_map(|planned| &planned.archive.output_files)
149            .map(|output| {
150                let path = Path::new(&output.path);
151                path.strip_prefix(".").unwrap_or(path)
152            })
153            .collect();
154        let mut jars = HashSet::new();
155        for path in &files {
156            let extension = path.extension().and_then(|ext| ext.to_str());
157            if matches!(extension, None | Some(CONFIG_FILE_EXTENSION | OFFSETS_FILE_EXTENSION)) &&
158                let Some(name) = path.file_stem().and_then(|stem| stem.to_str()) &&
159                let Some((StaticFileSegment::Transactions, range)) =
160                    StaticFileSegment::parse_filename(name) &&
161                StaticFileSegment::Transactions.filename(&range) == name
162            {
163                eyre::ensure!(
164                    path.parent() == Some(Path::new("static_files")),
165                    "Transaction static file {name} must be directly under static_files"
166                );
167                if !jars.insert(name) {
168                    continue
169                }
170                for extension in ["", CONFIG_FILE_EXTENSION, OFFSETS_FILE_EXTENSION] {
171                    let required = path.with_extension(extension);
172                    eyre::ensure!(
173                        files.contains(required.as_path()),
174                        "Incomplete transaction static file: missing {}",
175                        required.display()
176                    );
177                }
178            }
179        }
180        eyre::ensure!(
181            files.is_empty() || !jars.is_empty(),
182            "Selected transaction archives contain no transaction static files"
183        );
184        Ok(jars.into_iter().map(str::to_owned).collect())
185    }
186
187    /// Resolves parent traversal before cleanup can remove an intermediate directory and
188    /// checks the node configuration if the download retains it.
189    pub(super) fn validated_config_path(
190        &self,
191        config: PathBuf,
192        target: &Path,
193        static_files: Option<&Path>,
194        cleanup: bool,
195    ) -> Result<PathBuf> {
196        let parent = config.ancestors().find(|path| path.ends_with(".."));
197        let traversed = parent.is_some();
198        // Resolve only through the final `..`. The remaining path may not exist yet.
199        let resolved = if let Some(parent) = parent {
200            parent.canonicalize()?.join(config.strip_prefix(parent)?)
201        } else {
202            config
203        };
204        if !resolved.try_exists()? {
205            return Ok(resolved)
206        }
207        if cleanup {
208            for entry in MANAGED_DATADIR_PATHS {
209                let root = managed_datadir_path(entry, target, static_files);
210                if resolved.starts_with(&root) ||
211                    (traversed &&
212                        root.try_exists()? &&
213                        !root.is_symlink() &&
214                        resolved.starts_with(root.canonicalize()?))
215                {
216                    return Ok(resolved)
217                }
218            }
219        }
220        let verifier = OutputVerifier::new(target, static_files);
221        for output in self.archives.iter().flat_map(|planned| &planned.archive.output_files) {
222            let output = verifier.output_path(output)?;
223            if output == resolved {
224                return Ok(resolved)
225            }
226            if traversed &&
227                output.file_name() == resolved.file_name() &&
228                let (Some(output_dir), Some(config_dir)) = (output.parent(), resolved.parent()) &&
229                output_dir.try_exists()? &&
230                output_dir.canonicalize()? == config_dir.canonicalize()?
231            {
232                return Ok(resolved)
233            }
234        }
235        Config::from_path(&resolved)?.static_files.validate()?;
236        Ok(resolved)
237    }
238
239    /// Verifies every archive's existing outputs in parallel and splits off the archives that
240    /// already match, so each output file is hashed at most once before work begins.
241    pub(crate) fn partition_reusable(
242        self,
243        target_dir: &Path,
244        static_files_dir: Option<&Path>,
245    ) -> Result<CheckedDownloads> {
246        let verifier = OutputVerifier::new(target_dir, static_files_dir);
247        let checked = self
248            .archives
249            .into_par_iter()
250            .map(|planned| Ok((verifier.verify(&planned.archive.output_files)?, planned)))
251            .collect::<Result<Vec<_>>>()?;
252
253        let mut downloads = CheckedDownloads {
254            pending: Vec::new(),
255            reused: Vec::new(),
256            total_download_size: self.total_download_size,
257            total_output_size: self.total_output_size,
258        };
259        for (reusable, planned) in checked {
260            if reusable {
261                downloads.reused.push(planned);
262            } else {
263                downloads.pending.push(planned);
264            }
265        }
266        Ok(downloads)
267    }
268}
269
270/// Planned archives split by the startup reuse check.
271#[derive(Debug)]
272pub(crate) struct CheckedDownloads {
273    /// Archives that still need to be fetched and extracted.
274    pub(crate) pending: Vec<PlannedArchive>,
275    /// Archives whose declared outputs already verified on disk.
276    pub(crate) reused: Vec<PlannedArchive>,
277    /// Total compressed download size of all planned archives.
278    pub(crate) total_download_size: u64,
279    /// Total extracted plain-output size of all planned archives.
280    pub(crate) total_output_size: u64,
281}
282
283impl CheckedDownloads {
284    /// Returns the number of concrete archives in this snapshot selection, including reused ones.
285    pub(crate) const fn total_archives(&self) -> usize {
286        self.pending.len() + self.reused.len()
287    }
288}
289
290/// Returns the sort priority used to schedule archives.
291pub(crate) const fn archive_priority_rank(ty: SnapshotComponentType) -> u8 {
292    match ty {
293        SnapshotComponentType::State => 0,
294        SnapshotComponentType::RocksdbIndices => 1,
295        _ => 2,
296    }
297}
298
299/// Converts a selection into the manifest distance form used for archive lookup.
300fn selection_archive_distance(
301    selection: &ComponentSelection,
302    snapshot_block: u64,
303) -> Option<Option<u64>> {
304    match selection {
305        ComponentSelection::All => Some(None),
306        ComponentSelection::Distance(distance) => Some(Some(*distance)),
307        ComponentSelection::Since(block) => Some(Some(snapshot_block.saturating_sub(*block) + 1)),
308        ComponentSelection::None => None,
309    }
310}
311
312/// Returns the last block before the continuous range of selected bodies through the tip,
313/// or `None` when the range reaches genesis.
314pub(super) fn restored_bodies_boundary(
315    dir: &Path,
316    jars: &[String],
317    tip: u64,
318) -> Result<Option<u64>> {
319    let mut ranges = Vec::new();
320    for name in jars {
321        let header = read_static_file_header(&dir.join(name))?;
322        if header.segment() == StaticFileSegment::Transactions &&
323            let Some(range) = header.block_range()
324        {
325            ranges.push(range);
326        }
327    }
328    ranges.sort_unstable_by_key(|range| std::cmp::Reverse(range.end()));
329    let boundary = last_missing_block(tip, ranges.into_iter());
330    eyre::ensure!(
331        jars.is_empty() || boundary != Some(tip),
332        "Selected transaction files do not cover snapshot block {tip}"
333    );
334    Ok(boundary)
335}
336
337/// Sorts planned archives into a stable processing order.
338fn sort_planned_archives(all_downloads: &mut [PlannedArchive]) {
339    all_downloads.sort_by(|a, b| {
340        archive_priority_rank(a.ty)
341            .cmp(&archive_priority_rank(b.ty))
342            .then_with(|| a.component.cmp(&b.component))
343            .then_with(|| a.archive.file_name.cmp(&b.archive.file_name))
344    });
345}
346
347/// Expands component selections into archives and validates their output paths.
348pub(crate) fn collect_planned_archives(
349    manifest: &SnapshotManifest,
350    selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
351) -> Result<PlannedDownloads> {
352    let mut archives = Vec::new();
353    let mut total_download_size = 0;
354    let mut total_output_size = 0;
355
356    for (ty, selection) in selections {
357        let Some(distance) = selection_archive_distance(selection, manifest.block) else {
358            continue;
359        };
360
361        if let Some(ComponentManifest::Chunked(chunked)) = manifest.component(*ty) &&
362            !chunked.chunk_files_are_consistent()
363        {
364            eyre::bail!(
365                "Invalid modular manifest: {} chunk_files length ({}) does not match chunk count ({})",
366                ty.key(),
367                chunked.chunk_files.len(),
368                chunked.num_chunks()
369            );
370        }
371
372        // An empty set would download nothing while the component counts as downloaded.
373        if let Some(ComponentManifest::Files(set)) = manifest.component(*ty) &&
374            set.archives.is_empty()
375        {
376            eyre::bail!("Invalid modular manifest: {} has no archives", ty.key());
377        }
378
379        total_download_size += manifest.size_for_distance(*ty, distance);
380        total_output_size += manifest.output_size_for_distance(*ty, distance);
381
382        let snapshot_archives = manifest.snapshot_archives_for_distance(*ty, distance);
383        let component = ty.display_name().to_string();
384        if !snapshot_archives.is_empty() {
385            info!(target: "reth::cli",
386                component = %component,
387                archives = snapshot_archives.len(),
388                selection = %selection,
389                "Queued component for download"
390            );
391        }
392
393        for archive in snapshot_archives {
394            if archive.output_files.is_empty() {
395                eyre::bail!(
396                    "Invalid modular manifest: {} is missing plain output checksum metadata",
397                    archive.file_name
398                );
399            }
400
401            for output in &archive.output_files {
402                let path = output.relative_path()?;
403                eyre::ensure!(
404                    is_managed_snapshot_path(path, false),
405                    "Not a snapshot output path: `{}`",
406                    path.display()
407                );
408            }
409
410            archives.push(PlannedArchive { ty: *ty, component: component.clone(), archive });
411        }
412    }
413
414    sort_planned_archives(&mut archives);
415    Ok(PlannedDownloads { archives, total_download_size, total_output_size })
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::download::tests::snapshot_source;
422    use tempfile::tempdir;
423
424    fn test_manifest_with_component_tip(block: u64, total_blocks: u64) -> SnapshotManifest {
425        let chunk_count = total_blocks.div_ceil(10);
426        SnapshotManifest {
427            block,
428            chain_id: 1,
429            storage_version: 2,
430            timestamp: 0,
431            base_url: Some("https://example.com".to_string()),
432            reth_version: None,
433            components: BTreeMap::from([(
434                "transactions".to_string(),
435                ComponentManifest::Chunked(ChunkedArchive {
436                    blocks_per_file: 10,
437                    total_blocks,
438                    chunk_sizes: (1..=chunk_count).map(|i| i * 10).collect(),
439                    chunk_decompressed_sizes: (1..=chunk_count).map(|i| i * 100).collect(),
440                    chunk_files: vec![],
441                    chunk_output_files: (0..chunk_count)
442                        .map(|i| {
443                            vec![OutputFileChecksum {
444                                path: format!("static_files/tx-{i}"),
445                                size: (i + 1) * 100,
446                                blake3: format!("h{i}"),
447                            }]
448                        })
449                        .collect(),
450                }),
451            )]),
452            extensions: Default::default(),
453        }
454    }
455
456    #[test]
457    fn partition_reusable_moves_only_verified_archives() {
458        let dir = tempdir().unwrap();
459        let target_dir = dir.path();
460        let ok_file = target_dir.join("ok.bin");
461        std::fs::write(&ok_file, vec![1_u8; 4]).unwrap();
462        let ok_hash = blake3::hash(&[1_u8; 4]).to_hex().to_string();
463
464        let planned = vec![
465            PlannedArchive {
466                ty: SnapshotComponentType::State,
467                component: "State".to_string(),
468                archive: SnapshotArchive {
469                    url: "https://example.com/ok.tar.zst".to_string(),
470                    file_name: "ok.tar.zst".to_string(),
471                    size: Some(10),
472                    blake3: None,
473                    output_files: vec![OutputFileChecksum {
474                        path: "ok.bin".to_string(),
475                        size: 4,
476                        blake3: ok_hash,
477                    }],
478                },
479            },
480            PlannedArchive {
481                ty: SnapshotComponentType::Headers,
482                component: "Headers".to_string(),
483                archive: SnapshotArchive {
484                    url: "https://example.com/missing.tar.zst".to_string(),
485                    file_name: "missing.tar.zst".to_string(),
486                    size: Some(10),
487                    blake3: None,
488                    output_files: vec![OutputFileChecksum {
489                        path: "missing.bin".to_string(),
490                        size: 1,
491                        blake3: "deadbeef".to_string(),
492                    }],
493                },
494            },
495            PlannedArchive {
496                ty: SnapshotComponentType::Transactions,
497                component: "Transactions".to_string(),
498                archive: SnapshotArchive {
499                    url: "https://example.com/bad-size.tar.zst".to_string(),
500                    file_name: "bad-size.tar.zst".to_string(),
501                    size: Some(10),
502                    blake3: None,
503                    output_files: vec![],
504                },
505            },
506        ];
507
508        let downloads =
509            PlannedDownloads { archives: planned, total_download_size: 30, total_output_size: 5 }
510                .partition_reusable(target_dir, None)
511                .unwrap();
512        assert_eq!(downloads.total_archives(), 3);
513
514        let names = |archives: &[PlannedArchive]| {
515            archives.iter().map(|planned| planned.archive.file_name.clone()).collect::<Vec<_>>()
516        };
517        assert_eq!(names(&downloads.reused), ["ok.tar.zst"]);
518        assert_eq!(names(&downloads.pending), ["missing.tar.zst", "bad-size.tar.zst"]);
519    }
520
521    #[test]
522    fn rocksdb_archive_set_reuses_each_verified_sst() {
523        let dir = tempdir().unwrap();
524        let rocksdb_dir = dir.path().join("rocksdb");
525        std::fs::create_dir_all(&rocksdb_dir).unwrap();
526        std::fs::write(rocksdb_dir.join("000007.sst"), b"sst-7").unwrap();
527
528        let sst_archive = |number: u32, contents: &[u8]| {
529            let hash = blake3::hash(contents).to_hex().to_string();
530            SingleArchive {
531                file: format!("rocksdb_indices/{number:06}-{hash}.tar.zst"),
532                size: 10,
533                decompressed_size: contents.len() as u64,
534                blake3: None,
535                output_files: vec![OutputFileChecksum {
536                    path: format!("rocksdb/{number:06}.sst"),
537                    size: contents.len() as u64,
538                    blake3: hash,
539                }],
540            }
541        };
542        let manifest = SnapshotManifest {
543            block: 1,
544            chain_id: 1,
545            storage_version: 2,
546            timestamp: 0,
547            base_url: Some("https://example.com".to_string()),
548            reth_version: None,
549            components: BTreeMap::from([(
550                SnapshotComponentType::RocksdbIndices.key().to_string(),
551                ComponentManifest::Files(ArchiveSet {
552                    archives: vec![sst_archive(7, b"sst-7"), sst_archive(9, b"sst-9")],
553                }),
554            )]),
555            extensions: Default::default(),
556        };
557
558        let selections =
559            BTreeMap::from([(SnapshotComponentType::RocksdbIndices, ComponentSelection::All)]);
560        let planned = collect_planned_archives(&manifest, &selections).unwrap();
561        assert_eq!(planned.total_download_size, 20);
562        assert_eq!(planned.total_output_size, 10);
563
564        let downloads = planned.partition_reusable(dir.path(), None).unwrap();
565        let names = |archives: &[PlannedArchive]| {
566            archives.iter().map(|planned| planned.archive.file_name.clone()).collect::<Vec<_>>()
567        };
568        assert_eq!(names(&downloads.reused), [sst_archive(7, b"sst-7").file]);
569        assert_eq!(names(&downloads.pending), [sst_archive(9, b"sst-9").file]);
570    }
571
572    #[test]
573    fn archive_priority_prefers_state_then_rocksdb() {
574        let mut planned = [
575            PlannedArchive {
576                ty: SnapshotComponentType::Transactions,
577                component: "Transactions".to_string(),
578                archive: SnapshotArchive {
579                    url: "u3".to_string(),
580                    file_name: "t.tar.zst".to_string(),
581                    size: Some(1),
582                    blake3: None,
583                    output_files: vec![OutputFileChecksum {
584                        path: "a".to_string(),
585                        size: 1,
586                        blake3: "x".to_string(),
587                    }],
588                },
589            },
590            PlannedArchive {
591                ty: SnapshotComponentType::RocksdbIndices,
592                component: "RocksDB Indices".to_string(),
593                archive: SnapshotArchive {
594                    url: "u2".to_string(),
595                    file_name: "rocksdb_indices.tar.zst".to_string(),
596                    size: Some(1),
597                    blake3: None,
598                    output_files: vec![OutputFileChecksum {
599                        path: "b".to_string(),
600                        size: 1,
601                        blake3: "y".to_string(),
602                    }],
603                },
604            },
605            PlannedArchive {
606                ty: SnapshotComponentType::State,
607                component: "State (mdbx)".to_string(),
608                archive: SnapshotArchive {
609                    url: "u1".to_string(),
610                    file_name: "state.tar.zst".to_string(),
611                    size: Some(1),
612                    blake3: None,
613                    output_files: vec![OutputFileChecksum {
614                        path: "c".to_string(),
615                        size: 1,
616                        blake3: "z".to_string(),
617                    }],
618                },
619            },
620        ];
621
622        planned.sort_by(|a, b| {
623            archive_priority_rank(a.ty)
624                .cmp(&archive_priority_rank(b.ty))
625                .then_with(|| a.component.cmp(&b.component))
626                .then_with(|| a.archive.file_name.cmp(&b.archive.file_name))
627        });
628
629        assert_eq!(planned[0].ty, SnapshotComponentType::State);
630        assert_eq!(planned[1].ty, SnapshotComponentType::RocksdbIndices);
631        assert_eq!(planned[2].ty, SnapshotComponentType::Transactions);
632    }
633
634    #[test]
635    fn collect_planned_archives_tracks_download_and_output_totals() {
636        let mut components = BTreeMap::new();
637        components.insert(
638            "state".to_string(),
639            ComponentManifest::Single(SingleArchive {
640                file: "state.tar.zst".to_string(),
641                size: 10,
642                decompressed_size: 100,
643                blake3: None,
644                output_files: vec![OutputFileChecksum {
645                    path: "db/mdbx.dat".to_string(),
646                    size: 100,
647                    blake3: "h0".to_string(),
648                }],
649            }),
650        );
651        components.insert(
652            "transactions".to_string(),
653            ComponentManifest::Chunked(ChunkedArchive {
654                blocks_per_file: 500_000,
655                total_blocks: 1_000_000,
656                chunk_sizes: vec![20, 30],
657                chunk_decompressed_sizes: vec![200, 300],
658                chunk_files: vec![],
659                chunk_output_files: vec![
660                    vec![OutputFileChecksum {
661                        path: "static_files/tx-0".to_string(),
662                        size: 200,
663                        blake3: "h1".to_string(),
664                    }],
665                    vec![OutputFileChecksum {
666                        path: "static_files/tx-1".to_string(),
667                        size: 300,
668                        blake3: "h2".to_string(),
669                    }],
670                ],
671            }),
672        );
673
674        let manifest = SnapshotManifest {
675            block: 1_000_000,
676            chain_id: 1,
677            storage_version: 2,
678            timestamp: 0,
679            base_url: Some("https://example.com".to_string()),
680            reth_version: None,
681            components,
682            extensions: Default::default(),
683        };
684
685        let selections = BTreeMap::from([
686            (SnapshotComponentType::State, ComponentSelection::All),
687            (SnapshotComponentType::Transactions, ComponentSelection::Distance(500_000)),
688        ]);
689
690        let planned = collect_planned_archives(&manifest, &selections).unwrap();
691
692        assert_eq!(planned.total_download_size, 40);
693        assert_eq!(planned.total_output_size, 400);
694        assert_eq!(planned.archives.len(), 2);
695
696        let plan = DownloadPlan::from_planned(&manifest, &planned);
697        assert_eq!(
698            serde_json::to_value(plan).unwrap(),
699            serde_json::json!({
700                "schemaVersion": 1,
701                "chainId": 1,
702                "block": 1_000_000,
703                "totalDownloadSize": 40,
704                "totalOutputSize": 400,
705                "archives": [
706                    {
707                        "component": "state",
708                        "fileName": "state.tar.zst",
709                        "url": "https://example.com/state.tar.zst",
710                        "downloadSize": 10,
711                        "outputSize": 100
712                    },
713                    {
714                        "component": "transactions",
715                        "fileName": "transactions-500000-999999.tar.zst",
716                        "url": "https://example.com/transactions-500000-999999.tar.zst",
717                        "downloadSize": 30,
718                        "outputSize": 300
719                    }
720                ]
721            })
722        );
723    }
724
725    #[test]
726    fn collect_planned_archives_rejects_empty_archive_set() {
727        let manifest = SnapshotManifest {
728            block: 1,
729            chain_id: 1,
730            storage_version: 2,
731            timestamp: 0,
732            base_url: Some("https://example.com".to_string()),
733            reth_version: None,
734            components: BTreeMap::from([(
735                SnapshotComponentType::RocksdbIndices.key().to_string(),
736                ComponentManifest::Files(ArchiveSet { archives: vec![] }),
737            )]),
738            extensions: Default::default(),
739        };
740        let selections =
741            BTreeMap::from([(SnapshotComponentType::RocksdbIndices, ComponentSelection::All)]);
742
743        let err = collect_planned_archives(&manifest, &selections).unwrap_err();
744        assert_eq!(err.to_string(), "Invalid modular manifest: rocksdb_indices has no archives");
745    }
746
747    #[test]
748    fn collect_planned_archives_rejects_mismatched_chunk_files_length() {
749        let mut components = BTreeMap::new();
750        components.insert(
751            "transactions".to_string(),
752            ComponentManifest::Chunked(ChunkedArchive {
753                blocks_per_file: 500_000,
754                total_blocks: 1_000_000,
755                chunk_sizes: vec![20, 30],
756                chunk_decompressed_sizes: vec![200, 300],
757                chunk_files: vec!["static_files/transactions-0-499999.tar.zst".to_string()],
758                chunk_output_files: vec![
759                    vec![OutputFileChecksum {
760                        path: "static_files/tx-0".to_string(),
761                        size: 200,
762                        blake3: "h1".to_string(),
763                    }],
764                    vec![OutputFileChecksum {
765                        path: "static_files/tx-1".to_string(),
766                        size: 300,
767                        blake3: "h2".to_string(),
768                    }],
769                ],
770            }),
771        );
772
773        let manifest = SnapshotManifest {
774            block: 1_000_000,
775            chain_id: 1,
776            storage_version: 2,
777            timestamp: 0,
778            base_url: Some("https://example.com/mainnet".to_string()),
779            reth_version: None,
780            components,
781            extensions: Default::default(),
782        };
783        let selections =
784            BTreeMap::from([(SnapshotComponentType::Transactions, ComponentSelection::All)]);
785
786        let err = collect_planned_archives(&manifest, &selections).unwrap_err();
787        assert!(
788            err.to_string().contains("chunk_files length"),
789            "expected chunk_files length error, got: {err}"
790        );
791    }
792
793    #[test]
794    fn collect_planned_archives_rejects_a_directory_listed_as_a_file() {
795        let mut manifest = test_manifest_with_component_tip(9, 10);
796        let component = SnapshotComponentType::Transactions;
797        let ComponentManifest::Chunked(archive) =
798            manifest.components.get_mut(component.key()).unwrap()
799        else {
800            panic!("expected a chunked archive");
801        };
802        archive.chunk_output_files[0][0].path = "static_files".to_string();
803
804        let err = collect_planned_archives(
805            &manifest,
806            &BTreeMap::from([(component, ComponentSelection::All)]),
807        )
808        .unwrap_err();
809        assert_eq!(err.to_string(), "Not a snapshot output path: `static_files`");
810    }
811
812    #[test]
813    fn range_selections_use_snapshot_block_when_component_extends_past_it() {
814        // The snapshot ends at 20, but the final archive contains blocks 20 through 24.
815        let manifest = test_manifest_with_component_tip(20, 25);
816        let component = SnapshotComponentType::Transactions;
817        for (selection, expected_chunks) in [
818            (ComponentSelection::Since(19), vec![1, 2]),
819            (ComponentSelection::Distance(2), vec![1, 2]),
820            (ComponentSelection::Since(20), vec![2]),
821            (ComponentSelection::Distance(1), vec![2]),
822            (ComponentSelection::Since(10), vec![1, 2]),
823            (ComponentSelection::Since(9), vec![0, 1, 2]),
824            (ComponentSelection::Distance(0), vec![]),
825            (ComponentSelection::Distance(u64::MAX), vec![0, 1, 2]),
826            (ComponentSelection::All, vec![0, 1, 2]),
827        ] {
828            let planned =
829                collect_planned_archives(&manifest, &BTreeMap::from([(component, selection)]))
830                    .unwrap();
831            let expected_files = expected_chunks
832                .iter()
833                .map(|i| format!("transactions-{}-{}.tar.zst", i * 10, (i + 1) * 10 - 1))
834                .collect::<Vec<_>>();
835            let expected_size = expected_chunks.iter().map(|i| (i + 1) * 10).sum::<u64>();
836            assert_eq!(
837                planned.archives.iter().map(|a| a.archive.file_name.clone()).collect::<Vec<_>>(),
838                expected_files,
839                "{selection}"
840            );
841            assert_eq!(planned.total_download_size, expected_size, "{selection}");
842            assert_eq!(planned.total_output_size, expected_size * 10, "{selection}");
843
844            // The URL, count, and size APIs used by the UI must agree with the download plan.
845            let distance = selection_archive_distance(&selection, manifest.block).unwrap();
846            assert_eq!(
847                manifest.archive_urls_for_distance(component, distance),
848                expected_files
849                    .iter()
850                    .map(|file| format!("https://example.com/{file}"))
851                    .collect::<Vec<_>>(),
852                "{selection}"
853            );
854            assert_eq!(
855                manifest.chunks_for_distance(component, distance),
856                expected_chunks.len() as u64,
857                "{selection}"
858            );
859            assert_eq!(
860                manifest.size_for_distance(component, distance),
861                expected_size,
862                "{selection}"
863            );
864            assert_eq!(
865                manifest.output_size_for_distance(component, distance),
866                expected_size * 10,
867                "{selection}"
868            );
869        }
870    }
871
872    #[test]
873    fn range_selections_do_not_shift_back_to_a_shorter_component_tip() {
874        let manifest = test_manifest_with_component_tip(20, 18);
875        let component = SnapshotComponentType::Transactions;
876        for (selection, expected_files) in [
877            (ComponentSelection::Since(19), vec![]),
878            (ComponentSelection::Distance(2), vec![]),
879            (ComponentSelection::Since(17), vec!["transactions-10-19.tar.zst"]),
880            (ComponentSelection::Distance(4), vec!["transactions-10-19.tar.zst"]),
881        ] {
882            let planned =
883                collect_planned_archives(&manifest, &BTreeMap::from([(component, selection)]))
884                    .unwrap();
885            assert_eq!(
886                planned.archives.iter().map(|a| a.archive.file_name.as_str()).collect::<Vec<_>>(),
887                expected_files,
888                "{selection}"
889            );
890            let expected_size = if expected_files.is_empty() { 0 } else { 20 };
891            assert_eq!(planned.total_download_size, expected_size, "{selection}");
892            assert_eq!(planned.total_output_size, expected_size * 10, "{selection}");
893        }
894    }
895
896    #[test]
897    fn range_selections_preserve_legacy_tip_archives() {
898        // Legacy manifests stored the snapshot height in total_blocks, not the block count.
899        // At an exact chunk boundary, the legacy generator did not emit the next archive.
900        for (block, expected_files, expected_size) in
901            [(24, vec!["transactions-20-29.tar.zst"], 30), (20, vec![], 0)]
902        {
903            let manifest = test_manifest_with_component_tip(block, block);
904            let component = SnapshotComponentType::Transactions;
905            for selection in [ComponentSelection::Since(block), ComponentSelection::Distance(1)] {
906                let planned =
907                    collect_planned_archives(&manifest, &BTreeMap::from([(component, selection)]))
908                        .unwrap();
909                assert_eq!(
910                    planned
911                        .archives
912                        .iter()
913                        .map(|a| a.archive.file_name.as_str())
914                        .collect::<Vec<_>>(),
915                    expected_files,
916                    "{selection}"
917                );
918                assert_eq!(planned.total_download_size, expected_size, "{selection}");
919                assert_eq!(planned.total_output_size, expected_size * 10, "{selection}");
920                assert_eq!(
921                    manifest.chunks_for_distance(component, Some(1)),
922                    expected_files.len() as u64,
923                    "{selection}"
924                );
925            }
926        }
927    }
928
929    #[test]
930    fn transaction_archives_with_ambiguous_coverage() -> Result<()> {
931        let archives = tempdir()?;
932        let txs = SnapshotComponentType::Transactions;
933        let files = snapshot_source(Some(0..=25))?;
934        let dir = files.path().join("static_files");
935        let mut manifest =
936            generate_manifest(files.path(), archives.path(), None, 25, 1, 10, None, false)?;
937        let Some(ComponentManifest::Chunked(mut chunks)) = manifest.components.remove(txs.key())
938        else {
939            panic!("missing transaction chunks")
940        };
941        chunks.total_blocks = 25;
942        // The non-chunked selections omit the middle file that is still on disk.
943        let [first, _, last] = chunks.chunk_output_files.as_slice() else {
944            panic!("expected three transaction chunks")
945        };
946        let archive = SingleArchive {
947            file: "transactions.tar.zst".into(),
948            size: 0,
949            decompressed_size: 0,
950            blake3: None,
951            output_files: [first.as_slice(), last].concat(),
952        };
953        let selections = BTreeMap::from([(txs, ComponentSelection::Since(13))]);
954        for (component, expected) in [
955            (ComponentManifest::Chunked(chunks), 9),
956            (ComponentManifest::Single(archive.clone()), 19),
957            (ComponentManifest::Files(ArchiveSet { archives: vec![archive] }), 19),
958        ] {
959            manifest.components.insert(txs.key().into(), component);
960            let jars = collect_planned_archives(&manifest, &selections)?.transaction_jars()?;
961            assert_eq!(restored_bodies_boundary(&dir, &jars, manifest.block)?, Some(expected));
962        }
963        let jars = collect_planned_archives(&manifest, &selections)?.transaction_jars()?;
964        let err = restored_bodies_boundary(&dir, &jars, 26).unwrap_err();
965        assert_eq!(err.to_string(), "Selected transaction files do not cover snapshot block 26");
966        Ok(())
967    }
968
969    #[test]
970    fn transaction_plan_rejects_invalid_output_paths() -> Result<()> {
971        let manifest = test_manifest_with_component_tip(9, 10);
972        let selections =
973            BTreeMap::from([(SnapshotComponentType::Transactions, ComponentSelection::All)]);
974        let mut plan = collect_planned_archives(&manifest, &selections)?;
975        let misplaced = "Transaction static file static_file_transactions_0_9 must be directly under static_files";
976        for (path, expected) in [
977            ("static_files/backup/static_file_transactions_0_9", misplaced),
978            ("static_file_transactions_0_9", misplaced),
979            (
980                "static_files/static_file_receipts_0_9",
981                "Selected transaction archives contain no transaction static files",
982            ),
983        ] {
984            plan.archives[0].archive.output_files[0].path = path.into();
985            assert_eq!(plan.transaction_jars().unwrap_err().to_string(), expected, "{path}");
986        }
987        Ok(())
988    }
989}