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