|
| 1 | +use crate::{BlobProvider, L1ProviderError}; |
| 2 | +use reqwest::Client; |
| 3 | +use std::sync::Arc; |
| 4 | + |
| 5 | +use alloy_eips::eip4844::Blob; |
| 6 | +use alloy_primitives::B256; |
| 7 | + |
| 8 | +/// An implementation of a blob provider client using S3. |
| 9 | +#[derive(Debug, Clone)] |
| 10 | +pub struct S3BlobProvider { |
| 11 | + /// The base URL for the S3 service. |
| 12 | + pub base_url: String, |
| 13 | + /// HTTP client for making requests. |
| 14 | + pub client: Client, |
| 15 | +} |
| 16 | + |
| 17 | +impl S3BlobProvider { |
| 18 | + /// Creates a new [`S3BlobProvider`] from the provided url. |
| 19 | + pub fn new_http(base: reqwest::Url) -> Self { |
| 20 | + // If base ends with a slash, remove it |
| 21 | + let mut base = base.to_string(); |
| 22 | + if base.ends_with('/') { |
| 23 | + base.remove(base.len() - 1); |
| 24 | + } |
| 25 | + Self { base_url: base, client: reqwest::Client::new() } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +#[async_trait::async_trait] |
| 30 | +impl BlobProvider for S3BlobProvider { |
| 31 | + #[allow(clippy::large_stack_frames)] |
| 32 | + async fn blob( |
| 33 | + &self, |
| 34 | + _block_timestamp: u64, |
| 35 | + hash: B256, |
| 36 | + ) -> Result<Option<Arc<Blob>>, L1ProviderError> { |
| 37 | + let url = format!("{}/{}", self.base_url, hash); |
| 38 | + let response = self.client.get(&url).send().await.map_err(L1ProviderError::S3Provider)?; |
| 39 | + |
| 40 | + if response.status().is_success() { |
| 41 | + let blob_data = response.bytes().await.map_err(L1ProviderError::S3Provider)?; |
| 42 | + |
| 43 | + let blob = Blob::try_from(blob_data.as_ref()) |
| 44 | + .map_err(|_| L1ProviderError::Other("Invalid blob data"))?; |
| 45 | + Ok(Some(Arc::new(blob))) |
| 46 | + } else if response.status() == 404 { |
| 47 | + Ok(None) |
| 48 | + } else { |
| 49 | + Err(L1ProviderError::Other("S3 client HTTP error")) |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments