Skip to main content

reth_era_downloader/
client.rs

1use alloy_primitives::{hex, hex::ToHexExt};
2use bytes::Bytes;
3use eyre::{eyre, OptionExt};
4use futures_util::{stream::StreamExt, Stream, TryStreamExt};
5use reqwest::{Client, IntoUrl, Url};
6use reth_era::common::file_ops::EraFileType;
7use sha2::{Digest, Sha256};
8use std::{future::Future, path::Path, str::FromStr};
9use tokio::{
10    fs::{self, File},
11    io::{self, AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt},
12    try_join,
13};
14
15/// Downloaded index page filename
16const INDEX_HTML_FILE: &str = "index.html";
17
18/// Accesses the network over HTTP.
19pub trait HttpClient {
20    /// Makes an HTTP GET request to `url`. Returns a stream of response body bytes.
21    fn get<U: IntoUrl + Send + Sync>(
22        &self,
23        url: U,
24    ) -> impl Future<
25        Output = eyre::Result<impl Stream<Item = eyre::Result<Bytes>> + Send + Sync + Unpin>,
26    > + Send
27           + Sync;
28}
29
30impl HttpClient for Client {
31    async fn get<U: IntoUrl + Send + Sync>(
32        &self,
33        url: U,
34    ) -> eyre::Result<impl Stream<Item = eyre::Result<Bytes>> + Unpin> {
35        let response = Self::get(self, url).send().await?;
36
37        Ok(response.bytes_stream().map_err(|e| eyre::Error::new(e)))
38    }
39}
40
41/// An HTTP client with features for downloading ERA files from an external HTTP accessible
42/// endpoint.
43#[derive(Debug, Clone)]
44pub struct EraClient<Http> {
45    client: Http,
46    url: Url,
47    folder: Box<Path>,
48    era_type: EraFileType,
49}
50
51impl<Http: HttpClient + Clone> EraClient<Http> {
52    const CHECKSUMS: &'static str = "checksums.txt";
53
54    /// Constructs [`EraClient`] using `client` to download from `url` into `folder`.
55    ///
56    /// The file type is auto-detected from the URL. Use
57    /// [`with_era_type`](Self::with_era_type) to override.
58    pub fn new(client: Http, url: Url, folder: impl Into<Box<Path>>) -> Self {
59        let era_type = EraFileType::from_url(url.as_str());
60        Self { client, url, folder: folder.into(), era_type }
61    }
62
63    /// Override the auto-detected [`EraFileType`].
64    pub const fn with_era_type(mut self, era_type: EraFileType) -> Self {
65        self.era_type = era_type;
66        self
67    }
68
69    /// Performs a GET request on `url` and stores the response body into a file located within
70    /// the `folder`.
71    pub async fn download_to_file(&mut self, url: impl IntoUrl) -> eyre::Result<Box<Path>> {
72        let path = self.folder.to_path_buf();
73
74        let url = url.into_url()?;
75        let client = self.client.clone();
76        let file_name = url
77            .path_segments()
78            .ok_or_eyre("cannot-be-a-base")?
79            .next_back()
80            .ok_or_eyre("empty path segments")?;
81        let path = path.join(file_name);
82
83        if !self.is_downloaded(file_name, &path).await? {
84            let number = self
85                .file_name_to_number(file_name)
86                .ok_or_eyre("Cannot parse number from file name")?;
87
88            let mut tries = 1..3;
89            let mut actual_checksum: eyre::Result<_>;
90            loop {
91                actual_checksum = async {
92                    let mut file = File::create(&path).await?;
93                    let mut stream = client.get(url.clone()).await?;
94                    let mut hasher = Sha256::new();
95
96                    while let Some(item) = stream.next().await.transpose()? {
97                        io::copy(&mut item.as_ref(), &mut file).await?;
98                        hasher.update(item);
99                    }
100
101                    Ok(hasher.finalize().to_vec())
102                }
103                .await;
104
105                if actual_checksum.is_ok() || tries.next().is_none() {
106                    break;
107                }
108            }
109
110            if self.era_type == EraFileType::Era1 {
111                self.assert_checksum(number, actual_checksum?)
112                    .await
113                    .map_err(|e| eyre!("{e} for {file_name} at {}", path.display()))?;
114            }
115        }
116
117        Ok(path.into_boxed_path())
118    }
119
120    /// Recovers index of file following the latest downloaded file from a different run.
121    pub async fn recover_index(&self) -> Option<usize> {
122        let mut max = None;
123
124        if let Ok(mut dir) = fs::read_dir(&self.folder).await {
125            while let Ok(Some(entry)) = dir.next_entry().await {
126                if let Some(name) = entry.file_name().to_str() &&
127                    let Some(number) = self.file_name_to_number(name) &&
128                    (max.is_none() || matches!(max, Some(max) if number > max))
129                {
130                    max.replace(number + 1);
131                }
132            }
133        }
134
135        max
136    }
137
138    /// Deletes files that are outside-of the working range.
139    pub async fn delete_outside_range(&self, index: usize, max_files: usize) -> eyre::Result<()> {
140        let last = index + max_files;
141
142        if let Ok(mut dir) = fs::read_dir(&self.folder).await {
143            while let Ok(Some(entry)) = dir.next_entry().await {
144                if let Some(name) = entry.file_name().to_str() &&
145                    let Some(number) = self.file_name_to_number(name) &&
146                    (number < index || number >= last)
147                {
148                    reth_fs_util::remove_file_if_exists(entry.path())?;
149                }
150            }
151        }
152
153        Ok(())
154    }
155
156    /// Returns a download URL for the file corresponding to `number`.
157    pub async fn url(&self, number: usize) -> eyre::Result<Option<Url>> {
158        Ok(self.number_to_file_name(number).await?.map(|name| self.url.join(&name)).transpose()?)
159    }
160
161    /// Returns the number of files in the `folder`.
162    pub async fn files_count(&self) -> usize {
163        let mut count = 0usize;
164
165        let file_extension = self.era_type.extension().trim_start_matches('.');
166
167        if let Ok(mut dir) = fs::read_dir(&self.folder).await {
168            while let Ok(Some(entry)) = dir.next_entry().await {
169                if entry.path().extension() == Some(file_extension.as_ref()) {
170                    count += 1;
171                }
172            }
173        }
174
175        count
176    }
177
178    /// Fetches the list of ERA1/ERA files from `url` and stores it in a file located within
179    /// `folder`.
180    /// For era files, checksum.txt file does not exist, so the checksum verification is
181    /// skipped.
182    pub async fn fetch_file_list(&self) -> eyre::Result<()> {
183        let index_path = self.folder.to_path_buf().join(INDEX_HTML_FILE);
184        let checksums_path = self.folder.to_path_buf().join(Self::CHECKSUMS);
185
186        // Only for era1, we download also checksums file
187        if self.era_type == EraFileType::Era1 {
188            let checksums_url = self.url.join(Self::CHECKSUMS)?;
189            try_join!(
190                self.download_file_to_path(self.url.clone(), &index_path),
191                self.download_file_to_path(checksums_url, &checksums_path)
192            )?;
193        } else {
194            // Download only index file
195            self.download_file_to_path(self.url.clone(), &index_path).await?;
196        }
197
198        // Parse and extract era filenames from index.html
199        self.extract_era_filenames(&index_path).await?;
200
201        Ok(())
202    }
203
204    /// Extracts ERA filenames from `index.html` and writes them to the index file
205    async fn extract_era_filenames(&self, index_path: &Path) -> eyre::Result<()> {
206        let file = File::open(index_path).await?;
207        let reader = io::BufReader::new(file);
208        let mut lines = reader.lines();
209
210        let path = self.folder.to_path_buf().join("index");
211        let file = File::create(&path).await?;
212        let mut writer = io::BufWriter::new(file);
213
214        let ext = self.era_type.extension();
215        let ext_len = ext.len();
216
217        while let Some(line) = lines.next_line().await? {
218            if let Some(j) = line.find(ext) &&
219                let Some(i) = line[..j].rfind(|c: char| !c.is_alphanumeric() && c != '-')
220            {
221                let era = &line[i + 1..j + ext_len];
222                writer.write_all(era.as_bytes()).await?;
223                writer.write_all(b"\n").await?;
224            }
225        }
226
227        writer.flush().await?;
228        Ok(())
229    }
230
231    // Helper to download a file to a specified path
232    async fn download_file_to_path(&self, url: Url, path: &Path) -> eyre::Result<()> {
233        let mut stream = self.client.get(url).await?;
234        let mut file = File::create(path).await?;
235
236        while let Some(item) = stream.next().await.transpose()? {
237            io::copy(&mut item.as_ref(), &mut file).await?;
238        }
239
240        Ok(())
241    }
242
243    /// Returns ERA1/ERA file name that is ordered at `number`.
244    pub async fn number_to_file_name(&self, number: usize) -> eyre::Result<Option<String>> {
245        let path = self.folder.to_path_buf().join("index");
246        let file = File::open(&path).await?;
247        let reader = io::BufReader::new(file);
248        let mut lines = reader.lines();
249        for _ in 0..number {
250            lines.next_line().await?;
251        }
252
253        Ok(lines.next_line().await?)
254    }
255
256    async fn is_downloaded(&self, name: &str, path: impl AsRef<Path>) -> eyre::Result<bool> {
257        let path = path.as_ref();
258
259        match File::open(path).await {
260            Ok(file) => {
261                if self.era_type == EraFileType::Era1 {
262                    let number = self
263                        .file_name_to_number(name)
264                        .ok_or_else(|| eyre!("Cannot parse ERA number from {name}"))?;
265
266                    let actual_checksum = checksum(file).await?;
267                    let is_verified = self.verify_checksum(number, actual_checksum).await?;
268
269                    if !is_verified {
270                        fs::remove_file(path).await?;
271                    }
272
273                    Ok(is_verified)
274                } else {
275                    // For era files, we skip checksum verification, as checksum.txt does not exist
276                    Ok(true)
277                }
278            }
279            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
280            Err(e) => Err(e)?,
281        }
282    }
283
284    /// Returns `true` if `actual_checksum` matches expected checksum of the ERA1 file indexed by
285    /// `number` based on the [file list].
286    ///
287    /// [file list]: Self::fetch_file_list
288    async fn verify_checksum(&self, number: usize, actual_checksum: Vec<u8>) -> eyre::Result<bool> {
289        Ok(actual_checksum == self.expected_checksum(number).await?)
290    }
291
292    /// Returns `Ok` if `actual_checksum` matches expected checksum of the ERA1 file indexed by
293    /// `number` based on the [file list].
294    ///
295    /// [file list]: Self::fetch_file_list
296    async fn assert_checksum(&self, number: usize, actual_checksum: Vec<u8>) -> eyre::Result<()> {
297        let expected_checksum = self.expected_checksum(number).await?;
298
299        if actual_checksum == expected_checksum {
300            Ok(())
301        } else {
302            Err(eyre!(
303                "Checksum mismatch, got: {}, expected: {}",
304                actual_checksum.encode_hex(),
305                expected_checksum.encode_hex()
306            ))
307        }
308    }
309
310    /// Returns SHA-256 checksum for ERA1 file indexed by `number` based on the [file list].
311    ///
312    /// [file list]: Self::fetch_file_list
313    async fn expected_checksum(&self, number: usize) -> eyre::Result<Vec<u8>> {
314        let file = File::open(self.folder.join(Self::CHECKSUMS)).await?;
315        let reader = io::BufReader::new(file);
316        let mut lines = reader.lines();
317
318        for _ in 0..number {
319            lines.next_line().await?;
320        }
321        let expected_checksum =
322            lines.next_line().await?.ok_or_else(|| eyre!("Missing hash for number {number}"))?;
323        let expected_checksum = hex::decode(expected_checksum)?;
324
325        Ok(expected_checksum)
326    }
327
328    fn file_name_to_number(&self, file_name: &str) -> Option<usize> {
329        file_name.split('-').nth(1).and_then(|v| usize::from_str(v).ok())
330    }
331}
332
333async fn checksum(mut reader: impl AsyncRead + Unpin) -> eyre::Result<Vec<u8>> {
334    let mut hasher = Sha256::new();
335
336    // Create a buffer to read data into, sized for performance.
337    let mut data = vec![0; 64 * 1024];
338
339    loop {
340        // Read data from the reader into the buffer.
341        let len = reader.read(&mut data).await?;
342        if len == 0 {
343            break;
344        } // Exit loop if no more data.
345
346        // Update the hash with the data read.
347        hasher.update(&data[..len]);
348    }
349
350    // Finalize the hash after all data has been processed.
351    let hash = hasher.finalize().to_vec();
352
353    Ok(hash)
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use std::path::PathBuf;
360    use test_case::test_case;
361
362    impl EraClient<Client> {
363        fn empty() -> Self {
364            Self::new(Client::new(), Url::from_str("file:///").unwrap(), PathBuf::new())
365        }
366    }
367
368    #[test_case("mainnet-00600-a81ae85f.era1", Some(600))]
369    #[test_case("mainnet-00000-a81ae85f.era1", Some(0))]
370    #[test_case("00000-a81ae85f.era1", None)]
371    #[test_case("", None)]
372    fn test_file_name_to_number(file_name: &str, expected_number: Option<usize>) {
373        let client = EraClient::empty();
374
375        let actual_number = client.file_name_to_number(file_name);
376
377        assert_eq!(actual_number, expected_number);
378    }
379
380    #[test]
381    fn test_with_era_type_overrides_auto_detection() {
382        // URL without "era1" auto-detects as Era
383        let client = EraClient::new(
384            Client::new(),
385            Url::from_str("https://example.com/").unwrap(),
386            PathBuf::new(),
387        );
388        assert_eq!(client.era_type, EraFileType::Era);
389
390        // with_era_type overrides to Era1
391        let client = client.with_era_type(EraFileType::Era1);
392        assert_eq!(client.era_type, EraFileType::Era1);
393    }
394}