Skip to main content

reth_network/transactions/blob/
fetcher.rs

1//! Fetches the cells of blob transactions announced by eth/72 peers.
2//!
3//! eth/72 peers send blob transaction bodies without their blobs. The body is still fetched by
4//! the [`TransactionFetcher`](crate::transactions::TransactionFetcher), while this fetcher requests
5//! the first half of the columns with `GetCells`, which hold the blobs, checks them against the
6//! body and hands the transaction back for the pool import. Any other half needs a KZG recovery
7//! that recomputes every proof, about ten times the cost of validating the blobs.
8//!
9//! As EIP-8070 allows, most transactions are only sampled: the node fetches the columns its
10//! consensus client custodies, which can't rebuild the blobs, and one extra column from a peer with
11//! every column, which is checked and then dropped. A sample waits for two such peers, and is
12//! fetched in full if they don't announce it within two seconds.
13
14use super::{
15    error::StoreError,
16    role::{fetch_role, Role},
17    unverified::UnverifiedBlobTx,
18};
19use crate::transactions::{
20    announcement::{AnnouncedTransaction, TransactionAnnouncement},
21    constants::tx_manager::MIN_BLOB_FETCH_PROBABILITY,
22    PeerMetadata,
23};
24use alloy_consensus::constants::EIP4844_TX_TYPE_ID;
25use alloy_eips::eip7594::BlobCellMask;
26use alloy_primitives::{
27    map::{hash_map::Entry, B256Map, FbBuildHasher, HashMap},
28    B256,
29};
30use futures::{stream::FuturesUnordered, Future, StreamExt};
31use rand::Rng;
32use reth_eth_wire::{Cells, GetCells, NetworkPrimitives};
33use reth_metrics::{metrics::Counter, Metrics};
34use reth_network_api::{CellCustody, PeerRequest};
35use reth_network_peers::PeerId;
36use reth_network_types::session::config::INITIAL_REQUEST_TIMEOUT;
37use reth_transaction_pool::{blobstore::DATA_COLUMNS, PoolTransaction};
38use std::{
39    cmp::Reverse,
40    pin::Pin,
41    task::{Context, Poll},
42    time::{Duration, Instant},
43};
44use tokio::{
45    sync::oneshot,
46    time::{self, Sleep},
47};
48
49/// Most transactions waiting for their cells. This bounds the entries, while
50/// `MAX_BUFFERED_BYTES` bounds the bodies and cells they hold.
51const MAX_PENDING_TRANSACTIONS: usize = 4096;
52
53/// Most pending transactions one peer's announcements can add, so it can't fill the fetcher alone:
54/// filling it takes 4096 / 64 = 64 peers.
55const MAX_PENDING_PER_PEER: usize = 64;
56
57/// Most bytes held for stored bodies, each charged with the cells it still needs. A transaction
58/// takes at most about 0.9 MiB (6 blobs × 64 columns × 2 KiB cells, plus a 128 KiB input and
59/// 36 KiB of proofs), so the 64 MiB total fits about 70 of them.
60const MAX_BUFFERED_BYTES: usize = 64 * 1024 * 1024;
61
62/// Most bytes held for the bodies one peer sent, so it can't fill the buffer alone: filling it
63/// takes 64 / 16 = 4 peers.
64const MAX_BUFFERED_BYTES_PER_PEER: usize = MAX_BUFFERED_BYTES / 4;
65
66/// Most `GetCells` requests in flight.
67const MAX_INFLIGHT_REQUESTS: usize = 16;
68
69/// Most `GetCells` requests in flight to one peer, so a slow peer can't hold every request: the
70/// 16 requests in flight are spread over at least 16 / 4 = 4 peers.
71const MAX_INFLIGHT_REQUESTS_PER_PEER: usize = 4;
72
73/// Most cell checks running at once, independent of the requests in flight.
74const MAX_CONCURRENT_VERIFICATIONS: usize = 4;
75
76/// Most announcing peers kept per transaction to fetch its cells from.
77pub(super) const MAX_PROVIDERS_PER_TRANSACTION: usize = 16;
78
79// Least peers announcing every column before a transaction is sampled, set by EIP-8070.
80const MIN_SAMPLE_PROVIDERS: usize = 2;
81
82// How long a sample waits for enough peers with every column before it's fetched in full, as
83// geth does.
84const SAMPLE_AVAILABILITY_TIMEOUT: Duration = Duration::from_secs(2);
85
86/// How long a peer has to answer a `GetCells` request.
87const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
88
89/// How long a body fetched again has to arrive before the next provider is asked: as long as a
90/// session waits for one response.
91const REFETCH_TIMEOUT: Duration = INITIAL_REQUEST_TIMEOUT;
92
93/// How long a transaction waits for its body and cells before it's dropped.
94const PENDING_TTL: Duration = Duration::from_secs(120);
95
96/// How often expired transactions are removed.
97const EXPIRY_INTERVAL: Duration = Duration::from_millis(100);
98
99/// Fetches the cells of eth/72 blob transactions and checks them against their bodies.
100#[derive(Debug)]
101pub(crate) struct BlobFetcher<T> {
102    // Transactions whose cells are being fetched or checked.
103    pending: B256Map<Pending<T>>,
104    // Pending transactions added by each peer's announcements.
105    added_by_peer: HashMap<PeerId, usize>,
106    // Bytes held for the stored bodies.
107    bytes: usize,
108    // Bytes held for the bodies each peer sent.
109    bytes_by_peer: HashMap<PeerId, usize>,
110    // `GetCells` requests in flight, polled for their replies.
111    requests: FuturesUnordered<RequestFuture>,
112    // Number of `requests` sent to each peer, since the boxed futures don't expose their peer. A
113    // request counts until its future completes, even after its fetch is removed.
114    requests_by_peer: HashMap<PeerId, usize>,
115    // Id of the next `GetCells` request.
116    next_request_id: u64,
117    // Cell checks running off the async threads.
118    verifications: FuturesUnordered<VerifyFuture<T>>,
119    // When expired transactions were last removed.
120    last_expiry: Instant,
121    // Wakes the task when the earliest sample still waiting for providers is due to be fetched in
122    // full. Created on first use, since a `Sleep` needs a Tokio runtime.
123    sample_timer: Option<Pin<Box<Sleep>>>,
124    // The columns the consensus client custodies, which a sampled transaction fetches.
125    custody: CellCustody,
126    // Probability, in percent, of fetching a transaction in full rather than sampling it.
127    fetch_probability: u8,
128    // Wakes the transaction manager at the earliest outstanding body refetch deadline.
129    refetch_timer: Option<Pin<Box<Sleep>>>,
130    metrics: BlobFetcherMetrics,
131}
132
133// `T` is only stored by value in maps and moved into boxed futures, never pinned in place.
134impl<T> Unpin for BlobFetcher<T> {}
135
136type RequestFuture = Pin<Box<dyn Future<Output = (B256, PeerId, u64, Option<Cells>)> + Send>>;
137
138type VerifyFuture<T> = Pin<Box<dyn Future<Output = (B256, Option<(PeerId, T)>)> + Send>>;
139
140impl<T: PoolTransaction + 'static> BlobFetcher<T> {
141    /// Creates an empty fetcher that samples the columns in `custody`, and fetches a transaction
142    /// in full with `fetch_probability` percent, at least [`MIN_BLOB_FETCH_PROBABILITY`].
143    pub(crate) fn new(custody: CellCustody, fetch_probability: u8) -> Self {
144        Self {
145            pending: Default::default(),
146            added_by_peer: Default::default(),
147            bytes: 0,
148            bytes_by_peer: Default::default(),
149            requests: Default::default(),
150            requests_by_peer: Default::default(),
151            next_request_id: 0,
152            verifications: Default::default(),
153            last_expiry: Instant::now(),
154            sample_timer: None,
155            custody,
156            fetch_probability: fetch_probability.max(MIN_BLOB_FETCH_PROBABILITY),
157            refetch_timer: None,
158            metrics: Default::default(),
159        }
160    }
161
162    /// Records the blob transactions in an eth/72 `announcement` from `peer`, with the cells it
163    /// keeps, and removes those it declines so their bodies aren't fetched only to be dropped.
164    /// Announcements without a cell mask are ignored.
165    pub(crate) fn on_announcement(
166        &mut self,
167        peer: PeerId,
168        announcement: &mut TransactionAnnouncement,
169    ) {
170        let Some(mask) = announcement.cell_mask() else { return };
171        let mask = BlobCellMask::new(mask);
172        announcement.retain(|tx| {
173            !tx.metadata.is_some_and(|metadata| metadata.tx_type == EIP4844_TX_TYPE_ID) ||
174                self.announce(tx.hash, peer, mask)
175        });
176    }
177
178    /// Stores the body of a blob transaction that `peer` sent without blobs, if its cells are
179    /// being fetched.
180    ///
181    /// Returns `false` if the body is malformed. A body larger than the pool accepts by default
182    /// stops the fetch. A full buffer evicts bodies of the peers holding the most to make room if
183    /// that frees enough, and a body still without room is fetched again later, see
184    /// [`Self::poll_refetches`].
185    pub(crate) fn body(&mut self, peer: PeerId, tx: T) -> bool {
186        let hash = *tx.hash();
187        // Cells are only fetched for pending transactions, so other bodies would only take room.
188        let Some(pending) = self.pending.get_mut(&hash) else { return true };
189        if pending.state == State::Verifying {
190            return true
191        }
192        let sent = self.bytes_by_peer.get(&peer).copied().unwrap_or_default();
193        match pending.tx.body(peer, tx, MAX_BUFFERED_BYTES_PER_PEER - sent) {
194            Ok(size) => {
195                pending.declined = None;
196                self.bytes += size;
197                *self.bytes_by_peer.entry(peer).or_default() += size;
198                // Evicting only helps if the fetches it may drop cover the overflow, otherwise it
199                // drops them for a body that's dropped anyway.
200                if self.bytes > MAX_BUFFERED_BYTES &&
201                    self.evictable(&hash).map(|(_, pending)| pending.tx.bytes()).sum::<usize>() >=
202                        self.bytes - MAX_BUFFERED_BYTES
203                {
204                    while self.bytes > MAX_BUFFERED_BYTES && self.evict(&hash) {}
205                }
206                if self.bytes > MAX_BUFFERED_BYTES &&
207                    let Some(pending) = self.pending.get_mut(&hash)
208                {
209                    let tx = std::mem::take(&mut pending.tx);
210                    release(&mut self.bytes, &mut self.bytes_by_peer, &tx);
211                    pending.declined = Some(DeclinedBody { bytes: size, asked: None });
212                }
213                true
214            }
215            Err(StoreError::Invalid) => false,
216            Err(StoreError::NoRoom(bytes)) => {
217                pending.declined = Some(DeclinedBody { bytes, asked: None });
218                true
219            }
220            Err(StoreError::TooLarge) => {
221                self.remove(&hash);
222                true
223            }
224            Err(StoreError::Duplicate) => true,
225        }
226    }
227
228    /// Takes the bodies with room to be fetched again and registers a wakeup for the next retry.
229    pub(crate) fn poll_refetches(
230        &mut self,
231        cx: &mut Context<'_>,
232    ) -> Vec<(PeerId, AnnouncedTransaction)> {
233        let now = time::Instant::now();
234        let mut next_deadline = None;
235        let mut ready = false;
236        for declined in self.pending.values().filter_map(|pending| pending.declined) {
237            if let Some((_, deadline)) = declined.asking(now) {
238                next_deadline = Some(deadline.min(next_deadline.unwrap_or(deadline)));
239            } else {
240                ready = true;
241            }
242        }
243
244        let refetches = if ready { self.refetches(now) } else { Vec::new() };
245        if !refetches.is_empty() {
246            next_deadline.get_or_insert(now + REFETCH_TIMEOUT);
247        }
248        if let Some(deadline) = next_deadline {
249            let timer =
250                self.refetch_timer.get_or_insert_with(|| Box::pin(time::sleep_until(deadline)));
251            if timer.deadline() != deadline {
252                timer.as_mut().reset(deadline);
253            }
254            if timer.as_mut().poll(cx).is_ready() {
255                cx.waker().wake_by_ref();
256            }
257        } else {
258            self.refetch_timer = None;
259        }
260        refetches
261    }
262
263    // Reserves room for bodies being fetched again until they arrive or their deadlines pass.
264    fn refetches(&mut self, now: time::Instant) -> Vec<(PeerId, AnnouncedTransaction)> {
265        let mut refetches = Vec::new();
266        let (mut bytes, mut bytes_by_peer) = (self.bytes, self.bytes_by_peer.clone());
267        for declined in self.pending.values().filter_map(|pending| pending.declined) {
268            if let Some((peer, _)) = declined.asking(now) {
269                bytes += declined.bytes;
270                *bytes_by_peer.entry(peer).or_default() += declined.bytes;
271            }
272        }
273        for (&hash, pending) in &mut self.pending {
274            if let Some(declined) = &mut pending.declined &&
275                declined.asking(now).is_none() &&
276                bytes + declined.bytes <= MAX_BUFFERED_BYTES &&
277                let Some(peer) = declined.in_turn(&pending.providers).find(|id| {
278                    bytes_by_peer.get(id).copied().unwrap_or_default() + declined.bytes <=
279                        MAX_BUFFERED_BYTES_PER_PEER
280                })
281            {
282                declined.asked = Some((peer, now + REFETCH_TIMEOUT));
283                bytes += declined.bytes;
284                *bytes_by_peer.entry(peer).or_default() += declined.bytes;
285                // Another provider's announced size could get this one disconnected, while the
286                // hash already binds the body.
287                refetches.push((peer, AnnouncedTransaction { hash, metadata: None }));
288            }
289        }
290        self.metrics.refetched.increment(refetches.len() as u64);
291        refetches
292    }
293
294    /// Stops fetching the cells of `hash` and drops its body and cells, if any.
295    ///
296    /// Every dropped fetch goes through here, which releases its bytes and its peer's slot.
297    pub(crate) fn remove(&mut self, hash: &B256) {
298        if let Some(pending) = self.pending.remove(hash) {
299            release(&mut self.bytes, &mut self.bytes_by_peer, &pending.tx);
300            decrement(&mut self.added_by_peer, pending.added_by, 1);
301        }
302    }
303
304    /// Stops fetching cells from a disconnected `peer`. A fetch only it let the providers finish
305    /// is dropped, unless it is a sample that can still be fetched in full. The others it added
306    /// move to a remaining provider with room, or are dropped.
307    ///
308    /// This keeps a peer reconnecting under a new key from holding more than its slots.
309    pub(crate) fn drop_peer(&mut self, peer: &PeerId) {
310        let mut dropped = Vec::new();
311        let mut added = Vec::new();
312        for (&hash, pending) in &mut self.pending {
313            let could_finish = pending.can_finish();
314            pending.providers.retain(|(id, _)| id != peer);
315            if let Some(declined) = &mut pending.declined &&
316                declined.asked.is_some_and(|(id, _)| id == *peer)
317            {
318                declined.asked = None;
319            }
320            // Only fetches whose coverage this peer's departure removes are dropped. Others keep
321            // waiting for providers, as samplers announce only their custody columns. A complete
322            // fetch keeps its slot until checked, since its check result removes it.
323            if could_finish && !pending.can_finish() && !pending.fetch_in_full(&self.metrics) {
324                dropped.push(hash);
325                continue
326            }
327            if pending.added_by == *peer &&
328                pending.state != State::Verifying &&
329                !pending.tx.is_ready(pending.role.target())
330            {
331                added.push(hash);
332            }
333        }
334        for hash in &dropped {
335            self.remove(hash);
336        }
337        for hash in added {
338            let Some(pending) = self.pending.get_mut(&hash) else { continue };
339            let heir = pending.providers.iter().map(|(id, _)| *id).find(|id| {
340                self.added_by_peer.get(id).copied().unwrap_or_default() < MAX_PENDING_PER_PEER
341            });
342            if let Some(heir) = heir {
343                decrement(&mut self.added_by_peer, *peer, 1);
344                *self.added_by_peer.entry(heir).or_default() += 1;
345                pending.added_by = heir;
346            } else {
347                self.remove(&hash);
348            }
349        }
350    }
351
352    /// Advances requests and checks, and sends new requests to `peers`.
353    ///
354    /// Returns the transactions whose cells passed the check, with the peer that sent each body.
355    pub(crate) fn poll<N: NetworkPrimitives>(
356        &mut self,
357        cx: &mut Context<'_>,
358        peers: &HashMap<PeerId, PeerMetadata<N>, FbBuildHasher<64>>,
359    ) -> Poll<Vec<(PeerId, T)>> {
360        let mut verified = Vec::new();
361        while let Poll::Ready(Some((hash, result))) = self.verifications.poll_next_unpin(cx) {
362            self.remove(&hash);
363            if let Some(tx) = result {
364                self.metrics.verified.increment(1);
365                verified.push(tx);
366            } else {
367                // Either the cells or the body's proofs are invalid, and only the proofs aren't
368                // bound by the transaction hash, so nobody is certainly at fault.
369                self.metrics.invalid.increment(1);
370            }
371        }
372
373        while let Poll::Ready(Some((hash, peer, id, response))) = self.requests.poll_next_unpin(cx)
374        {
375            decrement(&mut self.requests_by_peer, peer, 1);
376            self.on_response(hash, peer, id, response);
377        }
378
379        self.expire_if_due(Instant::now());
380
381        let mut queued = self.queue_verifications();
382        let (sent, sample_deadline) = self.send_requests(peers);
383        queued |= sent;
384        // New futures need a first poll to register their wakers.
385        if queued {
386            cx.waker().wake_by_ref();
387        }
388        if let Some(deadline) = sample_deadline {
389            let deadline = tokio::time::Instant::from_std(deadline);
390            let timer = self
391                .sample_timer
392                .get_or_insert_with(|| Box::pin(tokio::time::sleep_until(deadline)));
393            timer.as_mut().reset(deadline);
394            if timer.as_mut().poll(cx).is_ready() {
395                cx.waker().wake_by_ref();
396            }
397        }
398        if verified.is_empty() {
399            Poll::Pending
400        } else {
401            Poll::Ready(verified)
402        }
403    }
404
405    // Records that `peer` announced the blob transaction `hash` with the cells in `mask`. Returns
406    // whether its cells are being fetched.
407    fn announce(&mut self, hash: B256, peer: PeerId, mask: BlobCellMask) -> bool {
408        let now = Instant::now();
409        // A fresh announcement starts a new fetch rather than joining one the next sweep removes.
410        if self.pending.get(&hash).is_some_and(|pending| pending.is_expired(now)) {
411            self.remove(&hash);
412        }
413        if mask.count() == 0 {
414            return self.pending.contains_key(&hash)
415        }
416        if !self.pending.contains_key(&hash) {
417            // Expired fetches are otherwise swept on poll, which may not have run since they
418            // expired. The sweep is rate limited, so a full fetcher doesn't scan on every hash.
419            if self.pending.len() >= MAX_PENDING_TRANSACTIONS && self.expire_if_due(now) == 0 {
420                return false
421            }
422            if self.added_by_peer.get(&peer).copied().unwrap_or_default() >= MAX_PENDING_PER_PEER {
423                return false
424            }
425            *self.added_by_peer.entry(peer).or_default() += 1;
426            let role = fetch_role(self.custody.get(), self.fetch_probability, &mut rand::rng());
427            if matches!(role, Role::Sampler { .. }) {
428                self.metrics.sampled.increment(1);
429            }
430            self.pending.insert(hash, Pending::new(peer, now, role));
431        }
432        let Some(pending) = self.pending.get_mut(&hash) else { return false };
433        let target = pending.role.target();
434        let providers = &mut pending.providers;
435        if let Some((_, announced)) = providers.iter_mut().find(|(id, _)| *id == peer) {
436            *announced = mask;
437        } else if providers.len() < MAX_PROVIDERS_PER_TRANSACTION {
438            providers.push((peer, mask));
439        } else {
440            // A full list swaps its peer with the fewest target columns it can be asked for for one
441            // with more, so peers with every column outrank samplers for a sample's extra column.
442            let role = pending.role;
443            let data = |mask: BlobCellMask| role.requestable(mask).intersection(target).count();
444            if let Some(weakest) = providers
445                .iter_mut()
446                .min_by_key(|(_, announced)| data(*announced))
447                .filter(|(_, announced)| data(*announced) < data(mask))
448            {
449                *weakest = (peer, mask);
450            }
451        }
452        // A sample starts once enough peers announced every column, and their leaving later
453        // doesn't undo it.
454        if let Role::Sampler { available, .. } = &mut pending.role &&
455            !*available
456        {
457            *available = providers
458                .iter()
459                .filter(|(_, announced)| *announced == BlobCellMask::ALL)
460                .count() >=
461                MIN_SAMPLE_PROVIDERS;
462        }
463        true
464    }
465
466    // Removes the expired transactions and returns how many.
467    fn expire(&mut self, now: Instant) -> usize {
468        let expired = self
469            .pending
470            .iter()
471            .filter(|(_, pending)| pending.is_expired(now))
472            .map(|(hash, _)| *hash)
473            .collect::<Vec<_>>();
474        for hash in &expired {
475            self.remove(hash);
476        }
477        self.metrics.expired.increment(expired.len() as u64);
478        expired.len()
479    }
480
481    // Removes the expired transactions at most once per `EXPIRY_INTERVAL`, so callers can run it on
482    // every announcement, and returns how many.
483    fn expire_if_due(&mut self, now: Instant) -> usize {
484        if now.duration_since(self.last_expiry) < EXPIRY_INTERVAL {
485            return 0
486        }
487        self.last_expiry = now;
488        self.expire(now)
489    }
490
491    // Yields the fetches eviction may drop: all but `keep`'s and those with every data column,
492    // which only wait for a check slot.
493    fn evictable(&self, keep: &B256) -> impl Iterator<Item = (&B256, &Pending<T>)> {
494        self.pending.iter().filter(move |(hash, pending)| {
495            *hash != keep && !pending.tx.is_ready(pending.role.target())
496        })
497    }
498
499    // Drops the earliest announced fetch, other than `keep`, of the peer holding the most bytes, so
500    // peers flooding bodies that never finish evict their own first. Returns whether one was
501    // dropped.
502    fn evict(&mut self, keep: &B256) -> bool {
503        let oldest = self
504            .evictable(keep)
505            .filter_map(|(hash, pending)| {
506                let held = self.bytes_by_peer.get(&pending.tx.sender()?).copied()?;
507                Some((*hash, held, pending.created))
508            })
509            .max_by_key(|&(_, held, created)| (held, Reverse(created)));
510        let Some((hash, ..)) = oldest else { return false };
511        self.remove(&hash);
512        self.metrics.evicted.increment(1);
513        true
514    }
515
516    // Stores the cells of a reply, keeping `peer` as a provider only if the reply brought columns
517    // it was asked for or the target still needs. A sample left without coverage is fetched in
518    // full, or dropped.
519    fn on_response(&mut self, hash: B256, peer: PeerId, id: u64, response: Option<Cells>) {
520        // A reply to a fetch that expired since only belongs to that fetch.
521        let Some(pending) = self.pending.get_mut(&hash) else { return };
522        let State::Requested(request, asked) = pending.state else { return };
523        if request != id {
524            return
525        }
526        pending.state = State::Idle;
527        // The session checked the reply against the request, so it only holds requested columns
528        // with whole cells per blob, which the body's bytes already cover. EIP-8070 lets a peer
529        // leave columns out under load, so a short reply has the rest requested.
530        let progressed = if let Some(Cells { cells, cell_mask, .. }) = response &&
531            let Some(cells) = cells.into_iter().next()
532        {
533            let mask = cell_mask.mask_at(0).map(BlobCellMask::new).unwrap_or_default();
534            let stored = pending.tx.cells(mask, cells).is_ok();
535            // A sample fetched in full drops cells asked before, to stay within the data columns.
536            if pending.role == Role::Provider {
537                pending.tx.retain(DATA_COLUMNS);
538            }
539            stored &&
540                (mask.intersection(asked).count() > 0 ||
541                    mask.intersection(pending.role.target()).count() > 0)
542        } else {
543            false
544        };
545        // A peer that sent none of the target columns it was asked for, nor any the target needs
546        // now, isn't asked again. The cells either sent are still checked with the rest.
547        if !progressed {
548            pending.providers.retain(|(provider, _)| *provider != peer);
549        }
550        if !pending.covers_target() && !pending.fetch_in_full(&self.metrics) {
551            self.remove(&hash);
552        }
553    }
554
555    // Starts checking the transactions whose body and data columns arrived.
556    fn queue_verifications(&mut self) -> bool {
557        let mut queued = false;
558        for (&hash, pending) in &mut self.pending {
559            if self.verifications.len() >= MAX_CONCURRENT_VERIFICATIONS {
560                break
561            }
562            if pending.state != State::Verifying && pending.tx.is_ready(pending.role.target()) {
563                let tx = std::mem::take(&mut pending.tx);
564                release(&mut self.bytes, &mut self.bytes_by_peer, &tx);
565                pending.state = State::Verifying;
566                queued = true;
567                self.verifications.push(Box::pin(verify(hash, tx, pending.role.keep())));
568            }
569        }
570        queued
571    }
572
573    // Requests missing columns of pending transactions from the peers that announced them.
574    //
575    // Returns whether a request was sent, and when the earliest sample still waiting for providers
576    // is due to be fetched in full.
577    fn send_requests<N: NetworkPrimitives>(
578        &mut self,
579        peers: &HashMap<PeerId, PeerMetadata<N>, FbBuildHasher<64>>,
580    ) -> (bool, Option<Instant>) {
581        let mut queued = false;
582        let mut sample_deadline: Option<Instant> = None;
583        let mut rng = rand::rng();
584        let now = Instant::now();
585        for (&hash, pending) in &mut self.pending {
586            if self.requests.len() >= MAX_INFLIGHT_REQUESTS {
587                break
588            }
589            // Fetching the data columns proves the blobs are available without those peers.
590            if matches!(pending.role, Role::Sampler { available: false, .. }) {
591                let deadline = pending.created + SAMPLE_AVAILABILITY_TIMEOUT;
592                if now >= deadline {
593                    pending.switch_to_full(&self.metrics);
594                } else {
595                    // Entries past the in-flight `break` are skipped: a request in flight completes
596                    // within `REQUEST_TIMEOUT` and wakes the task, which runs this loop again.
597                    sample_deadline =
598                        Some(sample_deadline.map_or(deadline, |due| due.min(deadline)));
599                }
600            }
601            // Cells are only requested once the body arrived, so a peer can't hold the fetcher
602            // with cells of bodies it never sends, and their bytes are already held for them.
603            if pending.state != State::Idle || pending.tx.blobs().is_none() {
604                continue
605            }
606            let sent = pending.candidates(&mut rng).find_map(|(peer, requested)| {
607                let inflight = self.requests_by_peer.get(&peer).copied().unwrap_or_default();
608                if inflight >= MAX_INFLIGHT_REQUESTS_PER_PEER {
609                    return None
610                }
611                let (tx, rx) = oneshot::channel();
612                let request = PeerRequest::GetCells {
613                    request: GetCells { hashes: vec![hash], cell_mask: requested.to_b128().into() },
614                    response: tx,
615                };
616                peers.get(&peer)?.request_tx.try_send(request).ok()?;
617                Some((peer, requested, rx))
618            });
619            let Some((peer, requested, rx)) = sent else { continue };
620            *self.requests_by_peer.entry(peer).or_default() += 1;
621            let id = self.next_request_id;
622            self.next_request_id += 1;
623            pending.state = State::Requested(id, requested.intersection(pending.role.target()));
624            queued = true;
625            self.requests.push(Box::pin(async move {
626                let response = tokio::time::timeout(REQUEST_TIMEOUT, rx)
627                    .await
628                    .ok()
629                    .and_then(Result::ok)
630                    .and_then(Result::ok);
631                (hash, peer, id, response)
632            }));
633        }
634        (queued, sample_deadline)
635    }
636}
637
638// Checks the cells of `tx` on a blocking thread.
639async fn verify<T: PoolTransaction + 'static>(
640    hash: B256,
641    tx: UnverifiedBlobTx<T>,
642    keep: BlobCellMask,
643) -> (B256, Option<(PeerId, T)>) {
644    let result = tokio::task::spawn_blocking(move || tx.verify(keep)).await.ok().flatten();
645    (hash, result)
646}
647
648// Decrements the count of `peer` by `by`, removing it at zero.
649fn decrement(counts: &mut HashMap<PeerId, usize>, peer: PeerId, by: usize) {
650    if let Entry::Occupied(mut entry) = counts.entry(peer) {
651        *entry.get_mut() -= by;
652        if *entry.get() == 0 {
653            entry.remove();
654        }
655    }
656}
657
658// Releases the bytes held for the body of `tx`, from the total and from its sender.
659fn release<T: PoolTransaction>(
660    bytes: &mut usize,
661    bytes_by_peer: &mut HashMap<PeerId, usize>,
662    tx: &UnverifiedBlobTx<T>,
663) {
664    *bytes -= tx.bytes();
665    if let Some(sender) = tx.sender() {
666        decrement(bytes_by_peer, sender, tx.bytes());
667    }
668}
669
670// A transaction whose cells are being fetched.
671#[derive(Debug)]
672struct Pending<T> {
673    // When it was first announced.
674    created: Instant,
675    // The peer whose slot it takes: the first announcer, or a provider it moved to.
676    added_by: PeerId,
677    // Peers that announced it, with the cells they announced.
678    providers: Vec<(PeerId, BlobCellMask)>,
679    // Whether it's fetched in full or sampled.
680    role: Role,
681    // Whether a request is in flight or its cells are being checked.
682    state: State,
683    // Its body and cells, taken out for the check.
684    tx: UnverifiedBlobTx<T>,
685    // Its body, if it arrived without room and has to be fetched again.
686    declined: Option<DeclinedBody>,
687}
688
689impl<T: PoolTransaction> Pending<T> {
690    fn new(added_by: PeerId, created: Instant, role: Role) -> Self {
691        Self {
692            created,
693            added_by,
694            providers: Vec::new(),
695            role,
696            state: State::Idle,
697            tx: UnverifiedBlobTx::default(),
698            declined: None,
699        }
700    }
701
702    // Returns whether it's been pending for longer than `PENDING_TTL`. A running check isn't
703    // expired, since its result removes the transaction by hash and could hit a newer fetch.
704    fn is_expired(&self, now: Instant) -> bool {
705        self.state != State::Verifying && now.duration_since(self.created) >= PENDING_TTL
706    }
707
708    // Yields the providers in order with the missing target columns each can send, or nothing
709    // until the providers cover the target.
710    fn candidates<'a>(
711        &'a self,
712        rng: &'a mut impl Rng,
713    ) -> impl Iterator<Item = (PeerId, BlobCellMask)> + 'a {
714        let missing = if self.covers_target() {
715            self.role.target().difference(self.tx.columns())
716        } else {
717            BlobCellMask::default()
718        };
719        self.providers.iter().filter_map(move |&(peer, announced)| {
720            let requested = missing.intersection(self.role.requestable(announced));
721            (requested.count() > 0)
722                .then(|| (peer, self.role.with_extra(requested, announced, self.tx.columns(), rng)))
723        })
724    }
725
726    // Turns a sample that can't finish into a full fetch if its data cells and providers cover
727    // the data columns, dropping its other cells. Returns whether it did.
728    fn fetch_in_full(&mut self, metrics: &BlobFetcherMetrics) -> bool {
729        if !matches!(self.role, Role::Sampler { .. }) || self.state == State::Verifying {
730            return false
731        }
732        let covered = self
733            .providers
734            .iter()
735            .fold(self.tx.columns_within(DATA_COLUMNS), |mask, (_, announced)| {
736                mask.union(*announced)
737            });
738        if !DATA_COLUMNS.is_subset_of(covered) {
739            return false
740        }
741        self.switch_to_full(metrics);
742        true
743    }
744
745    // Turns a sample into a full fetch, dropping its cells outside the data columns.
746    fn switch_to_full(&mut self, metrics: &BlobFetcherMetrics) {
747        self.role = Role::Provider;
748        self.tx.retain(DATA_COLUMNS);
749        metrics.samples_fetched_in_full.increment(1);
750    }
751
752    // Returns whether it's being checked, or its received columns and providers can still cover
753    // the target, which a complete fetch always does.
754    fn can_finish(&self) -> bool {
755        self.state == State::Verifying || self.covers_target()
756    }
757
758    // Returns whether the received columns and the providers cover the target. A sample first
759    // needs enough peers with every column, so samplers, which can hide the blobs, never start it.
760    fn covers_target(&self) -> bool {
761        let target = self.role.target();
762        if target.is_subset_of(self.tx.columns()) {
763            return true
764        }
765        if matches!(self.role, Role::Sampler { available: false, .. }) {
766            return false
767        }
768        let covered = self.providers.iter().fold(self.tx.columns(), |mask, (_, announced)| {
769            mask.union(self.role.requestable(*announced))
770        });
771        target.is_subset_of(covered)
772    }
773}
774
775// What a pending transaction is waiting on.
776#[derive(Debug, Clone, Copy, PartialEq, Eq)]
777enum State {
778    // Nothing: its cells can be requested.
779    Idle,
780    // The reply to the `GetCells` request with this id, for these target columns.
781    Requested(u64, BlobCellMask),
782    // The check of its cells.
783    Verifying,
784}
785
786// A body that arrived without room, to fetch again once it has.
787#[derive(Debug, Clone, Copy)]
788struct DeclinedBody {
789    // The bytes it's charged, with its data columns' cells.
790    bytes: usize,
791    // The provider it was last asked from again and the deadline for its reply, if any.
792    asked: Option<(PeerId, time::Instant)>,
793}
794
795impl DeclinedBody {
796    // Returns the provider and deadline if its reply is still expected at `now`.
797    fn asking(&self, now: time::Instant) -> Option<(PeerId, time::Instant)> {
798        self.asked.filter(|(_, deadline)| now < *deadline)
799    }
800
801    // Returns the `providers` in turn after the one last asked, so one that never sends the body
802    // is asked again only once the others were.
803    fn in_turn<'a>(
804        &self,
805        providers: &'a [(PeerId, BlobCellMask)],
806    ) -> impl Iterator<Item = PeerId> + use<'a> {
807        let start = self
808            .asked
809            .and_then(|(last, _)| providers.iter().position(|(id, _)| *id == last))
810            .map_or(0, |idx| idx + 1);
811        providers[start..].iter().chain(&providers[..start]).map(|(id, _)| *id)
812    }
813}
814
815/// Metrics of the eth/72 cell fetcher.
816#[derive(Metrics)]
817#[metrics(scope = "network.blob_fetcher")]
818struct BlobFetcherMetrics {
819    /// Transactions whose cells passed the check.
820    verified: Counter,
821    /// Transactions whose cells failed the check.
822    invalid: Counter,
823    /// Transactions dropped before their body and cells arrived.
824    expired: Counter,
825    /// Transactions whose body was dropped to make room for another.
826    evicted: Counter,
827    /// Transactions sampled rather than fetched in full.
828    sampled: Counter,
829    /// Samples fetched in full after too few peers announced every column in time, or after
830    /// losing the providers they needed.
831    samples_fetched_in_full: Counter,
832    /// Bodies fetched again after arriving without room.
833    refetched: Counter,
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839    use crate::test_utils::transactions::new_tx_manager;
840    use alloy_consensus::{Signed, TxEip4844, TxEip4844WithSidecar};
841    use alloy_primitives::Signature;
842    use futures::task::{noop_waker_ref, waker, ArcWake};
843    use reth_eth_wire::{
844        EthNetworkPrimitives, EthVersion, NewPooledTransactionHashes72, PooledTransactions,
845    };
846    use reth_ethereum_primitives::PooledTransactionVariant;
847    use reth_network_api::{PeerKind, PeerRequestSender};
848    use reth_network_p2p::error::RequestResult;
849    use reth_primitives_traits::SignerRecoverable;
850    use reth_transaction_pool::{
851        blobstore::BlobTransactionCellSidecar, test_utils::blob_tx_without_blobs,
852        validate::DEFAULT_MAX_TX_INPUT_BYTES, EthPooledTransaction,
853    };
854    use std::sync::Arc;
855    use tokio::sync::{mpsc, Notify};
856
857    type Peers = HashMap<PeerId, PeerMetadata<EthNetworkPrimitives>, FbBuildHasher<64>>;
858
859    fn peer(id: PeerId) -> (PeerMetadata<EthNetworkPrimitives>, mpsc::Receiver<PeerRequest>) {
860        let (tx, rx) = mpsc::channel(16);
861        let metadata = PeerMetadata::new(
862            PeerRequestSender::new(id, tx),
863            EthVersion::Eth72,
864            "test".into(),
865            100,
866            PeerKind::Basic,
867        );
868        (metadata, rx)
869    }
870
871    // Returns the next `GetCells` request sent to a peer.
872    fn next_request(
873        rx: &mut mpsc::Receiver<PeerRequest>,
874    ) -> (GetCells, oneshot::Sender<RequestResult<Cells>>) {
875        let Ok(PeerRequest::GetCells { request, response }) = rx.try_recv() else {
876            panic!("expected a GetCells request")
877        };
878        (request, response)
879    }
880
881    // Returns a reply with the cells of `hash` at the columns in `mask`.
882    fn reply(hash: B256, cells: &BlobTransactionCellSidecar, mask: BlobCellMask) -> Cells {
883        Cells {
884            hashes: vec![hash],
885            cells: vec![cells.matching_cells(mask).unwrap()],
886            cell_mask: mask.to_b128().into(),
887        }
888    }
889
890    async fn next_transactions(
891        fetcher: &mut BlobFetcher<EthPooledTransaction>,
892        peers: &Peers,
893    ) -> Vec<(PeerId, EthPooledTransaction)> {
894        tokio::time::timeout(
895            Duration::from_secs(10),
896            std::future::poll_fn(|cx| fetcher.poll(cx, peers)),
897        )
898        .await
899        .unwrap()
900    }
901
902    // Polls until the pending checks finish, expecting no transaction to pass.
903    async fn drain_checks(fetcher: &mut BlobFetcher<EthPooledTransaction>, peers: &Peers) {
904        tokio::time::timeout(Duration::from_secs(10), async {
905            while !fetcher.verifications.is_empty() {
906                assert!(std::future::poll_fn(|cx| Poll::Ready(fetcher.poll(cx, peers)))
907                    .await
908                    .is_pending());
909                tokio::task::yield_now().await;
910            }
911        })
912        .await
913        .unwrap();
914    }
915
916    // Checks that the byte, slot and request counts match the fetches they count.
917    fn assert_consistent(fetcher: &BlobFetcher<EthPooledTransaction>) {
918        let mut bytes_by_peer = HashMap::<PeerId, usize>::default();
919        for pending in fetcher.pending.values() {
920            if let Some(sender) = pending.tx.sender() {
921                *bytes_by_peer.entry(sender).or_default() += pending.tx.bytes();
922            }
923        }
924        assert_eq!(fetcher.bytes, bytes_by_peer.values().sum::<usize>());
925        assert_eq!(fetcher.bytes_by_peer, bytes_by_peer);
926        let mut added_by_peer = HashMap::<PeerId, usize>::default();
927        for pending in fetcher.pending.values() {
928            *added_by_peer.entry(pending.added_by).or_default() += 1;
929        }
930        assert_eq!(fetcher.added_by_peer, added_by_peer);
931        assert_eq!(fetcher.requests_by_peer.values().sum::<usize>(), fetcher.requests.len());
932    }
933
934    // Returns the role of a sample of `custody` with the extra column 0, before peers with every
935    // column were seen.
936    fn sample_role(custody: BlobCellMask) -> Role {
937        Role::Sampler { custody, extra: BlobCellMask::from_bits(1), available: false }
938    }
939
940    // Returns an eth/72 announcement of blob transactions with the cells in `mask`.
941    fn announcement(hashes: &[B256], mask: BlobCellMask) -> TransactionAnnouncement {
942        let msg = NewPooledTransactionHashes72 {
943            types: vec![EIP4844_TX_TYPE_ID; hashes.len()],
944            sizes: vec![1_000; hashes.len()],
945            hashes: hashes.to_vec(),
946            cell_mask: Some(mask.to_b128()),
947        };
948        TransactionAnnouncement::from_message(&msg.into(), &mut Default::default()).unwrap()
949    }
950
951    #[tokio::test]
952    async fn fetches_the_cells_needed_to_rebuild_the_blobs() {
953        let (tx, cells) = blob_tx_without_blobs(2);
954        let hash = *tx.hash();
955        let id = PeerId::random();
956        let (metadata, mut rx) = peer(id);
957        let peers = HashMap::from_iter([(id, metadata)]);
958        // A probability below the floor, which reth.toml doesn't check, is raised to it.
959        let mut fetcher = BlobFetcher::new(CellCustody::default(), 0);
960        assert_eq!(fetcher.fetch_probability, MIN_BLOB_FETCH_PROBABILITY);
961        let mut cx = Context::from_waker(noop_waker_ref());
962
963        // Without every data column the blobs need a slow recovery, so nothing is requested.
964        fetcher.announce(hash, id, BlobCellMask::from_bits(u128::MAX << 1));
965        assert!(fetcher.poll(&mut cx, &peers).is_pending());
966        assert!(rx.try_recv().is_err());
967
968        // Nor before the body arrives.
969        fetcher.announce(hash, id, BlobCellMask::ALL);
970        assert!(fetcher.poll(&mut cx, &peers).is_pending());
971        assert!(rx.try_recv().is_err());
972
973        assert!(fetcher.body(id, tx));
974        assert!(fetcher.poll(&mut cx, &peers).is_pending());
975        let (request, response) = next_request(&mut rx);
976        assert_eq!(request.cell_mask(0).unwrap(), DATA_COLUMNS);
977        response.send(Ok(reply(hash, &cells, DATA_COLUMNS))).unwrap();
978        let [(sender, tx)] = next_transactions(&mut fetcher, &peers).await.try_into().unwrap();
979        assert_eq!(sender, id);
980        assert_eq!(tx.blob_cell_availability().unwrap().get(), DATA_COLUMNS);
981        assert!(fetcher.pending.is_empty());
982    }
983
984    #[tokio::test]
985    async fn sample_waits_for_two_peers_with_every_column() {
986        let (tx, cells) = blob_tx_without_blobs(2);
987        let hash = *tx.hash();
988        let (sampler, first, second) = (PeerId::random(), PeerId::random(), PeerId::random());
989        let (sampler_metadata, mut sampler_rx) = peer(sampler);
990        let (first_metadata, mut first_rx) = peer(first);
991        let (second_metadata, _second_rx) = peer(second);
992        let peers = HashMap::from_iter([
993            (sampler, sampler_metadata),
994            (first, first_metadata),
995            (second, second_metadata),
996        ]);
997        let custody = BlobCellMask::from_bits(0b1111 << 70);
998        let role = sample_role(custody);
999        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1000        let mut cx = Context::from_waker(noop_waker_ref());
1001
1002        // Another sampler holding the target isn't enough to sample.
1003        fetcher.announce(hash, sampler, role.target());
1004        fetcher.pending.get_mut(&hash).unwrap().role = role;
1005        assert!(fetcher.body(sampler, tx));
1006        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1007        assert!(sampler_rx.try_recv().is_err());
1008
1009        // Nor is one peer with every column.
1010        fetcher.announce(hash, first, BlobCellMask::ALL);
1011        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1012        assert!(sampler_rx.try_recv().is_err());
1013
1014        // The sampler is only asked for the custody columns, and the extra one is asked from a
1015        // peer with every column. Once available, it stays a sample past the wait.
1016        fetcher.announce(hash, second, BlobCellMask::ALL);
1017        fetcher.pending.get_mut(&hash).unwrap().created -= SAMPLE_AVAILABILITY_TIMEOUT;
1018        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1019        let (request, response) = next_request(&mut sampler_rx);
1020        assert_eq!(request.cell_mask(0).unwrap(), custody);
1021        response.send(Ok(reply(hash, &cells, custody))).unwrap();
1022        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1023        let extra = role.target().difference(custody);
1024        let (request, response) = next_request(&mut first_rx);
1025        assert_eq!(request.cell_mask(0).unwrap(), extra);
1026        response.send(Ok(reply(hash, &cells, extra))).unwrap();
1027        let [(_, tx)] = next_transactions(&mut fetcher, &peers).await.try_into().unwrap();
1028        // The extra column was checked, but only the custody columns are kept and announced.
1029        assert_eq!(tx.blob_cell_availability().unwrap().get(), custody);
1030        assert!(fetcher.pending.is_empty());
1031    }
1032
1033    // Announces `hash` from `peer` with every column until the fetcher draws it as a sample, which
1034    // it does at least 85% of the time, so 64 draws fail with a probability of about 1e-53.
1035    fn announce_sample(fetcher: &mut BlobFetcher<EthPooledTransaction>, hash: B256, peer: PeerId) {
1036        for _ in 0..64 {
1037            fetcher.announce(hash, peer, BlobCellMask::ALL);
1038            if matches!(fetcher.pending[&hash].role, Role::Sampler { .. }) {
1039                return
1040            }
1041            fetcher.remove(&hash);
1042        }
1043        panic!("not drawn as a sample")
1044    }
1045
1046    #[tokio::test]
1047    async fn sample_from_the_custody_handle_asks_for_one_extra_column() {
1048        let (tx, cells) = blob_tx_without_blobs(2);
1049        let hash = *tx.hash();
1050        let (first, second) = (PeerId::random(), PeerId::random());
1051        let (first_metadata, mut first_rx) = peer(first);
1052        let (second_metadata, _second_rx) = peer(second);
1053        let peers = HashMap::from_iter([(first, first_metadata), (second, second_metadata)]);
1054        let custody = BlobCellMask::from_bits(0b1111 << 70);
1055        let handle = CellCustody::default();
1056        handle.set(custody);
1057        let mut fetcher = BlobFetcher::new(handle, MIN_BLOB_FETCH_PROBABILITY);
1058        let mut cx = Context::from_waker(noop_waker_ref());
1059        announce_sample(&mut fetcher, hash, first);
1060        fetcher.announce(hash, second, BlobCellMask::ALL);
1061        let Role::Sampler { custody: sampled, extra, available: true } =
1062            fetcher.pending[&hash].role
1063        else {
1064            panic!("expected an available sample")
1065        };
1066        assert_eq!(sampled, custody);
1067        assert_eq!(extra.count(), 1);
1068        assert_eq!(extra.intersection(custody).count(), 0);
1069
1070        // The extra column drawn with the role is asked together with the custody columns.
1071        assert!(fetcher.body(first, tx));
1072        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1073        let (request, response) = next_request(&mut first_rx);
1074        assert_eq!(request.cell_mask(0).unwrap(), custody.union(extra));
1075
1076        // A short reply leaves custody columns missing, which a peer with every column is asked
1077        // for with another extra column, outside the custody and the columns held.
1078        let held = custody.first(1).union(extra);
1079        response.send(Ok(reply(hash, &cells, held))).unwrap();
1080        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1081        let (request, _) = next_request(&mut first_rx);
1082        let requested = request.cell_mask(0).unwrap();
1083        let missing = custody.difference(held);
1084        assert!(missing.is_subset_of(requested));
1085        let added = requested.difference(missing);
1086        assert_eq!(added.count(), 1);
1087        assert_eq!(added.intersection(custody.union(held)).count(), 0);
1088    }
1089
1090    #[tokio::test]
1091    async fn sample_that_loses_its_coverage_is_fetched_in_full() {
1092        let (tx, _) = blob_tx_without_blobs(2);
1093        let hash = *tx.hash();
1094        let (full, low) = (PeerId::random(), PeerId::random());
1095        let (full_metadata, mut full_rx) = peer(full);
1096        let (low_metadata, mut low_rx) = peer(low);
1097        let peers = HashMap::from_iter([(full, full_metadata), (low, low_metadata)]);
1098        let handle = CellCustody::default();
1099        handle.set(BlobCellMask::from_bits(0b1111 << 70));
1100        let mut fetcher = BlobFetcher::new(handle, MIN_BLOB_FETCH_PROBABILITY);
1101        let mut cx = Context::from_waker(noop_waker_ref());
1102        announce_sample(&mut fetcher, hash, full);
1103        fetcher.announce(hash, low, BlobCellMask::ALL);
1104        // Once available, the sample stays so when `low` narrows its announcement to the data
1105        // columns, which can't serve the custody columns but cover the data columns on their own.
1106        fetcher.announce(hash, low, DATA_COLUMNS);
1107        assert!(matches!(fetcher.pending[&hash].role, Role::Sampler { available: true, .. }));
1108        assert!(fetcher.body(full, tx));
1109        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1110        let (request, response) = next_request(&mut full_rx);
1111        assert_eq!(request.cell_mask(0).unwrap(), fetcher.pending[&hash].role.target());
1112
1113        // Without a reply from `full`, only `low` is left, and the sample isn't dropped.
1114        response.send(Ok(Cells { cell_mask: request.cell_mask, ..Default::default() })).unwrap();
1115        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1116        assert!(fetcher.pending.contains_key(&hash));
1117        assert_eq!(fetcher.pending[&hash].role, Role::Provider);
1118        assert_eq!(fetcher.pending[&hash].providers, [(low, DATA_COLUMNS)]);
1119        let (request, _) = next_request(&mut low_rx);
1120        assert_eq!(request.cell_mask(0).unwrap(), DATA_COLUMNS);
1121    }
1122
1123    #[tokio::test]
1124    async fn sample_without_two_peers_with_every_column_is_fetched_in_full() {
1125        let (tx, _) = blob_tx_without_blobs(1);
1126        let hash = *tx.hash();
1127        let id = PeerId::random();
1128        let (metadata, mut rx) = peer(id);
1129        let peers = HashMap::from_iter([(id, metadata)]);
1130        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1131        let mut cx = Context::from_waker(noop_waker_ref());
1132        fetcher.announce(hash, id, BlobCellMask::ALL);
1133        fetcher.pending.get_mut(&hash).unwrap().role =
1134            sample_role(BlobCellMask::from_bits(0b1111 << 70));
1135        assert!(fetcher.body(id, tx));
1136        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1137        assert!(rx.try_recv().is_err());
1138
1139        // Past the wait, the only peer with every column is asked for the data columns.
1140        fetcher.pending.get_mut(&hash).unwrap().created -= SAMPLE_AVAILABILITY_TIMEOUT;
1141        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1142        let (request, _) = next_request(&mut rx);
1143        assert_eq!(request.cell_mask(0).unwrap(), DATA_COLUMNS);
1144
1145        // So is an available sample whose peers with every column leave, if the others hold the
1146        // data columns, dropping its custody cells. Without them it's dropped.
1147        let custody = BlobCellMask::from_bits(0b1111 << 70);
1148        let low = BlobCellMask::ALL.first(32);
1149        let (full, low_peer, high_peer) = (PeerId::random(), PeerId::random(), PeerId::random());
1150        for high in [None, Some(DATA_COLUMNS.difference(low))] {
1151            let (tx, cells) = blob_tx_without_blobs(2);
1152            let hash = *tx.hash();
1153            fetcher.announce(hash, low_peer, low);
1154            if let Some(high) = high {
1155                fetcher.announce(hash, high_peer, high);
1156            }
1157            fetcher.announce(hash, full, BlobCellMask::ALL);
1158            let pending = fetcher.pending.get_mut(&hash).unwrap();
1159            pending.role =
1160                Role::Sampler { custody, extra: BlobCellMask::from_bits(1), available: true };
1161            assert!(fetcher.body(low_peer, tx));
1162            fetcher.pending.get_mut(&hash).unwrap().state = State::Requested(1, custody);
1163            fetcher.on_response(hash, full, 1, Some(reply(hash, &cells, custody)));
1164            fetcher.drop_peer(&full);
1165            let Some(high) = high else {
1166                assert!(!fetcher.pending.contains_key(&hash));
1167                continue
1168            };
1169            let pending = &fetcher.pending[&hash];
1170            assert_eq!(pending.role, Role::Provider);
1171            assert_eq!(pending.tx.columns(), BlobCellMask::default());
1172            let candidates = pending.candidates(&mut rand::rng()).collect::<Vec<_>>();
1173            assert_eq!(candidates, [(low_peer, low), (high_peer, high)]);
1174        }
1175
1176        // A reply in flight when its sample switches keeps its peer's place if it holds custody
1177        // cells, or only a data column added as the request's extra one.
1178        for (blobs, sent) in [(3, custody), (4, BlobCellMask::from_bits(1 << 5))] {
1179            let (tx, cells) = blob_tx_without_blobs(blobs);
1180            let hash = *tx.hash();
1181            let holder = PeerId::random();
1182            fetcher.announce(hash, holder, custody.union(DATA_COLUMNS));
1183            fetcher.announce(hash, full, BlobCellMask::ALL);
1184            fetcher.pending.get_mut(&hash).unwrap().role =
1185                Role::Sampler { custody, extra: BlobCellMask::from_bits(1), available: true };
1186            assert!(fetcher.body(holder, tx));
1187            fetcher.pending.get_mut(&hash).unwrap().state = State::Requested(2, custody);
1188            fetcher.drop_peer(&full);
1189            assert_eq!(fetcher.pending[&hash].role, Role::Provider);
1190            fetcher.on_response(hash, holder, 2, Some(reply(hash, &cells, sent)));
1191            assert_eq!(fetcher.pending[&hash].providers, [(holder, custody.union(DATA_COLUMNS))]);
1192        }
1193    }
1194
1195    #[tokio::test]
1196    async fn waiting_sample_wakes_the_task_when_it_is_due() {
1197        struct Wake(Notify);
1198
1199        impl ArcWake for Wake {
1200            fn wake_by_ref(wake: &Arc<Self>) {
1201                wake.0.notify_one();
1202            }
1203        }
1204
1205        let (tx, _) = blob_tx_without_blobs(1);
1206        let hash = *tx.hash();
1207        let id = PeerId::random();
1208        let (metadata, mut rx) = peer(id);
1209        let peers = HashMap::from_iter([(id, metadata)]);
1210        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1211        let woken = Arc::new(Wake(Notify::new()));
1212        let waker = waker(woken.clone());
1213        let mut cx = Context::from_waker(&waker);
1214        fetcher.announce(hash, id, BlobCellMask::ALL);
1215        let pending = fetcher.pending.get_mut(&hash).unwrap();
1216        pending.role = sample_role(BlobCellMask::from_bits(0b1111 << 70));
1217        pending.created -= SAMPLE_AVAILABILITY_TIMEOUT - Duration::from_millis(50);
1218        assert!(fetcher.body(id, tx));
1219
1220        // The sample isn't due yet, and nothing else wakes the task.
1221        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1222        assert!(matches!(fetcher.pending[&hash].role, Role::Sampler { available: false, .. }));
1223        assert!(rx.try_recv().is_err());
1224
1225        tokio::time::timeout(Duration::from_secs(1), woken.0.notified()).await.unwrap();
1226        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1227        assert_eq!(fetcher.pending[&hash].role, Role::Provider);
1228        let (request, _) = next_request(&mut rx);
1229        assert_eq!(request.cell_mask(0).unwrap(), DATA_COLUMNS);
1230    }
1231
1232    #[tokio::test]
1233    async fn empty_reply_without_another_provider_drops_the_transaction() {
1234        let (tx, _) = blob_tx_without_blobs(1);
1235        let hash = *tx.hash();
1236        let id = PeerId::random();
1237        let (metadata, mut rx) = peer(id);
1238        let peers = HashMap::from_iter([(id, metadata)]);
1239        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1240        fetcher.announce(hash, id, BlobCellMask::ALL);
1241        assert!(fetcher.body(id, tx));
1242        let mut cx = Context::from_waker(noop_waker_ref());
1243        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1244        let (request, response) = next_request(&mut rx);
1245        response.send(Ok(Cells { cell_mask: request.cell_mask, ..Default::default() })).unwrap();
1246        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1247        assert!(fetcher.pending.is_empty());
1248        assert!(rx.try_recv().is_err());
1249    }
1250
1251    #[test]
1252    fn reply_with_only_an_extra_column_loses_its_place() {
1253        let (tx, cells) = blob_tx_without_blobs(1);
1254        let hash = *tx.hash();
1255        let (first, second) = (PeerId::random(), PeerId::random());
1256        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1257        let role = sample_role(BlobCellMask::from_bits(0b11 << 70));
1258        fetcher.announce(hash, first, BlobCellMask::ALL);
1259        fetcher.pending.get_mut(&hash).unwrap().role = role;
1260        fetcher.announce(hash, second, BlobCellMask::ALL);
1261        assert!(fetcher.body(first, tx));
1262        // A retry's extra column alone brings nothing missing, so the other provider is asked next.
1263        fetcher.pending.get_mut(&hash).unwrap().state = State::Requested(0, role.target());
1264        fetcher.on_response(
1265            hash,
1266            first,
1267            0,
1268            Some(reply(hash, &cells, BlobCellMask::from_bits(1 << 2))),
1269        );
1270        assert_eq!(fetcher.pending[&hash].providers, [(second, BlobCellMask::ALL)]);
1271    }
1272
1273    #[tokio::test]
1274    async fn empty_reply_falls_back_to_another_peer() {
1275        let (tx, cells) = blob_tx_without_blobs(1);
1276        let hash = *tx.hash();
1277        let (first, second) = (PeerId::random(), PeerId::random());
1278        let (p1, mut rx1) = peer(first);
1279        let (p2, mut rx2) = peer(second);
1280        let peers = HashMap::from_iter([(first, p1), (second, p2)]);
1281        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1282        fetcher.announce(hash, first, BlobCellMask::ALL);
1283        fetcher.announce(hash, second, BlobCellMask::ALL);
1284        assert!(fetcher.body(first, tx));
1285        let mut cx = Context::from_waker(noop_waker_ref());
1286        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1287        let (request, response) = next_request(&mut rx1);
1288        response.send(Ok(Cells { cell_mask: request.cell_mask, ..Default::default() })).unwrap();
1289        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1290        let (request, response) = next_request(&mut rx2);
1291        response.send(Ok(reply(hash, &cells, request.cell_mask(0).unwrap()))).unwrap();
1292        let [(_, tx)] = next_transactions(&mut fetcher, &peers).await.try_into().unwrap();
1293        assert_eq!(tx.blob_cell_availability().unwrap().get(), DATA_COLUMNS);
1294    }
1295
1296    #[tokio::test]
1297    async fn short_reply_requests_the_rest() {
1298        let (tx, cells) = blob_tx_without_blobs(1);
1299        let hash = *tx.hash();
1300        let (id, other) = (PeerId::random(), PeerId::random());
1301        let (metadata, mut rx) = peer(id);
1302        let (other_metadata, mut other_rx) = peer(other);
1303        let peers = HashMap::from_iter([(id, metadata), (other, other_metadata)]);
1304        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1305        fetcher.announce(hash, id, BlobCellMask::ALL);
1306        fetcher.announce(hash, other, BlobCellMask::ALL);
1307        assert!(fetcher.body(id, tx));
1308        let mut cx = Context::from_waker(noop_waker_ref());
1309        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1310        let (_, response) = next_request(&mut rx);
1311        let sent = BlobCellMask::from_bits(1);
1312        response.send(Ok(reply(hash, &cells, sent))).unwrap();
1313        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1314        let (request, response) = next_request(&mut rx);
1315        let rest = request.cell_mask(0).unwrap();
1316        assert_eq!(rest, DATA_COLUMNS.difference(sent));
1317        // The peer that made progress is asked for the rest, not another provider.
1318        assert!(other_rx.try_recv().is_err());
1319        response.send(Ok(reply(hash, &cells, rest))).unwrap();
1320        let [(_, tx)] = next_transactions(&mut fetcher, &peers).await.try_into().unwrap();
1321        assert_eq!(tx.blob_cell_availability().unwrap().get(), DATA_COLUMNS);
1322    }
1323
1324    #[tokio::test]
1325    async fn invalid_cells_drop_the_transaction() {
1326        let (tx, cells) = blob_tx_without_blobs(1);
1327        let hash = *tx.hash();
1328        let id = PeerId::random();
1329        let (metadata, mut rx) = peer(id);
1330        let peers = HashMap::from_iter([(id, metadata)]);
1331        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1332        fetcher.announce(hash, id, BlobCellMask::ALL);
1333        assert!(fetcher.body(id, tx));
1334        let mut cx = Context::from_waker(noop_waker_ref());
1335        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1336        let (request, response) = next_request(&mut rx);
1337        let mut corrupted = reply(hash, &cells, request.cell_mask(0).unwrap());
1338        corrupted.cells[0][0][31] ^= 1;
1339        response.send(Ok(corrupted)).unwrap();
1340        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1341        drain_checks(&mut fetcher, &peers).await;
1342        assert!(fetcher.pending.is_empty());
1343        assert!(rx.try_recv().is_err());
1344    }
1345
1346    #[tokio::test]
1347    async fn checks_that_finish_together_are_returned_together() {
1348        let txs = [blob_tx_without_blobs(1).0, blob_tx_without_blobs(2).0];
1349        let id = PeerId::random();
1350        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1351        fetcher.verifications.push(Box::pin(async move { (B256::ZERO, None) }));
1352        for tx in txs {
1353            fetcher.verifications.push(Box::pin(async move { (*tx.hash(), Some((id, tx))) }));
1354        }
1355        let verified = next_transactions(&mut fetcher, &Peers::default()).await;
1356        assert_eq!(verified.len(), 2);
1357    }
1358
1359    #[test]
1360    fn oversized_body_stops_the_fetch() {
1361        let (_, cells) = blob_tx_without_blobs(1);
1362        let tx = TxEip4844 {
1363            blob_versioned_hashes: cells.versioned_hashes().collect(),
1364            input: vec![0; DEFAULT_MAX_TX_INPUT_BYTES + 1].into(),
1365            ..Default::default()
1366        };
1367        let tx = Signed::new_unhashed(
1368            TxEip4844WithSidecar { tx, sidecar: cells.without_blobs().into() },
1369            Signature::test_signature(),
1370        );
1371        let pooled = PooledTransactionVariant::Eip4844(tx).try_into_recovered().unwrap();
1372        let tx = EthPooledTransaction::from_pooled(pooled);
1373        let id = PeerId::random();
1374        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1375        fetcher.announce(*tx.hash(), id, BlobCellMask::ALL);
1376        // The body isn't malformed, so its peer isn't reported.
1377        assert!(fetcher.body(id, tx.clone()));
1378        assert!(!fetcher.pending.contains_key(tx.hash()));
1379    }
1380
1381    #[test]
1382    fn body_that_does_not_fit_is_fetched_again() {
1383        let (tx, _) = blob_tx_without_blobs(1);
1384        let (id, hash) = (PeerId::random(), *tx.hash());
1385        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1386        // A body that doesn't fit with nothing else to evict isn't reported, and waits for room.
1387        let mut announcement = announcement(&[hash], BlobCellMask::ALL);
1388        fetcher.on_announcement(id, &mut announcement);
1389        fetcher.bytes = MAX_BUFFERED_BYTES;
1390        assert!(fetcher.body(id, tx.clone()));
1391        assert_eq!(fetcher.pending[&hash].tx.bytes(), 0);
1392        assert_eq!(fetcher.bytes, MAX_BUFFERED_BYTES);
1393        assert!(fetcher.refetches(time::Instant::now()).is_empty());
1394
1395        // Once there's room it's asked again without its announced size, only once until it
1396        // arrives.
1397        fetcher.bytes = 0;
1398        assert_eq!(
1399            fetcher.refetches(time::Instant::now()),
1400            [(id, AnnouncedTransaction { hash, metadata: None })]
1401        );
1402        assert!(fetcher.refetches(time::Instant::now()).is_empty());
1403        assert!(fetcher.body(id, tx));
1404        assert!(fetcher.pending[&hash].tx.bytes() > 0);
1405        assert_consistent(&fetcher);
1406    }
1407
1408    #[test]
1409    fn body_past_its_senders_share_is_asked_from_another_provider() {
1410        let (tx, _) = blob_tx_without_blobs(1);
1411        let (id, hash) = (PeerId::random(), *tx.hash());
1412        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1413        // A body past its sender's share waits for a provider with room.
1414        fetcher.bytes_by_peer.insert(id, MAX_BUFFERED_BYTES_PER_PEER);
1415        fetcher.announce(hash, id, BlobCellMask::ALL);
1416        assert!(fetcher.body(id, tx.clone()));
1417        assert_eq!(fetcher.pending[&hash].tx.bytes(), 0);
1418        assert!(fetcher.refetches(time::Instant::now()).is_empty());
1419        let other = PeerId::random();
1420        fetcher.announce(hash, other, BlobCellMask::ALL);
1421        assert_eq!(
1422            fetcher.refetches(time::Instant::now()),
1423            [(other, AnnouncedTransaction { hash, metadata: None })]
1424        );
1425        assert!(fetcher.body(other, tx));
1426        assert_eq!(fetcher.bytes_by_peer[&other], fetcher.pending[&hash].tx.bytes());
1427    }
1428
1429    #[test]
1430    fn body_not_sent_again_is_asked_from_the_next_provider() {
1431        let (tx, _) = blob_tx_without_blobs(1);
1432        let hash = *tx.hash();
1433        let (first, second) = (PeerId::random(), PeerId::random());
1434        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1435        fetcher.announce(hash, first, BlobCellMask::ALL);
1436        fetcher.announce(hash, second, BlobCellMask::ALL);
1437        fetcher.bytes = MAX_BUFFERED_BYTES;
1438        assert!(fetcher.body(first, tx));
1439        fetcher.bytes = 0;
1440
1441        // A provider that doesn't send the body holds it until the timeout, then the providers
1442        // are asked in turn.
1443        let refetch = |peer| [(peer, AnnouncedTransaction { hash, metadata: None })];
1444        let now = time::Instant::now();
1445        assert_eq!(fetcher.refetches(now), refetch(first));
1446        let timeout = now + REFETCH_TIMEOUT;
1447        assert!(fetcher.refetches(timeout - Duration::from_millis(1)).is_empty());
1448        assert_eq!(fetcher.refetches(timeout), refetch(second));
1449        assert_eq!(fetcher.refetches(timeout + REFETCH_TIMEOUT), refetch(first));
1450    }
1451
1452    #[tokio::test(start_paused = true)]
1453    async fn refetch_deadline_wakes_idle_transaction_manager() {
1454        let (mut manager, _network) = new_tx_manager().await;
1455        let (first, second) = (PeerId::repeat_byte(1), PeerId::repeat_byte(2));
1456        let (first_peer, mut first_requests) = peer(first);
1457        let (second_peer, mut second_requests) = peer(second);
1458        manager.peers.insert(first, first_peer);
1459        manager.peers.insert(second, second_peer);
1460
1461        let hash = B256::repeat_byte(1);
1462        assert!(manager.blob_fetcher.announce(hash, first, BlobCellMask::ALL));
1463        assert!(manager.blob_fetcher.announce(hash, second, BlobCellMask::ALL));
1464        manager.blob_fetcher.pending.get_mut(&hash).unwrap().declined =
1465            Some(DeclinedBody { bytes: 1, asked: None });
1466
1467        let task = tokio::spawn(manager);
1468        let first_request = tokio::time::timeout(REFETCH_TIMEOUT, first_requests.recv())
1469            .await
1470            .expect("first provider should be asked immediately");
1471        let Some(PeerRequest::GetPooledTransactions { request, response }) = first_request else {
1472            panic!("expected a body request for the first provider");
1473        };
1474        assert_eq!(request.0, [hash]);
1475        response.send(Ok(PooledTransactions(Vec::new()))).unwrap();
1476
1477        // The empty reply completes the request before the refetch deadline. With no other
1478        // activity, only the deadline can wake the manager to ask the second provider.
1479        let second_request =
1480            tokio::time::timeout(REFETCH_TIMEOUT + Duration::from_secs(1), second_requests.recv())
1481                .await
1482                .expect("refetch deadline should wake the manager");
1483        let Some(PeerRequest::GetPooledTransactions { request, .. }) = second_request else {
1484            panic!("expected a body request for the second provider");
1485        };
1486        assert_eq!(request.0, [hash]);
1487        task.abort();
1488    }
1489
1490    #[test]
1491    fn full_buffer_evicts_the_largest_holder() {
1492        // A full buffer evicts a body of the peer holding the most to make room.
1493        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1494        let id = PeerId::random();
1495        let [(largest, _), (smaller, _), (new, _)] = [3, 1, 2].map(blob_tx_without_blobs);
1496        let sizes = [&largest, &smaller].map(|tx| {
1497            let id = PeerId::random();
1498            fetcher.announce(*tx.hash(), id, BlobCellMask::ALL);
1499            assert!(fetcher.body(id, tx.clone()));
1500            fetcher.pending[tx.hash()].tx.bytes()
1501        });
1502        let new_size = UnverifiedBlobTx::default().body(id, new.clone(), usize::MAX).unwrap();
1503        let others = MAX_BUFFERED_BYTES - sizes.iter().sum::<usize>() - new_size + 1;
1504        fetcher.bytes += others;
1505        fetcher.announce(*new.hash(), id, BlobCellMask::ALL);
1506        assert!(fetcher.body(id, new.clone()));
1507        assert!(!fetcher.pending.contains_key(largest.hash()));
1508        assert!(
1509            fetcher.pending.contains_key(smaller.hash()) &&
1510                fetcher.pending.contains_key(new.hash())
1511        );
1512        fetcher.bytes -= others;
1513        assert_consistent(&fetcher);
1514    }
1515
1516    #[test]
1517    fn eviction_keeps_assembled_transactions() {
1518        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1519        let (holder, other) = (PeerId::random(), PeerId::random());
1520        let [(ready, cells), (incomplete, _), (new, _)] = [3, 2, 1].map(blob_tx_without_blobs);
1521        for tx in [&ready, &incomplete] {
1522            fetcher.announce(*tx.hash(), holder, BlobCellMask::ALL);
1523            assert!(fetcher.body(holder, tx.clone()));
1524        }
1525        // The older fetch has every data column and only waits for a check slot.
1526        let hash = *ready.hash();
1527        let pending = fetcher.pending.get_mut(&hash).unwrap();
1528        pending.created -= Duration::from_secs(1);
1529        pending.state = State::Requested(0, DATA_COLUMNS);
1530        fetcher.on_response(hash, holder, 0, Some(reply(hash, &cells, DATA_COLUMNS)));
1531        let new_size = UnverifiedBlobTx::default().body(other, new.clone(), usize::MAX).unwrap();
1532        let others = MAX_BUFFERED_BYTES - fetcher.bytes - new_size + 1;
1533        fetcher.bytes += others;
1534        fetcher.announce(*new.hash(), other, BlobCellMask::ALL);
1535        assert!(fetcher.body(other, new.clone()));
1536        assert!(fetcher.pending.contains_key(&hash) && fetcher.pending.contains_key(new.hash()));
1537        assert!(!fetcher.pending.contains_key(incomplete.hash()));
1538        fetcher.bytes -= others;
1539        assert_consistent(&fetcher);
1540    }
1541
1542    #[test]
1543    fn body_that_cannot_fit_evicts_nothing() {
1544        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1545        let (holder, other) = (PeerId::random(), PeerId::random());
1546        let [(incomplete, _), (new, _)] = [2, 1].map(blob_tx_without_blobs);
1547        fetcher.announce(*incomplete.hash(), holder, BlobCellMask::ALL);
1548        assert!(fetcher.body(holder, incomplete.clone()));
1549        // The bytes stand for assembled fetches, which eviction keeps, so no eviction makes room.
1550        let new_size = UnverifiedBlobTx::default().body(other, new.clone(), usize::MAX).unwrap();
1551        let others = MAX_BUFFERED_BYTES - new_size + 1;
1552        fetcher.bytes += others;
1553        fetcher.announce(*new.hash(), other, BlobCellMask::ALL);
1554        assert!(fetcher.body(other, new.clone()));
1555        assert!(fetcher.pending.contains_key(incomplete.hash()));
1556        assert_eq!(fetcher.pending[new.hash()].tx.bytes(), 0);
1557        assert!(fetcher.pending[new.hash()].declined.is_some());
1558        fetcher.bytes -= others;
1559        assert_consistent(&fetcher);
1560    }
1561
1562    #[tokio::test]
1563    async fn stale_reply_does_not_advance_a_newer_fetch() {
1564        let (tx, cells) = blob_tx_without_blobs(1);
1565        let hash = *tx.hash();
1566        let id = PeerId::random();
1567        let (metadata, mut rx) = peer(id);
1568        let peers = HashMap::from_iter([(id, metadata)]);
1569        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1570        fetcher.announce(hash, id, BlobCellMask::ALL);
1571        assert!(fetcher.body(id, tx.clone()));
1572        let mut cx = Context::from_waker(noop_waker_ref());
1573        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1574        let (_, stale) = next_request(&mut rx);
1575
1576        // The fetch expires and a new one for the same hash sends its own request.
1577        fetcher.expire(Instant::now() + PENDING_TTL);
1578        fetcher.announce(hash, id, BlobCellMask::ALL);
1579        assert!(fetcher.body(id, tx));
1580        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1581        let (_, current) = next_request(&mut rx);
1582
1583        // The reply to the expired fetch's request is ignored.
1584        stale.send(Ok(reply(hash, &cells, DATA_COLUMNS))).unwrap();
1585        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1586        assert!(matches!(fetcher.pending[&hash].state, State::Requested(..)));
1587        current.send(Ok(reply(hash, &cells, DATA_COLUMNS))).unwrap();
1588        assert_eq!(next_transactions(&mut fetcher, &peers).await.len(), 1);
1589    }
1590
1591    #[test]
1592    fn expiry_drops_bodies_and_cells() {
1593        let (tx, _) = blob_tx_without_blobs(1);
1594        let id = PeerId::random();
1595        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1596        fetcher.announce(*tx.hash(), id, BlobCellMask::ALL);
1597        assert!(fetcher.body(id, tx));
1598        let now = Instant::now();
1599        assert_eq!(fetcher.expire(now), 0);
1600        assert_eq!(fetcher.expire(now + PENDING_TTL), 1);
1601        assert!(fetcher.pending.is_empty());
1602    }
1603
1604    #[test]
1605    fn expired_fetches_make_room_for_new_announcements() {
1606        let mut fetcher = BlobFetcher::<EthPooledTransaction>::new(
1607            CellCustody::default(),
1608            MIN_BLOB_FETCH_PROBABILITY,
1609        );
1610        for _ in 0..MAX_PENDING_TRANSACTIONS {
1611            fetcher.announce(B256::random(), PeerId::random(), BlobCellMask::ALL);
1612        }
1613        for pending in fetcher.pending.values_mut() {
1614            pending.created -= PENDING_TTL;
1615        }
1616        let hash = B256::random();
1617        // A sweep within the interval of the last one is skipped, so the fetcher stays full.
1618        fetcher.last_expiry = Instant::now();
1619        fetcher.announce(hash, PeerId::random(), BlobCellMask::ALL);
1620        assert!(!fetcher.pending.contains_key(&hash));
1621        assert_eq!(fetcher.pending.len(), MAX_PENDING_TRANSACTIONS);
1622        fetcher.last_expiry -= EXPIRY_INTERVAL;
1623        fetcher.announce(hash, PeerId::random(), BlobCellMask::ALL);
1624        assert_eq!(fetcher.pending.keys().collect::<Vec<_>>(), [&hash]);
1625    }
1626
1627    #[test]
1628    fn full_provider_list_keeps_the_most_data_columns() {
1629        let hash = B256::random();
1630        let mut fetcher = BlobFetcher::<EthPooledTransaction>::new(
1631            CellCustody::default(),
1632            MIN_BLOB_FETCH_PROBABILITY,
1633        );
1634        for column in 0..MAX_PROVIDERS_PER_TRANSACTION {
1635            fetcher.announce(hash, PeerId::random(), BlobCellMask::from_bits(1 << column));
1636        }
1637        // A peer with no more data columns than the weakest provider isn't kept.
1638        let partial = PeerId::random();
1639        fetcher.announce(hash, partial, BlobCellMask::from_bits(1));
1640        // A peer with every data column replaces one with a single column.
1641        let full = PeerId::random();
1642        fetcher.announce(hash, full, BlobCellMask::ALL);
1643        let providers = &fetcher.pending[&hash].providers;
1644        assert_eq!(providers.len(), MAX_PROVIDERS_PER_TRANSACTION);
1645        assert!(providers.iter().any(|(id, _)| *id == full));
1646        assert!(providers.iter().all(|(id, _)| *id != partial));
1647
1648        // A sample ranks peers by the columns they can be asked for, so peers announcing only its
1649        // extra column make room for one with a custody column.
1650        let (sample, custody) = (B256::random(), BlobCellMask::from_bits(0b1111 << 70));
1651        fetcher.announce(sample, PeerId::random(), BlobCellMask::from_bits(1));
1652        fetcher.pending.get_mut(&sample).unwrap().role = sample_role(custody);
1653        for _ in 1..MAX_PROVIDERS_PER_TRANSACTION {
1654            fetcher.announce(sample, PeerId::random(), BlobCellMask::from_bits(1));
1655        }
1656        let custodian = PeerId::random();
1657        fetcher.announce(sample, custodian, custody.first(1));
1658        assert!(fetcher.pending[&sample].providers.iter().any(|(id, _)| *id == custodian));
1659    }
1660
1661    #[test]
1662    fn pending_transactions_are_bounded() {
1663        let mut fetcher = BlobFetcher::<EthPooledTransaction>::new(
1664            CellCustody::default(),
1665            MIN_BLOB_FETCH_PROBABILITY,
1666        );
1667        for _ in 0..=MAX_PENDING_TRANSACTIONS {
1668            fetcher.announce(B256::random(), PeerId::random(), BlobCellMask::ALL);
1669        }
1670        assert_eq!(fetcher.pending.len(), MAX_PENDING_TRANSACTIONS);
1671        // A removed transaction frees a slot.
1672        let hash = *fetcher.pending.keys().next().unwrap();
1673        fetcher.remove(&hash);
1674        fetcher.announce(B256::random(), PeerId::random(), BlobCellMask::ALL);
1675        assert_eq!(fetcher.pending.len(), MAX_PENDING_TRANSACTIONS);
1676    }
1677
1678    #[test]
1679    fn a_peer_adds_a_bounded_number_of_transactions() {
1680        let mut fetcher = BlobFetcher::<EthPooledTransaction>::new(
1681            CellCustody::default(),
1682            MIN_BLOB_FETCH_PROBABILITY,
1683        );
1684        let (first, second) = (PeerId::random(), PeerId::random());
1685        let hashes = (0..=MAX_PENDING_PER_PEER).map(|_| B256::random()).collect::<Vec<_>>();
1686        // A declined hash leaves the announcement, so its body isn't fetched only to be dropped.
1687        let mut announcement = announcement(&hashes, BlobCellMask::ALL);
1688        fetcher.on_announcement(first, &mut announcement);
1689        assert_eq!(fetcher.pending.len(), MAX_PENDING_PER_PEER);
1690        assert!(announcement
1691            .iter()
1692            .map(|tx| tx.hash)
1693            .eq(hashes[..MAX_PENDING_PER_PEER].iter().copied()));
1694        // Other peers keep their own slots.
1695        fetcher.announce(B256::random(), second, BlobCellMask::ALL);
1696        assert_eq!(fetcher.pending.len(), MAX_PENDING_PER_PEER + 1);
1697        // A removed transaction frees a slot for its peer.
1698        fetcher.remove(&hashes[0]);
1699        fetcher.announce(hashes[MAX_PENDING_PER_PEER], first, BlobCellMask::ALL);
1700        assert!(fetcher.pending.contains_key(&hashes[MAX_PENDING_PER_PEER]));
1701    }
1702
1703    #[test]
1704    fn disconnect_moves_slots_to_a_remaining_provider() {
1705        let mut fetcher = BlobFetcher::<EthPooledTransaction>::new(
1706            CellCustody::default(),
1707            MIN_BLOB_FETCH_PROBABILITY,
1708        );
1709        let (first, second, third) = (PeerId::random(), PeerId::random(), PeerId::random());
1710        let (shared, own, partial) = (B256::random(), B256::random(), B256::random());
1711        let (sampler, waiting) = (PeerId::random(), B256::random());
1712        fetcher.announce(shared, first, BlobCellMask::ALL);
1713        fetcher.announce(own, first, BlobCellMask::ALL);
1714        fetcher.announce(shared, second, BlobCellMask::ALL);
1715        fetcher.announce(partial, second, BlobCellMask::from_bits(1));
1716        fetcher.announce(partial, first, BlobCellMask::ALL);
1717        fetcher.announce(waiting, sampler, BlobCellMask::from_bits(1));
1718        fetcher.announce(waiting, first, BlobCellMask::from_bits(1));
1719        // The fetches the other providers can't finish are dropped, and the other moves to the
1720        // next provider. A fetch the peer didn't provide, or only partly, keeps waiting for one.
1721        fetcher.drop_peer(&first);
1722        assert_eq!(fetcher.pending.len(), 2);
1723        assert!(fetcher.pending.contains_key(&shared) && fetcher.pending.contains_key(&waiting));
1724        assert_eq!(fetcher.added_by_peer, HashMap::from_iter([(second, 1), (sampler, 1)]));
1725        // Without a remaining provider with room, the fetch is dropped.
1726        for _ in 0..MAX_PENDING_PER_PEER {
1727            fetcher.announce(B256::random(), third, BlobCellMask::ALL);
1728        }
1729        fetcher.announce(shared, third, BlobCellMask::ALL);
1730        fetcher.drop_peer(&second);
1731        assert!(!fetcher.pending.contains_key(&shared));
1732        assert_eq!(
1733            fetcher.added_by_peer,
1734            HashMap::from_iter([(third, MAX_PENDING_PER_PEER), (sampler, 1)])
1735        );
1736    }
1737
1738    #[tokio::test]
1739    async fn complete_transaction_outlives_its_last_provider() {
1740        let (tx, cells) = blob_tx_without_blobs(1);
1741        let hash = *tx.hash();
1742        let id = PeerId::random();
1743        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1744        fetcher.announce(hash, id, BlobCellMask::ALL);
1745        assert!(fetcher.body(id, tx));
1746        // The last cells arrive, but the provider leaves before a check slot frees up.
1747        fetcher.pending.get_mut(&hash).unwrap().state = State::Requested(0, DATA_COLUMNS);
1748        fetcher.on_response(hash, id, 0, Some(reply(hash, &cells, DATA_COLUMNS)));
1749        fetcher.drop_peer(&id);
1750        assert_eq!(next_transactions(&mut fetcher, &Peers::default()).await.len(), 1);
1751
1752        // So does a sample whose providers with every column leave: the first while its extra
1753        // column is missing, which only the second is then asked for, and the second once complete.
1754        let (tx, cells) = blob_tx_without_blobs(2);
1755        let hash = *tx.hash();
1756        let (sampler, first, second) = (PeerId::random(), PeerId::random(), PeerId::random());
1757        let custody = BlobCellMask::from_bits(0b1111 << 70);
1758        let role = sample_role(custody);
1759        let extra = role.target().difference(custody);
1760        fetcher.announce(hash, sampler, role.target());
1761        fetcher.pending.get_mut(&hash).unwrap().role = role;
1762        fetcher.announce(hash, first, BlobCellMask::ALL);
1763        fetcher.announce(hash, second, BlobCellMask::ALL);
1764        assert!(fetcher.body(sampler, tx));
1765        fetcher.pending.get_mut(&hash).unwrap().state = State::Requested(1, custody);
1766        fetcher.on_response(hash, sampler, 1, Some(reply(hash, &cells, custody)));
1767        fetcher.drop_peer(&first);
1768        let candidates = fetcher.pending[&hash].candidates(&mut rand::rng()).collect::<Vec<_>>();
1769        assert_eq!(candidates, [(second, extra)]);
1770        fetcher.pending.get_mut(&hash).unwrap().state = State::Requested(2, extra);
1771        fetcher.on_response(hash, second, 2, Some(reply(hash, &cells, extra)));
1772        fetcher.drop_peer(&second);
1773        assert_eq!(next_transactions(&mut fetcher, &Peers::default()).await.len(), 1);
1774    }
1775
1776    #[tokio::test]
1777    async fn stored_body_gets_its_cells_in_a_full_buffer() {
1778        let (tx, cells) = blob_tx_without_blobs(1);
1779        let hash = *tx.hash();
1780        let id = PeerId::random();
1781        let (metadata, mut rx) = peer(id);
1782        let peers = HashMap::from_iter([(id, metadata)]);
1783        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1784        fetcher.announce(hash, id, BlobCellMask::ALL);
1785        assert!(fetcher.body(id, tx));
1786        // The body's cells were charged with it, so other bodies filling the buffer can't stall
1787        // the fetch.
1788        let others = MAX_BUFFERED_BYTES - fetcher.bytes;
1789        fetcher.bytes += others;
1790        let mut cx = Context::from_waker(noop_waker_ref());
1791        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1792        let (request, response) = next_request(&mut rx);
1793        response.send(Ok(reply(hash, &cells, request.cell_mask(0).unwrap()))).unwrap();
1794        assert_eq!(next_transactions(&mut fetcher, &peers).await.len(), 1);
1795        assert_eq!(fetcher.bytes, others);
1796        fetcher.bytes -= others;
1797        assert_consistent(&fetcher);
1798    }
1799
1800    #[test]
1801    fn a_peer_holds_a_bounded_number_of_requests() {
1802        let id = PeerId::random();
1803        let (metadata, mut rx) = peer(id);
1804        let peers = HashMap::from_iter([(id, metadata)]);
1805        let mut fetcher = BlobFetcher::new(CellCustody::default(), MIN_BLOB_FETCH_PROBABILITY);
1806        for blobs in 1..=MAX_INFLIGHT_REQUESTS_PER_PEER as u8 + 1 {
1807            let (tx, _) = blob_tx_without_blobs(blobs);
1808            fetcher.announce(*tx.hash(), id, BlobCellMask::ALL);
1809            assert!(fetcher.body(id, tx));
1810        }
1811        let mut cx = Context::from_waker(noop_waker_ref());
1812        assert!(fetcher.poll(&mut cx, &peers).is_pending());
1813        for _ in 0..MAX_INFLIGHT_REQUESTS_PER_PEER {
1814            next_request(&mut rx);
1815        }
1816        assert!(rx.try_recv().is_err());
1817        assert_consistent(&fetcher);
1818    }
1819}