Skip to main content

reth_cli_commands/download/
manifest_cmd.rs

1use crate::download::manifest::{generate_manifest, SnapshotManifest};
2use clap::Parser;
3use eyre::{Result, WrapErr};
4use reth_db::{mdbx::DatabaseArguments, open_db_read_only, tables, Database};
5use reth_db_api::transaction::DbTx;
6use reth_primitives_traits::FastInstant as Instant;
7use reth_stages_types::StageId;
8use reth_static_file_types::DEFAULT_BLOCKS_PER_STATIC_FILE;
9use std::path::PathBuf;
10use tracing::{info, warn};
11
12/// Generate modular chunk archives and a snapshot manifest from a source datadir.
13///
14/// Archive naming convention:
15///   - Chunked: `{component}-{start}-{end}.tar.zst` (e.g. `transactions-0-499999.tar.zst`)
16#[derive(Debug, Parser)]
17pub struct SnapshotManifestCommand {
18    /// Source datadir containing static files.
19    #[arg(long, short = 'd')]
20    source_datadir: PathBuf,
21
22    /// Optional base URL where archives will be hosted.
23    #[arg(long)]
24    base_url: Option<String>,
25
26    /// Output directory where chunk archives and manifest.json are written.
27    #[arg(long, short = 'o')]
28    output_dir: PathBuf,
29
30    /// Block number this snapshot was taken at.
31    ///
32    /// If omitted, this is inferred from the source datadir's `Finish` stage checkpoint.
33    #[arg(long)]
34    block: Option<u64>,
35
36    /// Chain ID.
37    #[arg(long, default_value = "1")]
38    chain_id: u64,
39
40    /// Blocks per archive file for chunked components.
41    ///
42    /// If omitted, this is inferred from header static file ranges in the source datadir.
43    #[arg(long, value_parser = clap::value_parser!(u64).range(1..))]
44    blocks_per_file: Option<u64>,
45
46    /// Path to the manifest of a previously published snapshot of the same chain.
47    ///
48    /// Chunks sealed in both snapshots are hashed against it instead of being packaged again,
49    /// and the new manifest references their published archives. Fails if any sealed chunk's
50    /// files differ from the previous manifest. With `--rocksdb-archive-per-file`, RocksDB SST and
51    /// blob files that match an archive in it are reused the same way; new or changed files are
52    /// packaged.
53    #[arg(long)]
54    previous_manifest: Option<PathBuf>,
55
56    /// Package each RocksDB SST and blob file into its own archive instead of one archive.
57    ///
58    /// Unchanged files keep their archive name between snapshots, so they can be uploaded once
59    /// and reused with `--previous-manifest`. Downloaders without support for per-file archives
60    /// fail to parse the manifest, so only enable this once they have updated.
61    #[arg(long)]
62    rocksdb_archive_per_file: bool,
63}
64
65impl SnapshotManifestCommand {
66    /// Packages snapshot archives and writes the manifest file.
67    pub fn execute(self) -> Result<()> {
68        let block = match self.block {
69            Some(block) => block,
70            None => infer_snapshot_block(&self.source_datadir)?,
71        };
72        let blocks_per_file = match self.blocks_per_file {
73            Some(blocks_per_file) => blocks_per_file,
74            None => infer_blocks_per_file(&self.source_datadir)?,
75        };
76
77        info!(target: "reth::cli",
78            dir = ?self.source_datadir,
79            output = ?self.output_dir,
80            block,
81            blocks_per_file,
82            "Packaging modular snapshot archives"
83        );
84        let previous = self
85            .previous_manifest
86            .as_ref()
87            .map(|path| -> Result<SnapshotManifest> {
88                let json = reth_fs_util::read_to_string(path)?;
89                serde_json::from_str(&json)
90                    .wrap_err_with(|| format!("Invalid previous manifest: {}", path.display()))
91            })
92            .transpose()?;
93
94        let start = Instant::now();
95        let manifest = generate_manifest(
96            &self.source_datadir,
97            &self.output_dir,
98            self.base_url.as_deref(),
99            block,
100            self.chain_id,
101            blocks_per_file,
102            previous.as_ref(),
103            self.rocksdb_archive_per_file,
104        )?;
105
106        let num_components = manifest.components.len();
107        let json = serde_json::to_string_pretty(&manifest)?;
108        let output = self.output_dir.join("manifest.json");
109        reth_fs_util::write(&output, &json)?;
110        info!(target: "reth::cli",
111            path = ?output,
112            components = num_components,
113            block = manifest.block,
114            elapsed = ?start.elapsed(),
115            "Manifest written"
116        );
117
118        Ok(())
119    }
120}
121
122/// Infers the snapshot block from the source datadir.
123fn infer_snapshot_block(source_datadir: &std::path::Path) -> Result<u64> {
124    if let Ok(block) = infer_snapshot_block_from_db(source_datadir) {
125        return Ok(block);
126    }
127
128    let block = infer_snapshot_block_from_headers(source_datadir)?;
129    warn!(
130        target: "reth::cli",
131        block,
132        "Could not read Finish stage checkpoint from source DB, using header static-file tip"
133    );
134    Ok(block)
135}
136
137/// Reads the snapshot block from the source database Finish stage checkpoint.
138fn infer_snapshot_block_from_db(source_datadir: &std::path::Path) -> Result<u64> {
139    let candidates = [source_datadir.join("db"), source_datadir.to_path_buf()];
140
141    for db_path in candidates {
142        if !db_path.exists() {
143            continue;
144        }
145
146        let db = match open_db_read_only(&db_path, DatabaseArguments::default()) {
147            Ok(db) => db,
148            Err(_) => continue,
149        };
150
151        let tx = db.tx()?;
152        if let Some(checkpoint) = tx.get::<tables::StageCheckpoints>(StageId::Finish.to_string())? {
153            return Ok(checkpoint.block_number);
154        }
155    }
156
157    eyre::bail!(
158        "Could not infer --block from source DB (Finish checkpoint missing); pass --block manually"
159    );
160}
161
162/// Infers the snapshot block from the highest header static-file range.
163fn infer_snapshot_block_from_headers(source_datadir: &std::path::Path) -> Result<u64> {
164    let max_end = header_ranges(source_datadir)?
165        .into_iter()
166        .map(|(_, end)| end)
167        .max()
168        .ok_or_else(|| eyre::eyre!("No header static files found to infer --block"))?;
169    Ok(max_end)
170}
171
172/// Infers the static-file block span from header file ranges.
173fn infer_blocks_per_file(source_datadir: &std::path::Path) -> Result<u64> {
174    let mut inferred = None;
175    for (start, end) in header_ranges(source_datadir)? {
176        let span = end.saturating_sub(start).saturating_add(1);
177        if span == 0 {
178            continue;
179        }
180
181        if let Some(existing) = inferred {
182            if existing != span {
183                eyre::bail!(
184                    "Inconsistent header static file ranges; pass --blocks-per-file manually"
185                );
186            }
187        } else {
188            inferred = Some(span);
189        }
190    }
191
192    inferred.ok_or_else(|| {
193        eyre::eyre!(
194            "Could not infer --blocks-per-file from header static files; pass it manually (default is {DEFAULT_BLOCKS_PER_STATIC_FILE})"
195        )
196    })
197}
198
199/// Collects header static-file ranges from the source datadir.
200fn header_ranges(source_datadir: &std::path::Path) -> Result<Vec<(u64, u64)>> {
201    let static_files_dir = source_datadir.join("static_files");
202    let static_files_dir =
203        if static_files_dir.exists() { static_files_dir } else { source_datadir.to_path_buf() };
204
205    let entries = std::fs::read_dir(&static_files_dir).wrap_err_with(|| {
206        format!("Failed to read static files directory: {}", static_files_dir.display())
207    })?;
208
209    let mut ranges = Vec::new();
210    for entry in entries {
211        let entry = entry?;
212        let file_name = entry.file_name();
213        let file_name = file_name.to_string_lossy();
214        if let Some(range) = parse_headers_range(&file_name) {
215            ranges.push(range);
216        }
217    }
218
219    Ok(ranges)
220}
221
222/// Parses the block range from a header static-file name.
223fn parse_headers_range(file_name: &str) -> Option<(u64, u64)> {
224    let remainder = file_name.strip_prefix("static_file_headers_")?;
225    let (start, end_with_suffix) = remainder.split_once('_')?;
226
227    let start = start.parse::<u64>().ok()?;
228    let end_digits: String = end_with_suffix.chars().take_while(|ch| ch.is_ascii_digit()).collect();
229    let end = end_digits.parse::<u64>().ok()?;
230
231    Some((start, end))
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use tempfile::tempdir;
238
239    #[test]
240    fn parse_headers_range_works_with_suffixes() {
241        assert_eq!(parse_headers_range("static_file_headers_0_499999"), Some((0, 499_999)));
242        assert_eq!(
243            parse_headers_range("static_file_headers_500000_999999.jar"),
244            Some((500_000, 999_999))
245        );
246        assert_eq!(parse_headers_range("static_file_transactions_0_499999"), None);
247    }
248
249    #[test]
250    fn infer_blocks_per_file_from_header_ranges() {
251        let dir = tempdir().unwrap();
252        let sf = dir.path().join("static_files");
253        std::fs::create_dir_all(&sf).unwrap();
254        std::fs::write(sf.join("static_file_headers_0_499999"), []).unwrap();
255        std::fs::write(sf.join("static_file_headers_500000_999999.jar"), []).unwrap();
256
257        assert_eq!(infer_blocks_per_file(dir.path()).unwrap(), 500_000);
258    }
259
260    #[test]
261    fn infer_snapshot_block_from_headers_uses_max_end() {
262        let dir = tempdir().unwrap();
263        let sf = dir.path().join("static_files");
264        std::fs::create_dir_all(&sf).unwrap();
265        std::fs::write(sf.join("static_file_headers_0_499999"), []).unwrap();
266        std::fs::write(sf.join("static_file_headers_500000_999999"), []).unwrap();
267
268        assert_eq!(infer_snapshot_block_from_headers(dir.path()).unwrap(), 999_999);
269    }
270}