1pub 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
37const MAX_REBUILT_SIDECARS_SIZE: usize = 64 * 1024 * 1024;
39
40const MAX_COMPUTED_CELLS_SIZE: usize = 64 * 1024 * 1024;
42
43const MAX_COMPUTED_CELL_BLOBS: u32 = 32;
45
46const COMPUTED_CELL_BLOB_REFILL: Duration = Duration::from_millis(125);
48
49pub const DATA_COLUMNS: BlobCellMask = BlobCellMask::ALL.first(CELLS_PER_EXT_BLOB / 2);
51
52#[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 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 pub fn full() -> Self {
71 Self::new(BlobCellMask::ALL)
72 }
73
74 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 pub fn is_full(&self) -> bool {
86 self.get() == BlobCellMask::ALL
87 }
88
89 pub fn set_full(&self) {
91 self.set(BlobCellMask::ALL);
92 }
93
94 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#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct PooledBlobSidecar {
116 sidecar: BlobTransactionSidecarVariant,
117 availability: BlobCellAvailability,
118 cells: Option<Arc<BlobTransactionCellSidecar>>,
119}
120
121impl PooledBlobSidecar {
122 pub const fn new(
124 sidecar: BlobTransactionSidecarVariant,
125 availability: BlobCellAvailability,
126 ) -> Self {
127 Self { sidecar, availability, cells: None }
128 }
129
130 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 pub const fn sidecar(&self) -> &BlobTransactionSidecarVariant {
142 &self.sidecar
143 }
144
145 pub const fn is_eip7594(&self) -> bool {
147 self.sidecar.is_eip7594()
148 }
149
150 pub const fn availability(&self) -> &BlobCellAvailability {
152 &self.availability
153 }
154
155 pub fn into_sidecar(self) -> BlobTransactionSidecarVariant {
157 self.sidecar
158 }
159
160 pub fn cells(&self) -> Option<&BlobTransactionCellSidecar> {
162 self.cells.as_deref()
163 }
164
165 pub(crate) const fn take_cells(&mut self) -> Option<Arc<BlobTransactionCellSidecar>> {
167 self.cells.take()
168 }
169
170 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 Self::new(sidecar, BlobCellAvailability::full())
189 }
190}
191
192pub trait BlobStore: fmt::Debug + Send + Sync + 'static {
199 fn insert(&self, tx: B256, data: PooledBlobSidecar) -> Result<(), BlobStoreError>;
201
202 fn insert_all(&self, txs: Vec<(B256, PooledBlobSidecar)>) -> Result<(), BlobStoreError>;
204
205 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 fn delete(&self, tx: B256) -> Result<(), BlobStoreError>;
227
228 fn delete_all(&self, txs: Vec<B256>) -> Result<(), BlobStoreError>;
230
231 fn cleanup(&self) -> BlobStoreCleanupStat;
237
238 fn get(&self, tx: B256) -> Result<Option<Arc<BlobTransactionSidecarVariant>>, BlobStoreError>;
240
241 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 fn contains(&self, tx: B256) -> Result<bool, BlobStoreError>;
257
258 fn get_all(
265 &self,
266 txs: Vec<B256>,
267 ) -> Result<Vec<(B256, Arc<BlobTransactionSidecarVariant>)>, BlobStoreError>;
268
269 fn get_exact(
274 &self,
275 txs: Vec<B256>,
276 ) -> Result<Vec<Arc<BlobTransactionSidecarVariant>>, BlobStoreError>;
277
278 fn get_by_versioned_hashes_v1(
280 &self,
281 versioned_hashes: &[B256],
282 ) -> Result<Vec<Option<BlobAndProofV1>>, BlobStoreError>;
283
284 fn get_by_versioned_hashes_v2(
295 &self,
296 versioned_hashes: &[B256],
297 ) -> Result<Option<Vec<BlobAndProofV2>>, BlobStoreError>;
298
299 fn get_by_versioned_hashes_v3(
304 &self,
305 versioned_hashes: &[B256],
306 ) -> Result<Vec<Option<BlobAndProofV2>>, BlobStoreError>;
307
308 fn get_by_versioned_hashes_v4(
314 &self,
315 versioned_hashes: &[B256],
316 cell_mask: BlobCellMask,
317 ) -> Result<Vec<Option<BlobCellsAndProofsV1>>, BlobStoreError>;
318
319 fn has_versioned_hashes(&self, versioned_hashes: &[B256]) -> Result<Vec<bool>, BlobStoreError>;
324
325 fn get_cells(
347 &self,
348 tx_hash: TxHash,
349 cell_mask: BlobCellMask,
350 ) -> Result<Option<Vec<Cell>>, BlobStoreError>;
351
352 fn data_size_hint(&self) -> Option<usize>;
354
355 fn blobs_len(&self) -> usize;
357}
358
359#[derive(Debug, thiserror::Error)]
361pub enum BlobStoreError {
362 #[error("blob sidecar not found for transaction {0:?}")]
364 MissingSidecar(B256),
365 #[error("failed to decode blob data: {0}")]
367 DecodeError(#[from] alloy_rlp::Error),
368 #[error(transparent)]
370 Other(Box<dyn core::error::Error + Send + Sync>),
371}
372
373#[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
428fn without_blobs(sidecar: &BlobTransactionSidecarEip7594) -> BlobTransactionSidecarEip7594 {
430 BlobTransactionSidecarEip7594::new(
431 Vec::new(),
432 sidecar.commitments.clone(),
433 sidecar.cell_proofs.clone(),
434 )
435}
436
437#[derive(Debug)]
441pub(crate) struct RebuiltSidecars {
442 cache: Mutex<RebuiltCache>,
443 max_size: usize,
445}
446
447impl RebuiltSidecars {
448 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 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 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 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#[derive(Debug)]
506struct RebuiltCache {
507 sidecars: LruMap<TxHash, Arc<BlobTransactionSidecarVariant>, FbBuildHasher<32>>,
508 size: usize,
509}
510
511#[derive(Debug)]
521pub(crate) struct ComputedCells {
522 cache: Mutex<ComputedCache>,
523 max_size: usize,
525}
526
527impl ComputedCells {
528 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 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 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 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 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 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#[derive(Debug)]
625struct ComputedCache {
626 cells: LruMap<TxHash, Arc<[Cell]>, FbBuildHasher<32>>,
627 size: usize,
628 full_at: Instant,
629}
630
631impl ComputedCache {
632 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 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
651pub struct BlobStoreCleanupStat {
652 pub delete_succeed: usize,
654 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 struct TestStore {
666 store: Box<dyn BlobStore>,
667 cells_size: usize,
668 full_size: usize,
669 _dir: Option<tempfile::TempDir>,
670 }
671
672 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 assert_eq!(rebuilt.get_or_rebuild(first, &too_few), Some(full.clone()));
731
732 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 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 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 let mask = BlobCellMask::from_bits(0b101 << 63);
769 let expected = all.matching_cells(mask);
770 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 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 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 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 assert!(budget.spend(start, 4));
841 assert!(!budget.spend(start, 1));
842 assert!(!budget.spend(start + COMPUTED_CELL_BLOB_REFILL * 3, 1));
844 assert!(budget.spend(start + COMPUTED_CELL_BLOB_REFILL * 4, 1));
845
846 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 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 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 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 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 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}