Skip to main content

reth_transaction_pool/blobstore/
mod.rs

1//! Storage for blob data of EIP4844 transactions.
2
3pub use alloy_eips::eip7594::BlobTransactionCellSidecar;
4use alloy_eips::{
5    eip4844::{env_settings::EnvKzgSettings, BlobAndProofV1, BlobAndProofV2, BlobCellsAndProofsV1},
6    eip7594::{
7        BlobCellMask, BlobTransactionSidecarEip7594, BlobTransactionSidecarVariant, Cell,
8        BYTES_PER_CELL, CELLS_PER_EXT_BLOB,
9    },
10};
11use alloy_primitives::{map::FbBuildHasher, TxHash, B256};
12pub use converter::BlobSidecarConverter;
13pub use disk::{DiskFileBlobStore, DiskFileBlobStoreConfig, OpenDiskFileBlobStore};
14pub use mem::InMemoryBlobStore;
15pub use noop::NoopBlobStore;
16use parking_lot::Mutex;
17use reth_lru::LruMap;
18use std::{
19    fmt,
20    ops::Deref,
21    sync::{
22        atomic::{AtomicU64, AtomicUsize, Ordering},
23        Arc,
24    },
25    time::{Duration, Instant},
26};
27use tracing::error;
28pub use tracker::{BlobStoreCanonTracker, BlobStoreUpdates};
29
30pub(crate) mod cells;
31mod converter;
32pub mod disk;
33mod mem;
34mod noop;
35mod tracker;
36
37/// Most bytes of sidecars rebuilt from cells to keep in memory.
38const MAX_REBUILT_SIDECARS_SIZE: usize = 64 * 1024 * 1024;
39
40/// Most bytes of cells computed from full sidecars to keep in memory.
41const MAX_COMPUTED_CELLS_SIZE: usize = 64 * 1024 * 1024;
42
43/// Most blobs to compute cells for at once, ~60 ms of work at ~1.9 ms per blob.
44const MAX_COMPUTED_CELL_BLOBS: u32 = 32;
45
46/// Refill of one blob to compute, ~15 ms of work a second at ~1.9 ms per blob.
47const COMPUTED_CELL_BLOB_REFILL: Duration = Duration::from_millis(125);
48
49/// The first half of the columns, whose cells are the blob itself.
50pub const DATA_COLUMNS: BlobCellMask = BlobCellMask::ALL.first(CELLS_PER_EXT_BLOB / 2);
51
52/// Blob cell availability stored for a transaction.
53///
54/// Bit `i` corresponds to cell index `i`. The two words are stored least-significant first: index
55/// `0` contains cells `0..64` and index `1` contains cells `64..128`.
56#[derive(Debug, Clone)]
57pub struct BlobCellAvailability(Arc<[AtomicU64; 2]>);
58
59impl BlobCellAvailability {
60    const LOW_WORD: usize = 0;
61    const HIGH_WORD: usize = 1;
62
63    /// Creates availability for the cells in `mask`.
64    pub fn new(mask: BlobCellMask) -> Self {
65        let bits = mask.bits();
66        Self(Arc::new([AtomicU64::new(bits as u64), AtomicU64::new((bits >> 64) as u64)]))
67    }
68
69    /// Returns full availability for all blob cells.
70    pub fn full() -> Self {
71        Self::new(BlobCellMask::ALL)
72    }
73
74    /// Returns a snapshot of the available cells.
75    ///
76    /// The two words are loaded independently. After publication, writers only add bits so a
77    /// concurrent snapshot can understate availability but never overstate it.
78    pub fn get(&self) -> BlobCellMask {
79        let low = self.0[Self::LOW_WORD].load(Ordering::Relaxed) as u128;
80        let high = self.0[Self::HIGH_WORD].load(Ordering::Relaxed) as u128;
81        BlobCellMask::from_bits((high << 64) | low)
82    }
83
84    /// Returns true if all blob cells are available.
85    pub fn is_full(&self) -> bool {
86        self.get() == BlobCellMask::ALL
87    }
88
89    /// Marks every cell as available, once the missing cells were rebuilt.
90    pub fn set_full(&self) {
91        self.set(BlobCellMask::ALL);
92    }
93
94    // Sets availability before pool publication or after storing cells.
95    pub(crate) fn set(&self, mask: BlobCellMask) {
96        let bits = mask.bits();
97        self.0[Self::LOW_WORD].store(bits as u64, Ordering::Relaxed);
98        self.0[Self::HIGH_WORD].store((bits >> 64) as u64, Ordering::Relaxed);
99    }
100}
101
102impl PartialEq for BlobCellAvailability {
103    fn eq(&self, other: &Self) -> bool {
104        self.get() == other.get()
105    }
106}
107
108impl Eq for BlobCellAvailability {}
109
110/// A blob sidecar paired with its shared cell availability.
111///
112/// A sidecar fetched as cells keeps them in [`Self::cells`] until validation turns them into a
113/// full sidecar, or keeps them as they are for a sampler.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct PooledBlobSidecar {
116    sidecar: BlobTransactionSidecarVariant,
117    availability: BlobCellAvailability,
118    cells: Option<Arc<BlobTransactionCellSidecar>>,
119}
120
121impl PooledBlobSidecar {
122    /// Creates a sidecar with the given shared cell availability.
123    pub const fn new(
124        sidecar: BlobTransactionSidecarVariant,
125        availability: BlobCellAvailability,
126    ) -> Self {
127        Self { sidecar, availability, cells: None }
128    }
129
130    /// Creates a sidecar from fetched cells. Validation keeps the full sidecar they rebuild, or
131    /// keeps a sampler's cells as they are.
132    pub fn from_cells(cells: BlobTransactionCellSidecar) -> Self {
133        Self {
134            sidecar: cells.without_blobs().into(),
135            availability: BlobCellAvailability::new(cells.mask()),
136            cells: Some(Arc::new(cells)),
137        }
138    }
139
140    /// Returns the wrapped sidecar.
141    pub const fn sidecar(&self) -> &BlobTransactionSidecarVariant {
142        &self.sidecar
143    }
144
145    /// Returns whether this is an EIP-7594 sidecar.
146    pub const fn is_eip7594(&self) -> bool {
147        self.sidecar.is_eip7594()
148    }
149
150    /// Returns the shared cell availability.
151    pub const fn availability(&self) -> &BlobCellAvailability {
152        &self.availability
153    }
154
155    /// Consumes the wrapper and returns the sidecar.
156    pub fn into_sidecar(self) -> BlobTransactionSidecarVariant {
157        self.sidecar
158    }
159
160    /// Returns the fetched cells, if this sidecar was created with [`Self::from_cells`].
161    pub fn cells(&self) -> Option<&BlobTransactionCellSidecar> {
162        self.cells.as_deref()
163    }
164
165    // Takes the fetched cells out, leaving none.
166    pub(crate) const fn take_cells(&mut self) -> Option<Arc<BlobTransactionCellSidecar>> {
167        self.cells.take()
168    }
169
170    // Replaces the fetched cells with the full sidecar they rebuild, which still needs validation.
171    pub(crate) fn set_full_sidecar(&mut self, sidecar: BlobTransactionSidecarEip7594) {
172        self.sidecar = BlobTransactionSidecarVariant::Eip7594(sidecar);
173        self.cells = None;
174    }
175}
176
177impl Deref for PooledBlobSidecar {
178    type Target = BlobTransactionSidecarVariant;
179
180    fn deref(&self) -> &Self::Target {
181        &self.sidecar
182    }
183}
184
185impl From<BlobTransactionSidecarVariant> for PooledBlobSidecar {
186    fn from(sidecar: BlobTransactionSidecarVariant) -> Self {
187        // TODO: Initialize this with the actual mask once sparse sidecars are supported.
188        Self::new(sidecar, BlobCellAvailability::full())
189    }
190}
191
192/// A blob store that can be used to store blob data of EIP4844 transactions.
193///
194/// This type is responsible for keeping track of blob data until it is no longer needed (after
195/// finalization).
196///
197/// Note: this is Clone because it is expected to be wrapped in an Arc.
198pub trait BlobStore: fmt::Debug + Send + Sync + 'static {
199    /// Inserts the blob sidecar into the store
200    fn insert(&self, tx: B256, data: PooledBlobSidecar) -> Result<(), BlobStoreError>;
201
202    /// Inserts multiple blob sidecars into the store
203    fn insert_all(&self, txs: Vec<(B256, PooledBlobSidecar)>) -> Result<(), BlobStoreError>;
204
205    /// Inserts a validated sidecar that keeps only some cells, preserving any full sidecar and
206    /// replacing an earlier sample for the same transaction.
207    ///
208    /// The default rebuilds the blobs and inserts the full sidecar, so it fails with too few cells.
209    /// A store meant to hold samples must override it, because a sample the store rejects stays
210    /// pooled but is never announced or included.
211    fn insert_cells(
212        &self,
213        tx: B256,
214        data: BlobTransactionCellSidecar,
215    ) -> Result<(), BlobStoreError> {
216        if self.contains(tx)? {
217            return Ok(())
218        }
219        let sidecar = data
220            .recover(EnvKzgSettings::Default.get())
221            .map_err(|err| BlobStoreError::Other(Box::new(err)))?;
222        self.insert(tx, BlobTransactionSidecarVariant::Eip7594(sidecar).into())
223    }
224
225    /// Deletes the blob sidecar from the store
226    fn delete(&self, tx: B256) -> Result<(), BlobStoreError>;
227
228    /// Deletes multiple blob sidecars from the store
229    fn delete_all(&self, txs: Vec<B256>) -> Result<(), BlobStoreError>;
230
231    /// A maintenance function that can be called periodically to clean up the blob store, returns
232    /// the number of successfully deleted blobs and the number of failed deletions.
233    ///
234    /// This is intended to be called in the background to clean up any old or unused data, in case
235    /// the store uses deferred cleanup: [`DiskFileBlobStore`]
236    fn cleanup(&self) -> BlobStoreCleanupStat;
237
238    /// Retrieves the decoded blob data for the given transaction hash.
239    fn get(&self, tx: B256) -> Result<Option<Arc<BlobTransactionSidecarVariant>>, BlobStoreError>;
240
241    /// Retrieves the EIP-7594 sidecar of `tx` without its blobs, as served to eth/72 peers.
242    ///
243    /// Unlike [`Self::get`], this also returns sidecars stored only as cells. Returns `None` if
244    /// `tx` is missing or has a legacy sidecar.
245    fn get_without_blobs(
246        &self,
247        tx: B256,
248    ) -> Result<Option<BlobTransactionSidecarEip7594>, BlobStoreError> {
249        Ok(self.get(tx)?.and_then(|sidecar| sidecar.as_eip7594().map(without_blobs)))
250    }
251
252    /// Checks if the given transaction hash is in the blob store.
253    ///
254    /// This is also true for a transaction stored only as cells, even if [`Self::get`] cannot
255    /// rebuild its blobs.
256    fn contains(&self, tx: B256) -> Result<bool, BlobStoreError>;
257
258    /// Retrieves all decoded blob data for the given transaction hashes.
259    ///
260    /// This only returns the blobs that were found in the store.
261    /// If there's no blob it will not be returned.
262    ///
263    /// Note: this is not guaranteed to return the blobs in the same order as the input.
264    fn get_all(
265        &self,
266        txs: Vec<B256>,
267    ) -> Result<Vec<(B256, Arc<BlobTransactionSidecarVariant>)>, BlobStoreError>;
268
269    /// Returns the exact [`BlobTransactionSidecarVariant`] for the given transaction hashes in the
270    /// exact order they were requested.
271    ///
272    /// Returns an error if any of the blobs are not found in the blob store.
273    fn get_exact(
274        &self,
275        txs: Vec<B256>,
276    ) -> Result<Vec<Arc<BlobTransactionSidecarVariant>>, BlobStoreError>;
277
278    /// Return the [`BlobAndProofV1`]s for a list of blob versioned hashes.
279    fn get_by_versioned_hashes_v1(
280        &self,
281        versioned_hashes: &[B256],
282    ) -> Result<Vec<Option<BlobAndProofV1>>, BlobStoreError>;
283
284    /// Return the [`BlobAndProofV2`]s for a list of blob versioned hashes.
285    /// Blobs and proofs are returned only if they are present for _all_ requested
286    /// versioned hashes.
287    ///
288    /// This differs from [`BlobStore::get_by_versioned_hashes_v1`] in that it also returns all the
289    /// cell proofs in [`BlobAndProofV2`] supported by the EIP-7594 blob sidecar variant.
290    ///
291    /// The response also differs from [`BlobStore::get_by_versioned_hashes_v1`] in that this
292    /// returns `None` if any of the requested versioned hashes are not present in the blob store:
293    /// e.g. where v1 would return `[A, None, C]` v2 would return `None`. See also <https://github.com/ethereum/execution-apis/blob/main/src/engine/osaka.md#engine_getblobsv2>
294    fn get_by_versioned_hashes_v2(
295        &self,
296        versioned_hashes: &[B256],
297    ) -> Result<Option<Vec<BlobAndProofV2>>, BlobStoreError>;
298
299    /// Return the [`BlobAndProofV2`]s for a list of blob versioned hashes.
300    ///
301    /// The response is always the same length as the request. Missing or older-version blobs are
302    /// returned as `None` elements.
303    fn get_by_versioned_hashes_v3(
304        &self,
305        versioned_hashes: &[B256],
306    ) -> Result<Vec<Option<BlobAndProofV2>>, BlobStoreError>;
307
308    /// Return the [`BlobCellsAndProofsV1`]s for a list of blob versioned hashes and requested cell
309    /// indices.
310    ///
311    /// The response is always the same length as the request. Missing or older-version blobs are
312    /// returned as `None` elements.
313    fn get_by_versioned_hashes_v4(
314        &self,
315        versioned_hashes: &[B256],
316        cell_mask: BlobCellMask,
317    ) -> Result<Vec<Option<BlobCellsAndProofsV1>>, BlobStoreError>;
318
319    /// Return whether each requested blob versioned hash is available.
320    ///
321    /// A blob stored only as cells counts as available only if enough of them are kept to rebuild
322    /// it. The response is always the same length and order as the request.
323    fn has_versioned_hashes(&self, versioned_hashes: &[B256]) -> Result<Vec<bool>, BlobStoreError>;
324
325    /// Returns all requested cells for all blobs belonging to the transaction.
326    ///
327    /// The `cell_mask` is applied independently to every blob in the tx.
328    ///
329    /// Returned cells are flattened in blob order, then cell-index order. Returns `None` if the
330    /// transaction isn't stored or its cells can't be computed within the budget.
331    ///
332    /// Example:
333    /// If the tx contains blobs `[blob0, blob1]` and the requested indices are
334    /// `[2, 5, 9]`, the returned vector is:
335    ///
336    /// ```text
337    /// [
338    ///   blob0_cell2,
339    ///   blob0_cell5,
340    ///   blob0_cell9,
341    ///   blob1_cell2,
342    ///   blob1_cell5,
343    ///   blob1_cell9,
344    /// ]
345    /// ```
346    fn get_cells(
347        &self,
348        tx_hash: TxHash,
349        cell_mask: BlobCellMask,
350    ) -> Result<Option<Vec<Cell>>, BlobStoreError>;
351
352    /// Data size of all transactions in the blob store.
353    fn data_size_hint(&self) -> Option<usize>;
354
355    /// How many blobs are in the blob store.
356    fn blobs_len(&self) -> usize;
357}
358
359/// Error variants that can occur when interacting with a blob store.
360#[derive(Debug, thiserror::Error)]
361pub enum BlobStoreError {
362    /// Thrown if the blob sidecar is not found for a given transaction hash but was required.
363    #[error("blob sidecar not found for transaction {0:?}")]
364    MissingSidecar(B256),
365    /// Failed to decode the stored blob data.
366    #[error("failed to decode blob data: {0}")]
367    DecodeError(#[from] alloy_rlp::Error),
368    /// Other implementation specific error.
369    #[error(transparent)]
370    Other(Box<dyn core::error::Error + Send + Sync>),
371}
372
373/// Keeps track of the size of the blob store.
374#[derive(Debug, Default)]
375pub(crate) struct BlobStoreSize {
376    data_size: AtomicUsize,
377    num_blobs: AtomicUsize,
378}
379
380impl BlobStoreSize {
381    #[inline]
382    pub(crate) fn add_size(&self, add: usize) {
383        self.data_size.fetch_add(add, Ordering::Relaxed);
384    }
385
386    #[inline]
387    pub(crate) fn sub_size(&self, sub: usize) {
388        let _ = self.data_size.try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
389            Some(current.saturating_sub(sub))
390        });
391    }
392
393    #[inline]
394    pub(crate) fn update_len(&self, len: usize) {
395        self.num_blobs.store(len, Ordering::Relaxed);
396    }
397
398    #[inline]
399    pub(crate) fn inc_len(&self, add: usize) {
400        self.num_blobs.fetch_add(add, Ordering::Relaxed);
401    }
402
403    #[inline]
404    pub(crate) fn sub_len(&self, sub: usize) {
405        let _ = self.num_blobs.try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
406            Some(current.saturating_sub(sub))
407        });
408    }
409
410    #[inline]
411    pub(crate) fn data_size(&self) -> usize {
412        self.data_size.load(Ordering::Relaxed)
413    }
414
415    #[inline]
416    pub(crate) fn blobs_len(&self) -> usize {
417        self.num_blobs.load(Ordering::Relaxed)
418    }
419}
420
421impl PartialEq for BlobStoreSize {
422    fn eq(&self, other: &Self) -> bool {
423        self.data_size.load(Ordering::Relaxed) == other.data_size.load(Ordering::Relaxed) &&
424            self.num_blobs.load(Ordering::Relaxed) == other.num_blobs.load(Ordering::Relaxed)
425    }
426}
427
428/// Returns `sidecar` with its commitments and cell proofs, but no blobs.
429fn without_blobs(sidecar: &BlobTransactionSidecarEip7594) -> BlobTransactionSidecarEip7594 {
430    BlobTransactionSidecarEip7594::new(
431        Vec::new(),
432        sidecar.commitments.clone(),
433        sidecar.cell_proofs.clone(),
434    )
435}
436
437/// Sidecars rebuilt from stored cells, so reads don't rebuild them on every call.
438///
439/// Evicts the least recently used sidecars past [`MAX_REBUILT_SIDECARS_SIZE`].
440#[derive(Debug)]
441pub(crate) struct RebuiltSidecars {
442    cache: Mutex<RebuiltCache>,
443    // Most bytes to keep, [`MAX_REBUILT_SIDECARS_SIZE`] outside tests.
444    max_size: usize,
445}
446
447impl RebuiltSidecars {
448    /// Returns the cached sidecar, or rebuilds it outside the lock if `cells` is recoverable.
449    pub(crate) fn get_or_rebuild(
450        &self,
451        tx: TxHash,
452        cells: &BlobTransactionCellSidecar,
453    ) -> Option<Arc<BlobTransactionSidecarVariant>> {
454        if let Some(sidecar) = self.cache.lock().sidecars.get(&tx) {
455            return Some(Arc::clone(sidecar))
456        }
457        if !cells.is_recoverable() {
458            return None
459        }
460        let sidecar = match cells.recover(EnvKzgSettings::Default.get()) {
461            Ok(sidecar) => Arc::new(BlobTransactionSidecarVariant::Eip7594(sidecar)),
462            Err(err) => {
463                // Stored cells are validated, so this is a local fault.
464                error!(target: "txpool::blob", %err, ?tx, "Failed to rebuild blobs from cells");
465                return None
466            }
467        };
468        let cache = &mut *self.cache.lock();
469        // A concurrent read may have rebuilt it first.
470        if let Some(cached) = cache.sidecars.get(&tx) {
471            return Some(Arc::clone(cached))
472        }
473        cache.size += sidecar.size();
474        cache.sidecars.insert(tx, Arc::clone(&sidecar));
475        while cache.size > self.max_size &&
476            let Some((_, evicted)) = cache.sidecars.pop_oldest()
477        {
478            cache.size -= evicted.size();
479        }
480        Some(sidecar)
481    }
482
483    /// Drops the rebuilt sidecar of `tx`, if any.
484    pub(crate) fn remove(&self, tx: &TxHash) {
485        let cache = &mut *self.cache.lock();
486        if let Some(evicted) = cache.sidecars.remove(tx) {
487            cache.size -= evicted.size();
488        }
489    }
490}
491
492impl Default for RebuiltSidecars {
493    fn default() -> Self {
494        Self {
495            cache: Mutex::new(RebuiltCache {
496                sidecars: LruMap::with_hasher(u32::MAX, Default::default()),
497                size: 0,
498            }),
499            max_size: MAX_REBUILT_SIDECARS_SIZE,
500        }
501    }
502}
503
504// The rebuilt sidecars, least recently used first out, and their total size.
505#[derive(Debug)]
506struct RebuiltCache {
507    sidecars: LruMap<TxHash, Arc<BlobTransactionSidecarVariant>, FbBuildHasher<32>>,
508    size: usize,
509}
510
511/// Every cell of the full sidecars whose parity cells were requested, so serving them to several
512/// peers computes them once.
513///
514/// Computing cells is charged to one budget shared by all peers.
515///
516/// Evicts the least recently used cells past [`MAX_COMPUTED_CELLS_SIZE`]. A transaction hash
517/// commits to its versioned hashes, which full sidecars are checked against when stored, so cached
518/// cells never go stale. Cells of a deleted transaction can be cached again by a request racing the
519/// delete, or by one the disk store serves from its blob cache, and stay until evicted.
520#[derive(Debug)]
521pub(crate) struct ComputedCells {
522    cache: Mutex<ComputedCache>,
523    // Most bytes to keep, [`MAX_COMPUTED_CELLS_SIZE`] outside tests.
524    max_size: usize,
525}
526
527impl ComputedCells {
528    /// Returns the cells of `sidecar` at the columns in `cell_mask`. Data cells are copied from the
529    /// blobs, any parity cell computes every cell of `tx` outside the lock unless they are cached.
530    /// Returns `None` if they aren't cached and the budget is used up.
531    pub(crate) fn matching_cells(
532        &self,
533        tx: TxHash,
534        sidecar: &BlobTransactionSidecarEip7594,
535        cell_mask: BlobCellMask,
536    ) -> Result<Option<Vec<Cell>>, BlobStoreError> {
537        self.matching_cells_with_clock(tx, sidecar, cell_mask, Instant::now)
538    }
539
540    // Sample the clock only when a cache miss needs to reserve computation time.
541    fn matching_cells_with_clock(
542        &self,
543        tx: TxHash,
544        sidecar: &BlobTransactionSidecarEip7594,
545        cell_mask: BlobCellMask,
546        now: impl FnOnce() -> Instant,
547    ) -> Result<Option<Vec<Cell>>, BlobStoreError> {
548        if cell_mask.is_subset_of(DATA_COLUMNS) {
549            let mut cells = Vec::with_capacity(sidecar.blobs.len() * cell_mask.count());
550            for blob in &sidecar.blobs {
551                let data = blob.as_chunks::<BYTES_PER_CELL>().0;
552                cells.extend(cell_mask.selected_indices().map(|index| Cell::from(data[index])));
553            }
554            return Ok(Some(cells))
555        }
556        let cached = {
557            let cache = &mut *self.cache.lock();
558            let cached = cache.cells.get(&tx).cloned();
559            // Any peer can ask for uncached cells, so computing them shares one budget. Past it
560            // they're skipped, as EIP-8070 allows.
561            if cached.is_none() && !cache.spend(now(), sidecar.blobs.len()) {
562                return Ok(None)
563            }
564            cached
565        };
566        let cells = match cached {
567            Some(cells) => cells,
568            None => {
569                let cells: Arc<[Cell]> = sidecar
570                    .compute_cells()
571                    .map_err(|err| BlobStoreError::Other(Box::new(err)))?
572                    .into();
573                let cache = &mut *self.cache.lock();
574                // A concurrent request may have computed them first. Empty cells add no size, so
575                // caching them would escape the eviction.
576                if !cells.is_empty() && !cache.cells.contains(&tx) {
577                    cache.size += size_of_val(&*cells);
578                    cache.cells.insert(tx, Arc::clone(&cells));
579                    while cache.size > self.max_size &&
580                        let Some((_, evicted)) = cache.cells.pop_oldest()
581                    {
582                        cache.size -= size_of_val(&*evicted);
583                    }
584                }
585                cells
586            }
587        };
588        Ok(cell_mask.matching_cells_from_computed_cells(&cells))
589    }
590
591    /// Whether the cells of `tx` at `cell_mask` are free to serve or fit in the budget.
592    pub(crate) fn can_compute(&self, tx: &TxHash, cell_mask: BlobCellMask) -> bool {
593        if cell_mask.is_subset_of(DATA_COLUMNS) {
594            return true
595        }
596        let cache = self.cache.lock();
597        cache.cells.contains(tx) || cache.has_budget(Instant::now())
598    }
599
600    /// Drops the computed cells of `tx`, if any.
601    pub(crate) fn remove(&self, tx: &TxHash) {
602        let cache = &mut *self.cache.lock();
603        if let Some(evicted) = cache.cells.remove(tx) {
604            cache.size -= size_of_val(&*evicted);
605        }
606    }
607}
608
609impl Default for ComputedCells {
610    fn default() -> Self {
611        Self {
612            cache: Mutex::new(ComputedCache {
613                cells: LruMap::with_hasher(u32::MAX, Default::default()),
614                size: 0,
615                full_at: Instant::now(),
616            }),
617            max_size: MAX_COMPUTED_CELLS_SIZE,
618        }
619    }
620}
621
622// The computed cells, least recently used first out, their total size, and when the compute budget
623// is full again.
624#[derive(Debug)]
625struct ComputedCache {
626    cells: LruMap<TxHash, Arc<[Cell]>, FbBuildHasher<32>>,
627    size: usize,
628    full_at: Instant,
629}
630
631impl ComputedCache {
632    /// Spends `blobs` of the compute budget at `now`, or returns `false` if none is left.
633    fn spend(&mut self, now: Instant, blobs: usize) -> bool {
634        if !self.has_budget(now) {
635            return false
636        }
637        self.full_at = self.full_at.max(now) +
638            COMPUTED_CELL_BLOB_REFILL * u32::try_from(blobs).unwrap_or(u32::MAX);
639        true
640    }
641
642    /// Whether any of the compute budget is left at `now`.
643    fn has_budget(&self, now: Instant) -> bool {
644        self.full_at.saturating_duration_since(now) <=
645            COMPUTED_CELL_BLOB_REFILL * (MAX_COMPUTED_CELL_BLOBS - 1)
646    }
647}
648
649/// Statistics for the cleanup operation.
650#[derive(Debug, Clone, Default, PartialEq, Eq)]
651pub struct BlobStoreCleanupStat {
652    /// the number of successfully deleted blobs
653    pub delete_succeed: usize,
654    /// the number of failed deletions
655    pub delete_failed: usize,
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use crate::blobstore::cells::tests::{fixture, subset};
662    use alloy_eips::eip4844::Blob;
663
664    // A store with the sizes it counts for a cell sidecar and for the full sidecar.
665    struct TestStore {
666        store: Box<dyn BlobStore>,
667        cells_size: usize,
668        full_size: usize,
669        _dir: Option<tempfile::TempDir>,
670    }
671
672    // An in-memory and a disk store for `cells`.
673    fn stores(cells: &BlobTransactionCellSidecar) -> Vec<TestStore> {
674        let (full, _) = fixture();
675        let full = BlobTransactionSidecarVariant::Eip7594(full.clone());
676        let dir = tempfile::tempdir().unwrap();
677        let disk = DiskFileBlobStore::open(dir.path(), Default::default()).unwrap();
678        vec![
679            TestStore {
680                store: Box::new(InMemoryBlobStore::default()),
681                cells_size: cells.size(),
682                full_size: full.size(),
683                _dir: None,
684            },
685            TestStore {
686                store: Box::new(disk),
687                cells_size: disk::encode_cells(cells).len(),
688                full_size: full.rlp_encoded_fields_length(),
689                _dir: Some(dir),
690            },
691        ]
692    }
693
694    #[expect(dead_code)]
695    struct DynStore {
696        store: Box<dyn BlobStore>,
697    }
698
699    #[test]
700    fn blob_cell_availability_uses_cell_index_bit_order() {
701        let availability =
702            BlobCellAvailability(Arc::new([AtomicU64::new(1), AtomicU64::new(1 << 1)]));
703
704        let mask = availability.get();
705        assert!(mask.contains(0));
706        assert!(mask.contains(65));
707        assert_eq!(mask.count(), 2);
708    }
709
710    #[test]
711    fn set_full_marks_every_cell_for_every_clone() {
712        let availability = BlobCellAvailability::new(BlobCellMask::from_bits(1));
713        let shared = availability.clone();
714        availability.set_full();
715        assert!(shared.is_full());
716    }
717
718    #[test]
719    fn rebuilt_sidecars_are_cached_within_their_size() {
720        let (full, _) = fixture();
721        let full = Arc::new(BlobTransactionSidecarVariant::Eip7594(full.clone()));
722        let half = subset(BlobCellMask::from_bits(u128::MAX / 3));
723        let too_few = subset(BlobCellMask::from_bits(1));
724        let (first, second) = (B256::random(), B256::random());
725
726        let rebuilt = RebuiltSidecars { max_size: full.size(), ..Default::default() };
727        assert_eq!(rebuilt.get_or_rebuild(first, &too_few), None);
728        assert_eq!(rebuilt.get_or_rebuild(first, &half), Some(full.clone()));
729        // A cached sidecar is returned without rebuilding, even from unrecoverable cells.
730        assert_eq!(rebuilt.get_or_rebuild(first, &too_few), Some(full.clone()));
731
732        // Caching a second one goes over the size, so the first is evicted.
733        assert_eq!(rebuilt.get_or_rebuild(second, &half), Some(full.clone()));
734        assert_eq!(rebuilt.get_or_rebuild(first, &too_few), None);
735        assert_eq!(rebuilt.get_or_rebuild(second, &too_few), Some(full));
736        rebuilt.remove(&second);
737        let cache = rebuilt.cache.lock();
738        assert!(cache.sidecars.is_empty());
739        assert_eq!(cache.size, 0);
740    }
741
742    #[test]
743    fn data_cells_are_copied_from_the_blobs() {
744        // Distinct bytes in every field element, whose first byte keeps it below the modulus.
745        let mut blob = Blob::default();
746        for (index, byte) in blob.iter_mut().enumerate() {
747            if index % 32 != 0 {
748                *byte = index as u8 ^ (index >> 8) as u8;
749            }
750        }
751        let full =
752            BlobTransactionSidecarEip7594::try_from_blobs(vec![blob, Blob::default()]).unwrap();
753        let all = full.compute_cells().unwrap();
754        let computed = ComputedCells::default();
755
756        for mask in [DATA_COLUMNS, BlobCellMask::from_bits(0b1011 << 60)] {
757            let expected = mask.matching_cells_from_computed_cells(&all);
758            assert_eq!(computed.matching_cells(B256::ZERO, &full, mask).unwrap(), expected);
759        }
760        // No parity cell was asked for, so nothing was computed.
761        assert!(computed.cache.lock().cells.is_empty());
762    }
763
764    #[test]
765    fn computed_cells_are_cached_within_their_size() {
766        let (full, all) = fixture();
767        // A parity column, so the cells are computed.
768        let mask = BlobCellMask::from_bits(0b101 << 63);
769        let expected = all.matching_cells(mask);
770        // No blobs to compute cells from, so only cached cells can be returned for it.
771        let empty = BlobTransactionSidecarEip7594::default();
772        let (first, second) = (B256::random(), B256::random());
773
774        let computed = ComputedCells { max_size: size_of_val(all.cells()), ..Default::default() };
775        assert_eq!(computed.matching_cells(first, full, mask).unwrap(), expected);
776        assert_eq!(computed.matching_cells(first, &empty, mask).unwrap(), expected);
777
778        // Caching a second one goes over the size, so the first is evicted.
779        assert_eq!(computed.matching_cells(second, full, mask).unwrap(), expected);
780        assert_eq!(computed.matching_cells(first, &empty, mask).unwrap(), Some(Vec::new()));
781        assert_eq!(computed.matching_cells(second, &empty, mask).unwrap(), expected);
782        // Empty cells are not cached.
783        let third = B256::random();
784        assert_eq!(computed.matching_cells(third, &empty, mask).unwrap(), Some(Vec::new()));
785        assert!(!computed.cache.lock().cells.contains(&third));
786        computed.remove(&first);
787        computed.remove(&second);
788        let cache = computed.cache.lock();
789        assert!(cache.cells.is_empty());
790        assert_eq!(cache.size, 0);
791    }
792
793    #[test]
794    fn computed_cells_resume_at_budget_refill() {
795        let (full, all) = fixture();
796        let parity = BlobCellMask::from_bits(1 << 64);
797        let empty = BlobTransactionSidecarEip7594::default();
798        let (cached, uncached) = (B256::random(), B256::random());
799        let computed = ComputedCells::default();
800        let start = Instant::now();
801        let expected = all.matching_cells(parity);
802        assert_eq!(
803            computed.matching_cells_with_clock(cached, full, parity, || start).unwrap(),
804            expected
805        );
806
807        let remaining = MAX_COMPUTED_CELL_BLOBS as usize - full.blobs.len();
808        assert!(computed.cache.lock().spend(start, remaining));
809        let refill = start + COMPUTED_CELL_BLOB_REFILL;
810        let before_refill = refill - Duration::from_nanos(1);
811        assert_eq!(
812            computed.matching_cells_with_clock(uncached, full, parity, || before_refill).unwrap(),
813            None
814        );
815        // Cached cells and data cells cost nothing to serve.
816        assert_eq!(
817            computed.matching_cells_with_clock(cached, &empty, parity, || before_refill).unwrap(),
818            expected
819        );
820        assert_eq!(
821            computed
822                .matching_cells_with_clock(uncached, full, DATA_COLUMNS, || before_refill)
823                .unwrap(),
824            all.matching_cells(DATA_COLUMNS)
825        );
826        assert_eq!(
827            computed.matching_cells_with_clock(uncached, full, parity, || refill).unwrap(),
828            expected
829        );
830    }
831
832    #[test]
833    fn compute_budget_refills_one_blob_per_interval_up_to_the_cap() {
834        let start = Instant::now();
835        let max = MAX_COMPUTED_CELL_BLOBS as usize;
836        let budget = &mut ComputedCells::default().cache.into_inner();
837        budget.full_at = start;
838        assert!(budget.spend(start, max - 1));
839        // One blob left still computes a whole transaction.
840        assert!(budget.spend(start, 4));
841        assert!(!budget.spend(start, 1));
842        // The 3 blobs computed past the budget are paid back first.
843        assert!(!budget.spend(start + COMPUTED_CELL_BLOB_REFILL * 3, 1));
844        assert!(budget.spend(start + COMPUTED_CELL_BLOB_REFILL * 4, 1));
845
846        // A full budget doesn't save up idle time.
847        let later = start + COMPUTED_CELL_BLOB_REFILL * 1000;
848        budget.full_at = start;
849        assert!(budget.spend(later, max));
850        assert!(!budget.spend(later, 1));
851    }
852
853    #[test]
854    fn stores_rebuild_blobs_from_half_of_the_cells() {
855        let (full, all) = fixture();
856        let hash = all.versioned_hashes().next().unwrap();
857        let expected = BlobAndProofV2 {
858            blob: Box::new(full.blobs[0]),
859            proofs: full.cell_proofs[..CELLS_PER_EXT_BLOB].to_vec(),
860        };
861        let full = Arc::new(BlobTransactionSidecarVariant::Eip7594(full.clone()));
862        let (cells, proofs) = (all.cells(), all.proofs());
863        // Every other column.
864        let half = subset(BlobCellMask::from_bits(u128::MAX / 3));
865
866        for TestStore { store, cells_size, full_size, _dir } in stores(&half) {
867            let tx = B256::random();
868            store.insert_cells(tx, half.clone()).unwrap();
869            assert!(store.contains(tx).unwrap());
870            assert_eq!((store.blobs_len(), store.data_size_hint()), (1, Some(cells_size)));
871
872            let rebuilt = store.get(tx).unwrap().unwrap();
873            assert_eq!(rebuilt, full);
874            // Rebuilt once, then served from the cache.
875            assert!(Arc::ptr_eq(&rebuilt, &store.get(tx).unwrap().unwrap()));
876            assert_eq!(store.get_all(vec![tx, B256::ZERO]).unwrap(), vec![(tx, full.clone())]);
877            assert_eq!(store.get_exact(vec![tx]).unwrap(), vec![full.clone()]);
878            assert_eq!(
879                store.get_by_versioned_hashes_v3(&[hash, B256::ZERO]).unwrap(),
880                vec![Some(expected.clone()), None]
881            );
882            assert_eq!(store.has_versioned_hashes(&[hash, B256::ZERO]).unwrap(), vec![true, false]);
883
884            // Cells are served from the kept ones without rebuilding.
885            assert_eq!(
886                store.get_cells(tx, BlobCellMask::from_bits(0b101)).unwrap(),
887                Some(vec![cells[0], cells[2], cells[128], cells[130]])
888            );
889            assert_eq!(store.get_cells(tx, BlobCellMask::from_bits(0b110)).unwrap(), None);
890            assert_eq!(
891                store.get_by_versioned_hashes_v4(&[hash], BlobCellMask::from_bits(0b110)).unwrap(),
892                vec![Some(BlobCellsAndProofsV1 {
893                    blob_cells: vec![None, Some(cells[2])],
894                    proofs: vec![None, Some(proofs[2])],
895                })]
896            );
897
898            // A full sidecar replaces the cells, and later cells are ignored.
899            store.insert(tx, (*full).clone().into()).unwrap();
900            store.insert_cells(tx, half.clone()).unwrap();
901            assert_eq!(store.get(tx).unwrap(), Some(full.clone()));
902            assert_eq!(store.get_without_blobs(tx).unwrap(), Some(half.without_blobs()));
903            assert_eq!((store.blobs_len(), store.data_size_hint()), (1, Some(full_size)));
904            let other = B256::random();
905            store.insert_cells(other, half.clone()).unwrap();
906            store.insert_all(vec![(other, (*full).clone().into())]).unwrap();
907            assert_eq!((store.blobs_len(), store.data_size_hint()), (2, Some(2 * full_size)));
908        }
909    }
910
911    #[test]
912    fn stores_serve_cells_they_cannot_rebuild() {
913        let (_, all) = fixture();
914        let hash = all.versioned_hashes().next().unwrap();
915        let (cells, proofs) = (all.cells(), all.proofs());
916        let kept = BlobCellMask::from_bits(0b1011);
917        let partial = subset(kept);
918
919        for TestStore { store, cells_size, _dir, .. } in stores(&partial) {
920            let tx = B256::random();
921            store.insert_cells(tx, partial.clone()).unwrap();
922            assert_eq!((store.blobs_len(), store.data_size_hint()), (1, Some(cells_size)));
923            assert_eq!(store.get(tx).unwrap(), None);
924            assert!(matches!(
925                store.get_exact(vec![tx]),
926                Err(BlobStoreError::MissingSidecar(missing)) if missing == tx
927            ));
928            assert_eq!(store.get_by_versioned_hashes_v3(&[hash]).unwrap(), vec![None]);
929            assert_eq!(store.has_versioned_hashes(&[hash]).unwrap(), vec![false]);
930            // Its body can still be served without blobs.
931            assert_eq!(store.get_without_blobs(tx).unwrap(), Some(partial.without_blobs()));
932            assert_eq!(
933                store.get_cells(tx, kept).unwrap(),
934                Some(vec![cells[0], cells[1], cells[3], cells[128], cells[129], cells[131]])
935            );
936            assert_eq!(
937                store.get_by_versioned_hashes_v4(&[hash], BlobCellMask::from_bits(0b110)).unwrap(),
938                vec![Some(BlobCellsAndProofsV1 {
939                    blob_cells: vec![Some(cells[1]), None],
940                    proofs: vec![Some(proofs[1]), None],
941                })]
942            );
943
944            store.delete(tx).unwrap();
945            store.cleanup();
946            assert!(!store.contains(tx).unwrap());
947            assert_eq!((store.blobs_len(), store.data_size_hint()), (0, Some(0)));
948            assert_eq!(store.get_cells(tx, kept).unwrap(), None);
949        }
950    }
951
952    #[test]
953    fn stores_rebuild_blobs_from_a_later_cell_sidecar() {
954        let (full, all) = fixture();
955        let hash = all.versioned_hashes().next().unwrap();
956        let expected = BlobAndProofV2 {
957            blob: Box::new(full.blobs[0]),
958            proofs: full.cell_proofs[..CELLS_PER_EXT_BLOB].to_vec(),
959        };
960        let one_column = subset(BlobCellMask::from_bits(1));
961
962        for TestStore { store, _dir, .. } in stores(&one_column) {
963            store.insert_cells(B256::random(), one_column.clone()).unwrap();
964            store
965                .insert_cells(B256::random(), subset(BlobCellMask::from_bits(u128::MAX / 3)))
966                .unwrap();
967
968            assert_eq!(store.has_versioned_hashes(&[hash]).unwrap(), vec![true]);
969            assert_eq!(
970                store.get_by_versioned_hashes_v3(&[hash]).unwrap(),
971                vec![Some(expected.clone())]
972            );
973        }
974    }
975
976    #[test]
977    fn stores_merge_cells_of_one_blob_from_different_sidecars() {
978        let (_, all) = fixture();
979        let hash = all.versioned_hashes().next().unwrap();
980        let (cells, proofs) = (all.cells(), all.proofs());
981        let first = subset(BlobCellMask::from_bits(0b01));
982
983        for TestStore { store, _dir, .. } in stores(&first) {
984            store.insert_cells(B256::random(), first.clone()).unwrap();
985            store.insert_cells(B256::random(), subset(BlobCellMask::from_bits(0b10))).unwrap();
986
987            assert_eq!(
988                store.get_by_versioned_hashes_v4(&[hash], BlobCellMask::from_bits(0b11)).unwrap(),
989                vec![Some(BlobCellsAndProofsV1 {
990                    blob_cells: vec![Some(cells[0]), Some(cells[1])],
991                    proofs: vec![Some(proofs[0]), Some(proofs[1])],
992                })]
993            );
994        }
995    }
996}