Skip to main content

reth_cli_commands/download/
manifest.rs

1use blake3::Hasher;
2use eyre::{Result, WrapErr};
3use reqwest::Client;
4use reth_concurrency::sync::rayon::prelude::*;
5use reth_db::static_file::{iter_static_files, StaticFileEntry};
6use reth_static_file_types::StaticFileSegment;
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::{BTreeMap, HashMap},
10    io::Read,
11    path::{Component, Path, PathBuf},
12};
13use tracing::info;
14use url::Url;
15
16fn is_zero(value: &u64) -> bool {
17    *value == 0
18}
19
20/// A snapshot manifest describes available components for a snapshot at a given block height.
21///
22/// Each component is either a single archive (state), a set of chunked archives (static file
23/// segments like transactions, receipts, etc), or a set of per-file archives (RocksDB indices).
24/// Chunked components use `blocks_per_file` to define the block range per archive, matching
25/// reth's static file segment boundaries.
26///
27/// Archive paths are resolved relative to [`SnapshotManifest::base_url`] via URL joining.
28/// Single archives use [`SingleArchive::file`]; chunked archives default to
29/// `{component}-{start_block}-{end_block}.tar.zst`, or use [`ChunkedArchive::chunk_files`]
30/// when present so publishers can place finalized and tip chunks under different prefixes, or
31/// reference an earlier snapshot's archives by absolute URL:
32///
33/// ```text
34/// base_url = https://example.com/mainnet
35///   static_files/transactions-0-499999.tar.zst
36///   1700000/transactions-500000-999999.tar.zst
37///   1700000/state.tar.zst
38/// ```
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct SnapshotManifest {
41    /// Block number this snapshot was taken at.
42    pub block: u64,
43    /// Chain ID.
44    pub chain_id: u64,
45    /// Storage version (1 = legacy, 2 = current).
46    pub storage_version: u64,
47    /// Timestamp when the snapshot was created (unix seconds).
48    pub timestamp: u64,
49    /// Base URL for archive downloads. Component archive URLs are relative to this.
50    ///
51    /// When omitted, downloaders should derive the base URL from the manifest URL.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub base_url: Option<String>,
54    /// Reth version that produced this snapshot.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub reth_version: Option<String>,
57    /// Available snapshot components.
58    pub components: BTreeMap<String, ComponentManifest>,
59    /// Chain-specific manifest fields not interpreted by Reth.
60    ///
61    /// Extensions are retained so downstream commands can consume snapshot metadata without
62    /// refetching or reparsing the manifest selected by Reth.
63    #[serde(default, flatten)]
64    pub extensions: BTreeMap<String, serde_json::Value>,
65}
66
67/// Manifest entry for a single snapshot component.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69#[serde(untagged)]
70pub enum ComponentManifest {
71    /// A single archive file (used for state).
72    Single(SingleArchive),
73    /// A set of chunked archives split by block range (used for static file segments).
74    Chunked(ChunkedArchive),
75    /// A set of independent archives (used for RocksDB indices).
76    Files(ArchiveSet),
77}
78
79/// A single, non-chunked archive.
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct SingleArchive {
82    /// Archive file name (relative to base_url).
83    ///
84    /// Must be a relative path (no leading `/`). Nested paths like `1700000/state.tar.zst`
85    /// are supported when `base_url` points at the snapshot root.
86    pub file: String,
87    /// Compressed archive size in bytes.
88    pub size: u64,
89    /// Total extracted plain-output size in bytes.
90    ///
91    /// Older manifests may omit this, in which case downloaders should derive it from
92    /// `output_files`.
93    #[serde(default, skip_serializing_if = "is_zero")]
94    pub decompressed_size: u64,
95    /// Optional BLAKE3 checksum of the compressed archive.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub blake3: Option<String>,
98    /// Expected extracted plain files for this archive.
99    ///
100    /// This is the authoritative integrity source for the modular download path.
101    #[serde(default)]
102    pub output_files: Vec<OutputFileChecksum>,
103}
104
105/// A chunked archive set where each chunk covers a fixed block range.
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct ChunkedArchive {
108    /// Number of blocks per archive file. Matches reth's `blocks_per_file` config.
109    pub blocks_per_file: u64,
110    /// Total number of blocks covered by this component, including block zero.
111    ///
112    /// Coverage is contiguous from block zero. The final chunk may be partial; its actual
113    /// last block is `total_blocks - 1`, irrespective of its filename's range end.
114    /// Older manifests may store the declared snapshot block instead of the count.
115    pub total_blocks: u64,
116    /// Compressed size of each chunk in bytes, ordered from first to last.
117    /// Computed during manifest generation. Older manifests may omit this.
118    #[serde(default)]
119    pub chunk_sizes: Vec<u64>,
120    /// Extracted plain-output size of each chunk in bytes, ordered from first to last.
121    ///
122    /// Older manifests may omit this, in which case downloaders should derive it from
123    /// `chunk_output_files`.
124    #[serde(default, skip_serializing_if = "Vec::is_empty")]
125    pub chunk_decompressed_sizes: Vec<u64>,
126    /// Archive location for each chunk, ordered from first to last.
127    ///
128    /// When empty (older manifests), downloaders fall back to the default
129    /// `{component}-{start}-{end}.tar.zst` name. When set, the length must equal the chunk
130    /// count. Relative paths are joined with [`SnapshotManifest::base_url`] so publishers can
131    /// place chunks under different prefixes (for example `static_files/…` for finalized chunks
132    /// and `{timestamp}/…` for the tip chunk). Absolute URLs, such as archives reused from a
133    /// previous snapshot, are used as-is.
134    ///
135    /// Relative paths must not start with `/`: URL joining treats a leading slash as
136    /// host-absolute and would drop the `base_url` path prefix.
137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
138    pub chunk_files: Vec<String>,
139    /// Expected extracted plain files per chunk, ordered from first to last.
140    ///
141    /// This is the authoritative integrity source for the modular download path.
142    #[serde(default)]
143    pub chunk_output_files: Vec<Vec<OutputFileChecksum>>,
144}
145
146/// A set of archives that are downloaded, verified, and reused independently.
147///
148/// RocksDB SST files are immutable once written, and consecutive snapshots of the same database
149/// share almost all of them. Packaging each SST in its own archive, named after the file and its
150/// BLAKE3 checksum, lets publishers upload an archive once and reference it from later
151/// manifests, and lets downloads resume per file.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct ArchiveSet {
154    /// Archives in this set, each with its own path relative to [`SnapshotManifest::base_url`].
155    pub archives: Vec<SingleArchive>,
156}
157
158/// Expected metadata for one extracted plain file.
159#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
160pub struct OutputFileChecksum {
161    /// Relative path under the target datadir where this file is extracted.
162    pub path: String,
163    /// Plain file size in bytes.
164    pub size: u64,
165    /// BLAKE3 checksum of the plain file contents.
166    pub blake3: String,
167}
168
169impl OutputFileChecksum {
170    /// Returns the path as a relative path that stays below the directory it is joined to.
171    ///
172    /// Only normal components are accepted, plus the `./` prefix tar adds to entry paths.
173    /// Absolute paths and `..` are rejected because the path is joined onto the datadir for
174    /// verification and for removal before retries.
175    pub(crate) fn relative_path(&self) -> Result<&Path> {
176        let path = Path::new(&self.path);
177        eyre::ensure!(
178            path.components().all(|part| matches!(part, Component::Normal(_) | Component::CurDir)) &&
179                path.components().any(|part| matches!(part, Component::Normal(_))),
180            "Invalid manifest output file path `{}`: must be a relative path without `..`",
181            self.path
182        );
183        Ok(path)
184    }
185}
186
187/// A concrete snapshot archive with its download and verification metadata.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct SnapshotArchive {
190    pub url: String,
191    pub file_name: String,
192    /// Compressed archive size, or `None` when an older chunked manifest omits chunk sizes.
193    pub size: Option<u64>,
194    pub blake3: Option<String>,
195    pub output_files: Vec<OutputFileChecksum>,
196}
197
198impl SnapshotArchive {
199    /// Returns the total extracted plain-output size for this archive.
200    pub fn output_size(&self) -> u64 {
201        self.output_files.iter().map(|file| file.size).sum()
202    }
203}
204
205/// How much of a component to download.
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207pub enum ComponentSelection {
208    /// Download all chunks (full archive).
209    All,
210    /// Download only the most recent chunks covering at least `distance` blocks.
211    /// Maps to `PruneMode::Distance(distance)` in the generated config.
212    Distance(u64),
213    /// Download chunks starting at the specified block number.
214    /// Maps to `PruneMode::Before(block)` in the generated config.
215    Since(u64),
216    /// Don't download this component at all.
217    /// Maps to `PruneMode::Full` for tx-based segments, or a minimal distance for others.
218    None,
219}
220
221impl std::fmt::Display for ComponentSelection {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        match self {
224            Self::All => write!(f, "All"),
225            Self::Distance(d) => write!(f, "Last {d} blocks"),
226            Self::Since(block) => write!(f, "Since block {block}"),
227            Self::None => write!(f, "None"),
228        }
229    }
230}
231
232/// The types of snapshot components that can be downloaded.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
234pub enum SnapshotComponentType {
235    /// State database (mdbx). Always required. Single archive.
236    State,
237    /// Block headers static files. Chunked.
238    Headers,
239    /// Transaction static files. Chunked.
240    Transactions,
241    /// Transaction sender static files. Chunked. Only downloaded for archive nodes.
242    TransactionSenders,
243    /// Receipt static files. Chunked.
244    Receipts,
245    /// Account changeset static files. Chunked.
246    AccountChangesets,
247    /// Storage changeset static files. Chunked.
248    StorageChangesets,
249    /// RocksDB index files. A single archive, or one archive per SST or blob file plus one for the
250    /// remaining files. Optional and archive-only.
251    RocksdbIndices,
252}
253
254impl SnapshotComponentType {
255    /// All component types in display order.
256    pub const ALL: [Self; 8] = [
257        Self::State,
258        Self::Headers,
259        Self::Transactions,
260        Self::TransactionSenders,
261        Self::Receipts,
262        Self::AccountChangesets,
263        Self::StorageChangesets,
264        Self::RocksdbIndices,
265    ];
266
267    /// The string key used in the manifest JSON.
268    pub const fn key(&self) -> &'static str {
269        match self {
270            Self::State => "state",
271            Self::Headers => "headers",
272            Self::Transactions => "transactions",
273            Self::TransactionSenders => "transaction_senders",
274            Self::Receipts => "receipts",
275            Self::AccountChangesets => "account_changesets",
276            Self::StorageChangesets => "storage_changesets",
277            Self::RocksdbIndices => "rocksdb_indices",
278        }
279    }
280
281    /// Human-readable display name.
282    pub const fn display_name(&self) -> &'static str {
283        match self {
284            Self::State => "State (mdbx)",
285            Self::Headers => "Headers",
286            Self::Transactions => "Transactions",
287            Self::TransactionSenders => "Transaction Senders",
288            Self::Receipts => "Receipts",
289            Self::AccountChangesets => "Account Changesets",
290            Self::StorageChangesets => "Storage Changesets",
291            Self::RocksdbIndices => "RocksDB Indices",
292        }
293    }
294
295    /// Whether this component is always required for a functional node.
296    ///
297    /// State and headers are always needed — a node cannot operate without block headers.
298    pub const fn is_required(&self) -> bool {
299        matches!(self, Self::State | Self::Headers)
300    }
301
302    /// Whether this component type uses chunked archives.
303    pub const fn is_chunked(&self) -> bool {
304        !matches!(self, Self::State | Self::RocksdbIndices)
305    }
306}
307
308impl SnapshotManifest {
309    fn base_url_or_empty(&self) -> &str {
310        self.base_url.as_deref().unwrap_or("")
311    }
312
313    /// Look up a component by type.
314    pub fn component(&self, ty: SnapshotComponentType) -> Option<&ComponentManifest> {
315        self.components.get(ty.key())
316    }
317
318    /// Returns the total download size for the given set of component types.
319    pub fn total_size(&self, types: &[SnapshotComponentType]) -> u64 {
320        types.iter().filter_map(|ty| self.component(*ty).map(|c| c.total_size())).sum()
321    }
322
323    /// Returns all archive URLs for a given component type.
324    pub fn archive_urls(&self, ty: SnapshotComponentType) -> Vec<String> {
325        let Some(component) = self.component(ty) else {
326            return vec![];
327        };
328
329        match component {
330            ComponentManifest::Single(single) => {
331                vec![resolve_archive_url(self.base_url_or_empty(), &single.file)]
332            }
333            ComponentManifest::Files(set) => set
334                .archives
335                .iter()
336                .map(|archive| resolve_archive_url(self.base_url_or_empty(), &archive.file))
337                .collect(),
338            ComponentManifest::Chunked(chunked) => {
339                let key = ty.key();
340                let num_chunks = chunked.num_chunks();
341                (0..num_chunks)
342                    .map(|i| {
343                        resolve_archive_url(
344                            self.base_url_or_empty(),
345                            &chunked.chunk_relative_path(key, i),
346                        )
347                    })
348                    .collect()
349            }
350        }
351    }
352
353    /// Returns archive URLs for a component, limited to chunks covering at least `distance`
354    /// blocks ending at [`Self::block`]. Returns all URLs if distance is `None` (All mode).
355    pub fn archive_urls_for_distance(
356        &self,
357        ty: SnapshotComponentType,
358        distance: Option<u64>,
359    ) -> Vec<String> {
360        let Some(component) = self.component(ty) else {
361            return vec![];
362        };
363
364        match component {
365            ComponentManifest::Single(single) => {
366                vec![resolve_archive_url(self.base_url_or_empty(), &single.file)]
367            }
368            ComponentManifest::Files(set) => set
369                .archives
370                .iter()
371                .map(|archive| resolve_archive_url(self.base_url_or_empty(), &archive.file))
372                .collect(),
373            ComponentManifest::Chunked(chunked) => {
374                let key = ty.key();
375                let num_chunks = chunked.num_chunks();
376
377                let start_chunk = self.start_chunk_for_distance(chunked, distance);
378
379                (start_chunk..num_chunks)
380                    .map(|i| {
381                        resolve_archive_url(
382                            self.base_url_or_empty(),
383                            &chunked.chunk_relative_path(key, i),
384                        )
385                    })
386                    .collect()
387            }
388        }
389    }
390
391    /// Returns concrete snapshot archives for a component, optionally limited to a distance
392    /// ending at [`Self::block`].
393    pub fn snapshot_archives_for_distance(
394        &self,
395        ty: SnapshotComponentType,
396        distance: Option<u64>,
397    ) -> Vec<SnapshotArchive> {
398        let Some(component) = self.component(ty) else {
399            return vec![];
400        };
401
402        match component {
403            ComponentManifest::Single(single) => {
404                vec![single.snapshot_archive(self.base_url_or_empty())]
405            }
406            ComponentManifest::Files(set) => set
407                .archives
408                .iter()
409                .map(|archive| archive.snapshot_archive(self.base_url_or_empty()))
410                .collect(),
411            ComponentManifest::Chunked(chunked) => {
412                let key = ty.key();
413                let num_chunks = chunked.num_chunks();
414
415                let start_chunk = self.start_chunk_for_distance(chunked, distance);
416
417                (start_chunk..num_chunks)
418                    .map(|i| {
419                        let file_name = chunked.chunk_relative_path(key, i);
420                        let size = chunked.chunk_sizes.get(i as usize).copied();
421                        let output_files =
422                            chunked.chunk_output_files.get(i as usize).cloned().unwrap_or_default();
423
424                        SnapshotArchive {
425                            url: resolve_archive_url(self.base_url_or_empty(), &file_name),
426                            file_name,
427                            size,
428                            blake3: None,
429                            output_files,
430                        }
431                    })
432                    .collect()
433            }
434        }
435    }
436
437    /// Fails if any output file path in the manifest is not a plain relative path.
438    ///
439    /// Output paths come from an untrusted manifest, so this is checked before any archive is
440    /// planned.
441    pub fn validate_output_paths(&self) -> Result<()> {
442        for (key, component) in &self.components {
443            let outputs: Box<dyn Iterator<Item = &OutputFileChecksum>> = match component {
444                ComponentManifest::Single(single) => Box::new(single.output_files.iter()),
445                ComponentManifest::Chunked(chunked) => {
446                    Box::new(chunked.chunk_output_files.iter().flatten())
447                }
448                ComponentManifest::Files(set) => {
449                    Box::new(set.archives.iter().flat_map(|archive| &archive.output_files))
450                }
451            };
452            for output in outputs {
453                output.relative_path().wrap_err_with(|| format!("In component `{key}`"))?;
454            }
455        }
456        Ok(())
457    }
458
459    /// Returns the exact download size for a component given a distance ending at [`Self::block`].
460    ///
461    /// For single archives and archive sets, returns the full size. For chunked archives, sums
462    /// the sizes of the selected tail chunks from [`ChunkedArchive::chunk_sizes`].
463    pub fn size_for_distance(&self, ty: SnapshotComponentType, distance: Option<u64>) -> u64 {
464        let Some(component) = self.component(ty) else {
465            return 0;
466        };
467        match component {
468            ComponentManifest::Single(_) | ComponentManifest::Files(_) => component.total_size(),
469            ComponentManifest::Chunked(chunked) => {
470                if chunked.chunk_sizes.is_empty() {
471                    return 0;
472                }
473                let start_chunk = self.start_chunk_for_distance(chunked, distance);
474                chunked.chunk_sizes.iter().skip(start_chunk as usize).sum()
475            }
476        }
477    }
478
479    /// Returns the exact extracted plain-output size for a component given a distance ending at
480    /// [`Self::block`].
481    pub fn output_size_for_distance(
482        &self,
483        ty: SnapshotComponentType,
484        distance: Option<u64>,
485    ) -> u64 {
486        let Some(component) = self.component(ty) else {
487            return 0;
488        };
489
490        match component {
491            ComponentManifest::Single(_) | ComponentManifest::Files(_) => {
492                component.total_output_size()
493            }
494            ComponentManifest::Chunked(chunked) => {
495                let num_chunks = chunked.num_chunks();
496                let start_chunk = self.start_chunk_for_distance(chunked, distance);
497
498                (start_chunk..num_chunks)
499                    .map(|index| chunked.chunk_output_size(index as usize))
500                    .sum()
501            }
502        }
503    }
504
505    /// Returns the number of archives that would be downloaded for a distance ending at
506    /// [`Self::block`].
507    pub fn chunks_for_distance(&self, ty: SnapshotComponentType, distance: Option<u64>) -> u64 {
508        match self.component(ty) {
509            None => 0,
510            Some(ComponentManifest::Single(_)) => 1,
511            Some(ComponentManifest::Files(set)) => set.archives.len() as u64,
512            Some(ComponentManifest::Chunked(chunked)) => {
513                chunked.num_chunks() - self.start_chunk_for_distance(chunked, distance)
514            }
515        }
516    }
517
518    /// Returns the first chunk needed for a distance measured from the declared snapshot block.
519    fn start_chunk_for_distance(&self, chunked: &ChunkedArchive, distance: Option<u64>) -> u64 {
520        let Some(distance) = distance else { return 0 };
521        // The final archive may extend past the snapshot block. Counting back from its end
522        // would shift the requested history window forward and could skip a required chunk.
523        let first_block = self.block.saturating_sub(distance.saturating_sub(1));
524        // Legacy manifests used an inclusive block height for total_blocks. At equality,
525        // conservatively retain the boundary chunk if it exists.
526        if distance == 0 || first_block > chunked.total_blocks {
527            return chunked.num_chunks();
528        }
529        first_block / chunked.blocks_per_file
530    }
531
532    /// Fails if any chunked component declares zero blocks per archive.
533    pub(crate) fn validate_blocks_per_file(&self) -> Result<()> {
534        for (key, component) in &self.components {
535            if let ComponentManifest::Chunked(chunked) = component {
536                eyre::ensure!(
537                    chunked.blocks_per_file > 0,
538                    "Invalid modular manifest: {key} blocks_per_file must be greater than zero"
539                );
540            }
541        }
542        Ok(())
543    }
544}
545
546impl ComponentManifest {
547    /// Returns the total download size for this component.
548    pub fn total_size(&self) -> u64 {
549        match self {
550            Self::Single(s) => s.size,
551            Self::Chunked(c) => c.chunk_sizes.iter().sum(),
552            Self::Files(set) => set.archives.iter().map(|archive| archive.size).sum(),
553        }
554    }
555
556    /// Returns the total extracted plain-output size for this component.
557    pub fn total_output_size(&self) -> u64 {
558        match self {
559            Self::Single(single) => single.output_size(),
560            Self::Chunked(chunked) => chunked.total_output_size(),
561            Self::Files(set) => set.archives.iter().map(SingleArchive::output_size).sum(),
562        }
563    }
564}
565
566impl ChunkedArchive {
567    /// Returns the number of chunks.
568    pub fn num_chunks(&self) -> u64 {
569        self.total_blocks.div_ceil(self.blocks_per_file)
570    }
571
572    /// Returns the number of tail chunks required to cover at least `distance` blocks from the
573    /// tip.
574    pub fn tail_chunks_for_distance(&self, distance: u64) -> u64 {
575        let needed = distance.min(self.total_blocks);
576        if needed == 0 {
577            return 0;
578        }
579
580        // The first needed block determines the earliest chunk, including for a partial tail.
581        let first_chunk = (self.total_blocks - needed) / self.blocks_per_file;
582        self.num_chunks() - first_chunk
583    }
584
585    /// Returns `true` when `chunk_files` is empty or has exactly one path per chunk.
586    pub fn chunk_files_are_consistent(&self) -> bool {
587        self.chunk_files.is_empty() || self.chunk_files.len() as u64 == self.num_chunks()
588    }
589
590    /// Returns the archive location for chunk `index`: a path relative to the manifest base URL,
591    /// or an absolute URL for an archive reused from a previous snapshot.
592    ///
593    /// Uses [`Self::chunk_files`] when it has exactly one entry per chunk; otherwise the
594    /// default `{key}-{start}-{end}.tar.zst` name.
595    pub fn chunk_relative_path(&self, key: &str, index: u64) -> String {
596        if self.chunk_files.len() as u64 == self.num_chunks() &&
597            let Some(path) = self.chunk_files.get(index as usize)
598        {
599            return path.clone();
600        }
601        let start = index * self.blocks_per_file;
602        let end = (index + 1) * self.blocks_per_file - 1;
603        format!("{key}-{start}-{end}.tar.zst")
604    }
605
606    /// Returns the extracted plain-output size for one chunk.
607    pub fn chunk_output_size(&self, index: usize) -> u64 {
608        self.chunk_decompressed_sizes.get(index).copied().unwrap_or_else(|| {
609            self.chunk_output_files
610                .get(index)
611                .map(|files| files.iter().map(|file| file.size).sum())
612                .unwrap_or(0)
613        })
614    }
615
616    /// Returns the total extracted plain-output size across all chunks.
617    pub fn total_output_size(&self) -> u64 {
618        if !self.chunk_decompressed_sizes.is_empty() {
619            self.chunk_decompressed_sizes.iter().sum()
620        } else {
621            self.chunk_output_files
622                .iter()
623                .map(|files| files.iter().map(|file| file.size).sum::<u64>())
624                .sum()
625        }
626    }
627}
628
629/// Joins an archive path relative to `base_url`.
630///
631/// Ensures directory semantics for `base_url` so the last path segment is not replaced when
632/// joining nested paths like `static_files/headers-0-499999.tar.zst`. Leading slashes on
633/// `relative_path` are stripped so publisher paths stay relative to the base prefix. An absolute
634/// URL, such as an archive reused from a previous snapshot, is returned unchanged.
635fn resolve_archive_url(base_url: &str, relative_path: &str) -> String {
636    if Url::parse(relative_path).is_ok() {
637        return relative_path.to_string();
638    }
639
640    let relative_path = relative_path.trim_start_matches('/');
641
642    if base_url.is_empty() {
643        return relative_path.to_string();
644    }
645
646    let Ok(mut base) = Url::parse(base_url) else {
647        return format!("{}/{}", base_url.trim_end_matches('/'), relative_path);
648    };
649
650    // Url::join replaces the final path segment unless the base path ends with `/`.
651    let path = base.path();
652    if !path.ends_with('/') {
653        let mut with_slash = path.to_string();
654        with_slash.push('/');
655        base.set_path(&with_slash);
656    }
657
658    match base.join(relative_path) {
659        Ok(joined) => joined.to_string(),
660        Err(_) => format!("{}/{}", base_url.trim_end_matches('/'), relative_path),
661    }
662}
663
664impl SingleArchive {
665    /// Returns the total extracted plain-output size for this archive.
666    pub fn output_size(&self) -> u64 {
667        if self.decompressed_size != 0 {
668            self.decompressed_size
669        } else {
670            self.output_files.iter().map(|file| file.size).sum()
671        }
672    }
673
674    /// Returns the concrete download for this archive, resolved against `base_url`.
675    fn snapshot_archive(&self, base_url: &str) -> SnapshotArchive {
676        SnapshotArchive {
677            url: resolve_archive_url(base_url, &self.file),
678            file_name: self.file.clone(),
679            size: Some(self.size),
680            blake3: self.blake3.clone(),
681            output_files: self.output_files.clone(),
682        }
683    }
684}
685
686/// Fetches a snapshot manifest from a URL, rejecting zero blocks per archive.
687pub async fn fetch_manifest(manifest_url: &str) -> Result<SnapshotManifest> {
688    let client = Client::new();
689    let manifest: SnapshotManifest =
690        client.get(manifest_url).send().await?.error_for_status()?.json().await?;
691    manifest.validate_blocks_per_file()?;
692    Ok(manifest)
693}
694
695/// Package chunk archives from a source datadir and generate a manifest.
696///
697/// `block` selects chunks whose nominal ranges start at or before the snapshot height. Each
698/// selected file is archived in full; component block counts come from its actual stored ranges.
699///
700/// With a `previous` manifest, a chunk that is not the last chunk of its component in either
701/// manifest is not packaged again: its source files are hashed and must match the previous
702/// manifest's `chunk_output_files`, and the new manifest points `chunk_files` at the
703/// previously published archive. A mismatch is an error, since sealed history must not change.
704///
705/// RocksDB indices are packaged into one archive unless `rocksdb_archive_per_file` is set, in
706/// which case each SST and blob file gets its own archive. A file whose path and checksum match
707/// such an archive in the previous manifest is not packaged again and points at the previously
708/// published archive. Files that are new or changed are packaged, since compaction replaces them
709/// between snapshots.
710#[expect(clippy::too_many_arguments)]
711pub fn generate_manifest(
712    source_datadir: &Path,
713    output_dir: &Path,
714    base_url: Option<&str>,
715    block: u64,
716    chain_id: u64,
717    blocks_per_file: u64,
718    previous: Option<&SnapshotManifest>,
719    rocksdb_archive_per_file: bool,
720) -> Result<SnapshotManifest> {
721    eyre::ensure!(blocks_per_file > 0, "blocks_per_file must be greater than zero");
722    if let Some(previous) = previous {
723        eyre::ensure!(
724            previous.chain_id == chain_id,
725            "Previous manifest is for chain {}, not {chain_id}",
726            previous.chain_id
727        );
728        // Reused archives are referenced by absolute URL, which needs an absolute base URL.
729        eyre::ensure!(
730            previous.base_url.as_deref().is_some_and(|url| Url::parse(url).is_ok()),
731            "Previous manifest has no absolute base_url to locate its archives"
732        );
733    }
734
735    std::fs::create_dir_all(output_dir)?;
736
737    let mut components = BTreeMap::new();
738    let mut static_files_dir = source_datadir.join("static_files");
739    if !static_files_dir.exists() {
740        static_files_dir = source_datadir.to_path_buf();
741    }
742
743    let static_files = iter_static_files(&static_files_dir)?;
744
745    // Package chunked static-file components.
746    for ty in &[
747        SnapshotComponentType::Headers,
748        SnapshotComponentType::Transactions,
749        SnapshotComponentType::TransactionSenders,
750        SnapshotComponentType::Receipts,
751        SnapshotComponentType::AccountChangesets,
752        SnapshotComponentType::StorageChangesets,
753    ] {
754        let key = ty.key();
755        let segment = static_segment(*ty).expect("chunked components have a static file segment");
756        let Some(StaticFileEntry { block_range: last_range, .. }) =
757            static_files.get(segment).and_then(|files| {
758                files.iter().rfind(|file| file.header.expected_block_range().start() <= block)
759            })
760        else {
761            continue;
762        };
763
764        // Coverage starts at block zero, and selected files are archived in full, even past
765        // `block`.
766        let total_blocks = last_range
767            .end()
768            .checked_add(1)
769            .ok_or_else(|| eyre::eyre!("Block count overflows for {key}"))?;
770
771        let num_chunks = total_blocks.div_ceil(blocks_per_file);
772        let mut planned_chunks = Vec::with_capacity(num_chunks as usize);
773        let mut found_any = false;
774        for i in 0..num_chunks {
775            let start = i * blocks_per_file;
776            let end = (i + 1) * blocks_per_file - 1;
777            let source_files = source_files_for_chunk(source_datadir, *ty, start, end)?;
778
779            if source_files.is_empty() {
780                if found_any {
781                    eyre::bail!("Missing source files for {} chunk {}-{}", key, start, end);
782                }
783                continue;
784            }
785
786            found_any = true;
787            planned_chunks.push(PlannedChunk {
788                chunk_idx: i,
789                archive_path: output_dir.join(chunk_filename(key, start, end)),
790                source_files,
791            });
792        }
793
794        if found_any {
795            // Chunk indices only match the previous manifest's positions without leading gaps.
796            let previous_chunks = previous
797                .filter(|_| planned_chunks.len() as u64 == num_chunks)
798                .and_then(|manifest| match manifest.component(*ty)? {
799                    ComponentManifest::Chunked(chunked) => Some((manifest, chunked)),
800                    ComponentManifest::Single(_) | ComponentManifest::Files(_) => None,
801                })
802                // The width check comes first: the other checks divide by the previous width.
803                .filter(|(_, chunked)| {
804                    chunked.blocks_per_file == blocks_per_file &&
805                        chunked.chunk_files_are_consistent() &&
806                        chunked.chunk_sizes.len() as u64 == chunked.num_chunks() &&
807                        chunked.chunk_output_files.len() as u64 == chunked.num_chunks()
808                });
809
810            // The last chunk of either manifest may be partial, so only earlier chunks are reused.
811            let reusable_chunks = previous_chunks
812                .map_or(0, |(_, chunked)| num_chunks.min(chunked.num_chunks()).saturating_sub(1));
813
814            let mut packaged_chunks = planned_chunks
815                .into_par_iter()
816                .map(|planned| -> Result<PackagedChunk> {
817                    let start = planned.chunk_idx * blocks_per_file;
818                    let file_name = chunk_filename(key, start, start + blocks_per_file - 1);
819                    if planned.chunk_idx < reusable_chunks &&
820                        let Some((manifest, chunked)) = previous_chunks
821                    {
822                        let idx = planned.chunk_idx as usize;
823                        let output_files = hash_chunk_files(&planned.source_files)?;
824                        eyre::ensure!(
825                            output_files == chunked.chunk_output_files[idx],
826                            "{file_name} differs from the previous manifest"
827                        );
828
829                        return Ok(PackagedChunk {
830                            chunk_idx: planned.chunk_idx,
831                            size: chunked.chunk_sizes[idx],
832                            output_files,
833                            file: resolve_archive_url(
834                                manifest.base_url_or_empty(),
835                                &chunked.chunk_relative_path(key, planned.chunk_idx),
836                            ),
837                        });
838                    }
839
840                    let output_files =
841                        write_chunk_archive(&planned.archive_path, &planned.source_files)?;
842                    let size = std::fs::metadata(&planned.archive_path)?.len();
843                    Ok(PackagedChunk {
844                        chunk_idx: planned.chunk_idx,
845                        size,
846                        output_files,
847                        file: file_name,
848                    })
849                })
850                .collect::<Vec<_>>()
851                .into_iter()
852                .collect::<Result<Vec<_>>>()?;
853
854            packaged_chunks.sort_unstable_by_key(|chunk| chunk.chunk_idx);
855            // Chunked manifests index their arrays from block zero. An explicitly listed
856            // archive set can represent the transaction files left after pruning that prefix.
857            if *ty == SnapshotComponentType::Transactions && packaged_chunks[0].chunk_idx != 0 {
858                let archives = packaged_chunks
859                    .into_iter()
860                    .map(|chunk| SingleArchive {
861                        file: chunk.file,
862                        size: chunk.size,
863                        decompressed_size: chunk.output_files.iter().map(|file| file.size).sum(),
864                        blake3: None,
865                        output_files: chunk.output_files,
866                    })
867                    .collect();
868                components
869                    .insert(key.to_string(), ComponentManifest::Files(ArchiveSet { archives }));
870                continue
871            }
872            let chunk_files = packaged_chunks.iter().map(|chunk| chunk.file.clone()).collect();
873            let chunk_sizes = packaged_chunks.iter().map(|chunk| chunk.size).collect::<Vec<_>>();
874            let chunk_output_files =
875                packaged_chunks.into_iter().map(|chunk| chunk.output_files).collect::<Vec<_>>();
876            let total_size: u64 = chunk_sizes.iter().sum();
877            info!(target: "reth::cli",
878                component = ty.display_name(),
879                chunks = chunk_sizes.len(),
880                total_blocks,
881                size = %super::DownloadProgress::format_size(total_size),
882                "Found chunked component"
883            );
884            components.insert(
885                key.to_string(),
886                ComponentManifest::Chunked(ChunkedArchive {
887                    blocks_per_file,
888                    total_blocks,
889                    chunk_sizes,
890                    chunk_decompressed_sizes: chunk_output_files
891                        .iter()
892                        .map(|files| files.iter().map(|file| file.size).sum())
893                        .collect(),
894                    chunk_files,
895                    chunk_output_files,
896                }),
897            );
898        }
899    }
900
901    let (state_size, state_output_files) = package_single_component(
902        output_dir,
903        "state.tar.zst",
904        &state_source_files(source_datadir)?,
905    )?;
906    components.insert(
907        SnapshotComponentType::State.key().to_string(),
908        ComponentManifest::Single(SingleArchive {
909            file: "state.tar.zst".to_string(),
910            size: state_size,
911            decompressed_size: state_output_files.iter().map(|file| file.size).sum(),
912            blake3: None,
913            output_files: state_output_files,
914        }),
915    );
916
917    let rocksdb_files = rocksdb_source_files(source_datadir)?;
918    if !rocksdb_files.is_empty() {
919        let rocksdb = if rocksdb_archive_per_file {
920            let archives = package_rocksdb_archives(output_dir, rocksdb_files, previous)?;
921            info!(target: "reth::cli",
922                archives = archives.len(),
923                size = %super::DownloadProgress::format_size(
924                    archives.iter().map(|archive| archive.size).sum()
925                ),
926                "Found RocksDB indices"
927            );
928            ComponentManifest::Files(ArchiveSet { archives })
929        } else {
930            let (rocksdb_size, rocksdb_output_files) =
931                package_single_component(output_dir, "rocksdb_indices.tar.zst", &rocksdb_files)?;
932            ComponentManifest::Single(SingleArchive {
933                file: "rocksdb_indices.tar.zst".to_string(),
934                size: rocksdb_size,
935                decompressed_size: rocksdb_output_files.iter().map(|file| file.size).sum(),
936                blake3: None,
937                output_files: rocksdb_output_files,
938            })
939        };
940        components.insert(SnapshotComponentType::RocksdbIndices.key().to_string(), rocksdb);
941    }
942
943    let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
944
945    Ok(SnapshotManifest {
946        block,
947        chain_id,
948        storage_version: 2,
949        timestamp,
950        base_url: base_url.map(str::to_owned),
951        reth_version: Some(reth_node_core::version::version_metadata().short_version.to_string()),
952        components,
953        extensions: Default::default(),
954    })
955}
956
957/// Resolves an archive file path from a component key and naming convention.
958pub fn chunk_filename(component_key: &str, start: u64, end: u64) -> String {
959    format!("{component_key}-{start}-{end}.tar.zst")
960}
961
962#[derive(Debug)]
963struct PlannedChunk {
964    chunk_idx: u64,
965    archive_path: PathBuf,
966    source_files: Vec<PathBuf>,
967}
968
969#[derive(Debug)]
970struct PackagedChunk {
971    chunk_idx: u64,
972    size: u64,
973    output_files: Vec<OutputFileChecksum>,
974    /// Entry for `chunk_files`: the published URL when reused, otherwise the local file name.
975    file: String,
976}
977
978#[derive(Debug)]
979struct PlannedFile {
980    source_path: PathBuf,
981    relative_path: PathBuf,
982}
983
984fn source_files_for_chunk(
985    source_datadir: &Path,
986    component: SnapshotComponentType,
987    start: u64,
988    end: u64,
989) -> Result<Vec<PathBuf>> {
990    let Some(segment) = static_segment(component) else {
991        return Ok(Vec::new());
992    };
993
994    let static_files_dir = source_datadir.join("static_files");
995    let static_files_dir =
996        if static_files_dir.exists() { static_files_dir } else { source_datadir.to_path_buf() };
997    let prefix = format!("static_file_{}_{start}_{end}", segment.as_str());
998
999    let mut files = Vec::new();
1000    for entry in std::fs::read_dir(&static_files_dir)? {
1001        let entry = entry?;
1002        if !entry.file_type()?.is_file() {
1003            continue;
1004        }
1005        if entry.file_name().to_string_lossy().starts_with(&prefix) {
1006            files.push(entry.path());
1007        }
1008    }
1009
1010    files.sort_unstable();
1011    Ok(files)
1012}
1013
1014fn static_segment(component: SnapshotComponentType) -> Option<StaticFileSegment> {
1015    match component {
1016        SnapshotComponentType::Headers => Some(StaticFileSegment::Headers),
1017        SnapshotComponentType::Transactions => Some(StaticFileSegment::Transactions),
1018        SnapshotComponentType::TransactionSenders => Some(StaticFileSegment::TransactionSenders),
1019        SnapshotComponentType::Receipts => Some(StaticFileSegment::Receipts),
1020        SnapshotComponentType::AccountChangesets => Some(StaticFileSegment::AccountChangeSets),
1021        SnapshotComponentType::StorageChangesets => Some(StaticFileSegment::StorageChangeSets),
1022        SnapshotComponentType::State | SnapshotComponentType::RocksdbIndices => None,
1023    }
1024}
1025
1026fn state_source_files(source_datadir: &Path) -> Result<Vec<PlannedFile>> {
1027    let db_dir = source_datadir.join("db");
1028    if db_dir.exists() {
1029        return collect_files_recursive(&db_dir, Path::new("db"));
1030    }
1031
1032    if looks_like_db_dir(source_datadir)? {
1033        return collect_files_recursive(source_datadir, Path::new("db"));
1034    }
1035
1036    eyre::bail!("Could not find source state DB directory under {}", source_datadir.display());
1037}
1038
1039fn rocksdb_source_files(source_datadir: &Path) -> Result<Vec<PlannedFile>> {
1040    let rocksdb_dir = source_datadir.join("rocksdb");
1041    if !rocksdb_dir.exists() {
1042        return Ok(Vec::new());
1043    }
1044
1045    collect_files_recursive(&rocksdb_dir, Path::new("rocksdb"))
1046}
1047
1048fn looks_like_db_dir(path: &Path) -> Result<bool> {
1049    let entries = match std::fs::read_dir(path) {
1050        Ok(entries) => entries,
1051        Err(_) => return Ok(false),
1052    };
1053
1054    for entry in entries {
1055        let entry = entry?;
1056        if !entry.file_type()?.is_file() {
1057            continue;
1058        }
1059        let name = entry.file_name();
1060        let name = name.to_string_lossy();
1061        if name == "mdbx.dat" || name == "lock.mdb" || name == "data.mdb" {
1062            return Ok(true);
1063        }
1064    }
1065
1066    Ok(false)
1067}
1068
1069fn collect_files_recursive(root: &Path, output_prefix: &Path) -> Result<Vec<PlannedFile>> {
1070    let mut files = Vec::new();
1071    collect_files_recursive_inner(root, root, output_prefix, &mut files)?;
1072    files.sort_unstable_by(|a, b| a.relative_path.cmp(&b.relative_path));
1073    Ok(files)
1074}
1075
1076fn collect_files_recursive_inner(
1077    root: &Path,
1078    dir: &Path,
1079    output_prefix: &Path,
1080    files: &mut Vec<PlannedFile>,
1081) -> Result<()> {
1082    for entry in std::fs::read_dir(dir)? {
1083        let entry = entry?;
1084        let path = entry.path();
1085        let file_type = entry.file_type()?;
1086        if file_type.is_dir() {
1087            collect_files_recursive_inner(root, &path, output_prefix, files)?;
1088            continue;
1089        }
1090        if !file_type.is_file() {
1091            continue;
1092        }
1093
1094        let relative = path.strip_prefix(root)?.to_path_buf();
1095        files.push(PlannedFile { source_path: path, relative_path: output_prefix.join(relative) });
1096    }
1097
1098    Ok(())
1099}
1100
1101fn package_single_component(
1102    output_dir: &Path,
1103    archive_file_name: &str,
1104    files: &[PlannedFile],
1105) -> Result<(u64, Vec<OutputFileChecksum>)> {
1106    if files.is_empty() {
1107        eyre::bail!("Cannot package empty single archive: {}", archive_file_name);
1108    }
1109
1110    let archive_path = output_dir.join(archive_file_name);
1111    let output_files = write_archive_from_planned_files(&archive_path, files)?;
1112    let size = std::fs::metadata(&archive_path)?.len();
1113    Ok((size, output_files))
1114}
1115
1116/// Packages each RocksDB SST and blob file into its own archive and the remaining files into one.
1117///
1118/// SST archives are written to `rocksdb_indices/{file_stem}-{blake3}.tar.zst`, so an unchanged SST
1119/// gets the same archive name in every snapshot and publishers can upload it once. The file stem
1120/// keeps the final path segment unique, since downloads are cached by that segment.
1121///
1122/// An SST file that matches a single-file archive in the `previous` manifest's RocksDB indices is
1123/// not packaged; its archive entry points at the previously published archive instead.
1124fn package_rocksdb_archives(
1125    output_dir: &Path,
1126    files: Vec<PlannedFile>,
1127    previous: Option<&SnapshotManifest>,
1128) -> Result<Vec<SingleArchive>> {
1129    // Only immutable table and blob files directly under the RocksDB directory get their own
1130    // archive: their file numbers are unique there, while nested directories may repeat them.
1131    let (sst_files, other_files): (Vec<_>, Vec<_>) = files.into_iter().partition(|file| {
1132        file.relative_path.parent() == Some(Path::new("rocksdb")) &&
1133            file.relative_path.extension().is_some_and(|ext| ext == "sst" || ext == "blob")
1134    });
1135
1136    // Published SST archives by the file they extract, with absolute URLs.
1137    let mut published = HashMap::new();
1138    if let Some(previous) = previous &&
1139        let Some(ComponentManifest::Files(set)) =
1140            previous.component(SnapshotComponentType::RocksdbIndices)
1141    {
1142        for archive in &set.archives {
1143            if let [output] = archive.output_files.as_slice() {
1144                published.insert(
1145                    output.clone(),
1146                    SingleArchive {
1147                        file: resolve_archive_url(previous.base_url_or_empty(), &archive.file),
1148                        ..archive.clone()
1149                    },
1150                );
1151            }
1152        }
1153    }
1154
1155    let sst_dir = output_dir.join("rocksdb_indices");
1156    std::fs::create_dir_all(&sst_dir)?;
1157    let mut archives = sst_files
1158        .into_par_iter()
1159        .map(|planned| -> Result<SingleArchive> {
1160            if !published.is_empty() &&
1161                let Some(archive) = published.get(&hash_planned_file(&planned)?)
1162            {
1163                return Ok(archive.clone());
1164            }
1165
1166            let stem = planned
1167                .relative_path
1168                .file_stem()
1169                .ok_or_else(|| {
1170                    eyre::eyre!("Invalid RocksDB file path: {}", planned.relative_path.display())
1171                })?
1172                .to_string_lossy()
1173                .to_string();
1174            // The archive name depends on the checksum, which is known once the file is read.
1175            let temp_path = sst_dir.join(format!("{stem}.tar.zst.tmp"));
1176            let output_files =
1177                write_archive_from_planned_files(&temp_path, std::slice::from_ref(&planned))?;
1178            let output = &output_files[0];
1179            let file = format!("rocksdb_indices/{stem}-{}.tar.zst", output.blake3);
1180            std::fs::rename(&temp_path, output_dir.join(&file))?;
1181            Ok(SingleArchive {
1182                size: std::fs::metadata(output_dir.join(&file))?.len(),
1183                decompressed_size: output.size,
1184                file,
1185                blake3: None,
1186                output_files,
1187            })
1188        })
1189        .collect::<Result<Vec<_>>>()?;
1190    // Reused archives are absolute URLs, so order by the SST each archive extracts.
1191    archives.sort_unstable_by(|a, b| a.output_files[0].path.cmp(&b.output_files[0].path));
1192
1193    if !other_files.is_empty() {
1194        let file = "rocksdb_indices.tar.zst";
1195        let (size, output_files) = package_single_component(output_dir, file, &other_files)?;
1196        archives.push(SingleArchive {
1197            file: file.to_string(),
1198            size,
1199            decompressed_size: output_files.iter().map(|file| file.size).sum(),
1200            blake3: None,
1201            output_files,
1202        });
1203    }
1204
1205    Ok(archives)
1206}
1207
1208fn write_chunk_archive(path: &Path, source_files: &[PathBuf]) -> Result<Vec<OutputFileChecksum>> {
1209    write_archive_from_planned_files(path, &chunk_planned_files(source_files)?)
1210}
1211
1212/// Computes the output checksums a chunk archive of these files would record, without packaging.
1213fn hash_chunk_files(source_files: &[PathBuf]) -> Result<Vec<OutputFileChecksum>> {
1214    chunk_planned_files(source_files)?.iter().map(hash_planned_file).collect()
1215}
1216
1217/// Computes the output checksum an archive would record for this file, without packaging.
1218fn hash_planned_file(planned: &PlannedFile) -> Result<OutputFileChecksum> {
1219    let mut reader = HashingReader::new(reth_fs_util::open(&planned.source_path)?);
1220    std::io::copy(&mut reader, &mut std::io::sink())?;
1221    Ok(OutputFileChecksum {
1222        path: planned.relative_path.to_string_lossy().to_string(),
1223        size: reader.bytes_read,
1224        blake3: reader.finalize(),
1225    })
1226}
1227
1228fn chunk_planned_files(source_files: &[PathBuf]) -> Result<Vec<PlannedFile>> {
1229    source_files
1230        .iter()
1231        .map(|source_path| {
1232            let file_name = source_path.file_name().ok_or_else(|| {
1233                eyre::eyre!("Invalid source file path: {}", source_path.display())
1234            })?;
1235            Ok(PlannedFile {
1236                source_path: source_path.clone(),
1237                relative_path: PathBuf::from("static_files").join(file_name),
1238            })
1239        })
1240        .collect()
1241}
1242
1243fn write_archive_from_planned_files(
1244    path: &Path,
1245    files: &[PlannedFile],
1246) -> Result<Vec<OutputFileChecksum>> {
1247    let file = std::fs::File::create(path)?;
1248    let mut encoder = zstd::Encoder::new(file, 0)?;
1249    // Emit standard zstd frames with checksums for compatibility with external
1250    // tools such as `pzstd -d`.
1251    encoder.include_checksum(true)?;
1252    let mut builder = tar::Builder::new(encoder);
1253
1254    let mut output_files = Vec::with_capacity(files.len());
1255    for planned in files {
1256        let mut header = tar::Header::new_gnu();
1257        header.set_size(std::fs::metadata(&planned.source_path)?.len());
1258        header.set_mode(0o644);
1259        header.set_cksum();
1260
1261        let source_file = std::fs::File::open(&planned.source_path)?;
1262        let mut reader = HashingReader::new(source_file);
1263        builder.append_data(&mut header, &planned.relative_path, &mut reader)?;
1264
1265        output_files.push(OutputFileChecksum {
1266            path: planned.relative_path.to_string_lossy().to_string(),
1267            size: reader.bytes_read,
1268            blake3: reader.finalize(),
1269        });
1270    }
1271
1272    builder.finish()?;
1273    let encoder = builder.into_inner()?;
1274    encoder.finish()?;
1275
1276    Ok(output_files)
1277}
1278
1279struct HashingReader<R> {
1280    inner: R,
1281    hasher: Hasher,
1282    bytes_read: u64,
1283}
1284
1285impl<R: Read> HashingReader<R> {
1286    fn new(inner: R) -> Self {
1287        Self { inner, hasher: Hasher::new(), bytes_read: 0 }
1288    }
1289
1290    fn finalize(self) -> String {
1291        self.hasher.finalize().to_hex().to_string()
1292    }
1293}
1294
1295impl<R: Read> Read for HashingReader<R> {
1296    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1297        let n = self.inner.read(buf)?;
1298        if n > 0 {
1299            self.bytes_read += n as u64;
1300            self.hasher.update(&buf[..n]);
1301        }
1302        Ok(n)
1303    }
1304}
1305
1306#[cfg(test)]
1307pub(super) mod tests {
1308    use super::*;
1309    use alloy_consensus::Header;
1310    use alloy_primitives::B256;
1311    use reth_node_api::NodeTypes;
1312    use reth_provider::{test_utils::MockNodeTypes, StaticFileProviderBuilder, StaticFileWriter};
1313    use tempfile::tempdir;
1314
1315    fn test_manifest() -> SnapshotManifest {
1316        let mut components = BTreeMap::new();
1317        components.insert(
1318            "state".to_string(),
1319            ComponentManifest::Single(SingleArchive {
1320                file: "state.tar.zst".to_string(),
1321                size: 100,
1322                decompressed_size: 0,
1323                blake3: None,
1324                output_files: vec![],
1325            }),
1326        );
1327        components.insert(
1328            "transactions".to_string(),
1329            ComponentManifest::Chunked(ChunkedArchive {
1330                blocks_per_file: 500_000,
1331                total_blocks: 1_500_000,
1332                chunk_sizes: vec![80_000, 100_000, 120_000],
1333                chunk_decompressed_sizes: vec![],
1334                chunk_files: vec![],
1335                chunk_output_files: vec![vec![], vec![], vec![]],
1336            }),
1337        );
1338        components.insert(
1339            "headers".to_string(),
1340            ComponentManifest::Chunked(ChunkedArchive {
1341                blocks_per_file: 500_000,
1342                total_blocks: 1_500_000,
1343                chunk_sizes: vec![40_000, 50_000, 60_000],
1344                chunk_decompressed_sizes: vec![],
1345                chunk_files: vec![],
1346                chunk_output_files: vec![vec![], vec![], vec![]],
1347            }),
1348        );
1349        SnapshotManifest {
1350            block: 1_500_000,
1351            chain_id: 1,
1352            storage_version: 2,
1353            timestamp: 0,
1354            base_url: Some("https://example.com".to_string()),
1355            reth_version: None,
1356            components,
1357            extensions: Default::default(),
1358        }
1359    }
1360
1361    fn snapshot_source() -> tempfile::TempDir {
1362        let source = tempdir().unwrap();
1363        reth_fs_util::create_dir_all(source.path().join("db")).unwrap();
1364        reth_fs_util::write(source.path().join("db/mdbx.dat"), b"state-data").unwrap();
1365        source
1366    }
1367
1368    pub(crate) fn write_test_static_files(source: &Path, segment: StaticFileSegment, tip: u64) {
1369        let static_files = source.join("static_files");
1370        reth_fs_util::create_dir_all(&static_files).unwrap();
1371
1372        let provider = StaticFileProviderBuilder::read_write(&static_files)
1373            .with_blocks_per_file(10)
1374            .build::<<MockNodeTypes as NodeTypes>::Primitives>()
1375            .unwrap();
1376
1377        let mut writer = provider.get_writer(0, segment).unwrap();
1378        for number in 0..=tip {
1379            if segment == StaticFileSegment::Headers {
1380                writer
1381                    .append_header(&Header { number, ..Default::default() }, &B256::ZERO)
1382                    .unwrap();
1383            } else {
1384                writer.increment_block(number).unwrap();
1385            }
1386        }
1387
1388        writer.commit().unwrap();
1389    }
1390
1391    #[test]
1392    fn manifest_preserves_extensions() {
1393        let manifest: SnapshotManifest = serde_json::from_str(
1394            r#"{
1395                "block": 1,
1396                "chain_id": 1,
1397                "storage_version": 2,
1398                "timestamp": 0,
1399                "components": {},
1400                "consensus": { "archive": "consensus.tar.zst" }
1401            }"#,
1402        )
1403        .unwrap();
1404
1405        assert_eq!(
1406            manifest.extensions.get("consensus"),
1407            Some(&serde_json::json!({ "archive": "consensus.tar.zst" }))
1408        );
1409    }
1410
1411    #[test]
1412    fn archive_urls_for_distance_all() {
1413        let m = test_manifest();
1414        let urls = m.archive_urls_for_distance(SnapshotComponentType::Transactions, None);
1415        assert_eq!(urls.len(), 3);
1416        assert_eq!(urls[0], "https://example.com/transactions-0-499999.tar.zst");
1417        assert_eq!(urls[2], "https://example.com/transactions-1000000-1499999.tar.zst");
1418    }
1419
1420    #[test]
1421    fn archive_urls_for_distance_partial() {
1422        let m = test_manifest();
1423        // 600k blocks → needs 2 chunks (each 500k)
1424        let urls = m.archive_urls_for_distance(SnapshotComponentType::Transactions, Some(600_000));
1425        assert_eq!(urls.len(), 2);
1426        assert_eq!(urls[0], "https://example.com/transactions-500000-999999.tar.zst");
1427        assert_eq!(urls[1], "https://example.com/transactions-1000000-1499999.tar.zst");
1428    }
1429
1430    #[test]
1431    fn archive_urls_for_distance_single_component() {
1432        let m = test_manifest();
1433        // Single archives always return one URL regardless of distance
1434        let urls = m.archive_urls_for_distance(SnapshotComponentType::State, Some(100));
1435        assert_eq!(urls.len(), 1);
1436        assert_eq!(urls[0], "https://example.com/state.tar.zst");
1437    }
1438
1439    #[test]
1440    fn archive_urls_for_distance_rocksdb_indices_single_component() {
1441        let mut components = BTreeMap::new();
1442        components.insert(
1443            "rocksdb_indices".to_string(),
1444            ComponentManifest::Single(SingleArchive {
1445                file: "rocksdb_indices.tar.zst".to_string(),
1446                size: 777,
1447                decompressed_size: 0,
1448                blake3: None,
1449                output_files: vec![],
1450            }),
1451        );
1452        let m = SnapshotManifest {
1453            block: 1,
1454            chain_id: 1,
1455            storage_version: 2,
1456            timestamp: 0,
1457            base_url: Some("https://example.com".to_string()),
1458            reth_version: None,
1459            components,
1460            extensions: Default::default(),
1461        };
1462
1463        let urls = m.archive_urls_for_distance(SnapshotComponentType::RocksdbIndices, Some(10));
1464        assert_eq!(urls.len(), 1);
1465        assert_eq!(urls[0], "https://example.com/rocksdb_indices.tar.zst");
1466        assert_eq!(m.size_for_distance(SnapshotComponentType::RocksdbIndices, Some(10)), 777);
1467    }
1468
1469    #[test]
1470    fn generate_manifest_reuses_unchanged_rocksdb_ssts_from_previous_manifest() {
1471        let source = tempdir().unwrap();
1472        let db_dir = source.path().join("db");
1473        std::fs::create_dir_all(&db_dir).unwrap();
1474        std::fs::write(db_dir.join("mdbx.dat"), b"state-data").unwrap();
1475        let rocksdb_dir = source.path().join("rocksdb");
1476        std::fs::create_dir_all(&rocksdb_dir).unwrap();
1477        std::fs::write(rocksdb_dir.join("CURRENT"), b"MANIFEST-000001").unwrap();
1478        std::fs::write(rocksdb_dir.join("000007.sst"), b"sst-7").unwrap();
1479        std::fs::write(rocksdb_dir.join("000009.sst"), b"sst-9").unwrap();
1480        let hash = |contents: &[u8]| blake3::hash(contents).to_hex().to_string();
1481        let rocksdb_archives = |manifest: &SnapshotManifest| {
1482            let Some(ComponentManifest::Files(set)) =
1483                manifest.component(SnapshotComponentType::RocksdbIndices)
1484            else {
1485                panic!("rocksdb indices should be an archive set")
1486            };
1487            set.archives.clone()
1488        };
1489
1490        let previous = generate_manifest(
1491            source.path(),
1492            tempdir().unwrap().path(),
1493            Some("https://example.com/previous"),
1494            0,
1495            1,
1496            500_000,
1497            None,
1498            true,
1499        )
1500        .unwrap();
1501        let previous_archives = rocksdb_archives(&previous);
1502
1503        // 000007 is unchanged, 000009 is rewritten in place, and 000011 is new.
1504        std::fs::write(rocksdb_dir.join("000009.sst"), b"sst-9-compacted").unwrap();
1505        std::fs::write(rocksdb_dir.join("000011.sst"), b"sst-11").unwrap();
1506        let output = tempdir().unwrap();
1507        let mut next = generate_manifest(
1508            source.path(),
1509            output.path(),
1510            None,
1511            0,
1512            1,
1513            500_000,
1514            Some(&previous),
1515            true,
1516        )
1517        .unwrap();
1518        let archives = rocksdb_archives(&next);
1519
1520        let reused_sst = format!("rocksdb_indices/000007-{}.tar.zst", hash(b"sst-7"));
1521        let files = archives.iter().map(|archive| archive.file.as_str()).collect::<Vec<_>>();
1522        assert_eq!(
1523            files,
1524            [
1525                format!("https://example.com/previous/{reused_sst}"),
1526                format!("rocksdb_indices/000009-{}.tar.zst", hash(b"sst-9-compacted")),
1527                format!("rocksdb_indices/000011-{}.tar.zst", hash(b"sst-11")),
1528                "rocksdb_indices.tar.zst".to_string(),
1529            ]
1530        );
1531        assert_eq!(archives[0].size, previous_archives[0].size);
1532        assert_eq!(archives[0].output_files, previous_archives[0].output_files);
1533        assert!(!output.path().join(&reused_sst).exists());
1534        for archive in &archives[1..] {
1535            assert!(output.path().join(&archive.file).exists(), "{}", archive.file);
1536        }
1537
1538        // An archive reused from an older manifest keeps its absolute URL in later manifests.
1539        next.base_url = Some("https://example.com/next".to_string());
1540        let later = generate_manifest(
1541            source.path(),
1542            tempdir().unwrap().path(),
1543            None,
1544            0,
1545            1,
1546            500_000,
1547            Some(&next),
1548            true,
1549        )
1550        .unwrap();
1551        let later_archives = rocksdb_archives(&later);
1552        assert_eq!(later_archives[0].file, format!("https://example.com/previous/{reused_sst}"));
1553        assert_eq!(
1554            later_archives[2].file,
1555            format!("https://example.com/next/rocksdb_indices/000011-{}.tar.zst", hash(b"sst-11"))
1556        );
1557    }
1558
1559    #[test]
1560    fn generate_manifest_into_source_datadir_does_not_package_its_own_archives() {
1561        let source = tempdir().unwrap();
1562        let db_dir = source.path().join("db");
1563        std::fs::create_dir_all(&db_dir).unwrap();
1564        std::fs::write(db_dir.join("mdbx.dat"), b"state-data").unwrap();
1565        let rocksdb_dir = source.path().join("rocksdb");
1566        std::fs::create_dir_all(&rocksdb_dir).unwrap();
1567        std::fs::write(rocksdb_dir.join("CURRENT"), b"MANIFEST-000001").unwrap();
1568        std::fs::write(rocksdb_dir.join("000007.sst"), b"sst-7").unwrap();
1569
1570        for _ in 0..2 {
1571            let manifest =
1572                generate_manifest(source.path(), source.path(), None, 0, 1, 500_000, None, true)
1573                    .unwrap();
1574            let Some(ComponentManifest::Files(set)) =
1575                manifest.component(SnapshotComponentType::RocksdbIndices)
1576            else {
1577                panic!("rocksdb indices should be an archive set")
1578            };
1579            let outputs = set
1580                .archives
1581                .iter()
1582                .flat_map(|archive| &archive.output_files)
1583                .map(|file| file.path.as_str())
1584                .collect::<Vec<_>>();
1585            assert_eq!(outputs, ["rocksdb/000007.sst", "rocksdb/CURRENT"]);
1586        }
1587    }
1588
1589    #[test]
1590    fn rocksdb_archive_set_resolves_every_archive() {
1591        let json = r#"{
1592            "block": 1,
1593            "chain_id": 1,
1594            "storage_version": 2,
1595            "timestamp": 0,
1596            "base_url": "https://example.com/1700000",
1597            "components": {
1598                "rocksdb_indices": {
1599                    "archives": [
1600                        {
1601                            "file": "../rocksdb_indices/000007-aa.tar.zst",
1602                            "size": 10,
1603                            "decompressed_size": 100,
1604                            "output_files": [
1605                                {"path": "rocksdb/000007.sst", "size": 100, "blake3": "aa"}
1606                            ]
1607                        },
1608                        {
1609                            "file": "rocksdb_indices.tar.zst",
1610                            "size": 2,
1611                            "output_files": [
1612                                {"path": "rocksdb/CURRENT", "size": 15, "blake3": "bb"}
1613                            ]
1614                        }
1615                    ]
1616                }
1617            }
1618        }"#;
1619        let m: SnapshotManifest = serde_json::from_str(json).unwrap();
1620        let ty = SnapshotComponentType::RocksdbIndices;
1621        assert!(matches!(m.component(ty), Some(ComponentManifest::Files(_))));
1622        m.validate_output_paths().unwrap();
1623
1624        let urls = [
1625            "https://example.com/rocksdb_indices/000007-aa.tar.zst",
1626            "https://example.com/1700000/rocksdb_indices.tar.zst",
1627        ];
1628        assert_eq!(m.archive_urls(ty), urls);
1629        assert_eq!(m.archive_urls_for_distance(ty, Some(10)), urls);
1630        let archives = m.snapshot_archives_for_distance(ty, Some(10));
1631        assert_eq!(archives.iter().map(|archive| archive.url.as_str()).collect::<Vec<_>>(), urls);
1632        assert_eq!(archives[0].output_files[0].path, "rocksdb/000007.sst");
1633        assert_eq!(m.chunks_for_distance(ty, Some(10)), 2);
1634        assert_eq!(m.size_for_distance(ty, Some(10)), 12);
1635        assert_eq!(m.total_size(&[ty]), 12);
1636        assert_eq!(m.output_size_for_distance(ty, Some(10)), 115);
1637    }
1638
1639    #[test]
1640    fn archive_urls_for_distance_missing_component() {
1641        let m = test_manifest();
1642        let urls = m.archive_urls_for_distance(SnapshotComponentType::Receipts, None);
1643        assert!(urls.is_empty());
1644    }
1645
1646    #[test]
1647    fn chunks_for_distance_all() {
1648        let m = test_manifest();
1649        assert_eq!(m.chunks_for_distance(SnapshotComponentType::Transactions, None), 3);
1650    }
1651
1652    #[test]
1653    fn chunks_for_distance_partial() {
1654        let m = test_manifest();
1655        assert_eq!(m.chunks_for_distance(SnapshotComponentType::Transactions, Some(600_000)), 2);
1656        assert_eq!(m.chunks_for_distance(SnapshotComponentType::Transactions, Some(100_000)), 1);
1657    }
1658
1659    #[test]
1660    fn chunks_for_distance_single() {
1661        let m = test_manifest();
1662        assert_eq!(m.chunks_for_distance(SnapshotComponentType::State, None), 1);
1663        assert_eq!(m.chunks_for_distance(SnapshotComponentType::State, Some(100)), 1);
1664    }
1665
1666    /// A snapshot whose final chunk is partial: `total_blocks` is not a multiple of
1667    /// `blocks_per_file`, so the last chunk holds fewer than `blocks_per_file` blocks.
1668    /// Three chunks: `[0, 500k)`, `[500k, 1M)`, and `[1M, 1.005M)` — the last holds 5_000 blocks.
1669    fn partial_tail_manifest() -> SnapshotManifest {
1670        let mut components = BTreeMap::new();
1671        components.insert(
1672            "transactions".to_string(),
1673            ComponentManifest::Chunked(ChunkedArchive {
1674                blocks_per_file: 500_000,
1675                total_blocks: 1_005_000,
1676                chunk_sizes: vec![10, 20, 30],
1677                chunk_decompressed_sizes: vec![100, 200, 300],
1678                chunk_files: vec![],
1679                chunk_output_files: vec![vec![], vec![], vec![]],
1680            }),
1681        );
1682        SnapshotManifest {
1683            block: 1_005_000,
1684            chain_id: 1,
1685            storage_version: 2,
1686            timestamp: 0,
1687            base_url: Some("https://example.com".to_string()),
1688            reth_version: None,
1689            components,
1690            extensions: Default::default(),
1691        }
1692    }
1693
1694    #[test]
1695    fn tail_chunks_for_distance_accounts_for_partial_final_chunk() {
1696        let chunked = ChunkedArchive {
1697            blocks_per_file: 500_000,
1698            total_blocks: 1_005_000,
1699            chunk_sizes: vec![10, 20, 30],
1700            chunk_decompressed_sizes: vec![],
1701            chunk_files: vec![],
1702            chunk_output_files: vec![],
1703        };
1704        // The final chunk holds only 5_000 blocks, so covering 10_064 blocks needs the last two
1705        // chunks. The naive `distance.div_ceil(blocks_per_file)` returns 1 here and falls short.
1706        assert_eq!(chunked.tail_chunks_for_distance(10_064), 2);
1707        // A distance that fits inside the final chunk still needs just one.
1708        assert_eq!(chunked.tail_chunks_for_distance(5_000), 1);
1709        // One block more than the final chunk holds must pull in the previous chunk.
1710        assert_eq!(chunked.tail_chunks_for_distance(5_001), 2);
1711        assert_eq!(chunked.tail_chunks_for_distance(1), 1);
1712        // Covering everything selects all chunks and never exceeds the chunk count.
1713        assert_eq!(chunked.tail_chunks_for_distance(1_005_000), 3);
1714        assert_eq!(chunked.tail_chunks_for_distance(u64::MAX), 3);
1715    }
1716
1717    #[test]
1718    fn partial_final_chunk_downloads_enough_history() {
1719        let m = partial_tail_manifest();
1720        // The published snapshot's final chunk is partial (5_000 blocks). A --full download
1721        // asking for 10_064 blocks must pull the last two chunks, then prune the surplus,
1722        // rather than the single short tail chunk the old distance math selected.
1723        assert_eq!(m.chunks_for_distance(SnapshotComponentType::Transactions, Some(10_064)), 2);
1724
1725        let urls = m.archive_urls_for_distance(SnapshotComponentType::Transactions, Some(10_064));
1726        assert_eq!(urls.len(), 2);
1727        assert_eq!(urls[0], "https://example.com/transactions-500000-999999.tar.zst");
1728        assert_eq!(urls[1], "https://example.com/transactions-1000000-1499999.tar.zst");
1729
1730        let archives =
1731            m.snapshot_archives_for_distance(SnapshotComponentType::Transactions, Some(10_064));
1732        assert_eq!(archives.len(), 2);
1733
1734        // Reported sizes cover the selected tail chunks (indices 1 and 2).
1735        assert_eq!(m.size_for_distance(SnapshotComponentType::Transactions, Some(10_064)), 20 + 30);
1736        assert_eq!(
1737            m.output_size_for_distance(SnapshotComponentType::Transactions, Some(10_064)),
1738            200 + 300
1739        );
1740
1741        // A distance that fits inside the final chunk still selects a single chunk.
1742        assert_eq!(m.chunks_for_distance(SnapshotComponentType::Transactions, Some(5_000)), 1);
1743    }
1744
1745    #[test]
1746    fn chunks_for_distance_missing() {
1747        let m = test_manifest();
1748        assert_eq!(m.chunks_for_distance(SnapshotComponentType::Receipts, None), 0);
1749    }
1750
1751    #[test]
1752    fn component_selection_display() {
1753        assert_eq!(ComponentSelection::All.to_string(), "All");
1754        assert_eq!(ComponentSelection::Distance(10_064).to_string(), "Last 10064 blocks");
1755        assert_eq!(ComponentSelection::Since(15_537_394).to_string(), "Since block 15537394");
1756        assert_eq!(ComponentSelection::None.to_string(), "None");
1757    }
1758
1759    #[test]
1760    fn archive_urls_aligned_to_blocks_per_file() {
1761        // When total_blocks is not aligned to blocks_per_file, chunk boundaries
1762        // must still align to blocks_per_file (not total_blocks).
1763        let mut components = BTreeMap::new();
1764        components.insert(
1765            "storage_changesets".to_string(),
1766            ComponentManifest::Chunked(ChunkedArchive {
1767                blocks_per_file: 500_000,
1768                total_blocks: 24_396_822,
1769                chunk_sizes: vec![100; 49], // 49 chunks
1770                chunk_decompressed_sizes: vec![],
1771                chunk_files: vec![],
1772                chunk_output_files: vec![vec![]; 49],
1773            }),
1774        );
1775        let m = SnapshotManifest {
1776            block: 24_396_822,
1777            chain_id: 1,
1778            storage_version: 2,
1779            timestamp: 0,
1780            base_url: Some("https://example.com".to_string()),
1781            reth_version: None,
1782            components,
1783            extensions: Default::default(),
1784        };
1785        let urls = m.archive_urls(SnapshotComponentType::StorageChangesets);
1786        assert_eq!(urls.len(), 49);
1787        // First chunk: 0-499999 (not 0-396821 or similar)
1788        assert_eq!(urls[0], "https://example.com/storage_changesets-0-499999.tar.zst");
1789        // Last chunk: 24000000-24499999 (not 24000000-24396821)
1790        assert_eq!(urls[48], "https://example.com/storage_changesets-24000000-24499999.tar.zst");
1791    }
1792
1793    #[test]
1794    fn size_for_distance_sums_tail_chunks() {
1795        let m = test_manifest();
1796        // Transactions has chunk_sizes [80_000, 100_000, 120_000]
1797        // All: sum of all 3
1798        assert_eq!(m.size_for_distance(SnapshotComponentType::Transactions, None), 300_000);
1799        // Last 500K blocks = 1 chunk = last chunk only
1800        assert_eq!(
1801            m.size_for_distance(SnapshotComponentType::Transactions, Some(500_000)),
1802            120_000
1803        );
1804        // Last 600K blocks = 2 chunks = last two
1805        assert_eq!(
1806            m.size_for_distance(SnapshotComponentType::Transactions, Some(600_000)),
1807            220_000
1808        );
1809        // Single archive (state) always returns full size
1810        assert_eq!(m.size_for_distance(SnapshotComponentType::State, Some(100)), 100);
1811        // Missing component
1812        assert_eq!(m.size_for_distance(SnapshotComponentType::Receipts, None), 0);
1813    }
1814
1815    #[test]
1816    fn snapshot_archive_size_is_none_only_when_chunk_size_is_missing() {
1817        let mut m = test_manifest();
1818        if let Some(ComponentManifest::Single(single)) = m.components.get_mut("state") {
1819            single.size = 0;
1820        }
1821        if let Some(ComponentManifest::Chunked(chunked)) = m.components.get_mut("headers") {
1822            chunked.chunk_sizes.clear();
1823        }
1824
1825        let state = m.snapshot_archives_for_distance(SnapshotComponentType::State, None);
1826        let headers = m.snapshot_archives_for_distance(SnapshotComponentType::Headers, None);
1827
1828        assert_eq!(state[0].size, Some(0));
1829        assert!(headers.iter().all(|archive| archive.size.is_none()));
1830    }
1831
1832    #[test]
1833    fn manifest_output_paths_must_stay_relative() {
1834        fn output(path: &str) -> OutputFileChecksum {
1835            OutputFileChecksum { path: path.into(), size: 0, blake3: String::new() }
1836        }
1837
1838        let mut manifest = test_manifest();
1839        let mut with_outputs = |single: &[&str], chunks: &[&str]| {
1840            manifest.components.insert(
1841                "state".into(),
1842                ComponentManifest::Single(SingleArchive {
1843                    file: "state.tar.zst".into(),
1844                    size: 1,
1845                    decompressed_size: 0,
1846                    blake3: None,
1847                    output_files: single.iter().map(|path| output(path)).collect(),
1848                }),
1849            );
1850            manifest.components.insert(
1851                "transactions".into(),
1852                ComponentManifest::Chunked(ChunkedArchive {
1853                    blocks_per_file: 500_000,
1854                    total_blocks: 500_000,
1855                    chunk_sizes: vec![1],
1856                    chunk_decompressed_sizes: vec![],
1857                    chunk_files: vec![],
1858                    chunk_output_files: vec![chunks.iter().map(|path| output(path)).collect()],
1859                }),
1860            );
1861            manifest.validate_output_paths()
1862        };
1863
1864        with_outputs(&["db/mdbx.dat", "./static_files/headers"], &["static_files/a/b"]).unwrap();
1865        for bad in ["/etc/passwd", "../outside", "db/../../outside", "db/..", ".", "", "./"] {
1866            let err = with_outputs(&[bad], &[]).unwrap_err();
1867            assert!(format!("{err:#}").contains("Invalid manifest output file path"), "{bad}");
1868            assert!(with_outputs(&[], &[bad]).is_err(), "{bad}");
1869        }
1870    }
1871
1872    #[test]
1873    fn output_size_for_distance_uses_manifest_or_output_files() {
1874        let m = test_manifest();
1875        assert_eq!(m.output_size_for_distance(SnapshotComponentType::Transactions, None), 0);
1876
1877        let mut components = BTreeMap::new();
1878        components.insert(
1879            "state".to_string(),
1880            ComponentManifest::Single(SingleArchive {
1881                file: "state.tar.zst".to_string(),
1882                size: 100,
1883                decompressed_size: 1_000,
1884                blake3: None,
1885                output_files: vec![OutputFileChecksum {
1886                    path: "db/mdbx.dat".to_string(),
1887                    size: 1_000,
1888                    blake3: "h0".to_string(),
1889                }],
1890            }),
1891        );
1892        components.insert(
1893            "transactions".to_string(),
1894            ComponentManifest::Chunked(ChunkedArchive {
1895                blocks_per_file: 500_000,
1896                total_blocks: 1_000_000,
1897                chunk_sizes: vec![80_000, 120_000],
1898                chunk_decompressed_sizes: vec![111, 222],
1899                chunk_files: vec![],
1900                chunk_output_files: vec![
1901                    vec![OutputFileChecksum {
1902                        path: "static_files/static_file_transactions_0_499999.bin".to_string(),
1903                        size: 111,
1904                        blake3: "h0".to_string(),
1905                    }],
1906                    vec![OutputFileChecksum {
1907                        path: "static_files/static_file_transactions_500000_999999.bin".to_string(),
1908                        size: 222,
1909                        blake3: "h1".to_string(),
1910                    }],
1911                ],
1912            }),
1913        );
1914        let manifest = SnapshotManifest {
1915            block: 1_000_000,
1916            chain_id: 1,
1917            storage_version: 2,
1918            timestamp: 0,
1919            base_url: Some("https://example.com".to_string()),
1920            reth_version: None,
1921            components,
1922            extensions: Default::default(),
1923        };
1924
1925        assert_eq!(manifest.output_size_for_distance(SnapshotComponentType::State, None), 1_000);
1926        assert_eq!(
1927            manifest.output_size_for_distance(SnapshotComponentType::Transactions, None),
1928            333
1929        );
1930        assert_eq!(
1931            manifest.output_size_for_distance(SnapshotComponentType::Transactions, Some(500_000)),
1932            222
1933        );
1934    }
1935
1936    #[test]
1937    fn archive_descriptors_include_checksum_metadata() {
1938        let mut components = BTreeMap::new();
1939        components.insert(
1940            "state".to_string(),
1941            ComponentManifest::Single(SingleArchive {
1942                file: "state.tar.zst".to_string(),
1943                size: 100,
1944                decompressed_size: 1_000,
1945                blake3: Some("abc123".to_string()),
1946                output_files: vec![OutputFileChecksum {
1947                    path: "db/mdbx.dat".to_string(),
1948                    size: 1000,
1949                    blake3: "s0".to_string(),
1950                }],
1951            }),
1952        );
1953        components.insert(
1954            "transactions".to_string(),
1955            ComponentManifest::Chunked(ChunkedArchive {
1956                blocks_per_file: 500_000,
1957                total_blocks: 1_000_000,
1958                chunk_sizes: vec![80_000, 120_000],
1959                chunk_decompressed_sizes: vec![111, 222],
1960                chunk_files: vec![],
1961                chunk_output_files: vec![
1962                    vec![OutputFileChecksum {
1963                        path: "static_files/static_file_transactions_0_499999.bin".to_string(),
1964                        size: 111,
1965                        blake3: "h0".to_string(),
1966                    }],
1967                    vec![OutputFileChecksum {
1968                        path: "static_files/static_file_transactions_500000_999999.bin".to_string(),
1969                        size: 222,
1970                        blake3: "h1".to_string(),
1971                    }],
1972                ],
1973            }),
1974        );
1975
1976        let m = SnapshotManifest {
1977            block: 1_000_000,
1978            chain_id: 1,
1979            storage_version: 2,
1980            timestamp: 0,
1981            base_url: Some("https://example.com".to_string()),
1982            reth_version: None,
1983            components,
1984            extensions: Default::default(),
1985        };
1986
1987        let state = m.snapshot_archives_for_distance(SnapshotComponentType::State, None);
1988        assert_eq!(state.len(), 1);
1989        assert_eq!(state[0].file_name, "state.tar.zst");
1990        assert_eq!(state[0].blake3.as_deref(), Some("abc123"));
1991        assert_eq!(state[0].output_files.len(), 1);
1992
1993        let tx = m.snapshot_archives_for_distance(SnapshotComponentType::Transactions, None);
1994        assert_eq!(tx.len(), 2);
1995        assert_eq!(tx[0].blake3, None);
1996        assert_eq!(tx[1].blake3, None);
1997        assert_eq!(tx[0].output_files[0].size, 111);
1998    }
1999
2000    #[test]
2001    fn generate_manifest_includes_state_single_archive() {
2002        let source = tempdir().unwrap();
2003        let output = tempdir().unwrap();
2004        let db_dir = source.path().join("db");
2005        std::fs::create_dir_all(&db_dir).unwrap();
2006        std::fs::write(db_dir.join("mdbx.dat"), b"state-data").unwrap();
2007
2008        let manifest =
2009            generate_manifest(source.path(), output.path(), None, 0, 1, 500_000, None, false)
2010                .unwrap();
2011
2012        let state = manifest.component(SnapshotComponentType::State).unwrap();
2013        let ComponentManifest::Single(state) = state else {
2014            panic!("state should be a single archive")
2015        };
2016        assert_eq!(state.file, "state.tar.zst");
2017        assert!(state.decompressed_size > 0);
2018        assert!(!state.output_files.is_empty());
2019        assert_eq!(state.output_files[0].path, "db/mdbx.dat");
2020        assert!(output.path().join("state.tar.zst").exists());
2021    }
2022
2023    #[test]
2024    fn generate_manifest_includes_rocksdb_single_archive_when_present() {
2025        let source = tempdir().unwrap();
2026        let output = tempdir().unwrap();
2027        let db_dir = source.path().join("db");
2028        std::fs::create_dir_all(&db_dir).unwrap();
2029        std::fs::write(db_dir.join("mdbx.dat"), b"state-data").unwrap();
2030        let rocksdb_dir = source.path().join("rocksdb");
2031        std::fs::create_dir_all(&rocksdb_dir).unwrap();
2032        std::fs::write(rocksdb_dir.join("CURRENT"), b"MANIFEST-000001").unwrap();
2033
2034        let manifest =
2035            generate_manifest(source.path(), output.path(), None, 0, 1, 500_000, None, false)
2036                .unwrap();
2037
2038        let rocksdb = manifest.component(SnapshotComponentType::RocksdbIndices).unwrap();
2039        let ComponentManifest::Single(rocksdb) = rocksdb else {
2040            panic!("rocksdb indices should be a single archive")
2041        };
2042        assert_eq!(rocksdb.file, "rocksdb_indices.tar.zst");
2043        assert!(rocksdb.decompressed_size > 0);
2044        assert!(!rocksdb.output_files.is_empty());
2045        assert_eq!(rocksdb.output_files[0].path, "rocksdb/CURRENT");
2046        assert!(output.path().join("rocksdb_indices.tar.zst").exists());
2047    }
2048
2049    #[test]
2050    fn generate_manifest_packages_each_rocksdb_sst_separately() {
2051        let source = tempdir().unwrap();
2052        let db_dir = source.path().join("db");
2053        std::fs::create_dir_all(&db_dir).unwrap();
2054        std::fs::write(db_dir.join("mdbx.dat"), b"state-data").unwrap();
2055        let rocksdb_dir = source.path().join("rocksdb");
2056        std::fs::create_dir_all(&rocksdb_dir).unwrap();
2057        std::fs::write(rocksdb_dir.join("CURRENT"), b"MANIFEST-000001").unwrap();
2058        std::fs::write(rocksdb_dir.join("MANIFEST-000001"), b"manifest").unwrap();
2059        std::fs::write(rocksdb_dir.join("000007.sst"), b"sst-7").unwrap();
2060        std::fs::write(rocksdb_dir.join("000009.sst"), b"sst-9").unwrap();
2061        std::fs::write(rocksdb_dir.join("000010.blob"), b"blob-10").unwrap();
2062        // A nested SST with a top-level file name stays in the shared archive.
2063        std::fs::create_dir_all(rocksdb_dir.join("checkpoint")).unwrap();
2064        std::fs::write(rocksdb_dir.join("checkpoint/000007.sst"), b"sst-7").unwrap();
2065        let sst_7_hash = blake3::hash(b"sst-7").to_hex().to_string();
2066        let sst_9_hash = blake3::hash(b"sst-9").to_hex().to_string();
2067
2068        let output = tempdir().unwrap();
2069        let manifest =
2070            generate_manifest(source.path(), output.path(), None, 0, 1, 500_000, None, true)
2071                .unwrap();
2072
2073        let rocksdb = manifest.component(SnapshotComponentType::RocksdbIndices).unwrap();
2074        let ComponentManifest::Files(set) = rocksdb else {
2075            panic!("rocksdb indices should be an archive set")
2076        };
2077        let files = set.archives.iter().map(|archive| archive.file.clone()).collect::<Vec<_>>();
2078        assert_eq!(
2079            files,
2080            [
2081                format!("rocksdb_indices/000007-{sst_7_hash}.tar.zst"),
2082                format!("rocksdb_indices/000009-{sst_9_hash}.tar.zst"),
2083                format!("rocksdb_indices/000010-{}.tar.zst", blake3::hash(b"blob-10").to_hex()),
2084                "rocksdb_indices.tar.zst".to_string(),
2085            ]
2086        );
2087        for archive in &set.archives {
2088            assert!(output.path().join(&archive.file).exists(), "{}", archive.file);
2089            assert_eq!(
2090                archive.size,
2091                std::fs::metadata(output.path().join(&archive.file)).unwrap().len()
2092            );
2093        }
2094        assert_eq!(
2095            set.archives[0].output_files,
2096            [OutputFileChecksum {
2097                path: "rocksdb/000007.sst".to_string(),
2098                size: 5,
2099                blake3: sst_7_hash
2100            }]
2101        );
2102        assert_eq!(set.archives[0].decompressed_size, 5);
2103        assert_eq!(
2104            set.archives[3].output_files.iter().map(|file| file.path.as_str()).collect::<Vec<_>>(),
2105            ["rocksdb/CURRENT", "rocksdb/MANIFEST-000001", "rocksdb/checkpoint/000007.sst"]
2106        );
2107        assert!(!output.path().join("rocksdb_indices/000007.tar.zst.tmp").exists());
2108        assert_eq!(manifest.chunks_for_distance(SnapshotComponentType::RocksdbIndices, None), 4);
2109
2110        // An unchanged SST keeps its archive name in a later snapshot, so publishers can reuse it.
2111        std::fs::remove_file(rocksdb_dir.join("000009.sst")).unwrap();
2112        std::fs::write(rocksdb_dir.join("000011.sst"), b"sst-11").unwrap();
2113        let later_output = tempdir().unwrap();
2114        let later =
2115            generate_manifest(source.path(), later_output.path(), None, 0, 1, 500_000, None, true)
2116                .unwrap();
2117        let Some(ComponentManifest::Files(later_set)) =
2118            later.component(SnapshotComponentType::RocksdbIndices)
2119        else {
2120            panic!("rocksdb indices should be an archive set")
2121        };
2122        assert_eq!(later_set.archives[0].file, set.archives[0].file);
2123        assert_eq!(
2124            later_set.archives[2].file,
2125            format!("rocksdb_indices/000011-{}.tar.zst", blake3::hash(b"sst-11").to_hex())
2126        );
2127    }
2128
2129    #[test]
2130    fn resolve_archive_url_joins_nested_paths_under_base() {
2131        assert_eq!(
2132            resolve_archive_url(
2133                "https://example.com/mainnet",
2134                "static_files/headers-0-499999.tar.zst"
2135            ),
2136            "https://example.com/mainnet/static_files/headers-0-499999.tar.zst"
2137        );
2138        assert_eq!(
2139            resolve_archive_url("https://example.com/mainnet/", "1700000/state.tar.zst"),
2140            "https://example.com/mainnet/1700000/state.tar.zst"
2141        );
2142        assert_eq!(
2143            resolve_archive_url("https://example.com/mainnet", "headers-0-499999.tar.zst"),
2144            "https://example.com/mainnet/headers-0-499999.tar.zst"
2145        );
2146    }
2147
2148    #[test]
2149    fn chunk_files_resolve_relative_to_root_base_url() {
2150        let mut components = BTreeMap::new();
2151        components.insert(
2152            "headers".to_string(),
2153            ComponentManifest::Chunked(ChunkedArchive {
2154                blocks_per_file: 500_000,
2155                total_blocks: 1_000_000,
2156                chunk_sizes: vec![40_000, 50_000],
2157                chunk_decompressed_sizes: vec![],
2158                chunk_files: vec![
2159                    "static_files/headers-0-499999.tar.zst".to_string(),
2160                    "1700000/headers-500000-999999.tar.zst".to_string(),
2161                ],
2162                chunk_output_files: vec![vec![], vec![]],
2163            }),
2164        );
2165        components.insert(
2166            "state".to_string(),
2167            ComponentManifest::Single(SingleArchive {
2168                file: "1700000/state.tar.zst".to_string(),
2169                size: 100,
2170                decompressed_size: 0,
2171                blake3: None,
2172                output_files: vec![],
2173            }),
2174        );
2175
2176        let m = SnapshotManifest {
2177            block: 1_000_000,
2178            chain_id: 1,
2179            storage_version: 2,
2180            timestamp: 1_700_000,
2181            base_url: Some("https://example.com/mainnet".to_string()),
2182            reth_version: None,
2183            components,
2184            extensions: Default::default(),
2185        };
2186
2187        let urls = m.archive_urls(SnapshotComponentType::Headers);
2188        assert_eq!(urls.len(), 2, "exactly 2 header chunk URLs");
2189        assert_eq!(
2190            urls[0], "https://example.com/mainnet/static_files/headers-0-499999.tar.zst",
2191            "finalized chunk stays under static_files/"
2192        );
2193        assert_eq!(
2194            urls[1], "https://example.com/mainnet/1700000/headers-500000-999999.tar.zst",
2195            "tip chunk resolves under the run timestamp directory"
2196        );
2197
2198        let state = m.snapshot_archives_for_distance(SnapshotComponentType::State, None);
2199        assert_eq!(state.len(), 1, "exactly one state archive");
2200        assert_eq!(
2201            state[0].url, "https://example.com/mainnet/1700000/state.tar.zst",
2202            "single archive file path joins under root base_url without ../"
2203        );
2204        assert_eq!(state[0].file_name, "1700000/state.tar.zst");
2205
2206        let headers =
2207            m.snapshot_archives_for_distance(SnapshotComponentType::Headers, Some(500_000));
2208        assert_eq!(headers.len(), 1, "distance selection returns only the tip chunk");
2209        assert_eq!(
2210            headers[0].file_name, "1700000/headers-500000-999999.tar.zst",
2211            "file_name keeps the relative path from chunk_files"
2212        );
2213        assert_eq!(
2214            headers[0].url,
2215            "https://example.com/mainnet/1700000/headers-500000-999999.tar.zst"
2216        );
2217    }
2218
2219    #[test]
2220    fn chunk_files_absent_keeps_default_chunk_names() {
2221        let m = test_manifest();
2222        let archives = m.snapshot_archives_for_distance(SnapshotComponentType::Transactions, None);
2223        assert_eq!(archives.len(), 3);
2224        assert_eq!(archives[0].file_name, "transactions-0-499999.tar.zst");
2225        assert_eq!(archives[0].url, "https://example.com/transactions-0-499999.tar.zst");
2226    }
2227
2228    #[test]
2229    fn resolve_archive_url_normalizes_parent_dirs_and_leading_slashes() {
2230        assert_eq!(
2231            resolve_archive_url("https://example.com/static_files", "../1700000/state.tar.zst"),
2232            "https://example.com/1700000/state.tar.zst",
2233            "../ under a static_files base resolves to the run directory"
2234        );
2235        assert_eq!(
2236            resolve_archive_url(
2237                "https://example.com/mainnet",
2238                "/static_files/headers-0-499999.tar.zst"
2239            ),
2240            "https://example.com/mainnet/static_files/headers-0-499999.tar.zst",
2241            "leading slash is stripped so the base path prefix is preserved"
2242        );
2243    }
2244
2245    #[test]
2246    fn resolve_archive_url_keeps_absolute_urls() {
2247        let url = "https://example.com/previous/headers-0-9.tar.zst";
2248        for base_url in ["", "https://example.com/mainnet", "not-a-url"] {
2249            assert_eq!(resolve_archive_url(base_url, url), url, "base_url {base_url:?}");
2250        }
2251    }
2252
2253    #[test]
2254    fn mismatched_chunk_files_length_falls_back_to_default_names() {
2255        let mut components = BTreeMap::new();
2256        components.insert(
2257            "headers".to_string(),
2258            ComponentManifest::Chunked(ChunkedArchive {
2259                blocks_per_file: 500_000,
2260                total_blocks: 1_000_000,
2261                chunk_sizes: vec![40_000, 50_000],
2262                chunk_decompressed_sizes: vec![],
2263                // Only one entry for two chunks — ignored in favor of default names.
2264                chunk_files: vec!["static_files/headers-0-499999.tar.zst".to_string()],
2265                chunk_output_files: vec![vec![], vec![]],
2266            }),
2267        );
2268        let m = SnapshotManifest {
2269            block: 1_000_000,
2270            chain_id: 1,
2271            storage_version: 2,
2272            timestamp: 0,
2273            base_url: Some("https://example.com/mainnet".to_string()),
2274            reth_version: None,
2275            components,
2276            extensions: Default::default(),
2277        };
2278
2279        let ComponentManifest::Chunked(chunked) =
2280            m.component(SnapshotComponentType::Headers).unwrap()
2281        else {
2282            panic!("headers should be chunked");
2283        };
2284        assert!(!chunked.chunk_files_are_consistent());
2285
2286        let urls = m.archive_urls(SnapshotComponentType::Headers);
2287        assert_eq!(urls.len(), 2);
2288        assert_eq!(
2289            urls[0], "https://example.com/mainnet/headers-0-499999.tar.zst",
2290            "mismatched chunk_files must not partially apply"
2291        );
2292        assert_eq!(urls[1], "https://example.com/mainnet/headers-500000-999999.tar.zst");
2293    }
2294
2295    #[test]
2296    fn generate_manifest_uses_actual_component_block_ranges() {
2297        let source = snapshot_source();
2298        let output = tempdir().unwrap();
2299        write_test_static_files(source.path(), StaticFileSegment::Headers, 24);
2300        write_test_static_files(source.path(), StaticFileSegment::Transactions, 21);
2301
2302        // The declared height is beyond both components' actual tips, within the same chunk.
2303        let manifest =
2304            generate_manifest(source.path(), output.path(), None, 29, 1, 10, None, false).unwrap();
2305        assert_eq!(manifest.block, 29);
2306        for (component, expected_blocks) in
2307            [(SnapshotComponentType::Headers, 25), (SnapshotComponentType::Transactions, 22)]
2308        {
2309            let ComponentManifest::Chunked(chunked) = manifest.component(component).unwrap() else {
2310                panic!("component should be chunked");
2311            };
2312
2313            assert_eq!(chunked.total_blocks, expected_blocks);
2314            assert_eq!(chunked.num_chunks(), 3);
2315            assert_eq!(chunked.chunk_sizes.len(), 3);
2316            assert_eq!(chunked.chunk_output_files.len(), 3);
2317            assert_eq!(chunked.tail_chunks_for_distance(6), 2);
2318            for (index, size) in chunked.chunk_sizes.iter().enumerate() {
2319                let path =
2320                    output.path().join(chunked.chunk_relative_path(component.key(), index as u64));
2321                assert_eq!(reth_fs_util::metadata(path).unwrap().len(), *size);
2322            }
2323        }
2324    }
2325
2326    #[test]
2327    fn generate_manifest_includes_genesis_and_chunk_boundary_blocks() {
2328        for tip in [0, 9, 10, 19, 20] {
2329            let source = snapshot_source();
2330            let output = tempdir().unwrap();
2331            write_test_static_files(source.path(), StaticFileSegment::Headers, tip);
2332
2333            let manifest =
2334                generate_manifest(source.path(), output.path(), None, tip, 1, 10, None, false)
2335                    .unwrap();
2336            let ComponentManifest::Chunked(chunked) =
2337                manifest.component(SnapshotComponentType::Headers).unwrap()
2338            else {
2339                panic!("headers should be chunked");
2340            };
2341
2342            assert_eq!(chunked.total_blocks, tip + 1);
2343            assert_eq!(chunked.num_chunks(), tip / 10 + 1);
2344            assert_eq!(chunked.chunk_sizes.len() as u64, chunked.num_chunks());
2345        }
2346    }
2347
2348    #[test]
2349    fn generate_manifest_counts_whole_selected_chunks() {
2350        let source = snapshot_source();
2351        write_test_static_files(source.path(), StaticFileSegment::Headers, 24);
2352
2353        // Selecting a chunk copies its whole file, including blocks beyond the declared height.
2354        for (block, expected_blocks) in [(9, 10), (10, 20), (20, 25), (39, 25)] {
2355            let output = tempdir().unwrap();
2356            let manifest =
2357                generate_manifest(source.path(), output.path(), None, block, 1, 10, None, false)
2358                    .unwrap();
2359
2360            let ComponentManifest::Chunked(chunked) =
2361                manifest.component(SnapshotComponentType::Headers).unwrap()
2362            else {
2363                panic!("headers should be chunked");
2364            };
2365
2366            assert_eq!(chunked.total_blocks, expected_blocks);
2367            assert_eq!(chunked.chunk_sizes.len() as u64, chunked.num_chunks());
2368        }
2369    }
2370
2371    #[test]
2372    fn generate_manifest_reuses_sealed_chunks_from_previous_manifest() {
2373        let previous_source = snapshot_source();
2374        let previous_output = tempdir().unwrap();
2375        write_test_static_files(previous_source.path(), StaticFileSegment::Headers, 24);
2376        let previous = generate_manifest(
2377            previous_source.path(),
2378            previous_output.path(),
2379            Some("https://example.com/previous"),
2380            24,
2381            1,
2382            10,
2383            None,
2384            false,
2385        )
2386        .unwrap();
2387
2388        let source = snapshot_source();
2389        let output = tempdir().unwrap();
2390        write_test_static_files(source.path(), StaticFileSegment::Headers, 34);
2391        let manifest = generate_manifest(
2392            source.path(),
2393            output.path(),
2394            None,
2395            34,
2396            1,
2397            10,
2398            Some(&previous),
2399            false,
2400        )
2401        .unwrap();
2402
2403        let ComponentManifest::Chunked(previous_headers) =
2404            previous.component(SnapshotComponentType::Headers).unwrap()
2405        else {
2406            panic!("headers should be chunked");
2407        };
2408
2409        let ComponentManifest::Chunked(headers) =
2410            manifest.component(SnapshotComponentType::Headers).unwrap()
2411        else {
2412            panic!("headers should be chunked");
2413        };
2414
2415        // Chunks 0 and 1 were sealed in both snapshots; chunk 2 was the previous tip.
2416        assert_eq!(
2417            manifest.archive_urls(SnapshotComponentType::Headers),
2418            vec![
2419                "https://example.com/previous/headers-0-9.tar.zst",
2420                "https://example.com/previous/headers-10-19.tar.zst",
2421                "headers-20-29.tar.zst",
2422                "headers-30-39.tar.zst",
2423            ]
2424        );
2425        assert_eq!(headers.chunk_sizes[..2], previous_headers.chunk_sizes[..2]);
2426        assert_eq!(headers.chunk_output_files[..2], previous_headers.chunk_output_files[..2]);
2427        assert!(!output.path().join("headers-0-9.tar.zst").exists());
2428        assert!(!output.path().join("headers-10-19.tar.zst").exists());
2429        for index in 2..4 {
2430            let path = output.path().join(headers.chunk_relative_path("headers", index));
2431            assert_eq!(
2432                reth_fs_util::metadata(path).unwrap().len(),
2433                headers.chunk_sizes[index as usize]
2434            );
2435        }
2436
2437        // A later snapshot keeps pointing reused chunks at their original archives.
2438        let mut manifest = manifest;
2439        manifest.base_url = Some("https://example.com/current".to_string());
2440        let next_source = snapshot_source();
2441        write_test_static_files(next_source.path(), StaticFileSegment::Headers, 44);
2442        let next = generate_manifest(
2443            next_source.path(),
2444            tempdir().unwrap().path(),
2445            None,
2446            44,
2447            1,
2448            10,
2449            Some(&manifest),
2450            false,
2451        )
2452        .unwrap();
2453        assert_eq!(
2454            next.archive_urls(SnapshotComponentType::Headers),
2455            vec![
2456                "https://example.com/previous/headers-0-9.tar.zst",
2457                "https://example.com/previous/headers-10-19.tar.zst",
2458                "https://example.com/current/headers-20-29.tar.zst",
2459                "headers-30-39.tar.zst",
2460                "headers-40-49.tar.zst",
2461            ]
2462        );
2463    }
2464
2465    #[test]
2466    fn generate_manifest_rejects_sealed_chunk_that_differs_from_previous_manifest() {
2467        let source = snapshot_source();
2468        write_test_static_files(source.path(), StaticFileSegment::Headers, 24);
2469        let mut previous = generate_manifest(
2470            source.path(),
2471            tempdir().unwrap().path(),
2472            Some("https://example.com/previous"),
2473            24,
2474            1,
2475            10,
2476            None,
2477            false,
2478        )
2479        .unwrap();
2480        let Some(ComponentManifest::Chunked(headers)) =
2481            previous.components.get_mut(SnapshotComponentType::Headers.key())
2482        else {
2483            panic!("headers should be chunked");
2484        };
2485
2486        headers.chunk_output_files[0][0].blake3 = "00".repeat(32);
2487
2488        let err = generate_manifest(
2489            source.path(),
2490            tempdir().unwrap().path(),
2491            None,
2492            24,
2493            1,
2494            10,
2495            Some(&previous),
2496            false,
2497        )
2498        .unwrap_err();
2499        assert!(err.to_string().contains("differs from the previous manifest"), "{err}");
2500    }
2501
2502    #[test]
2503    fn generate_manifest_rejects_previous_manifest_without_absolute_base_url() {
2504        let source = snapshot_source();
2505        write_test_static_files(source.path(), StaticFileSegment::Headers, 24);
2506        let mut previous = generate_manifest(
2507            source.path(),
2508            tempdir().unwrap().path(),
2509            Some("https://example.com/previous"),
2510            24,
2511            1,
2512            10,
2513            None,
2514            false,
2515        )
2516        .unwrap();
2517
2518        for base_url in [None, Some(""), Some("previous")] {
2519            previous.base_url = base_url.map(str::to_owned);
2520            let err = generate_manifest(
2521                source.path(),
2522                tempdir().unwrap().path(),
2523                None,
2524                24,
2525                1,
2526                10,
2527                Some(&previous),
2528                false,
2529            )
2530            .unwrap_err();
2531            assert_eq!(
2532                err.to_string(),
2533                "Previous manifest has no absolute base_url to locate its archives"
2534            );
2535        }
2536    }
2537
2538    #[test]
2539    fn generate_manifest_packages_chunks_when_previous_chunk_files_are_inconsistent() {
2540        let source = snapshot_source();
2541        write_test_static_files(source.path(), StaticFileSegment::Headers, 24);
2542        let mut previous = generate_manifest(
2543            source.path(),
2544            tempdir().unwrap().path(),
2545            Some("https://example.com/previous"),
2546            24,
2547            1,
2548            10,
2549            None,
2550            false,
2551        )
2552        .unwrap();
2553        let Some(ComponentManifest::Chunked(headers)) =
2554            previous.components.get_mut(SnapshotComponentType::Headers.key())
2555        else {
2556            panic!("headers should be chunked");
2557        };
2558
2559        headers.chunk_files.truncate(1);
2560
2561        let output = tempdir().unwrap();
2562        let manifest = generate_manifest(
2563            source.path(),
2564            output.path(),
2565            None,
2566            24,
2567            1,
2568            10,
2569            Some(&previous),
2570            false,
2571        )
2572        .unwrap();
2573        assert_eq!(
2574            manifest.archive_urls(SnapshotComponentType::Headers),
2575            vec!["headers-0-9.tar.zst", "headers-10-19.tar.zst", "headers-20-29.tar.zst"]
2576        );
2577        assert!(output.path().join("headers-0-9.tar.zst").exists());
2578    }
2579
2580    #[test]
2581    fn generate_manifest_packages_chunks_when_previous_blocks_per_file_is_zero() {
2582        let source = snapshot_source();
2583        write_test_static_files(source.path(), StaticFileSegment::Headers, 24);
2584        let mut previous = generate_manifest(
2585            source.path(),
2586            tempdir().unwrap().path(),
2587            Some("https://example.com/previous"),
2588            24,
2589            1,
2590            10,
2591            None,
2592            false,
2593        )
2594        .unwrap();
2595        let Some(ComponentManifest::Chunked(headers)) =
2596            previous.components.get_mut(SnapshotComponentType::Headers.key())
2597        else {
2598            panic!("headers should be chunked");
2599        };
2600
2601        headers.blocks_per_file = 0;
2602
2603        let output = tempdir().unwrap();
2604        let manifest = generate_manifest(
2605            source.path(),
2606            output.path(),
2607            None,
2608            24,
2609            1,
2610            10,
2611            Some(&previous),
2612            false,
2613        )
2614        .unwrap();
2615        assert_eq!(
2616            manifest.archive_urls(SnapshotComponentType::Headers),
2617            vec!["headers-0-9.tar.zst", "headers-10-19.tar.zst", "headers-20-29.tar.zst"]
2618        );
2619        assert!(output.path().join("headers-0-9.tar.zst").exists());
2620    }
2621}