Skip to main content

reth_network/transactions/blob/
unverified.rs

1//! Collects the body and separately fetched cells of an eth/72 blob transaction until they can
2//! be verified.
3
4use super::error::StoreError;
5use alloy_eips::{
6    eip4844::env_settings::EnvKzgSettings,
7    eip7594::{BlobCellMask, Cell, BYTES_PER_CELL, CELLS_PER_EXT_BLOB, MAX_BLOBS_PER_TX_FUSAKA},
8};
9use alloy_rlp::Encodable;
10use reth_network_peers::PeerId;
11use reth_transaction_pool::{
12    blobstore::{BlobTransactionCellSidecar, PooledBlobSidecar, DATA_COLUMNS},
13    validate::DEFAULT_MAX_TX_INPUT_BYTES,
14    PoolTransaction,
15};
16
17/// The body and cells received for one eth/72 blob transaction, whose body arrives without blobs.
18///
19/// Cells are only checked by [`UnverifiedBlobTx::verify`], once the needed columns arrived.
20#[derive(Debug)]
21pub(super) struct UnverifiedBlobTx<T> {
22    // The first body received and its sender.
23    body: Option<(PeerId, T)>,
24    // Cells received, with disjoint masks.
25    replies: Vec<CellReply>,
26    // Columns of all replies.
27    mask: BlobCellMask,
28    // Bytes of the body and of its data columns' cells, charged when the body is stored.
29    bytes: usize,
30}
31
32impl<T> Default for UnverifiedBlobTx<T> {
33    fn default() -> Self {
34        Self { body: None, replies: Vec::new(), mask: BlobCellMask::default(), bytes: 0 }
35    }
36}
37
38impl<T: PoolTransaction> UnverifiedBlobTx<T> {
39    /// Returns the bytes charged for the body and its data columns' cells, or 0 before the body.
40    pub(super) const fn bytes(&self) -> usize {
41        self.bytes
42    }
43
44    /// Returns the peer that sent the stored body, or `None` before the body arrives.
45    pub(super) fn sender(&self) -> Option<PeerId> {
46        self.body.as_ref().map(|(peer, _)| *peer)
47    }
48
49    /// Returns the columns stored.
50    pub(super) const fn columns(&self) -> BlobCellMask {
51        self.mask
52    }
53
54    /// Returns the columns of the replies that lie entirely within `keep`.
55    pub(super) fn columns_within(&self, keep: BlobCellMask) -> BlobCellMask {
56        self.replies
57            .iter()
58            .filter(|reply| reply.mask.is_subset_of(keep))
59            .fold(BlobCellMask::default(), |mask, reply| mask.union(reply.mask))
60    }
61
62    /// Drops the replies with columns outside `keep`, so those columns can be asked again.
63    pub(super) fn retain(&mut self, keep: BlobCellMask) {
64        self.replies.retain(|reply| reply.mask.is_subset_of(keep));
65        self.mask = self.columns_within(keep);
66    }
67
68    /// Returns the blob count of the stored body, or `None` before the body arrives.
69    pub(super) fn blobs(&self) -> Option<usize> {
70        self.body.as_ref().and_then(|(_, tx)| tx.blob_versioned_hashes()).map(<[_]>::len)
71    }
72
73    /// Returns whether the body and every column in `target` are stored.
74    pub(super) const fn is_ready(&self, target: BlobCellMask) -> bool {
75        self.body.is_some() && target.count() > 0 && target.is_subset_of(self.mask)
76    }
77
78    /// Stores the body of `tx` sent by `peer` if it and its data columns' cells fit in `room`
79    /// bytes, keeping the first body. Returns the bytes charged.
80    pub(super) fn body(&mut self, peer: PeerId, tx: T, room: usize) -> Result<usize, StoreError> {
81        let Some(sidecar) = tx.blob_sidecar().and_then(|sidecar| sidecar.as_eip7594()) else {
82            return Err(StoreError::Invalid)
83        };
84        let Some(hashes) = tx.blob_versioned_hashes() else { return Err(StoreError::Invalid) };
85        // The commitments are bound to the transaction hash through the versioned hashes, while
86        // the proofs are only checked against the cells.
87        // Cells can't cover more blobs than a transaction carries, so such a body never finishes.
88        if !sidecar.blobs.is_empty() ||
89            hashes.is_empty() ||
90            hashes.len() > MAX_BLOBS_PER_TX_FUSAKA as usize ||
91            sidecar.cell_proofs.len() != hashes.len() * CELLS_PER_EXT_BLOB ||
92            !sidecar.versioned_hashes().eq(hashes.iter().copied())
93        {
94            return Err(StoreError::Invalid)
95        }
96        // The pool refuses larger blob transactions by default, measured as it does, so such a body
97        // would only take room. It isn't malformed, since a pool can be set to accept it.
98        let input = tx.input().len().saturating_add(
99            tx.access_list().map(|access_list| access_list.length()).unwrap_or_default(),
100        );
101        if input > DEFAULT_MAX_TX_INPUT_BYTES {
102            return Err(StoreError::TooLarge)
103        }
104        if self.body.is_some() {
105            return Err(StoreError::Duplicate)
106        }
107        // Charging the cells up front means a stored body can always get them. The transaction
108        // size leaves out the sidecar, whose proofs are most of the body.
109        let size =
110            tx.size() + sidecar.size() + hashes.len() * DATA_COLUMNS.count() * BYTES_PER_CELL;
111        if size > room {
112            return Err(StoreError::NoRoom(size))
113        }
114        self.body = Some((peer, tx));
115        self.bytes = size;
116        Ok(size)
117    }
118
119    /// Stores the `cells` at the columns in `mask`, which must match the stored body.
120    ///
121    /// Cells overlapping stored columns are duplicates, which only a stale reply can be since
122    /// requests ask for missing columns.
123    pub(super) fn cells(
124        &mut self,
125        mask: BlobCellMask,
126        mut cells: Vec<Cell>,
127    ) -> Result<(), StoreError> {
128        let Some(blobs) = self.blobs() else { return Err(StoreError::Invalid) };
129        if mask.count() == 0 || cells.len() != mask.count() * blobs {
130            return Err(StoreError::Invalid)
131        }
132        if self.mask.intersection(mask).count() > 0 {
133            return Err(StoreError::Duplicate)
134        }
135        // Decoding can leave spare capacity beyond the cells the body was charged for.
136        cells.shrink_to_fit();
137        self.mask = self.mask.union(mask);
138        self.replies.push(CellReply { mask, cells });
139        Ok(())
140    }
141
142    /// Checks the cells against the body's commitments and proofs, and attaches those at the
143    /// `keep` columns to it.
144    ///
145    /// Returns the body's sender and the transaction, or `None` if the body is missing or the
146    /// cells or the body's proofs are invalid. This runs KZG checks, so it must run off the async
147    /// threads.
148    pub(super) fn verify(self, keep: BlobCellMask) -> Option<(PeerId, T)> {
149        let (peer, mut transaction) = self.body?;
150        // `body` only stores bodies with an EIP-7594 sidecar.
151        let metadata = transaction.blob_sidecar()?.as_eip7594()?;
152        let hashes = transaction.blob_versioned_hashes()?;
153        // Cells are laid out blob by blob, and each column has one reply, see `cells`.
154        let mut cells = Vec::with_capacity(metadata.commitments.len() * self.mask.count());
155        for blob in 0..metadata.commitments.len() {
156            for column in self.mask.selected_indices() {
157                let reply = self.replies.iter().find(|reply| reply.mask.contains(column))?;
158                let position = reply.mask.selected_indices().position(|index| index == column)?;
159                cells.push(*reply.cells.get(blob * reply.mask.count() + position)?);
160            }
161        }
162        let sidecar = BlobTransactionCellSidecar::new(
163            metadata.commitments.clone(),
164            metadata.cell_proofs.clone(),
165            cells,
166            self.mask,
167        )?;
168        sidecar.validate(hashes, EnvKzgSettings::Default.get()).ok()?;
169        // A sample drops its random columns once checked, so they're never announced.
170        let sidecar = if keep == self.mask {
171            sidecar
172        } else {
173            BlobTransactionCellSidecar::new(
174                metadata.commitments.clone(),
175                metadata.cell_proofs.clone(),
176                sidecar.matching_cells(keep)?,
177                keep,
178            )?
179        };
180        transaction.set_blob_sidecar(PooledBlobSidecar::from_cells(sidecar)).then_some(())?;
181        Some((peer, transaction))
182    }
183}
184
185// The cells of one `Cells` reply, for every blob at the columns in `mask`.
186#[derive(Debug)]
187struct CellReply {
188    mask: BlobCellMask,
189    cells: Vec<Cell>,
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use alloy_eips::{
196        eip4844::Blob,
197        eip7594::{BlobTransactionSidecarEip7594, BlobTransactionSidecarVariant},
198    };
199    use reth_transaction_pool::{test_utils::blob_tx_without_blobs, EthPooledTransaction};
200
201    #[test]
202    fn body_and_cells_are_verified() {
203        let (tx, cells) = blob_tx_without_blobs(1);
204        let peer = PeerId::random();
205        let mut unverified = UnverifiedBlobTx::default();
206        unverified.body(peer, tx, usize::MAX).unwrap();
207        assert!(!unverified.is_ready(DATA_COLUMNS));
208        let data = cells.matching_cells(DATA_COLUMNS).unwrap();
209        assert_eq!(unverified.cells(DATA_COLUMNS, data), Ok(()));
210        assert!(unverified.is_ready(DATA_COLUMNS));
211        let (sender, tx) = unverified.verify(DATA_COLUMNS).unwrap();
212        assert_eq!(sender, peer);
213        assert_eq!(tx.blob_cell_availability().unwrap().get(), DATA_COLUMNS);
214    }
215
216    #[test]
217    fn dropped_columns_are_still_checked() {
218        let (tx, cells) = blob_tx_without_blobs(1);
219        let (kept, dropped) = (BlobCellMask::from_bits(0b0011), BlobCellMask::from_bits(0b0100));
220        let verify = |dropped_cells| {
221            let mut unverified = UnverifiedBlobTx::default();
222            unverified.body(PeerId::random(), tx.clone(), usize::MAX).unwrap();
223            unverified.cells(kept, cells.matching_cells(kept).unwrap()).unwrap();
224            unverified.cells(dropped, dropped_cells).unwrap();
225            unverified.verify(kept)
226        };
227        let (_, sampled) = verify(cells.matching_cells(dropped).unwrap()).unwrap();
228        assert_eq!(sampled.blob_cell_availability().unwrap().get(), kept);
229        assert!(verify(vec![Cell::repeat_byte(1)]).is_none());
230    }
231
232    #[test]
233    fn cells_of_several_blobs_from_several_replies_are_merged() {
234        let (tx, cells) = blob_tx_without_blobs(3);
235        let mut unverified = UnverifiedBlobTx::default();
236        unverified.body(PeerId::random(), tx, usize::MAX).unwrap();
237        let (low, high) = (BlobCellMask::from_bits(0b0011), BlobCellMask::from_bits(0b1100));
238        assert_eq!(unverified.cells(high, cells.matching_cells(high).unwrap()), Ok(()));
239        assert_eq!(unverified.cells(low, cells.matching_cells(low).unwrap()), Ok(()));
240        let both = BlobCellMask::from_bits(0b1111);
241        assert!(unverified.is_ready(both));
242        let (_, tx) = unverified.verify(low).unwrap();
243        let sidecar = tx.blob_sidecar().and_then(PooledBlobSidecar::cells).unwrap();
244        assert_eq!(sidecar.cells(), cells.matching_cells(low).unwrap());
245        assert_eq!(tx.blob_cell_availability().unwrap().get(), low);
246    }
247
248    #[test]
249    fn malformed_bodies_are_rejected() {
250        let (tx, cells) = blob_tx_without_blobs(1);
251        let mut unverified = UnverifiedBlobTx::default();
252        // A body with its blobs isn't an eth/72 body.
253        let mut with_blobs = tx.clone();
254        let full = BlobTransactionSidecarEip7594::try_from_blobs(vec![Blob::default()]).unwrap();
255        assert!(with_blobs.set_blob_sidecar(PooledBlobSidecar::from(
256            BlobTransactionSidecarVariant::Eip7594(full)
257        )));
258        assert_eq!(
259            unverified.body(PeerId::random(), with_blobs, usize::MAX),
260            Err(StoreError::Invalid)
261        );
262        // Commitments must match the versioned hashes.
263        let mut wrong_commitment = tx;
264        let mut sidecar = cells.without_blobs();
265        sidecar.commitments[0] = Default::default();
266        assert!(wrong_commitment.set_blob_sidecar(PooledBlobSidecar::from(
267            BlobTransactionSidecarVariant::Eip7594(sidecar)
268        )));
269        assert_eq!(
270            unverified.body(PeerId::random(), wrong_commitment, usize::MAX),
271            Err(StoreError::Invalid)
272        );
273        // A body with more blobs than a transaction can carry.
274        let (too_many, _) = blob_tx_without_blobs(MAX_BLOBS_PER_TX_FUSAKA as u8 + 1);
275        assert_eq!(
276            unverified.body(PeerId::random(), too_many, usize::MAX),
277            Err(StoreError::Invalid)
278        );
279        assert_eq!(unverified.blobs(), None);
280    }
281
282    #[test]
283    fn only_the_first_body_is_kept() {
284        let (tx, _) = blob_tx_without_blobs(1);
285        let (first, second) = (PeerId::random(), PeerId::random());
286        let mut unverified = UnverifiedBlobTx::default();
287        unverified.body(first, tx.clone(), usize::MAX).unwrap();
288        assert_eq!(unverified.body(second, tx, usize::MAX), Err(StoreError::Duplicate));
289        assert_eq!(unverified.body.unwrap().0, first);
290    }
291
292    #[test]
293    fn overlapping_cells_are_redundant() {
294        let (tx, cells) = blob_tx_without_blobs(1);
295        let mask = BlobCellMask::from_bits(1);
296        let mut unverified = UnverifiedBlobTx::default();
297        unverified.body(PeerId::random(), tx, usize::MAX).unwrap();
298        assert_eq!(unverified.cells(mask, cells.matching_cells(mask).unwrap()), Ok(()));
299        assert_eq!(
300            unverified.cells(mask, cells.matching_cells(mask).unwrap()),
301            Err(StoreError::Duplicate)
302        );
303        assert_eq!(unverified.replies.len(), 1);
304    }
305
306    #[test]
307    fn cells_must_match_the_body() {
308        let (tx, cells) = blob_tx_without_blobs(2);
309        let (_, single) = blob_tx_without_blobs(1);
310        let mask = BlobCellMask::from_bits(1);
311        let mut unverified = UnverifiedBlobTx::<EthPooledTransaction>::default();
312        // Cells are only stored once the body shows the blob count.
313        assert_eq!(
314            unverified.cells(mask, cells.matching_cells(mask).unwrap()),
315            Err(StoreError::Invalid)
316        );
317        unverified.body(PeerId::random(), tx, usize::MAX).unwrap();
318        assert_eq!(
319            unverified.cells(mask, single.matching_cells(mask).unwrap()),
320            Err(StoreError::Invalid)
321        );
322        assert_eq!(unverified.cells(mask, cells.matching_cells(mask).unwrap()), Ok(()));
323        assert_eq!(unverified.columns(), mask);
324    }
325
326    #[test]
327    fn counts_the_bytes_of_the_body_and_its_cells() {
328        let (tx, cells) = blob_tx_without_blobs(1);
329        let mut unverified = UnverifiedBlobTx::default();
330        // The body is charged with its data columns' cells up front, so it needs room for both.
331        let size =
332            UnverifiedBlobTx::default().body(PeerId::random(), tx.clone(), usize::MAX).unwrap();
333        assert!(size > DATA_COLUMNS.count() * BYTES_PER_CELL);
334        assert_eq!(
335            unverified.body(PeerId::random(), tx.clone(), size - 1),
336            Err(StoreError::NoRoom(size))
337        );
338        assert_eq!(unverified.bytes(), 0);
339        assert_eq!(unverified.body(PeerId::random(), tx, size), Ok(size));
340        let mut data = cells.matching_cells(DATA_COLUMNS).unwrap();
341        data.reserve(data.len());
342        assert_eq!(unverified.cells(DATA_COLUMNS, data), Ok(()));
343        assert_eq!(unverified.bytes(), size);
344        // The stored reply holds no spare capacity.
345        assert_eq!(unverified.replies[0].cells.capacity(), unverified.replies[0].cells.len());
346    }
347}