Skip to main content

reth_rpc/validation/
blob_cache.rs

1//! Small cache of successfully validated builder-submission blobs.
2//!
3//! A blob versioned hash identifies its KZG commitment, not the blob bytes. EIP-7594 validation
4//! verifies that the blob's cells and proofs match that commitment. This check is independent of
5//! the block containing the blob, so a successful validation can be reused across submissions,
6//! even if the original submission later fails a separate block check.
7//!
8//! Cache hits require an exact match of the blob, commitment, and all cell proofs. Every submission
9//! still checks bundle lengths and derives versioned hashes in bundle order. Payload validation
10//! then compares those hashes with the EIP-4844 transactions in the submitted block; the cache
11//! only skips repeated KZG verification.
12
13use super::ValidationApiError;
14use alloy_consensus::EnvKzgSettings;
15use alloy_eips::eip7594::{BlobTransactionSidecarEip7594, CELLS_PER_EXT_BLOB};
16use alloy_primitives::B256;
17use alloy_rpc_types_engine::BlobsBundleV2;
18use parking_lot::Mutex;
19use std::collections::VecDeque;
20
21/// Maximum number of individual blobs retained across competing submissions.
22const VALIDATED_BLOB_CACHE_CAPACITY: usize = 15;
23
24/// Reuses KZG validation only for exact V2 blob sidecar matches.
25#[derive(Debug, Default)]
26pub(super) struct BlobValidationCache {
27    /// Every entry contains exactly one validated blob.
28    entries: Mutex<VecDeque<BlobTransactionSidecarEip7594>>,
29}
30
31impl BlobValidationCache {
32    /// Validates a V2 bundle, verifying only blobs absent from the cache.
33    pub(super) fn validate(&self, bundle: BlobsBundleV2) -> Result<Vec<B256>, ValidationApiError> {
34        if bundle.blobs.len() != bundle.commitments.len() ||
35            bundle.blobs.len().checked_mul(CELLS_PER_EXT_BLOB) != Some(bundle.proofs.len())
36        {
37            return Err(ValidationApiError::InvalidBlobsBundle)
38        }
39        if bundle.blobs.is_empty() {
40            return Ok(Vec::new())
41        }
42
43        let versioned_hashes = bundle.versioned_hashes();
44        let hits = {
45            let entries = self.entries.lock();
46            (0..bundle.blobs.len())
47                .map(|index| {
48                    let proofs = &bundle.proofs
49                        [index * CELLS_PER_EXT_BLOB..(index + 1) * CELLS_PER_EXT_BLOB];
50                    entries.iter().any(|cached| {
51                        cached.commitments[0] == bundle.commitments[index] &&
52                            cached.cell_proofs == proofs &&
53                            cached.blobs[0] == bundle.blobs[index]
54                    })
55                })
56                .collect::<Vec<_>>()
57        };
58        if hits.iter().all(|hit| *hit) {
59            return Ok(versioned_hashes)
60        }
61
62        let (_, missing) = bundle
63            .try_partition_blobs(|index, _, _, _| hits[index])
64            .map_err(|_| ValidationApiError::InvalidBlobsBundle)?;
65        let sidecar =
66            missing.try_into_sidecar().map_err(|_| ValidationApiError::InvalidBlobsBundle)?;
67        let missing_hashes = sidecar.versioned_hashes().collect::<Vec<_>>();
68        sidecar.validate(&missing_hashes, EnvKzgSettings::default().get())?;
69
70        for index in 0..sidecar.blobs.len() {
71            let proofs =
72                &sidecar.cell_proofs[index * CELLS_PER_EXT_BLOB..(index + 1) * CELLS_PER_EXT_BLOB];
73            self.insert(BlobTransactionSidecarEip7594::new(
74                vec![sidecar.blobs[index]],
75                vec![sidecar.commitments[index]],
76                proofs.to_vec(),
77            ));
78        }
79
80        Ok(versioned_hashes)
81    }
82
83    fn insert(&self, sidecar: BlobTransactionSidecarEip7594) {
84        let mut entries = self.entries.lock();
85        if entries
86            .iter()
87            .any(|cached| cached.commitments == sidecar.commitments && cached == &sidecar)
88        {
89            return;
90        }
91        if entries.len() == VALIDATED_BLOB_CACHE_CAPACITY {
92            entries.pop_front();
93        }
94        entries.push_back(sidecar);
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use alloy_consensus::{Blob, BlobTransactionSidecar, Bytes48, SidecarBuilder, SimpleCoder};
102    use alloy_rpc_types_engine::BlobsBundleV1;
103
104    fn valid_v1_bundle(data: &[u8]) -> BlobsBundleV1 {
105        let mut builder = SidecarBuilder::<SimpleCoder>::new();
106        builder.ingest(data);
107        BlobsBundleV1::new([builder.build::<BlobTransactionSidecar>().unwrap()])
108    }
109
110    fn valid_v2_bundle(data: &[u8]) -> BlobsBundleV2 {
111        valid_v1_bundle(data).try_into_v2().unwrap()
112    }
113
114    #[test]
115    fn mixed_bundle_validates_only_missing_blobs() {
116        let cache = BlobValidationCache::default();
117        let mut bundle = valid_v2_bundle(b"first blob");
118        let second = valid_v2_bundle(b"second blob");
119        cache.validate(valid_v2_bundle(b"first blob")).unwrap();
120
121        bundle.blobs.extend(second.blobs);
122        bundle.commitments.extend(second.commitments);
123        bundle.proofs.extend(second.proofs);
124        assert_eq!(cache.validate(bundle.clone()).unwrap(), bundle.versioned_hashes());
125        assert_eq!(cache.entries.lock().len(), 2);
126    }
127
128    #[test]
129    fn v2_reuses_only_exact_validated_blobs() {
130        let cache = BlobValidationCache::default();
131        let hashes = valid_v2_bundle(b"peer das blob").versioned_hashes();
132
133        assert_eq!(cache.validate(valid_v2_bundle(b"peer das blob")).unwrap(), hashes);
134        assert_eq!(cache.validate(valid_v2_bundle(b"peer das blob")).unwrap(), hashes);
135        assert_eq!(cache.entries.lock().len(), 1);
136
137        let mut changed_blob = valid_v2_bundle(b"peer das blob");
138        changed_blob.blobs[0].0[0] ^= 1;
139        assert!(cache.validate(changed_blob).is_err());
140
141        let mut changed_proof = valid_v2_bundle(b"peer das blob");
142        changed_proof.proofs[0].0[0] ^= 1;
143        assert!(cache.validate(changed_proof).is_err());
144        assert_eq!(cache.entries.lock().len(), 1);
145    }
146
147    #[test]
148    fn validates_uncached_blob_even_when_another_hits() {
149        let cache = BlobValidationCache::default();
150        let mut bundle = valid_v2_bundle(b"first blob");
151        let mut second = valid_v2_bundle(b"second blob");
152        cache.validate(valid_v2_bundle(b"first blob")).unwrap();
153
154        second.proofs[0].0[0] ^= 1;
155        bundle.blobs.extend(second.blobs);
156        bundle.commitments.extend(second.commitments);
157        bundle.proofs.extend(second.proofs);
158        assert!(cache.validate(bundle).is_err());
159        assert_eq!(cache.entries.lock().len(), 1);
160    }
161
162    #[test]
163    fn rejects_incomplete_bundles_without_changing_cache() {
164        let cache = BlobValidationCache::default();
165        let mut v2 = BlobsBundleV2::empty();
166        v2.blobs.push(Blob::default());
167        v2.commitments.push(Bytes48::ZERO);
168        v2.proofs = vec![Bytes48::ZERO; CELLS_PER_EXT_BLOB - 1];
169        assert!(matches!(cache.validate(v2), Err(ValidationApiError::InvalidBlobsBundle)));
170        assert!(cache.entries.lock().is_empty());
171    }
172
173    #[test]
174    fn empty_bundle_still_checks_lengths() {
175        let cache = BlobValidationCache::default();
176        assert!(cache.validate(BlobsBundleV2::empty()).unwrap().is_empty());
177
178        let mut malformed = BlobsBundleV2::empty();
179        malformed.proofs.push(Bytes48::ZERO);
180        assert!(matches!(cache.validate(malformed), Err(ValidationApiError::InvalidBlobsBundle)));
181    }
182
183    #[test]
184    fn retains_only_fifteen_recent_blobs() {
185        let cache = BlobValidationCache::default();
186        let blob = Blob::default();
187        for index in 0..=VALIDATED_BLOB_CACHE_CAPACITY {
188            cache.insert(BlobTransactionSidecarEip7594::new(
189                vec![blob],
190                vec![Bytes48::repeat_byte(index as u8)],
191                vec![Bytes48::ZERO; CELLS_PER_EXT_BLOB],
192            ));
193        }
194
195        let entries = cache.entries.lock();
196        assert_eq!(entries.len(), VALIDATED_BLOB_CACHE_CAPACITY);
197        assert_eq!(entries.front().unwrap().commitments[0], Bytes48::repeat_byte(1));
198    }
199}