Skip to main content

reth_cli_commands/download/
verify.rs

1use super::{
2    extract::ensure_no_symlinks, manifest::OutputFileChecksum,
3    progress::ArchiveVerificationProgress,
4};
5use blake3::Hasher;
6use eyre::Result;
7use reth_concurrency::sync::rayon::{self, prelude::*};
8use reth_fs_util::{self as fs, FsPathError};
9use std::{
10    collections::HashMap,
11    io::{ErrorKind, Read},
12    mem,
13    path::{Path, PathBuf},
14};
15use tracing::warn;
16
17/// Read size per hash update. Large enough for `update_rayon` to split across threads.
18const HASH_BUFFER_SIZE: usize = 4 * 1024 * 1024;
19
20/// Sizes and BLAKE3 hashes of regular files, computed from the bytes extraction wrote to them,
21/// keyed by output path.
22#[derive(Debug, Default)]
23pub(crate) struct ExtractedHashes(HashMap<PathBuf, (u64, blake3::Hash)>);
24
25impl ExtractedHashes {
26    /// Records the size and hash of the file written to `path`.
27    pub(crate) fn insert(&mut self, path: PathBuf, size: u64, hash: blake3::Hash) {
28        self.0.insert(path, (size, hash));
29    }
30
31    /// Drops every recorded hash.
32    pub(crate) fn clear(&mut self) {
33        self.0.clear();
34    }
35}
36
37/// Verifies and cleans up extracted output files in one target directory.
38pub(crate) struct OutputVerifier<'a> {
39    /// Directory containing the output files declared by the manifest.
40    target_dir: &'a Path,
41    /// Custom location of static file outputs.
42    static_files_dir: Option<&'a Path>,
43}
44
45impl<'a> OutputVerifier<'a> {
46    /// Creates a verifier for one extraction target directory.
47    pub(crate) const fn new(target_dir: &'a Path, static_files_dir: Option<&'a Path>) -> Self {
48        Self { target_dir, static_files_dir }
49    }
50
51    /// Returns `true` only when every declared output file exists and matches size and BLAKE3.
52    /// Returns `false` if any file is missing, mismatched, or no outputs were declared, and an
53    /// error if a file exists but cannot be inspected or read.
54    pub(crate) fn verify(&self, output_files: &[OutputFileChecksum]) -> Result<bool> {
55        self.verify_with_progress(output_files, None, None)
56    }
57
58    /// Returns `true` only when every declared output file exists and matches size and BLAKE3,
59    /// updating the optional verification progress as file bytes are hashed.
60    ///
61    /// Sizes are checked before any file is hashed, then files are hashed in parallel. A file
62    /// with a hash in `extracted` of its declared size is checked against that hash instead of
63    /// being read back, but must still open for reading.
64    pub(crate) fn verify_with_progress(
65        &self,
66        output_files: &[OutputFileChecksum],
67        progress: Option<&ArchiveVerificationProgress<'_>>,
68        extracted: Option<&ExtractedHashes>,
69    ) -> Result<bool> {
70        if output_files.is_empty() {
71            return Ok(false);
72        }
73
74        let mut paths = Vec::with_capacity(output_files.len());
75        for expected in output_files {
76            let output_path = self.output_path(expected)?;
77            match fs::metadata(&output_path) {
78                Ok(meta) if meta.len() == expected.size => paths.push(output_path),
79                Ok(_) => return Ok(false),
80                Err(FsPathError::Metadata { source, .. })
81                    if source.kind() == ErrorKind::NotFound =>
82                {
83                    return Ok(false)
84                }
85                Err(error) => return Err(error.into()),
86            }
87        }
88
89        output_files
90            .par_iter()
91            .zip(paths)
92            .map(|(expected, path)| {
93                if let Some(&(size, hash)) = extracted.and_then(|hashes| hashes.0.get(&path)) &&
94                    size == expected.size
95                {
96                    // The archive sets the file mode, which can leave the output unreadable.
97                    fs::open(&path)?;
98                    if let Some(progress) = progress {
99                        progress.record_verified(size);
100                    }
101                    return Ok(hash.to_hex().eq_ignore_ascii_case(&expected.blake3))
102                }
103                Self::file_blake3_hex(&path, expected.size, progress)
104                    .map(|actual| actual.eq_ignore_ascii_case(&expected.blake3))
105            })
106            .find_any(|verified| !matches!(verified, Ok(true)))
107            .unwrap_or(Ok(true))
108    }
109
110    /// Removes any declared output files so a fresh archive attempt can restart cleanly.
111    ///
112    /// Files are only removed if their path stays below the output root and no existing parent
113    /// directory is a symlink. Extraction rejects link entries, so this guards against links
114    /// already present in the datadir; the check is not atomic with the removal.
115    pub(crate) fn cleanup(&self, output_files: &[OutputFileChecksum]) {
116        for output in output_files {
117            match self.removal_path(output) {
118                Ok(path) => {
119                    let _ = fs::remove_file(path);
120                }
121                Err(error) => {
122                    warn!(target: "reth::cli", path = %output.path, %error, "Skipping output cleanup");
123                }
124            }
125        }
126    }
127
128    /// Returns the path to remove for `output`, or an error if removing it could touch anything
129    /// outside the output root.
130    fn removal_path(&self, output: &OutputFileChecksum) -> Result<PathBuf> {
131        let (root, relative) = self.resolve(output)?;
132        if let Some(parent) = relative.parent() {
133            ensure_no_symlinks(root, parent)?;
134        }
135        Ok(root.join(relative))
136    }
137
138    /// Resolves archive paths consistently for verification and retry cleanup.
139    pub(crate) fn output_path(&self, output: &OutputFileChecksum) -> Result<PathBuf> {
140        self.resolve(output).map(|(root, relative)| root.join(relative))
141    }
142
143    /// Returns the output root and the validated path of `output` relative to it.
144    fn resolve<'p>(&'p self, output: &'p OutputFileChecksum) -> Result<(&'p Path, &'p Path)> {
145        let path = output.relative_path()?;
146        if let Some(static_files_dir) = self.static_files_dir &&
147            let Some(relative_path) = super::extract::static_file_relative_path(path)
148        {
149            return Ok((static_files_dir, relative_path))
150        }
151        Ok((self.target_dir, path))
152    }
153
154    /// Computes the hex-encoded BLAKE3 checksum for one plain output file.
155    ///
156    /// The next buffer is read while the current one is hashed, so disk reads overlap hashing
157    /// instead of alternating with it.
158    fn file_blake3_hex(
159        path: &Path,
160        size: u64,
161        progress: Option<&ArchiveVerificationProgress<'_>>,
162    ) -> Result<String> {
163        let mut file = fs::open(path)?;
164        let mut hasher = Hasher::new();
165        let buf_len = size.min(HASH_BUFFER_SIZE as u64) as usize;
166        let mut current = vec![0_u8; buf_len];
167        let mut next = vec![0_u8; buf_len];
168
169        let mut filled = read_full(&mut file, &mut current)?;
170        while filled > 0 {
171            let (_, read) = rayon::join(
172                || {
173                    #[cfg(not(all(feature = "fuzz", dst)))]
174                    hasher.update_rayon(&current[..filled]);
175                    #[cfg(all(feature = "fuzz", dst))]
176                    hasher.update(&current[..filled]);
177                },
178                || read_full(&mut file, &mut next),
179            );
180            if let Some(progress) = progress {
181                progress.record_verified(filled as u64);
182            }
183            filled = read?;
184            mem::swap(&mut current, &mut next);
185        }
186
187        Ok(hasher.finalize().to_hex().to_string())
188    }
189}
190
191/// Reads until `buf` is full or the reader is exhausted, returning the number of bytes read.
192///
193/// Full buffers keep every `update_rayon` call aligned, so BLAKE3 can hash it as parallel
194/// subtrees.
195fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
196    let mut filled = 0;
197    while filled < buf.len() {
198        match reader.read(&mut buf[filled..]) {
199            Ok(0) => break,
200            Ok(n) => filled += n,
201            Err(error) if error.kind() == ErrorKind::Interrupted => {}
202            Err(error) => return Err(error),
203        }
204    }
205    Ok(filled)
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    fn checksum(path: &str, data: &[u8]) -> OutputFileChecksum {
213        OutputFileChecksum {
214            path: path.into(),
215            size: data.len() as u64,
216            blake3: blake3::hash(data).to_hex().to_string(),
217        }
218    }
219
220    #[test]
221    fn verify_detects_each_kind_of_output_mismatch() {
222        let dir = tempfile::tempdir().unwrap();
223        let large: Vec<u8> = (0..2 * HASH_BUFFER_SIZE + 123).map(|i| (i % 251) as u8).collect();
224        let small = b"small".to_vec();
225        fs::write(dir.path().join("large"), &large).unwrap();
226        fs::write(dir.path().join("small"), &small).unwrap();
227        let outputs = vec![checksum("large", &large), checksum("small", &small)];
228        let verifier = OutputVerifier::new(dir.path(), None);
229
230        assert!(verifier.verify(&outputs).unwrap(), "matching multi-buffer outputs verify");
231
232        let mut uppercase = outputs.clone();
233        uppercase[0].blake3 = uppercase[0].blake3.to_ascii_uppercase();
234        assert!(verifier.verify(&uppercase).unwrap(), "checksums compare case-insensitively");
235
236        let mut flipped = large.clone();
237        flipped[HASH_BUFFER_SIZE + 7] ^= 1;
238        fs::write(dir.path().join("large"), &flipped).unwrap();
239        assert!(!verifier.verify(&outputs).unwrap(), "one flipped byte fails verification");
240
241        fs::write(dir.path().join("large"), &large[1..]).unwrap();
242        assert!(!verifier.verify(&outputs).unwrap(), "size mismatch fails verification");
243
244        fs::remove_file(dir.path().join("large")).unwrap();
245        assert!(!verifier.verify(&outputs).unwrap(), "missing file fails verification");
246
247        assert!(!verifier.verify(&[]).unwrap(), "archives without outputs never verify");
248    }
249
250    #[cfg(unix)]
251    #[test]
252    fn verify_returns_metadata_errors_other_than_not_found() {
253        let dir = tempfile::tempdir().unwrap();
254        fs::write(dir.path().join("file"), b"data").unwrap();
255        let verifier = OutputVerifier::new(dir.path(), None);
256
257        assert!(!verifier.verify(&[checksum("missing", b"data")]).unwrap());
258        assert!(
259            verifier.verify(&[checksum("file/child", b"data")]).is_err(),
260            "a path through a regular file is an error, not a missing output"
261        );
262    }
263
264    #[test]
265    fn custom_static_files_verification_and_cleanup() {
266        let datadir = tempfile::tempdir().unwrap();
267        let static_dir = tempfile::tempdir().unwrap();
268        let default_file = datadir.path().join("static_files/headers");
269        fs::create_dir_all(default_file.parent().unwrap()).unwrap();
270        fs::write(&default_file, b"headers").unwrap();
271        let outputs = [OutputFileChecksum {
272            path: "./static_files/headers".into(),
273            size: 7,
274            blake3: blake3::hash(b"headers").to_hex().to_string(),
275        }];
276        let verifier = OutputVerifier::new(datadir.path(), Some(static_dir.path()));
277        assert!(!verifier.verify(&outputs).unwrap());
278        let custom_file = static_dir.path().join("headers");
279        fs::write(&custom_file, b"headers").unwrap();
280        assert!(verifier.verify(&outputs).unwrap());
281        verifier.cleanup(&outputs);
282        assert!(!custom_file.exists());
283        assert_eq!(fs::read(default_file).unwrap(), b"headers");
284    }
285
286    #[test]
287    fn cleanup_ignores_output_paths_outside_target() {
288        let root = tempfile::tempdir().unwrap();
289        let datadir = root.path().join("datadir");
290        fs::create_dir_all(&datadir).unwrap();
291        let outside = root.path().join("outside");
292        fs::write(&outside, b"keep").unwrap();
293        let inside = datadir.join("inside");
294        fs::write(&inside, b"remove").unwrap();
295
296        let outputs = [
297            checksum(outside.to_str().unwrap(), b"keep"),
298            checksum("../outside", b"keep"),
299            checksum("db/../../outside", b"keep"),
300            checksum("inside", b"remove"),
301        ];
302        let verifier = OutputVerifier::new(&datadir, None);
303        assert!(verifier.verify(&outputs).is_err(), "invalid paths are never verified");
304        verifier.cleanup(&outputs);
305
306        assert_eq!(fs::read(&outside).unwrap(), b"keep");
307        assert!(!inside.exists());
308    }
309
310    #[cfg(unix)]
311    #[test]
312    fn cleanup_does_not_follow_symlinked_parents() {
313        let root = tempfile::tempdir().unwrap();
314        let datadir = root.path().join("datadir");
315        let static_dir = root.path().join("static");
316        let outside = root.path().join("outside");
317        fs::create_dir_all(&datadir).unwrap();
318        fs::create_dir_all(&static_dir).unwrap();
319        fs::create_dir_all(outside.join("nested")).unwrap();
320        for path in ["mdbx.dat", "headers", "nested/headers"] {
321            fs::write(outside.join(path), b"keep").unwrap();
322        }
323        std::os::unix::fs::symlink(&outside, datadir.join("db")).unwrap();
324        std::os::unix::fs::symlink(&outside, static_dir.join("link")).unwrap();
325        std::os::unix::fs::symlink(&outside, static_dir.join("nested")).unwrap();
326
327        let outputs = [
328            checksum("db/mdbx.dat", b"keep"),
329            checksum("static_files/link/headers", b"keep"),
330            checksum("static_files/nested/nested/headers", b"keep"),
331        ];
332        for static_files_dir in [None, Some(static_dir.as_path())] {
333            OutputVerifier::new(&datadir, static_files_dir).cleanup(&outputs);
334        }
335
336        for path in ["mdbx.dat", "headers", "nested/headers"] {
337            assert_eq!(fs::read(outside.join(path)).unwrap(), b"keep");
338        }
339
340        // A symlink as the output itself is unlinked without touching its target.
341        std::os::unix::fs::symlink(outside.join("mdbx.dat"), datadir.join("link")).unwrap();
342        OutputVerifier::new(&datadir, None).cleanup(&[checksum("link", b"keep")]);
343        assert!(datadir.join("link").symlink_metadata().is_err());
344        assert_eq!(fs::read(outside.join("mdbx.dat")).unwrap(), b"keep");
345    }
346}