Skip to main content

reth_network/transactions/
fetcher.rs

1//! Fetches transactions that peers announced with `NewPooledTransactionHashes`.
2//!
3//! The [`TransactionFetcher`] tracks every announced hash that is not known yet, together with the
4//! peers that announced it, and turns those announcements into `GetPooledTransactions` requests.
5//!
6//! # Model
7//!
8//! Every tracked hash is in exactly one of two states:
9//!
10//! - _pending_: waiting for one of the peers that announced it, its _candidates_, to become idle
11//! - _fetching_: part of exactly one inflight request
12//!
13//! A hash remembers the peers that announced it as candidates. Each peer keeps a FIFO queue of
14//! hashes to request, and the first peers to announce a hash get it queued right away. Later
15//! announcers are only remembered, so that a hash is not given up on when the first announcers
16//! fail to deliver it, without costing a queue entry per announcement. A request for an idle peer
17//! is built by draining its queue in the order the announcements were processed, skipping hashes
18//! that are being fetched from another peer or are not tracked anymore, until the request is
19//! full. Packing a request is therefore proportional to the request size and independent of the
20//! total number of pending hashes. FIFO refers to the fetcher's input order; callers may
21//! reorder or deduplicate hashes within a wire announcement.
22//!
23//! When a request resolves, delivered hashes are dropped from tracking. Undelivered hashes go back
24//! to pending and are queued for their remaining candidates, most recent announcers first, or are
25//! dropped if none remain. The responding peer is dropped as a candidate for every undelivered
26//! hash that precedes the last delivered hash of the request, treating it as skipped, and for
27//! all requested hashes if the response was empty or the request failed.
28//! Undelivered hashes after the last delivered hash keep the peer as a candidate only if it
29//! delivered at least half of the request, treating that tail as potentially truncated. This is
30//! a retry heuristic: transaction counts do not establish whether the response reached a byte
31//! limit. Requiring half the request limits repeated low-progress retries. A dropped peer's later
32//! announcements of the hash are ignored while it is tracked, so it cannot take retries from
33//! candidates that were not asked yet.
34//!
35//! Request timeouts are enforced by the peer's session, which resolves the request with
36//! [`RequestError::Timeout`], so the fetcher does not run any timers. A first timeout is retried
37//! once when the responding peer is the only remaining source; otherwise another source is tried.
38//!
39//! # Bounds
40//!
41//! - a configurable number of inflight requests per peer, one by default, and a global inflight
42//!   request limit
43//! - a per peer limit on the number of tracked hashes it is a candidate for, so a single peer
44//!   cannot flood the fetcher with announcements
45//! - a global limit on the number of tracked hashes, at which the peer tracking the most hashes
46//!   gives up its oldest pending hash, so a group of peers flooding the fetcher evicts its own
47//!   hashes rather than everyone else's
48//! - a fixed number of candidates per hash and a separate fetch-attempt limit, so remembering
49//!   recent fallback sources does not allow unlimited retries
50
51use super::{
52    announcement::{AnnouncedTransaction, TransactionMetadata},
53    config::TransactionFetcherConfig,
54    constants::{
55        tx_fetcher::{
56            AVERAGE_BYTE_SIZE_TX_ENCODED, MAX_COUNT_CANDIDATE_PEERS_PER_HASH,
57            MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH, MAX_FETCH_ATTEMPTS_PER_HASH,
58        },
59        SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
60        SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST,
61    },
62    PeerMetadata,
63};
64use crate::metrics::TransactionFetcherMetrics;
65use alloy_consensus::transaction::PooledTransaction;
66use alloy_primitives::{
67    map::{B256Map, B256Set, Entry, FbBuildHasher, HashMap},
68    TxHash,
69};
70use futures::{stream::FuturesUnordered, Future, FutureExt, Stream, StreamExt};
71use reth_eth_wire::{EthVersion, GetPooledTransactions, PooledTransactions};
72use reth_eth_wire_types::{EthNetworkPrimitives, NetworkPrimitives};
73use reth_network_api::PeerRequest;
74use reth_network_p2p::error::{RequestError, RequestResult};
75use reth_network_peers::PeerId;
76use reth_primitives_traits::SignedTransaction;
77use smallvec::SmallVec;
78use std::{
79    collections::{BinaryHeap, VecDeque},
80    pin::Pin,
81    sync::Arc,
82    task::{ready, Context, Poll},
83};
84use tokio::sync::{mpsc::error::TrySendError, oneshot};
85use tracing::{trace, warn};
86
87/// Maximum live entries inspected in a global fallback eviction search.
88const MAX_EVICTION_ATTEMPTS: usize = 8;
89
90/// Fetches transactions that peers announced but that are not in the pool yet.
91///
92/// Announcements are recorded with [`Self::on_announcement`], requests are sent with
93/// [`Self::dispatch`] and resolved requests are yielded as [`FetchEvent`]s by the [`Stream`]
94/// implementation. See the [module docs](self) for how requests are scheduled.
95#[derive(Debug)]
96pub struct TransactionFetcher<N: NetworkPrimitives = EthNetworkPrimitives> {
97    /// All tracked hashes with their candidate peers and fetch state.
98    hashes: B256Map<TxEntry>,
99    /// Tracked hashes in the order they were added, used to evict the oldest pending hash once
100    /// the fetcher is at capacity and the peer tracking the most hashes has none pending. Entries
101    /// are removed lazily, so it may contain hashes that are not tracked anymore. Fetching hashes
102    /// skipped by an eviction search are moved to the back.
103    order: VecDeque<(TxHash, u64)>,
104    /// Fetch state of all peers that announced tracked hashes.
105    peers: HashMap<PeerKey, PeerState>,
106    /// Maps peer ids to their compact key.
107    peer_keys: HashMap<PeerId, PeerKey, FbBuildHasher<64>>,
108    /// Key assigned to the next new peer. Keys are never reused, so the candidates of a hash can
109    /// safely refer to peers that disconnected in the meantime.
110    next_peer_key: u32,
111    /// Distinguishes overlapping requests, including repeat requests for the same hash.
112    next_request_id: u64,
113    /// Distinguishes a re-announcement from stale queue entries for an earlier tracked hash.
114    next_generation: u64,
115    /// Idle peers with queued hashes, in the order they became ready.
116    ready: VecDeque<PeerKey>,
117    /// All inflight `GetPooledTransactions` requests.
118    inflight: FuturesUnordered<InflightRequest<N::PooledTransaction>>,
119    /// Number of tracked hashes that are part of an inflight request.
120    num_fetching: usize,
121    // Reused when verifying responses, so no maps are allocated per response.
122    scratch_requested: B256Map<Candidate>,
123    /// Reused when verifying responses, so no sets are allocated per response.
124    scratch_delivered: B256Set,
125    /// Reused when processing announcements, so no vector is allocated per announcement.
126    scratch_queue: Vec<(TxHash, u64)>,
127    /// Configured limits.
128    config: TransactionFetcherConfig,
129    metrics: TransactionFetcherMetrics,
130}
131
132impl<N: NetworkPrimitives> TransactionFetcher<N> {
133    /// Creates a new fetcher with the given config.
134    pub fn new(config: TransactionFetcherConfig) -> Self {
135        let metrics = TransactionFetcherMetrics::default();
136        metrics.capacity_inflight_requests.increment(config.max_inflight_requests as u64);
137
138        Self {
139            hashes: Default::default(),
140            order: Default::default(),
141            peers: Default::default(),
142            peer_keys: Default::default(),
143            next_peer_key: 0,
144            next_request_id: 0,
145            next_generation: 0,
146            ready: Default::default(),
147            inflight: Default::default(),
148            num_fetching: 0,
149            scratch_requested: Default::default(),
150            scratch_delivered: Default::default(),
151            scratch_queue: Default::default(),
152            config,
153            metrics,
154        }
155    }
156
157    /// Returns the fetcher's config.
158    pub const fn config(&self) -> &TransactionFetcherConfig {
159        &self.config
160    }
161
162    /// Returns the number of tracked hashes, pending and fetching.
163    pub fn num_hashes(&self) -> usize {
164        self.hashes.len()
165    }
166
167    /// Returns the number of hashes that are waiting for an idle candidate peer.
168    pub fn num_pending_hashes(&self) -> usize {
169        self.hashes.len().saturating_sub(self.num_fetching)
170    }
171
172    /// Returns the number of hashes that are part of an inflight request.
173    pub const fn num_fetching_hashes(&self) -> usize {
174        self.num_fetching
175    }
176
177    /// Returns the number of inflight requests.
178    pub fn num_inflight_requests(&self) -> usize {
179        self.inflight.len()
180    }
181
182    /// Returns `true` if there is no inflight request to the peer.
183    pub fn is_idle(&self, peer_id: &PeerId) -> bool {
184        self.peer_keys
185            .get(peer_id)
186            .and_then(|key| self.peers.get(key))
187            .is_none_or(|peer| peer.inflight == 0)
188    }
189
190    /// Records hashes announced by the peer and queues them for fetching.
191    ///
192    /// The metadata of a hash is the announced transaction type and size, if the announcement
193    /// carried it. The caller is expected to have filtered out hashes that are already known.
194    ///
195    /// Requests are only sent by [`Self::dispatch`].
196    pub fn on_announcement(
197        &mut self,
198        peer_id: PeerId,
199        announcement: impl IntoIterator<Item = AnnouncedTransaction>,
200    ) {
201        let key = self.peer_key(peer_id);
202        let max_per_peer = self.config.max_announced_hashes_per_peer as usize;
203        let max_total = self.config.max_capacity_cache_txns_pending_fetch as usize;
204
205        let mut dropped_peer_limit = 0u64;
206        let mut evicted_at_capacity = 0u64;
207        let mut dropped_at_capacity = 0u64;
208
209        // The peer's count of tracked hashes and the hashes to queue for it are kept locally and
210        // applied once at the end, so every announced hash costs a single map lookup.
211        let Some(peer) = self.peers.get(&key) else { return };
212        let mut tracked = peer.tracked;
213        let mut queue = std::mem::take(&mut self.scratch_queue);
214        queue.clear();
215        // Entries at the front of `queue` already evicted or moved into the peer queue.
216        let mut queue_start = 0;
217        // Other peers can only lose tracked hashes during this announcement. Refresh their
218        // heap entries lazily instead of scanning every peer for each hash at capacity.
219        let mut eviction = None;
220        // Gossip commonly replaces the same fallback peer for every hash in a batch. Apply
221        // that peer's accounting once, flushing before eviction needs up-to-date counts.
222        let mut retired_candidates = DeferredCandidateRemovals::default();
223
224        for AnnouncedTransaction { hash, metadata } in announcement {
225            let at_capacity = self.hashes.len() >= max_total;
226
227            // whether the hash is queued for the peer right away
228            let (eager, generation) = match self.hashes.entry(hash) {
229                Entry::Occupied(mut occupied) => {
230                    let entry = occupied.get_mut();
231                    if let Some(candidate) = entry.candidate_mut(key) {
232                        // Keep the latest metadata for repeat announcements from this peer.
233                        candidate.set_metadata(metadata);
234                        continue
235                    }
236                    if entry.failed.contains(&key) {
237                        continue
238                    }
239                    if tracked >= max_per_peer {
240                        dropped_peer_limit += 1;
241                        continue
242                    }
243                    if entry.candidates.len() == MAX_COUNT_CANDIDATE_PEERS_PER_HASH {
244                        // Keep the first eager sources and the most recent fallback sources.
245                        // A fixed first-N list lets early co-announcers exclude every later source.
246                        let replace = (MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH..
247                            entry.candidates.len())
248                            .find(|&idx| {
249                                entry.fetching_by.is_none_or(|(fetching, _)| {
250                                    entry.candidates[idx].peer != fetching
251                                })
252                            })
253                            .expect("only one candidate can be fetching");
254                        let removed = entry.candidates.remove(replace);
255                        retired_candidates.record_removed(removed.peer, &mut self.peers);
256                    }
257                    // The first announcers get the hash queued right away, later ones are only
258                    // remembered and asked once the earlier ones failed to deliver.
259                    let eager = entry.candidates.len() < MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH ||
260                        (entry.fetching_by.is_none() &&
261                            !entry.candidates.iter().any(Candidate::is_queued));
262                    let candidate = if eager {
263                        Candidate::queued(key, metadata)
264                    } else {
265                        Candidate::unqueued(key, metadata)
266                    };
267                    entry.candidates.push(candidate);
268                    (eager, entry.generation)
269                }
270                Entry::Vacant(vacant) => {
271                    let generation = self.next_generation;
272                    self.next_generation += 1;
273                    if tracked >= max_per_peer {
274                        dropped_peer_limit += 1;
275                        continue
276                    }
277                    if at_capacity {
278                        retired_candidates.flush(&mut self.peers);
279                        // the evicted hash may be one of this peer's, so its count is synced
280                        if let Some(peer) = self.peers.get_mut(&key) {
281                            peer.tracked = tracked;
282                        }
283                        if self.evict_pending(key, &queue, &mut queue_start, &mut eviction) {
284                            evicted_at_capacity += 1;
285                            tracked = self.peers.get(&key).map_or(tracked, |peer| peer.tracked);
286                        } else {
287                            dropped_at_capacity += 1;
288                            continue
289                        }
290                        self.hashes.insert(hash, TxEntry::new(key, metadata, generation));
291                    } else {
292                        vacant.insert(TxEntry::new(key, metadata, generation));
293                    }
294                    self.record_order(hash, generation);
295                    (true, generation)
296                }
297            };
298
299            tracked += 1;
300            if eager {
301                queue.push((hash, generation));
302            }
303        }
304
305        retired_candidates.flush(&mut self.peers);
306        let queued = queue.len() - queue_start;
307        if let Some(peer) = self.peers.get_mut(&key) {
308            peer.tracked = tracked;
309            for &(hash, generation) in &queue[queue_start..] {
310                peer.push_queue(
311                    &self.hashes,
312                    key,
313                    (hash, generation),
314                    QueuePosition::Back,
315                    max_per_peer,
316                );
317            }
318        }
319        queue.clear();
320        self.scratch_queue = queue;
321
322        if dropped_peer_limit > 0 {
323            self.metrics.announced_hashes_dropped_peer_limit.increment(dropped_peer_limit);
324        }
325        if evicted_at_capacity > 0 {
326            self.metrics.hashes_evicted_at_capacity.increment(evicted_at_capacity);
327        }
328        if dropped_at_capacity > 0 {
329            self.metrics.announced_hashes_dropped_at_capacity.increment(dropped_at_capacity);
330        }
331
332        if queued > 0 {
333            trace!(target: "net::tx",
334                peer_id=format!("{peer_id:#}"),
335                queued,
336                dropped_peer_limit,
337                evicted_at_capacity,
338                dropped_at_capacity,
339                "queued announced hashes"
340            );
341        }
342        if queued > 0 || queue_start > 0 {
343            self.mark_ready(key, QueuePosition::Back);
344        }
345    }
346
347    /// Sends `GetPooledTransactions` requests to idle peers that have queued hashes.
348    ///
349    /// Stops when the global inflight request limit is reached. `max_hashes_per_request` caps
350    /// each request independently of hashes inflight to other peers, so stalled peers cannot
351    /// shrink requests to responsive peers. Zero sends nothing. The caller must enforce its
352    /// import backpressure when consuming responses; decoded responses remain bounded by
353    /// the configured inflight request limit.
354    ///
355    /// Returns the number of requests sent. New requests are only polled by the next call to
356    /// [`Stream::poll_next`], so the caller must poll the fetcher again if any were sent.
357    pub fn dispatch(
358        &mut self,
359        peers: &HashMap<PeerId, PeerMetadata<N>, FbBuildHasher<64>>,
360        max_hashes_per_request: usize,
361    ) -> usize {
362        if max_hashes_per_request == 0 {
363            return 0
364        }
365        let max_inflight = self.config.max_inflight_requests as usize;
366        let mut sent = 0;
367        // peers whose session channel is full, they get another chance on the next dispatch
368        let mut retry = SmallVec::<[PeerKey; 4]>::new();
369
370        while self.inflight.len() < max_inflight {
371            let Some(key) = self.ready.pop_front() else { break };
372            let Some(peer) = self.peers.get_mut(&key) else { continue };
373            peer.ready = false;
374            if peer.inflight >= self.config.max_inflight_requests_per_peer {
375                continue
376            }
377            let peer_id = peer.peer_id;
378            // the session is gone if the manager doesn't know the peer anymore
379            let Some(session) = peers.get(&peer_id) else { continue };
380
381            let limit = max_hashes_per_request
382                .min(SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST);
383            let request_id = self.next_request_id;
384            self.next_request_id += 1;
385            let (hashes, announced) = self.pack_request(key, request_id, limit);
386            if hashes.is_empty() {
387                continue
388            }
389
390            let (response, rx) = oneshot::channel();
391            let request = PeerRequest::GetPooledTransactions {
392                request: GetPooledTransactions(hashes.clone()),
393                response,
394            };
395
396            match session.request_tx().try_send(request) {
397                Ok(()) => {
398                    trace!(target: "net::tx",
399                        peer_id=format!("{peer_id:#}"),
400                        hashes=hashes.len(),
401                        "sending `GetPooledTransactions` request to peer's session"
402                    );
403                    if let Some(peer) = self.peers.get_mut(&key) {
404                        peer.inflight += 1;
405                    }
406                    self.inflight.push(InflightRequest {
407                        peer: key,
408                        request_id,
409                        peer_id,
410                        version: session.version(),
411                        client_version: session.client_version.clone(),
412                        hashes,
413                        announced,
414                        response: rx,
415                    });
416                    sent += 1;
417                    // the peer may be allowed more than one inflight request
418                    self.mark_ready(key, QueuePosition::Back);
419                }
420                Err(err) => {
421                    self.unpack_request(key, request_id, hashes);
422                    match err {
423                        TrySendError::Full(_) => {
424                            self.metrics.egress_peer_channel_full.increment(1);
425                            retry.push(key);
426                        }
427                        TrySendError::Closed(_) => self.on_peer_disconnected(&peer_id),
428                    }
429                }
430            }
431        }
432
433        for key in retry {
434            self.mark_ready(key, QueuePosition::Back);
435        }
436
437        sent
438    }
439
440    /// Stops tracking the given hashes because the transactions were received, e.g. over
441    /// broadcast.
442    ///
443    /// Hashes that are part of an inflight request are simply not rescheduled when that request
444    /// resolves.
445    pub fn on_transactions_received<'a>(&mut self, hashes: impl IntoIterator<Item = &'a TxHash>) {
446        for hash in hashes {
447            self.remove_hash(hash);
448        }
449    }
450
451    /// Removes the peer as a candidate for all hashes it announced and drops pending hashes that
452    /// have no candidate left.
453    ///
454    /// An inflight request to the peer resolves with an error once its session is gone, which
455    /// reschedules the requested hashes.
456    pub fn on_peer_disconnected(&mut self, peer_id: &PeerId) {
457        let Some(key) = self.peer_keys.remove(peer_id) else { return };
458        if self.peers.remove(&key).is_none() {
459            return
460        }
461
462        // Every tracked hash is visited, since the peer is a candidate of hashes that are not in
463        // its queue as well. Disconnects are rare compared to announcements, so this is cheaper
464        // overall than checking for gone peers whenever candidates are counted.
465        let mut dropped = 0u64;
466        let mut requeue = Vec::new();
467        self.hashes.retain(|hash, entry| {
468            let before = entry.candidates.len();
469            entry.candidates.retain(|candidate| candidate.peer != key);
470            if entry.candidates.len() == before || entry.fetching_by.is_some() {
471                return true
472            }
473            if entry.candidates.is_empty() {
474                dropped += 1;
475                return false
476            }
477            // the hash must stay queued for at least one candidate
478            if !entry.candidates.iter().any(|candidate| candidate.is_queued()) {
479                requeue.push((entry.generation, *hash, entry.unqueued_candidates()));
480            }
481            true
482        });
483
484        let mut requeued = SmallVec::<[PeerKey; MAX_COUNT_CANDIDATE_PEERS_PER_HASH]>::new();
485        // Requeue at the front in reverse announcement order.
486        requeue.sort_unstable_by_key(|(generation, _, _)| std::cmp::Reverse(*generation));
487        for (_, hash, targets) in requeue {
488            self.requeue(hash, targets, &mut requeued);
489        }
490
491        if dropped > 0 {
492            self.metrics.hashes_dropped_no_candidate_peers.increment(dropped);
493        }
494        // retried hashes go to the most recent announcers first
495        for key in requeued {
496            self.mark_ready(key, QueuePosition::Front);
497        }
498    }
499
500    /// Updates the fetcher's gauges.
501    pub fn update_metrics(&self) {
502        self.metrics.inflight_transaction_requests.set(self.inflight.len() as f64);
503        self.metrics.hashes_inflight_transaction_requests.set(self.num_fetching as f64);
504        self.metrics.hashes_pending_fetch.set(self.num_pending_hashes() as f64);
505    }
506
507    /// Returns the key of the peer, registering the peer if it isn't known yet.
508    fn peer_key(&mut self, peer_id: PeerId) -> PeerKey {
509        *self.peer_keys.entry(peer_id).or_insert_with(|| {
510            let key = PeerKey(self.next_peer_key);
511            self.next_peer_key += 1;
512            self.peers.insert(key, PeerState::new(peer_id));
513            key
514        })
515    }
516
517    /// Marks the peer as ready for a request if it is idle and has hashes queued, either behind
518    /// the other ready peers or ahead of them.
519    fn mark_ready(&mut self, key: PeerKey, position: QueuePosition) {
520        if let Some(peer) = self.peers.get_mut(&key) &&
521            !peer.ready &&
522            !peer.queue.is_empty() &&
523            peer.inflight < self.config.max_inflight_requests_per_peer
524        {
525            peer.ready = true;
526            match position {
527                QueuePosition::Front => self.ready.push_front(key),
528                QueuePosition::Back => self.ready.push_back(key),
529            }
530        }
531    }
532
533    /// Queues the hash for the peer, at the back or the front of its queue, and marks it as
534    /// queued in the hash's candidate entry.
535    fn enqueue(&mut self, key: PeerKey, hash: TxHash, position: QueuePosition) {
536        let max_per_peer = self.config.max_announced_hashes_per_peer as usize;
537        let Some(peer) = self.peers.get_mut(&key) else { return };
538        let Some(entry) = self.hashes.get_mut(&hash) else { return };
539        let generation = entry.generation;
540        if let Some(candidate) = entry.candidate_mut(key) {
541            candidate.queued = true;
542        }
543        peer.push_queue(&self.hashes, key, (hash, generation), position, max_per_peer);
544    }
545
546    /// Records a newly tracked hash in the eviction order.
547    ///
548    /// Stale lifetimes are removed lazily. Once the order reaches twice the capacity it is
549    /// compacted in place, retaining only the current generation of every tracked hash.
550    fn record_order(&mut self, hash: TxHash, generation: u64) {
551        let max_len = 2 * self.config.max_capacity_cache_txns_pending_fetch as usize;
552        if self.order.len() >= max_len {
553            self.order.retain(|(hash, generation)| {
554                self.hashes.get(hash).is_some_and(|entry| entry.generation == *generation)
555            });
556        }
557        self.order.push_back((hash, generation));
558    }
559
560    /// Evicts a pending hash to make room for one announced by `announcer` and returns whether
561    /// one was found.
562    ///
563    /// Prefer the oldest exclusively announced pending hash of the peer tracking the most
564    /// hashes, so a group of peers flooding the fetcher gives up its own hashes when possible. The
565    /// announcer gives way when it tracks as many hashes as the busiest peer. If the
566    /// chosen peer has no exclusively announced pending hash, the oldest pending hash overall
567    /// is evicted. Preferring exclusive hashes protects other peers' work when possible, while
568    /// the fallback prevents co-announcements from making the entire cache unevictable.
569    ///
570    /// `queued` are the hashes of the current announcement that are not in the announcer's queue
571    /// yet; `queued_start` marks entries already evicted or moved into the peer queue.
572    fn evict_pending(
573        &mut self,
574        announcer: PeerKey,
575        queued: &[(TxHash, u64)],
576        queued_start: &mut usize,
577        eviction: &mut Option<EvictionState>,
578    ) -> bool {
579        let eviction = eviction.get_or_insert_with(|| EvictionState {
580            peers: self
581                .peers
582                .iter()
583                .filter(|(key, peer)| **key != announcer && peer.tracked > 0)
584                .map(|(key, peer)| (peer.tracked, *key))
585                .collect(),
586            exclusive: Default::default(),
587        });
588        let heap = &mut eviction.peers;
589        let (mut tracked, mut key) = loop {
590            let Some(&(previous, key)) = heap.peek() else { break (0, announcer) };
591            let current = self.peers.get(&key).map_or(0, |peer| peer.tracked);
592            if current == previous {
593                break (current, key)
594            }
595            heap.pop();
596            if current > 0 {
597                heap.push((current, key));
598            }
599        };
600        if let Some(peer) = self.peers.get(&announcer) &&
601            peer.tracked >= tracked
602        {
603            key = announcer;
604            tracked = peer.tracked;
605        }
606        if tracked == 0 {
607            return self.evict_oldest_pending()
608        }
609        if self.evict_oldest_pending_of(key, &mut eviction.exclusive) {
610            return true
611        }
612        if key == announcer {
613            while *queued_start < queued.len() {
614                let (hash, generation) = queued[*queued_start];
615                *queued_start += 1;
616                let Some(entry) =
617                    self.hashes.get(&hash).filter(|entry| entry.generation == generation)
618                else {
619                    continue
620                };
621                if entry.candidates.len() == 1 && entry.fetching_by.is_none() {
622                    self.remove_hash(&hash);
623                    return true
624                }
625                // Preserve shared entries skipped by the cursor in this announcement.
626                self.enqueue(key, hash, QueuePosition::Back);
627            }
628        }
629        self.evict_oldest_pending()
630    }
631
632    /// Evicts the oldest pending hash announced only by this peer, if one exists.
633    ///
634    /// Scan each selected peer's queue once per announcement. A bounded prefix can hide
635    /// exclusive victims behind shared hashes; caching avoids rescanning that prefix for every
636    /// eviction. Newly tracked hashes from the current announcement are handled by its cursor.
637    fn evict_oldest_pending_of(
638        &mut self,
639        key: PeerKey,
640        exclusive: &mut HashMap<PeerKey, VecDeque<(TxHash, u64)>>,
641    ) -> bool {
642        let candidates = exclusive.entry(key).or_insert_with(|| {
643            self.peers
644                .get(&key)
645                .into_iter()
646                .flat_map(|peer| &peer.queue)
647                .filter(|(hash, generation)| {
648                    self.hashes.get(hash).is_some_and(|entry| {
649                        entry.generation == *generation &&
650                            entry.candidates.len() == 1 &&
651                            entry.has_candidate(key) &&
652                            entry.fetching_by.is_none()
653                    })
654                })
655                .copied()
656                .collect()
657        });
658        while let Some((hash, generation)) = candidates.pop_front() {
659            if self.hashes.get(&hash).is_some_and(|entry| {
660                entry.generation == generation &&
661                    entry.candidates.len() == 1 &&
662                    entry.has_candidate(key) &&
663                    entry.fetching_by.is_none()
664            }) {
665                self.remove_hash(&hash);
666                return true
667            }
668        }
669        false
670    }
671
672    /// Evicts the oldest pending hash, including shared hashes, as a last resort.
673    ///
674    /// Shared hashes cannot be exempt from eviction: co-announcements could pin every slot.
675    /// Returns `false` if only fetching hashes were found within the search budget. Fetching
676    /// hashes are moved to the back of the order, so the next search continues past them.
677    fn evict_oldest_pending(&mut self) -> bool {
678        let mut attempts = 0;
679        while attempts < MAX_EVICTION_ATTEMPTS {
680            let Some((hash, generation)) = self.order.pop_front() else { break };
681            let Some(entry) = self.hashes.get(&hash).filter(|entry| entry.generation == generation)
682            else {
683                continue
684            };
685            attempts += 1;
686            if entry.fetching_by.is_some() {
687                self.order.push_back((hash, generation));
688                continue
689            }
690            self.remove_hash(&hash);
691            return true
692        }
693        false
694    }
695
696    /// Drains the peer's queue into a request, in announcement order, until the request holds
697    /// `max_hashes` hashes or the expected response size reaches the configured soft limit. A
698    /// transaction that on its own exceeds the size limit is requested alone.
699    ///
700    /// The returned hashes are marked as fetched by the peer, with what it announced for each.
701    fn pack_request(
702        &mut self,
703        key: PeerKey,
704        request_id: u64,
705        max_hashes: usize,
706    ) -> (Vec<TxHash>, Vec<Candidate>) {
707        let max_bytes =
708            self.config.soft_limit_byte_size_pooled_transactions_response_on_pack_request;
709        let Some(peer) = self.peers.get_mut(&key) else { return Default::default() };
710
711        let mut hashes = Vec::with_capacity(peer.queue.len().min(max_hashes));
712        let mut announced = Vec::with_capacity(hashes.capacity());
713        let mut bytes = 0usize;
714
715        while let Some((hash, generation)) = peer.queue.pop_front() {
716            // skip hashes that were delivered in the meantime, or that this peer is no longer a
717            // candidate for
718            let Some(entry) =
719                self.hashes.get_mut(&hash).filter(|entry| entry.generation == generation)
720            else {
721                continue
722            };
723            let Some(candidate) = entry.candidate_mut(key) else { continue };
724            candidate.queued = false;
725            let candidate = *candidate;
726            let size = candidate.request_size();
727
728            // hashes that are being fetched elsewhere are queued again if that fetch fails
729            if entry.fetching_by.is_some() {
730                continue
731            }
732
733            if !hashes.is_empty() && bytes.saturating_add(size) > max_bytes {
734                if let Some(candidate) = entry.candidate_mut(key) {
735                    candidate.queued = true;
736                }
737                peer.queue.push_front((hash, generation));
738                break
739            }
740
741            entry.fetching_by = Some((key, request_id));
742            entry.attempts += 1;
743            self.num_fetching += 1;
744            bytes = bytes.saturating_add(size);
745            hashes.push(hash);
746            announced.push(candidate);
747
748            if hashes.len() >= max_hashes {
749                break
750            }
751        }
752
753        (hashes, announced)
754    }
755
756    /// Reverts [`Self::pack_request`] for a request that could not be sent: the hashes are pending
757    /// again and are queued at the front of the peer's queue in their original order.
758    fn unpack_request(&mut self, key: PeerKey, request_id: u64, hashes: Vec<TxHash>) {
759        for hash in hashes.into_iter().rev() {
760            if let Some(entry) = self.hashes.get_mut(&hash) &&
761                entry.fetching_by == Some((key, request_id))
762            {
763                entry.fetching_by = None;
764                entry.attempts -= 1;
765                self.num_fetching -= 1;
766                self.enqueue(key, hash, QueuePosition::Front);
767            }
768        }
769    }
770
771    /// Queues a pending hash for the given candidates, the ones that don't have it queued, and
772    /// records those peers in `requeued`.
773    fn requeue(
774        &mut self,
775        hash: TxHash,
776        targets: SmallVec<[PeerKey; MAX_COUNT_CANDIDATE_PEERS_PER_HASH]>,
777        requeued: &mut SmallVec<[PeerKey; MAX_COUNT_CANDIDATE_PEERS_PER_HASH]>,
778    ) {
779        for key in targets {
780            self.enqueue(key, hash, QueuePosition::Front);
781            if !requeued.contains(&key) {
782                requeued.push(key);
783            }
784        }
785    }
786
787    /// Stops tracking the hash.
788    fn remove_hash(&mut self, hash: &TxHash) {
789        let Some(entry) = self.hashes.remove(hash) else { return };
790        if entry.fetching_by.is_some() {
791            self.num_fetching -= 1;
792        }
793        for candidate in &entry.candidates {
794            if let Some(peer) = self.peers.get_mut(&candidate.peer) {
795                peer.tracked = peer.tracked.saturating_sub(1);
796            }
797        }
798    }
799
800    /// Processes a resolved request and returns the corresponding event.
801    fn on_resolved(
802        &mut self,
803        resolved: ResolvedRequest<N::PooledTransaction>,
804    ) -> FetchEvent<N::PooledTransaction> {
805        let ResolvedRequest {
806            peer: key,
807            request_id,
808            peer_id,
809            version,
810            client_version,
811            hashes: requested,
812            announced,
813            result,
814        } = resolved;
815
816        if let Some(peer) = self.peers.get_mut(&key) {
817            peer.inflight = peer.inflight.saturating_sub(1);
818        }
819
820        let mut delivered = std::mem::take(&mut self.scratch_delivered);
821        delivered.clear();
822
823        let outcome = result.map(|mut transactions| {
824            let check =
825                self.check_response(&mut transactions, &requested, announced, &mut delivered);
826            (transactions, check)
827        });
828
829        let timed_out = matches!(&outcome, Err(RequestError::Timeout));
830        self.on_delivery(key, request_id, &requested, &delivered, timed_out);
831        self.scratch_delivered = delivered;
832
833        if matches!(&outcome, Ok((_, check)) if check.mismatched) {
834            return self.on_announcement_mismatch(key, peer_id)
835        }
836        self.mark_ready(key, QueuePosition::Back);
837
838        match outcome {
839            Ok((transactions, ResponseCheck { unsolicited, .. })) => {
840                if unsolicited > 0 {
841                    trace!(target: "net::tx",
842                        peer_id=format!("{peer_id:#}"),
843                        unsolicited,
844                        "received transactions in `PooledTransactions` response that weren't requested"
845                    );
846                }
847                if !transactions.is_empty() {
848                    self.metrics.fetched_transactions.increment(transactions.len() as u64);
849                    FetchEvent::TransactionsFetched {
850                        peer_id,
851                        version,
852                        client_version,
853                        transactions,
854                        report_peer: unsolicited > 0,
855                    }
856                } else if unsolicited > 0 {
857                    // the peer only sent transactions we didn't ask for
858                    FetchEvent::FetchError { peer_id, error: RequestError::BadResponse }
859                } else {
860                    trace!(target: "net::tx",
861                        peer_id=format!("{peer_id:#}"),
862                        requested=requested.len(),
863                        "received empty `PooledTransactions` response, peer failed to serve hashes it announced"
864                    );
865                    FetchEvent::EmptyResponse { peer_id }
866                }
867            }
868            Err(error) => FetchEvent::FetchError { peer_id, error },
869        }
870    }
871
872    // Filters a response down to the requested transactions and records them in `delivered`. One
873    // contradicting its announcement records nothing, so its hashes are retried with others.
874    fn check_response(
875        &mut self,
876        transactions: &mut PooledTransactions<N::PooledTransaction>,
877        requested: &[TxHash],
878        announced: Vec<Candidate>,
879        delivered: &mut B256Set,
880    ) -> ResponseCheck {
881        let mut requested_set = std::mem::take(&mut self.scratch_requested);
882        requested_set.clear();
883        requested_set.extend(requested.iter().copied().zip(announced));
884        let check = verify_response(transactions, &requested_set, delivered);
885        self.scratch_requested = requested_set;
886
887        if check.unsolicited > 0 {
888            self.metrics.unsolicited_transactions.increment(check.unsolicited as u64);
889        }
890        if check.mismatched {
891            delivered.clear();
892        }
893        check
894    }
895
896    // Retires the responding session from fetch scheduling if it is still tracked.
897    fn on_announcement_mismatch(
898        &mut self,
899        key: PeerKey,
900        peer_id: PeerId,
901    ) -> FetchEvent<N::PooledTransaction> {
902        // A response from a closed session must not retire the peer's current session.
903        if self.peer_keys.get(&peer_id) != Some(&key) {
904            return FetchEvent::FetchError { peer_id, error: RequestError::BadResponse }
905        }
906        self.metrics.announcement_mismatches.increment(1);
907        warn!(target: "net::tx",
908            peer_id=format!("{peer_id:#}"),
909            "received transactions in `PooledTransactions` response that don't match their announced type or size"
910        );
911        // Stop scheduling requests while the session's disconnect is pending.
912        self.on_peer_disconnected(&peer_id);
913        FetchEvent::AnnouncementMismatch { peer_id }
914    }
915
916    /// Settles the requested hashes of a resolved request: delivered hashes are dropped and
917    /// undelivered hashes are rescheduled for their remaining candidates.
918    fn on_delivery(
919        &mut self,
920        key: PeerKey,
921        request_id: u64,
922        requested: &[TxHash],
923        delivered: &B256Set,
924        timed_out: bool,
925    ) {
926        // Position right after the last delivered hash. Drop the responder as a candidate for
927        // missing hashes before it. Keep it for the undelivered tail only if at least half of
928        // the requested hashes were delivered, treating that tail as potentially truncated.
929        // This is a retry heuristic: transaction counts do not establish whether the response
930        // reached a byte limit. Requiring half the request limits repeated low-progress retries.
931        let cutoff = if 2 * delivered.len() >= requested.len() {
932            requested
933                .iter()
934                .rposition(|hash| delivered.contains(hash))
935                .map_or(requested.len(), |idx| idx + 1)
936        } else {
937            requested.len()
938        };
939
940        let mut dropped = 0u64;
941        let mut requeued = SmallVec::<[PeerKey; MAX_COUNT_CANDIDATE_PEERS_PER_HASH]>::new();
942
943        // iterate in reverse so that queueing at the front of a queue preserves the request order
944        for (idx, hash) in requested.iter().enumerate().rev() {
945            if delivered.contains(hash) {
946                self.remove_hash(hash);
947                continue
948            }
949
950            // the hash was received elsewhere in the meantime, or was even announced and assigned
951            // to another peer again
952            let Some(entry) = self.hashes.get_mut(hash) else { continue };
953            if entry.fetching_by != Some((key, request_id)) {
954                continue
955            }
956            entry.fetching_by = None;
957            self.num_fetching -= 1;
958
959            // A short adaptive session timeout can expire before the first response from the
960            // only source arrives. Allow one retry; prefer another source whenever available.
961            let retry_only_source = timed_out && entry.attempts == 1 && entry.candidates.len() == 1;
962            let peers = &mut self.peers;
963            let failed = &mut entry.failed;
964            entry.candidates.retain(|candidate| {
965                // disconnected peers are pruned as well
966                let Some(peer) = peers.get_mut(&candidate.peer) else { return false };
967                if idx < cutoff && candidate.peer == key && !retry_only_source {
968                    peer.tracked = peer.tracked.saturating_sub(1);
969                    failed.push(key);
970                    return false
971                }
972                true
973            });
974
975            if entry.candidates.is_empty() || entry.attempts >= MAX_FETCH_ATTEMPTS_PER_HASH {
976                // Rotating fallback candidates must not allow unlimited retries for one hash.
977                self.remove_hash(hash);
978                dropped += 1;
979                continue
980            }
981
982            let targets = entry.unqueued_candidates();
983            self.requeue(*hash, targets, &mut requeued);
984        }
985
986        if dropped > 0 {
987            self.metrics.hashes_dropped_no_candidate_peers.increment(dropped);
988            trace!(target: "net::tx", dropped, "dropped hashes with no candidates or exhausted fetch attempts");
989        }
990
991        // retried hashes go to the most recent announcers first
992        for key in requeued {
993            self.mark_ready(key, QueuePosition::Front);
994        }
995    }
996}
997
998#[cfg(test)]
999impl<N: NetworkPrimitives> TransactionFetcher<N> {
1000    /// Returns the connected peers that are candidates for the hash, in announcement order.
1001    pub(super) fn candidate_peers(&self, hash: &TxHash) -> Vec<PeerId> {
1002        self.hashes
1003            .get(hash)
1004            .map(|entry| {
1005                entry
1006                    .candidates
1007                    .iter()
1008                    .filter_map(|candidate| self.peers.get(&candidate.peer))
1009                    .map(|peer| peer.peer_id)
1010                    .collect()
1011            })
1012            .unwrap_or_default()
1013    }
1014
1015    /// Returns the peer the hash is currently fetched from, if any.
1016    fn fetching_peer(&self, hash: &TxHash) -> Option<PeerId> {
1017        let (key, _) = self.hashes.get(hash)?.fetching_by?;
1018        self.peers.get(&key).map(|peer| peer.peer_id)
1019    }
1020
1021    /// Returns the hashes queued for the peer, oldest first. May include hashes that are not
1022    /// tracked anymore or are being fetched elsewhere.
1023    pub(super) fn queued_hashes(&self, peer_id: &PeerId) -> Vec<TxHash> {
1024        self.peer_keys
1025            .get(peer_id)
1026            .and_then(|key| self.peers.get(key))
1027            .map(|peer| peer.queue.iter().map(|(hash, _)| *hash).collect())
1028            .unwrap_or_default()
1029    }
1030
1031    /// Returns the number of peers the fetcher tracks.
1032    fn num_peers(&self) -> usize {
1033        self.peers.len()
1034    }
1035
1036    /// Panics if the internal bookkeeping is inconsistent.
1037    fn assert_invariants(&self) {
1038        let fetching = self.hashes.values().filter(|entry| entry.fetching_by.is_some()).count();
1039        assert_eq!(fetching, self.num_fetching, "fetching counter out of sync");
1040
1041        let ordered = self
1042            .order
1043            .iter()
1044            .filter(|(hash, generation)| {
1045                self.hashes.get(hash).is_some_and(|entry| entry.generation == *generation)
1046            })
1047            .map(|(hash, _)| *hash)
1048            .collect::<B256Set>();
1049        assert!(
1050            self.order.len() <= 2 * self.config.max_capacity_cache_txns_pending_fetch as usize,
1051            "eviction order grew beyond its bound"
1052        );
1053
1054        for (hash, entry) in &self.hashes {
1055            assert!(
1056                !entry.candidates.is_empty() || entry.fetching_by.is_some(),
1057                "{hash} is pending without candidates"
1058            );
1059            assert!(
1060                entry.candidates.len() <= MAX_COUNT_CANDIDATE_PEERS_PER_HASH,
1061                "{hash} has too many candidates"
1062            );
1063            let mut unique = entry.candidates.iter().map(|c| c.peer).collect::<Vec<_>>();
1064            unique.sort_unstable();
1065            unique.dedup();
1066            assert_eq!(unique.len(), entry.candidates.len(), "{hash} has duplicate candidates");
1067            assert!(ordered.contains(hash), "{hash} is missing from the eviction order");
1068            if let Some((peer, request_id)) = entry.fetching_by {
1069                assert!(
1070                    self.inflight.iter().any(|request| request.peer == peer &&
1071                        request.request_id == request_id &&
1072                        request.hashes.contains(hash)),
1073                    "fetching hash has no matching request"
1074                );
1075            }
1076            assert!(entry.attempts <= MAX_FETCH_ATTEMPTS_PER_HASH);
1077        }
1078
1079        // a hash flagged as queued is in the peer's queue, and a pending hash is queued for at
1080        // least one connected candidate, otherwise it could starve
1081        let queued = self
1082            .peers
1083            .iter()
1084            .map(|(key, peer)| {
1085                assert!(
1086                    peer.queue.len() <= 2 * self.config.max_announced_hashes_per_peer as usize,
1087                    "queue of {:#} grew beyond its bound",
1088                    peer.peer_id
1089                );
1090                (
1091                    *key,
1092                    peer.queue
1093                        .iter()
1094                        .filter(|(hash, generation)| {
1095                            self.hashes
1096                                .get(hash)
1097                                .is_some_and(|entry| entry.generation == *generation)
1098                        })
1099                        .map(|(hash, _)| *hash)
1100                        .collect::<B256Set>(),
1101                )
1102            })
1103            .collect::<HashMap<_, _>>();
1104        for (hash, entry) in &self.hashes {
1105            let mut fetchable = entry.fetching_by.is_some();
1106            for candidate in &entry.candidates {
1107                let queue =
1108                    queued.get(&candidate.peer).expect("candidate refers to a disconnected peer");
1109                if candidate.is_queued() {
1110                    assert!(
1111                        queue.contains(hash),
1112                        "{hash} is flagged but not queued for {:?}",
1113                        candidate.peer
1114                    );
1115                    fetchable = true;
1116                }
1117            }
1118            assert!(fetchable, "pending {hash} is not queued for any connected candidate");
1119        }
1120
1121        for (key, peer) in &self.peers {
1122            assert_eq!(
1123                peer.inflight as usize,
1124                self.inflight.iter().filter(|request| request.peer == *key).count()
1125            );
1126            assert!(peer.inflight <= self.config.max_inflight_requests_per_peer);
1127            if peer.inflight < self.config.max_inflight_requests_per_peer &&
1128                peer.queue.iter().any(|(hash, generation)| {
1129                    self.hashes.get(hash).is_some_and(|entry| {
1130                        entry.generation == *generation &&
1131                            entry.fetching_by.is_none() &&
1132                            entry
1133                                .candidates
1134                                .iter()
1135                                .any(|candidate| candidate.peer == *key && candidate.is_queued())
1136                    })
1137                })
1138            {
1139                assert!(peer.ready, "idle peer has queued work but is not ready");
1140            }
1141            let tracked = self.hashes.values().filter(|entry| entry.has_candidate(*key)).count();
1142            assert_eq!(tracked, peer.tracked, "tracked counter of {:#} out of sync", peer.peer_id);
1143            assert!(
1144                peer.tracked <= self.config.max_announced_hashes_per_peer as usize,
1145                "{:#} exceeds the per peer limit",
1146                peer.peer_id
1147            );
1148            assert_eq!(
1149                peer.ready,
1150                self.ready.contains(key),
1151                "ready flag of {:#} out of sync",
1152                peer.peer_id
1153            );
1154            if peer.ready {
1155                assert!(
1156                    !peer.queue.is_empty(),
1157                    "{:#} is ready without queued hashes",
1158                    peer.peer_id
1159                );
1160                assert!(
1161                    peer.inflight < self.config.max_inflight_requests_per_peer,
1162                    "{:#} is ready but busy",
1163                    peer.peer_id
1164                );
1165            }
1166            assert_eq!(
1167                self.peer_keys.get(&peer.peer_id),
1168                Some(key),
1169                "peer key mapping out of sync"
1170            );
1171        }
1172
1173        for (peer_id, key) in &self.peer_keys {
1174            assert!(self.peers.contains_key(key), "{peer_id:#} maps to an unknown key");
1175        }
1176
1177        let inflight = self.peers.values().map(|peer| peer.inflight as usize).sum::<usize>();
1178        assert!(inflight <= self.inflight.len(), "peers claim more inflight requests than exist");
1179    }
1180}
1181
1182impl<N: NetworkPrimitives> Default for TransactionFetcher<N> {
1183    fn default() -> Self {
1184        Self::new(TransactionFetcherConfig::default())
1185    }
1186}
1187
1188impl<N: NetworkPrimitives> Stream for TransactionFetcher<N> {
1189    type Item = FetchEvent<N::PooledTransaction>;
1190
1191    /// Advances all inflight requests and yields the next resolved request as an event.
1192    ///
1193    /// Never terminates, returns [`Poll::Pending`] while no request is inflight.
1194    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1195        // `FuturesUnordered` yields `None` while empty but keeps working once new requests are
1196        // pushed, so this is mapped to pending
1197        match self.inflight.poll_next_unpin(cx) {
1198            Poll::Ready(Some(resolved)) => Poll::Ready(Some(self.on_resolved(resolved))),
1199            Poll::Ready(None) | Poll::Pending => Poll::Pending,
1200        }
1201    }
1202}
1203
1204/// Represents possible events from fetching transactions.
1205#[derive(Debug)]
1206pub enum FetchEvent<T = PooledTransaction> {
1207    /// Triggered when transactions are successfully fetched.
1208    TransactionsFetched {
1209        /// The ID of the peer from which transactions were fetched.
1210        peer_id: PeerId,
1211        /// The negotiated protocol of the session that served the response.
1212        version: EthVersion,
1213        /// The client version of the session that served the response.
1214        client_version: Arc<str>,
1215        /// The transactions that were fetched, if available.
1216        transactions: PooledTransactions<T>,
1217        /// Whether the peer should be penalized for sending unsolicited transactions or for
1218        /// misbehavior.
1219        report_peer: bool,
1220    },
1221    /// Triggered when there is an error in fetching transactions.
1222    FetchError {
1223        /// The ID of the peer from which an attempt to fetch transactions resulted in an error.
1224        peer_id: PeerId,
1225        /// The specific error that occurred while fetching.
1226        error: RequestError,
1227    },
1228    /// An empty response was received.
1229    EmptyResponse {
1230        /// The ID of the sender.
1231        peer_id: PeerId,
1232    },
1233    /// The response held a transaction whose type or size differs from what the peer announced,
1234    /// so none of it is imported and the requested hashes are retried with other peers.
1235    AnnouncementMismatch {
1236        /// The ID of the peer that sent the response.
1237        peer_id: PeerId,
1238    },
1239}
1240
1241/// Compact identifier of a peer within the fetcher.
1242#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1243struct PeerKey(u32);
1244
1245/// Cached eviction work for one announcement. Other peers can only lose candidates; newly
1246/// tracked hashes from this announcer are handled by the announcement's scratch cursor.
1247#[derive(Debug)]
1248struct EvictionState {
1249    peers: BinaryHeap<(usize, PeerKey)>,
1250    exclusive: HashMap<PeerKey, VecDeque<(TxHash, u64)>>,
1251}
1252
1253/// Position for newly queued hashes or ready peers.
1254#[derive(Debug, Clone, Copy)]
1255enum QueuePosition {
1256    Front,
1257    Back,
1258}
1259
1260/// Batches consecutive removals from the same candidate peer during an announcement.
1261#[derive(Debug, Default)]
1262struct DeferredCandidateRemovals {
1263    pending: Option<(PeerKey, usize)>,
1264}
1265
1266impl DeferredCandidateRemovals {
1267    fn record_removed(&mut self, key: PeerKey, peers: &mut HashMap<PeerKey, PeerState>) {
1268        if let Some((pending_key, count)) = &mut self.pending &&
1269            *pending_key == key
1270        {
1271            *count += 1;
1272        } else {
1273            self.flush(peers);
1274            self.pending = Some((key, 1));
1275        }
1276    }
1277
1278    /// Synchronizes tracked counts before capacity eviction or the end of an announcement.
1279    fn flush(&mut self, peers: &mut HashMap<PeerKey, PeerState>) {
1280        if let Some((key, count)) = self.pending.take() {
1281            peers.get_mut(&key).expect("candidate peer is connected").tracked -= count;
1282        }
1283    }
1284}
1285
1286/// State of a tracked hash.
1287#[derive(Debug)]
1288struct TxEntry {
1289    /// Peers that announced the hash and may be asked for it, oldest first.
1290    candidates: SmallVec<[Candidate; MAX_COUNT_CANDIDATE_PEERS_PER_HASH]>,
1291    /// Identity of this tracking lifetime, also stored in lazy queue entries.
1292    generation: u64,
1293    /// The peer and request currently fetching the transaction, if any.
1294    fetching_by: Option<(PeerKey, u64)>,
1295    /// Sent requests for this entry, bounded independently of candidate replacement.
1296    attempts: usize,
1297    /// Peers dropped as candidates after failing to deliver the hash, whose announcements of it
1298    /// are ignored. Bounded by `attempts`, since each failed request adds at most one peer.
1299    failed: SmallVec<[PeerKey; 2]>,
1300}
1301
1302impl TxEntry {
1303    /// A new entry for a hash that is queued for the announcing peer.
1304    fn new(peer: PeerKey, metadata: Option<TransactionMetadata>, generation: u64) -> Self {
1305        let mut candidates = SmallVec::new();
1306        candidates.push(Candidate::queued(peer, metadata));
1307        Self { candidates, generation, fetching_by: None, attempts: 0, failed: SmallVec::new() }
1308    }
1309
1310    fn has_candidate(&self, key: PeerKey) -> bool {
1311        self.candidates.iter().any(|candidate| candidate.peer == key)
1312    }
1313
1314    /// Returns the candidates that don't have the hash queued, in the order they announced it.
1315    fn unqueued_candidates(&self) -> SmallVec<[PeerKey; MAX_COUNT_CANDIDATE_PEERS_PER_HASH]> {
1316        self.candidates
1317            .iter()
1318            .filter(|candidate| !candidate.is_queued())
1319            .map(|candidate| candidate.peer)
1320            .collect()
1321    }
1322
1323    fn candidate_mut(&mut self, key: PeerKey) -> Option<&mut Candidate> {
1324        self.candidates.iter_mut().find(|candidate| candidate.peer == key)
1325    }
1326}
1327
1328/// A peer that announced a hash.
1329#[derive(Debug, Clone, Copy)]
1330struct Candidate {
1331    peer: PeerKey,
1332    // The exact announced transaction size, or zero if the announcement carried no metadata.
1333    size: usize,
1334    // The announced transaction type, if the announcement carried metadata.
1335    tx_type: Option<u8>,
1336    // Whether the hash is in the peer's queue.
1337    queued: bool,
1338}
1339
1340impl Candidate {
1341    // Bytes an announced size may be off by, to tolerate encoding differences between clients.
1342    const SIZE_TOLERANCE: usize = 8;
1343
1344    /// A candidate that has the hash queued.
1345    const fn queued(peer: PeerKey, metadata: Option<TransactionMetadata>) -> Self {
1346        let mut candidate = Self::unqueued(peer, metadata);
1347        candidate.queued = true;
1348        candidate
1349    }
1350
1351    /// A candidate that doesn't have the hash queued.
1352    const fn unqueued(peer: PeerKey, metadata: Option<TransactionMetadata>) -> Self {
1353        let mut candidate = Self { peer, size: 0, tx_type: None, queued: false };
1354        candidate.set_metadata(metadata);
1355        candidate
1356    }
1357
1358    const fn is_queued(&self) -> bool {
1359        self.queued
1360    }
1361
1362    const fn set_metadata(&mut self, metadata: Option<TransactionMetadata>) {
1363        if let Some(TransactionMetadata { tx_type, size }) = metadata {
1364            self.size = size;
1365            self.tx_type = Some(tx_type);
1366        } else {
1367            self.size = 0;
1368            self.tx_type = None;
1369        }
1370    }
1371
1372    /// Returns the size to account for when packing the hash into a request to this peer.
1373    fn request_size(&self) -> usize {
1374        if self.size == 0 {
1375            AVERAGE_BYTE_SIZE_TX_ENCODED
1376        } else {
1377            self.size.min(SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE)
1378        }
1379    }
1380
1381    // Returns `false` if `tx` differs from the announced type or size. eth/72 peers announce and
1382    // serve blob transactions without their blobs, so both sizes are of the same encoding.
1383    fn matches<T: SignedTransaction>(&self, tx: &T) -> bool {
1384        self.tx_type.is_none_or(|tx_type| {
1385            tx_type == tx.ty() && self.size.abs_diff(tx.encode_2718_len()) <= Self::SIZE_TOLERANCE
1386        })
1387    }
1388}
1389
1390/// Fetch state of a peer.
1391#[derive(Debug)]
1392struct PeerState {
1393    peer_id: PeerId,
1394    /// Hashes the peer announced, oldest first. Entries are removed lazily, so the queue may
1395    /// contain hashes that are not tracked anymore or that the peer is no longer a candidate for.
1396    queue: VecDeque<(TxHash, u64)>,
1397    /// Number of tracked hashes that list this peer as a candidate.
1398    tracked: usize,
1399    /// Number of inflight requests to this peer.
1400    inflight: u8,
1401    /// Whether the peer is queued in the ready list.
1402    ready: bool,
1403}
1404
1405impl PeerState {
1406    const fn new(peer_id: PeerId) -> Self {
1407        Self { peer_id, queue: VecDeque::new(), tracked: 0, inflight: 0, ready: false }
1408    }
1409
1410    /// Queues the hash at the back or the front of the queue.
1411    ///
1412    /// Queues are bounded: once a queue holds twice `max_tracked` hashes, entries the peer is no
1413    /// longer a candidate for and duplicates are removed. A duplicate can occur when a hash is
1414    /// tracked again after it was delivered or evicted, while its old entry still lingers in the
1415    /// queue. Generations prevent those stale entries from selecting a newer tracking lifetime.
1416    fn push_queue(
1417        &mut self,
1418        hashes: &B256Map<TxEntry>,
1419        key: PeerKey,
1420        queued: (TxHash, u64),
1421        position: QueuePosition,
1422        max_tracked: usize,
1423    ) {
1424        if self.queue.len() >= 2 * max_tracked {
1425            let mut seen = B256Set::with_capacity_and_hasher(self.tracked, Default::default());
1426            self.queue.retain(|(hash, generation)| {
1427                hashes.get(hash).is_some_and(|entry| {
1428                    entry.generation == *generation && entry.has_candidate(key)
1429                }) && seen.insert(*hash)
1430            });
1431        }
1432        match position {
1433            QueuePosition::Front => self.queue.push_front(queued),
1434            QueuePosition::Back => self.queue.push_back(queued),
1435        }
1436    }
1437}
1438
1439/// An inflight `GetPooledTransactions` request.
1440#[derive(Debug)]
1441struct InflightRequest<T> {
1442    peer: PeerKey,
1443    request_id: u64,
1444    peer_id: PeerId,
1445    version: EthVersion,
1446    client_version: Arc<str>,
1447    /// The requested hashes, in request order.
1448    hashes: Vec<TxHash>,
1449    // What the peer announced for each requested hash, kept so the response is checked even if
1450    // the peer disconnects or announces again before it resolves.
1451    announced: Vec<Candidate>,
1452    response: oneshot::Receiver<RequestResult<PooledTransactions<T>>>,
1453}
1454
1455impl<T> Future for InflightRequest<T> {
1456    type Output = ResolvedRequest<T>;
1457
1458    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1459        let this = self.get_mut();
1460        let result =
1461            ready!(this.response.poll_unpin(cx)).unwrap_or(Err(RequestError::ChannelClosed));
1462        Poll::Ready(ResolvedRequest {
1463            peer: this.peer,
1464            request_id: this.request_id,
1465            peer_id: this.peer_id,
1466            version: this.version,
1467            client_version: this.client_version.clone(),
1468            hashes: std::mem::take(&mut this.hashes),
1469            announced: std::mem::take(&mut this.announced),
1470            result,
1471        })
1472    }
1473}
1474
1475/// A resolved `GetPooledTransactions` request.
1476#[derive(Debug)]
1477struct ResolvedRequest<T> {
1478    peer: PeerKey,
1479    request_id: u64,
1480    peer_id: PeerId,
1481    version: EthVersion,
1482    client_version: Arc<str>,
1483    hashes: Vec<TxHash>,
1484    announced: Vec<Candidate>,
1485    result: RequestResult<PooledTransactions<T>>,
1486}
1487
1488// What `TransactionFetcher::check_response` found in a response.
1489#[derive(Debug, Clone, Copy)]
1490struct ResponseCheck {
1491    // Number of transactions that weren't requested and were dropped.
1492    unsolicited: usize,
1493    // Whether a requested transaction differs from what its peer announced.
1494    mismatched: bool,
1495}
1496
1497/// Filters a response down to the transactions that were requested, dropping duplicates.
1498///
1499/// Records the delivered hashes in `delivered`, and reports the unsolicited transactions dropped
1500/// and whether a requested transaction differs from the type or size its peer announced.
1501fn verify_response<T: SignedTransaction>(
1502    transactions: &mut PooledTransactions<T>,
1503    requested: &B256Map<Candidate>,
1504    delivered: &mut B256Set,
1505) -> ResponseCheck {
1506    let mut check = ResponseCheck { unsolicited: 0, mismatched: false };
1507    transactions.0.retain(|tx| {
1508        let hash = *tx.tx_hash();
1509        let Some(candidate) = requested.get(&hash) else {
1510            check.unsolicited += 1;
1511            return false
1512        };
1513        // Checked before duplicates are dropped, so every copy must match the announcement.
1514        check.mismatched |= !candidate.matches(tx);
1515        delivered.insert(hash)
1516    });
1517    check
1518}
1519
1520#[cfg(test)]
1521mod tests {
1522    use super::*;
1523    use crate::test_utils::transactions::new_mock_session_with_capacity;
1524    use alloy_consensus::{
1525        constants::{EIP1559_TX_TYPE_ID, EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID},
1526        transaction::{Recovered, TxEip4844WithSidecar},
1527        SignableTransaction, TxEip1559, TxEip4844,
1528    };
1529    use alloy_eips::{
1530        eip2718::Encodable2718,
1531        eip4844::{Blob, Bytes48},
1532        eip7594::{BlobTransactionSidecarEip7594, CELLS_PER_EXT_BLOB},
1533    };
1534    use alloy_primitives::{Bytes, Signature, B256};
1535    use futures::task::noop_waker_ref;
1536    use rand::{rngs::StdRng, seq::IndexedRandom, Rng, SeedableRng};
1537    use reth_eth_wire::EthVersion;
1538    use reth_ethereum_primitives::{PooledTransactionVariant, TransactionSigned};
1539    use reth_transaction_pool::{
1540        test_utils::MockTransactionFactory, EthPooledTransaction, PoolTransaction,
1541    };
1542    use tokio::sync::mpsc;
1543
1544    type Fetcher = TransactionFetcher<EthNetworkPrimitives>;
1545    type ResponseSender =
1546        oneshot::Sender<RequestResult<PooledTransactions<PooledTransactionVariant>>>;
1547
1548    const KIB: usize = 1024;
1549
1550    fn peer(n: u8) -> PeerId {
1551        PeerId::repeat_byte(n)
1552    }
1553
1554    fn hash(n: u64) -> TxHash {
1555        let mut bytes = [0u8; 32];
1556        bytes[24..].copy_from_slice(&n.to_be_bytes());
1557        B256::from(bytes)
1558    }
1559
1560    fn hashes(range: std::ops::Range<u64>) -> Vec<TxHash> {
1561        range.map(hash).collect()
1562    }
1563
1564    fn pooled_txs(count: usize) -> Vec<PooledTransactionVariant> {
1565        let mut factory = MockTransactionFactory::default();
1566        (0..count)
1567            .map(|_| {
1568                let recovered: Recovered<TransactionSigned> =
1569                    factory.create_eip1559().transaction.into();
1570                PooledTransactionVariant::try_from(recovered.into_inner())
1571                    .expect("eip1559 transaction converts to pooled transaction")
1572            })
1573            .collect()
1574    }
1575
1576    fn hashes_of(txs: &[PooledTransactionVariant]) -> Vec<TxHash> {
1577        txs.iter().map(|tx| *tx.tx_hash()).collect()
1578    }
1579
1580    /// A fetcher with mock peer sessions.
1581    struct Rig {
1582        fetcher: Fetcher,
1583        peers: HashMap<PeerId, PeerMetadata<EthNetworkPrimitives>, FbBuildHasher<64>>,
1584        sessions: HashMap<PeerId, mpsc::Receiver<PeerRequest>, FbBuildHasher<64>>,
1585    }
1586
1587    impl Rig {
1588        fn new() -> Self {
1589            Self::with_config(TransactionFetcherConfig::default())
1590        }
1591
1592        fn with_config(config: TransactionFetcherConfig) -> Self {
1593            Self {
1594                fetcher: Fetcher::new(config),
1595                peers: Default::default(),
1596                sessions: Default::default(),
1597            }
1598        }
1599
1600        fn verify(&self) {
1601            self.fetcher.assert_invariants();
1602        }
1603
1604        fn add_peer(&mut self, peer_id: PeerId) {
1605            self.add_peer_with_capacity(peer_id, 8);
1606        }
1607
1608        fn add_peer_with_capacity(&mut self, peer_id: PeerId, capacity: usize) {
1609            let (peer, rx) = new_mock_session_with_capacity(peer_id, EthVersion::Eth68, capacity);
1610            self.peers.insert(peer_id, peer);
1611            self.sessions.insert(peer_id, rx);
1612        }
1613
1614        // Announces without metadata, so requests are packed with the 512-byte estimate and
1615        // responses aren't checked against an announced type or size.
1616        fn announce(&mut self, peer_id: PeerId, hashes: &[TxHash]) {
1617            self.fetcher.on_announcement(
1618                peer_id,
1619                hashes.iter().map(|&hash| AnnouncedTransaction { hash, metadata: None }),
1620            );
1621            self.verify();
1622        }
1623
1624        fn announce_with_sizes(
1625            &mut self,
1626            peer_id: PeerId,
1627            entries: impl IntoIterator<Item = (TxHash, usize)>,
1628        ) {
1629            self.fetcher.on_announcement(
1630                peer_id,
1631                entries.into_iter().map(|(hash, size)| AnnouncedTransaction {
1632                    hash,
1633                    metadata: Some(TransactionMetadata { tx_type: EIP1559_TX_TYPE_ID, size }),
1634                }),
1635            );
1636            self.verify();
1637        }
1638
1639        fn dispatch(&mut self) -> usize {
1640            self.dispatch_with_budget(usize::MAX)
1641        }
1642
1643        fn dispatch_with_budget(&mut self, max_hashes_per_request: usize) -> usize {
1644            let sent = self.fetcher.dispatch(&self.peers, max_hashes_per_request);
1645            self.verify();
1646            sent
1647        }
1648
1649        /// Takes the next request the peer's session received.
1650        fn take_request(&mut self, peer_id: PeerId) -> Option<(Vec<TxHash>, ResponseSender)> {
1651            match self.sessions.get_mut(&peer_id)?.try_recv().ok()? {
1652                PeerRequest::GetPooledTransactions { request, response } => {
1653                    Some((request.0, response))
1654                }
1655                _ => unreachable!("the fetcher only sends `GetPooledTransactions` requests"),
1656            }
1657        }
1658
1659        fn next_event(&mut self) -> Option<FetchEvent<PooledTransactionVariant>> {
1660            let mut cx = Context::from_waker(noop_waker_ref());
1661            let event = match self.fetcher.poll_next_unpin(&mut cx) {
1662                Poll::Ready(event) => event,
1663                Poll::Pending => None,
1664            };
1665            self.verify();
1666            event
1667        }
1668
1669        fn drain_events(&mut self) -> Vec<FetchEvent<PooledTransactionVariant>> {
1670            std::iter::from_fn(|| self.next_event()).collect()
1671        }
1672
1673        fn respond(
1674            &mut self,
1675            peer_id: PeerId,
1676            txs: Vec<PooledTransactionVariant>,
1677        ) -> FetchEvent<PooledTransactionVariant> {
1678            let (_, response) = self.take_request(peer_id).expect("request inflight");
1679            response.send(Ok(PooledTransactions(txs))).unwrap();
1680            self.next_event().expect("response yields an event")
1681        }
1682
1683        fn fail(
1684            &mut self,
1685            peer_id: PeerId,
1686            error: RequestError,
1687        ) -> FetchEvent<PooledTransactionVariant> {
1688            let (_, response) = self.take_request(peer_id).expect("request inflight");
1689            response.send(Err(error)).unwrap();
1690            self.next_event().expect("error yields an event")
1691        }
1692
1693        fn disconnect(&mut self, peer_id: PeerId) {
1694            self.peers.remove(&peer_id);
1695            self.sessions.remove(&peer_id);
1696            self.fetcher.on_peer_disconnected(&peer_id);
1697            self.verify();
1698        }
1699    }
1700
1701    #[test]
1702    fn announced_hashes_are_requested_from_announcing_peer() {
1703        let mut rig = Rig::new();
1704        let peer_a = peer(1);
1705        rig.add_peer(peer_a);
1706        let mut txs = pooled_txs(2);
1707        txs.sort_unstable_by_key(|tx| std::cmp::Reverse(*tx.tx_hash()));
1708        let hashes = hashes_of(&txs);
1709
1710        let mut cx = Context::from_waker(noop_waker_ref());
1711        assert!(rig.fetcher.poll_next_unpin(&mut cx).is_pending());
1712        rig.announce(peer_a, &hashes[..1]);
1713        rig.announce(peer_a, &hashes[1..]);
1714        // The latest metadata is kept, and sizes off by up to the tolerance are accepted.
1715        rig.announce_with_sizes(
1716            peer_a,
1717            [
1718                (hashes[0], txs[0].encode_2718_len()),
1719                (hashes[1], txs[1].encode_2718_len() + Candidate::SIZE_TOLERANCE),
1720            ],
1721        );
1722        assert_eq!(rig.fetcher.queued_hashes(&peer_a), hashes);
1723        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_a]);
1724        assert_eq!(rig.fetcher.num_pending_hashes(), 2);
1725        assert!(rig.fetcher.is_idle(&peer_a));
1726
1727        assert_eq!(rig.dispatch(), 1);
1728        assert!(!rig.fetcher.is_idle(&peer_a));
1729        assert_eq!(rig.fetcher.num_inflight_requests(), 1);
1730        assert_eq!(rig.fetcher.num_fetching_hashes(), 2);
1731        assert_eq!(rig.fetcher.num_pending_hashes(), 0);
1732        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_a));
1733
1734        let (requested, response) = rig.take_request(peer_a).unwrap();
1735        assert_eq!(requested, hashes);
1736        response.send(Ok(PooledTransactions(txs.clone()))).unwrap();
1737
1738        let FetchEvent::TransactionsFetched { peer_id, transactions, report_peer, .. } =
1739            rig.next_event().unwrap()
1740        else {
1741            panic!("expected fetched transactions")
1742        };
1743        assert_eq!(peer_id, peer_a);
1744        assert_eq!(transactions.len(), 2);
1745        assert!(!report_peer);
1746
1747        assert_eq!(rig.fetcher.num_hashes(), 0);
1748        assert_eq!(rig.fetcher.num_inflight_requests(), 0);
1749        assert!(rig.fetcher.is_idle(&peer_a));
1750        assert!(rig.fetcher.poll_next_unpin(&mut cx).is_pending());
1751    }
1752
1753    #[test]
1754    fn request_is_capped_by_hash_count() {
1755        let mut rig = Rig::new();
1756        let peer_a = peer(1);
1757        rig.add_peer(peer_a);
1758        let hashes = hashes(0..300);
1759
1760        // no size metadata, so the count limit is what bounds the request
1761        rig.announce(peer_a, &hashes);
1762        assert_eq!(rig.dispatch(), 1);
1763
1764        let (requested, response) = rig.take_request(peer_a).unwrap();
1765        assert_eq!(requested.len(), SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST);
1766        assert_eq!(requested, hashes[..256]);
1767        assert_eq!(rig.fetcher.num_pending_hashes(), 44);
1768
1769        // the peer is busy until the request resolves
1770        assert_eq!(rig.dispatch(), 0);
1771        response.send(Err(RequestError::BadResponse)).unwrap();
1772        rig.next_event().unwrap();
1773        assert_eq!(rig.fetcher.num_pending_hashes(), 44);
1774
1775        assert_eq!(rig.dispatch(), 1);
1776        let (requested, _) = rig.take_request(peer_a).unwrap();
1777        assert_eq!(requested, hashes[256..]);
1778    }
1779
1780    #[test]
1781    fn request_is_capped_by_expected_response_size() {
1782        let mut rig = Rig::new();
1783        let peer_a = peer(1);
1784        rig.add_peer(peer_a);
1785        let hashes = hashes(0..3);
1786
1787        rig.announce_with_sizes(
1788            peer_a,
1789            [(hashes[0], 100 * KIB), (hashes[1], 100 * KIB), (hashes[2], 100)],
1790        );
1791
1792        rig.dispatch();
1793        let (requested, response) = rig.take_request(peer_a).unwrap();
1794        assert_eq!(requested, hashes[..1], "second transaction doesn't fit in 128 KiB");
1795
1796        response.send(Ok(PooledTransactions(vec![]))).unwrap();
1797        rig.next_event().unwrap();
1798        // the empty response dropped the peer as candidate for the first hash
1799        assert_eq!(rig.fetcher.num_hashes(), 2);
1800
1801        rig.dispatch();
1802        let (requested, _) = rig.take_request(peer_a).unwrap();
1803        assert_eq!(requested, hashes[1..]);
1804    }
1805
1806    #[test]
1807    fn announced_size_is_per_peer() {
1808        let mut rig = Rig::new();
1809        let peer_a = peer(1);
1810        let peer_b = peer(2);
1811        rig.add_peer(peer_a);
1812        rig.add_peer(peer_b);
1813        let hashes = hashes(0..2);
1814
1815        // peer_a doesn't know the sizes, peer_b announces a huge first transaction
1816        rig.announce(peer_a, &hashes);
1817        rig.announce_with_sizes(peer_b, [(hashes[0], 1024 * KIB), (hashes[1], 100)]);
1818
1819        // peer_a's request is packed with the size estimate
1820        rig.dispatch();
1821        let (requested, response) = rig.take_request(peer_a).unwrap();
1822        assert_eq!(requested, hashes);
1823        response.send(Ok(PooledTransactions(vec![]))).unwrap();
1824        rig.next_event().unwrap();
1825
1826        // peer_b's request honors the size it announced
1827        rig.dispatch();
1828        let (requested, _) = rig.take_request(peer_b).unwrap();
1829        assert_eq!(requested, hashes[..1]);
1830    }
1831
1832    #[test]
1833    fn announced_sizes_are_capped() {
1834        let mut rig = Rig::new();
1835        let peer_a = peer(1);
1836        rig.add_peer(peer_a);
1837        let hashes = hashes(0..3);
1838
1839        // absurd sizes must not break the size accounting
1840        rig.announce_with_sizes(
1841            peer_a,
1842            [(hashes[0], usize::MAX - 1), (hashes[1], usize::MAX), (hashes[2], 100)],
1843        );
1844
1845        rig.dispatch();
1846        let (requested, response) = rig.take_request(peer_a).unwrap();
1847        assert_eq!(requested, hashes[..1], "an oversized transaction is requested alone");
1848        response.send(Err(RequestError::BadResponse)).unwrap();
1849        rig.next_event().unwrap();
1850
1851        rig.dispatch();
1852        let (requested, _) = rig.take_request(peer_a).unwrap();
1853        assert_eq!(requested, hashes[1..2]);
1854
1855        let metadata = TransactionMetadata { tx_type: EIP4844_TX_TYPE_ID, size: usize::MAX };
1856        let candidate = Candidate::queued(PeerKey(0), Some(metadata));
1857        assert_eq!(
1858            (candidate.tx_type, candidate.size, candidate.is_queued()),
1859            (Some(EIP4844_TX_TYPE_ID), usize::MAX, true)
1860        );
1861        assert_eq!(candidate.request_size(), SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE);
1862    }
1863
1864    #[test]
1865    fn hash_is_fetched_from_one_peer_at_a_time() {
1866        let mut rig = Rig::new();
1867        let peer_a = peer(1);
1868        let peer_b = peer(2);
1869        rig.add_peer(peer_a);
1870        rig.add_peer(peer_b);
1871        let txs = pooled_txs(1);
1872        let hashes = hashes_of(&txs);
1873
1874        rig.announce(peer_a, &hashes);
1875        rig.announce(peer_b, &hashes);
1876        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_a, peer_b]);
1877
1878        assert_eq!(rig.dispatch(), 1);
1879        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_a));
1880        assert!(rig.take_request(peer_b).is_none());
1881        // peer_b's queue entry was consumed without a request
1882        assert!(rig.fetcher.queued_hashes(&peer_b).is_empty());
1883        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_a, peer_b]);
1884
1885        rig.respond(peer_a, txs);
1886        assert_eq!(rig.fetcher.num_hashes(), 0);
1887        assert_eq!(rig.dispatch(), 0);
1888    }
1889
1890    #[test]
1891    fn failed_request_is_retried_with_alternate_peer() {
1892        let mut rig = Rig::new();
1893        let peer_a = peer(1);
1894        let peer_b = peer(2);
1895        rig.add_peer(peer_a);
1896        rig.add_peer(peer_b);
1897        let txs = pooled_txs(2);
1898        let hashes = hashes_of(&txs);
1899
1900        rig.announce(peer_a, &hashes);
1901        rig.announce(peer_b, &hashes);
1902        rig.dispatch();
1903        // peer_b skipped the hashes while they were inflight to peer_a
1904        assert!(rig.fetcher.queued_hashes(&peer_b).is_empty());
1905
1906        let FetchEvent::FetchError { peer_id, error } = rig.fail(peer_a, RequestError::Timeout)
1907        else {
1908            panic!("expected fetch error")
1909        };
1910        assert_eq!(peer_id, peer_a);
1911        assert!(matches!(error, RequestError::Timeout));
1912
1913        // the hashes are pending again for peer_b only and queued in request order
1914        assert_eq!(rig.fetcher.num_pending_hashes(), 2);
1915        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_b]);
1916        assert_eq!(rig.fetcher.queued_hashes(&peer_b), hashes);
1917
1918        assert_eq!(rig.dispatch(), 1);
1919        assert!(rig.take_request(peer_a).is_none());
1920        let event = rig.respond(peer_b, txs);
1921        assert!(
1922            matches!(event, FetchEvent::TransactionsFetched { peer_id, .. } if peer_id == peer_b)
1923        );
1924        assert_eq!(rig.fetcher.num_hashes(), 0);
1925    }
1926
1927    #[test]
1928    fn empty_response_drops_peer_as_candidate() {
1929        let mut rig = Rig::new();
1930        let peer_a = peer(1);
1931        rig.add_peer(peer_a);
1932        let hashes = hashes(0..2);
1933
1934        rig.announce(peer_a, &hashes);
1935        rig.dispatch();
1936        let event = rig.respond(peer_a, vec![]);
1937        assert!(matches!(event, FetchEvent::EmptyResponse { peer_id } if peer_id == peer_a));
1938
1939        // no other peer announced the hashes, so they are dropped
1940        assert_eq!(rig.fetcher.num_hashes(), 0);
1941        assert_eq!(rig.dispatch(), 0);
1942    }
1943
1944    #[test]
1945    fn reannouncing_failed_peers_do_not_overtake_untried_candidates() {
1946        let mut rig = Rig::new();
1947        let (peer_a, peer_b, honest) = (peer(1), peer(2), peer(3));
1948        let txs = pooled_txs(1);
1949        let h = hashes_of(&txs)[0];
1950        rig.add_peer(peer_a);
1951        rig.add_peer(honest);
1952        rig.add_peer(peer_b);
1953
1954        rig.announce(peer_a, &[h]);
1955        rig.dispatch();
1956        rig.announce(honest, &[h]);
1957        rig.dispatch();
1958        rig.announce(peer_b, &[h]);
1959        rig.dispatch();
1960
1961        // the failing peers take turns re-announcing the hash and answering empty
1962        let (mut failing, mut other) = (peer_a, peer_b);
1963        for _ in 0..MAX_FETCH_ATTEMPTS_PER_HASH {
1964            if rig.fetcher.fetching_peer(&h) == Some(honest) {
1965                break
1966            }
1967            rig.respond(failing, vec![]);
1968            rig.dispatch();
1969            rig.announce(failing, &[h]);
1970            rig.dispatch();
1971            std::mem::swap(&mut failing, &mut other);
1972        }
1973
1974        assert_eq!(rig.fetcher.fetching_peer(&h), Some(honest));
1975        assert_eq!(rig.fetcher.candidate_peers(&h), vec![honest]);
1976        let event = rig.respond(honest, txs);
1977        assert!(
1978            matches!(event, FetchEvent::TransactionsFetched { peer_id, .. } if peer_id == honest)
1979        );
1980        assert_eq!(rig.fetcher.num_hashes(), 0);
1981    }
1982
1983    #[test]
1984    fn untried_candidate_is_asked_after_a_single_empty_response() {
1985        let mut rig = Rig::new();
1986        let (peer_a, honest) = (peer(1), peer(2));
1987        let h = hash(1);
1988        rig.add_peer(peer_a);
1989        rig.add_peer(honest);
1990
1991        rig.announce(peer_a, &[h]);
1992        rig.dispatch();
1993        rig.announce(honest, &[h]);
1994        rig.dispatch();
1995        rig.respond(peer_a, vec![]);
1996        rig.dispatch();
1997        assert_eq!(rig.fetcher.fetching_peer(&h), Some(honest));
1998    }
1999
2000    #[test]
2001    fn partial_response_keeps_peer_for_truncated_tail() {
2002        let mut rig = Rig::new();
2003        let peer_a = peer(1);
2004        rig.add_peer(peer_a);
2005        let txs = pooled_txs(4);
2006        let hashes = hashes_of(&txs);
2007
2008        rig.announce(peer_a, &hashes);
2009        rig.dispatch();
2010
2011        // the first half is delivered, the rest looks like truncation
2012        rig.respond(peer_a, txs[..2].to_vec());
2013        assert_eq!(rig.fetcher.num_pending_hashes(), 2);
2014        assert_eq!(rig.fetcher.candidate_peers(&hashes[2]), vec![peer_a]);
2015        assert_eq!(rig.fetcher.queued_hashes(&peer_a), hashes[2..]);
2016
2017        rig.dispatch();
2018        let (requested, _) = rig.take_request(peer_a).unwrap();
2019        assert_eq!(requested, hashes[2..]);
2020    }
2021
2022    #[test]
2023    fn small_partial_response_drops_peer_for_all_undelivered_hashes() {
2024        let mut rig = Rig::new();
2025        let peer_a = peer(1);
2026        let peer_b = peer(2);
2027        rig.add_peer(peer_a);
2028        rig.add_peer(peer_b);
2029        let txs = pooled_txs(10);
2030        let hashes = hashes_of(&txs);
2031
2032        rig.announce(peer_a, &hashes);
2033        rig.announce(peer_b, &hashes[..5]);
2034        rig.dispatch();
2035        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_a));
2036
2037        // Delivering fewer than half of the requested hashes drops peer_a for the rest,
2038        // limiting repeated low-progress retries regardless of transaction sizes.
2039        rig.respond(peer_a, txs[..1].to_vec());
2040        assert_eq!(rig.fetcher.num_hashes(), 4, "hashes without another candidate are dropped");
2041        for hash in &hashes[1..5] {
2042            assert_eq!(rig.fetcher.candidate_peers(hash), vec![peer_b]);
2043        }
2044        assert!(rig.fetcher.queued_hashes(&peer_a).is_empty());
2045    }
2046
2047    #[test]
2048    fn skipped_hashes_without_alternates_are_dropped() {
2049        let mut rig = Rig::new();
2050        let peer_a = peer(1);
2051        rig.add_peer(peer_a);
2052        let txs = pooled_txs(4);
2053        let hashes = hashes_of(&txs);
2054
2055        rig.announce(peer_a, &hashes);
2056        rig.dispatch();
2057        rig.respond(peer_a, txs[1..3].to_vec());
2058
2059        // the first hash was skipped and has no other candidate, the last one is retried
2060        assert_eq!(rig.fetcher.num_hashes(), 1);
2061        assert_eq!(rig.fetcher.candidate_peers(&hashes[3]), vec![peer_a]);
2062        assert!(rig.fetcher.candidate_peers(&hashes[0]).is_empty());
2063    }
2064
2065    #[test]
2066    fn unsolicited_and_duplicate_transactions_are_filtered_and_reported() {
2067        let mut rig = Rig::new();
2068        let peer_a = peer(1);
2069        rig.add_peer(peer_a);
2070        let txs = pooled_txs(2);
2071        let hashes = hashes_of(&txs);
2072
2073        rig.announce(peer_a, &hashes[..1]);
2074        rig.dispatch();
2075
2076        let FetchEvent::TransactionsFetched { transactions, report_peer, .. } =
2077            rig.respond(peer_a, vec![txs[0].clone(), txs[1].clone(), txs[0].clone()])
2078        else {
2079            panic!("expected fetched transactions")
2080        };
2081        assert!(report_peer);
2082        assert_eq!(transactions.0, txs[..1]);
2083        assert_eq!(rig.fetcher.num_hashes(), 0);
2084    }
2085
2086    #[test]
2087    fn response_with_only_unsolicited_transactions_is_a_bad_response() {
2088        let mut rig = Rig::new();
2089        let peer_a = peer(1);
2090        let peer_b = peer(2);
2091        rig.add_peer(peer_a);
2092        rig.add_peer(peer_b);
2093        let txs = pooled_txs(2);
2094        let hashes = hashes_of(&txs);
2095
2096        rig.announce(peer_a, &hashes[..1]);
2097        rig.announce(peer_b, &hashes[..1]);
2098        rig.dispatch();
2099
2100        let event = rig.respond(peer_a, txs[1..].to_vec());
2101        assert!(matches!(
2102            event,
2103            FetchEvent::FetchError { peer_id, error: RequestError::BadResponse } if peer_id == peer_a
2104        ));
2105        // treated like a failed request, peer_b gets to try
2106        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_b]);
2107        rig.dispatch();
2108        assert!(rig.take_request(peer_b).is_some());
2109    }
2110
2111    #[test]
2112    fn response_contradicting_announced_metadata_is_rejected() {
2113        let txs = pooled_txs(2);
2114        let hashes = hashes_of(&txs);
2115        let size = txs[0].encode_2718_len();
2116        let wrong_size = TransactionMetadata {
2117            tx_type: EIP1559_TX_TYPE_ID,
2118            size: size + Candidate::SIZE_TOLERANCE + 1,
2119        };
2120        let wrong_type = TransactionMetadata { tx_type: LEGACY_TX_TYPE_ID, size };
2121
2122        for metadata in [wrong_size, wrong_type] {
2123            let mut rig = Rig::new();
2124            let peer_a = peer(1);
2125            let peer_b = peer(2);
2126            rig.add_peer(peer_a);
2127            rig.add_peer(peer_b);
2128            let announced = AnnouncedTransaction { hash: hashes[0], metadata: Some(metadata) };
2129            rig.fetcher.on_announcement(peer_a, [announced]);
2130            rig.announce(peer_a, &hashes[1..]);
2131            rig.announce(peer_b, &hashes[..1]);
2132            rig.dispatch_with_budget(1);
2133            let (_, response) = rig.take_request(peer_a).unwrap();
2134            response.send(Ok(PooledTransactions(txs[..1].to_vec()))).unwrap();
2135
2136            // The response is checked against what was announced when it was requested.
2137            rig.announce_with_sizes(peer_a, [(hashes[0], size)]);
2138            let event = rig.next_event().unwrap();
2139            assert!(
2140                matches!(event, FetchEvent::AnnouncementMismatch { peer_id } if peer_id == peer_a),
2141                "{metadata:?}"
2142            );
2143            // The alternate peer can retry while the responding peer is being disconnected.
2144            assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_b]);
2145            assert!(rig.fetcher.candidate_peers(&hashes[1]).is_empty());
2146            assert_eq!(rig.dispatch(), 1);
2147            assert!(rig.take_request(peer_a).is_none());
2148        }
2149
2150        // A buffered response from a closed session leaves the peer's new session alone.
2151        let mut rig = Rig::new();
2152        let peer_a = peer(1);
2153        rig.add_peer(peer_a);
2154        rig.announce_with_sizes(peer_a, [(hashes[0], wrong_size.size)]);
2155        rig.dispatch();
2156        let (_, response) = rig.take_request(peer_a).unwrap();
2157        response.send(Ok(PooledTransactions(txs[..1].to_vec()))).unwrap();
2158        rig.disconnect(peer_a);
2159        rig.add_peer(peer_a);
2160        rig.announce(peer_a, &hashes[1..]);
2161        assert!(matches!(
2162            rig.next_event().unwrap(),
2163            FetchEvent::FetchError { peer_id, error: RequestError::BadResponse } if peer_id == peer_a
2164        ));
2165        assert_eq!(rig.fetcher.queued_hashes(&peer_a), hashes[1..]);
2166    }
2167
2168    #[test]
2169    fn oversized_response_is_checked_against_exact_announced_size() {
2170        let body = TxEip1559 { input: Bytes::from(vec![0; 4 * KIB * KIB]), ..Default::default() };
2171        let tx = PooledTransactionVariant::Eip1559(body.into_signed(Signature::test_signature()));
2172        let size = tx.encode_2718_len();
2173        let mut rig = Rig::new();
2174        let responder = peer(1);
2175        rig.add_peer(responder);
2176        rig.announce_with_sizes(responder, [(*tx.tx_hash(), size + KIB)]);
2177        assert_eq!(rig.dispatch(), 1);
2178        assert!(matches!(
2179            rig.respond(responder, vec![tx]),
2180            FetchEvent::AnnouncementMismatch { peer_id } if peer_id == responder
2181        ));
2182    }
2183
2184    #[test]
2185    fn duplicate_transactions_in_response_are_deduplicated() {
2186        let mut rig = Rig::new();
2187        let peer_a = peer(1);
2188        rig.add_peer(peer_a);
2189        let txs = pooled_txs(1);
2190
2191        rig.announce(peer_a, &hashes_of(&txs));
2192        rig.dispatch();
2193
2194        let FetchEvent::TransactionsFetched { transactions, report_peer, .. } =
2195            rig.respond(peer_a, vec![txs[0].clone(), txs[0].clone()])
2196        else {
2197            panic!("expected fetched transactions")
2198        };
2199        assert_eq!(transactions.len(), 1);
2200        assert!(!report_peer);
2201
2202        // A blob sidecar isn't covered by the hash, so a later copy must match as well.
2203        let blob_tx = |blobs: usize| {
2204            let sidecar = BlobTransactionSidecarEip7594::new(
2205                vec![Blob::default(); blobs],
2206                vec![Bytes48::default(); blobs],
2207                vec![Bytes48::default(); blobs * CELLS_PER_EXT_BLOB],
2208            );
2209            let tx = TxEip4844WithSidecar { tx: TxEip4844::default(), sidecar: sidecar.into() };
2210            PooledTransactionVariant::Eip4844(tx.into_signed(Signature::test_signature()))
2211        };
2212        let (small, large) = (blob_tx(1), blob_tx(2));
2213        assert_eq!(small.tx_hash(), large.tx_hash());
2214        let metadata =
2215            TransactionMetadata { tx_type: EIP4844_TX_TYPE_ID, size: small.encode_2718_len() };
2216        let announced = AnnouncedTransaction { hash: *small.tx_hash(), metadata: Some(metadata) };
2217        rig.fetcher.on_announcement(peer_a, [announced]);
2218        rig.dispatch();
2219        assert!(matches!(
2220            rig.respond(peer_a, vec![small, large]),
2221            FetchEvent::AnnouncementMismatch { peer_id, .. } if peer_id == peer_a
2222        ));
2223    }
2224
2225    #[test]
2226    fn announced_pool_blob_transaction_matches_its_served_body() {
2227        let sidecar = BlobTransactionSidecarEip7594::new(
2228            vec![Blob::default()],
2229            vec![Bytes48::default()],
2230            vec![Bytes48::default(); CELLS_PER_EXT_BLOB],
2231        );
2232        let tx = TxEip4844WithSidecar { tx: TxEip4844::default(), sidecar: sidecar.into() };
2233        let served = PooledTransactionVariant::Eip4844(tx.into_signed(Signature::test_signature()));
2234        // The pool announces a transaction with its cached encoded length.
2235        let pooled = EthPooledTransaction::from_pooled(Recovered::new_unchecked(
2236            served.clone(),
2237            Default::default(),
2238        ));
2239
2240        let metadata =
2241            TransactionMetadata { tx_type: EIP4844_TX_TYPE_ID, size: pooled.encoded_length() };
2242        assert!(Candidate::queued(PeerKey(0), Some(metadata)).matches(&served));
2243    }
2244
2245    #[test]
2246    fn received_transactions_stop_tracking() {
2247        let mut rig = Rig::new();
2248        let peer_a = peer(1);
2249        rig.add_peer(peer_a);
2250        let txs = pooled_txs(3);
2251        let hashes = hashes_of(&txs);
2252
2253        rig.announce(peer_a, &hashes[..2]);
2254        rig.dispatch();
2255        rig.announce(peer_a, &hashes[2..]);
2256        assert_eq!(rig.fetcher.num_fetching_hashes(), 2);
2257        assert_eq!(rig.fetcher.num_pending_hashes(), 1);
2258
2259        // one inflight and the pending hash arrive over broadcast
2260        rig.fetcher.on_transactions_received([&hashes[0], &hashes[2]]);
2261        rig.fetcher.assert_invariants();
2262        assert_eq!(rig.fetcher.num_hashes(), 1);
2263        assert_eq!(rig.fetcher.num_fetching_hashes(), 1);
2264
2265        // the response doesn't include the hash received over broadcast, which must not be
2266        // rescheduled, but includes the other one
2267        let FetchEvent::TransactionsFetched { transactions, .. } =
2268            rig.respond(peer_a, txs[1..2].to_vec())
2269        else {
2270            panic!("expected fetched transactions")
2271        };
2272        assert_eq!(transactions.len(), 1);
2273        assert_eq!(rig.fetcher.num_hashes(), 0);
2274        assert_eq!(rig.dispatch(), 0);
2275    }
2276
2277    #[test]
2278    fn response_delivering_hash_received_over_broadcast_is_still_returned() {
2279        let mut rig = Rig::new();
2280        let peer_a = peer(1);
2281        rig.add_peer(peer_a);
2282        let txs = pooled_txs(1);
2283        let hashes = hashes_of(&txs);
2284
2285        rig.announce(peer_a, &hashes);
2286        rig.dispatch();
2287        rig.fetcher.on_transactions_received(&hashes);
2288
2289        let FetchEvent::TransactionsFetched { transactions, report_peer, .. } =
2290            rig.respond(peer_a, txs)
2291        else {
2292            panic!("expected fetched transactions")
2293        };
2294        assert_eq!(transactions.len(), 1);
2295        assert!(!report_peer, "the transaction was requested, even if it arrived elsewhere first");
2296        assert_eq!(rig.fetcher.num_hashes(), 0);
2297    }
2298
2299    #[test]
2300    fn peer_disconnect_drops_hashes_without_alternates() {
2301        let mut rig = Rig::new();
2302        let peer_a = peer(1);
2303        let peer_b = peer(2);
2304        rig.add_peer(peer_a);
2305        rig.add_peer(peer_b);
2306        let hashes = hashes(0..2);
2307
2308        rig.announce(peer_a, &hashes);
2309        rig.announce(peer_b, &hashes[1..]);
2310
2311        rig.disconnect(peer_a);
2312        assert_eq!(rig.fetcher.num_hashes(), 1);
2313        assert_eq!(rig.fetcher.candidate_peers(&hashes[1]), vec![peer_b]);
2314        assert!(rig.fetcher.is_idle(&peer_a));
2315
2316        rig.dispatch();
2317        let (requested, _) = rig.take_request(peer_b).unwrap();
2318        assert_eq!(requested, hashes[1..]);
2319    }
2320
2321    #[test]
2322    fn inflight_request_of_disconnected_peer_is_rescheduled() {
2323        let mut rig = Rig::new();
2324        let peer_a = peer(1);
2325        let peer_b = peer(2);
2326        rig.add_peer(peer_a);
2327        rig.add_peer(peer_b);
2328        let txs = pooled_txs(2);
2329        let hashes = hashes_of(&txs);
2330
2331        rig.announce(peer_a, &hashes);
2332        rig.announce(peer_b, &hashes);
2333        rig.dispatch();
2334        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_a));
2335
2336        // dropping the session drops the pending request, which resolves it with an error
2337        rig.disconnect(peer_a);
2338        assert_eq!(
2339            rig.fetcher.num_fetching_hashes(),
2340            2,
2341            "hashes stay inflight until the request resolves"
2342        );
2343
2344        let event = rig.next_event().unwrap();
2345        assert!(matches!(
2346            event,
2347            FetchEvent::FetchError { peer_id, error: RequestError::ChannelClosed } if peer_id == peer_a
2348        ));
2349        assert_eq!(rig.fetcher.num_pending_hashes(), 2);
2350        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_b]);
2351
2352        rig.dispatch();
2353        let event = rig.respond(peer_b, txs);
2354        assert!(matches!(event, FetchEvent::TransactionsFetched { .. }));
2355        assert_eq!(rig.fetcher.num_hashes(), 0);
2356    }
2357
2358    #[test]
2359    fn per_peer_announcement_limit_is_enforced() {
2360        let config =
2361            TransactionFetcherConfig { max_announced_hashes_per_peer: 3, ..Default::default() };
2362        let mut rig = Rig::with_config(config);
2363        let peer_a = peer(1);
2364        let peer_b = peer(2);
2365        rig.add_peer(peer_a);
2366        rig.add_peer(peer_b);
2367        let txs = pooled_txs(5);
2368        let hashes = hashes_of(&txs);
2369
2370        rig.announce(peer_a, &hashes);
2371        assert_eq!(rig.fetcher.num_hashes(), 3);
2372        assert_eq!(rig.fetcher.queued_hashes(&peer_a), hashes[..3]);
2373
2374        // the limit is per peer, another peer can still announce the dropped hashes
2375        rig.announce(peer_b, &hashes[3..]);
2376        assert_eq!(rig.fetcher.num_hashes(), 5);
2377        assert_eq!(rig.fetcher.candidate_peers(&hashes[4]), vec![peer_b]);
2378
2379        // delivering frees up the budget of the peer
2380        rig.dispatch();
2381        rig.respond(peer_a, txs[..3].to_vec());
2382        rig.announce(peer_a, &hashes[3..]);
2383        assert_eq!(rig.fetcher.candidate_peers(&hashes[3]), vec![peer_b, peer_a]);
2384    }
2385
2386    #[test]
2387    fn global_capacity_evicts_oldest_pending_hash() {
2388        let config = TransactionFetcherConfig {
2389            max_capacity_cache_txns_pending_fetch: 2,
2390            ..Default::default()
2391        };
2392        let mut rig = Rig::with_config(config);
2393        let peer_a = peer(1);
2394        let peer_b = peer(2);
2395        rig.add_peer(peer_a);
2396        rig.add_peer(peer_b);
2397        let txs = pooled_txs(5);
2398        let hashes = hashes_of(&txs);
2399
2400        // the oldest pending hash makes room for a new one
2401        rig.announce(peer_a, &hashes[..3]);
2402        assert_eq!(rig.fetcher.num_hashes(), 2);
2403        assert!(rig.fetcher.candidate_peers(&hashes[0]).is_empty());
2404        assert_eq!(rig.fetcher.candidate_peers(&hashes[2]), vec![peer_a]);
2405
2406        // hashes that are being fetched are not evicted, the announcement is dropped instead
2407        rig.dispatch();
2408        let (requested, response) = rig.take_request(peer_a).unwrap();
2409        assert_eq!(requested, hashes[1..3]);
2410        rig.announce(peer_b, &hashes[3..4]);
2411        assert_eq!(rig.fetcher.num_hashes(), 2);
2412        assert!(rig.fetcher.candidate_peers(&hashes[3]).is_empty());
2413
2414        // the second hash is delivered, the third is pending again. Both peers then track one
2415        // hash and the announcing peer gives way, so its own older hash makes room.
2416        response.send(Ok(PooledTransactions(txs[1..2].to_vec()))).unwrap();
2417        rig.next_event().unwrap();
2418        assert_eq!(rig.fetcher.num_hashes(), 1);
2419        rig.announce(peer_b, &hashes[3..4]);
2420        assert_eq!(rig.fetcher.num_hashes(), 2);
2421        rig.announce(peer_b, &hashes[4..5]);
2422        assert_eq!(rig.fetcher.num_hashes(), 2);
2423        assert_eq!(rig.fetcher.candidate_peers(&hashes[2]), vec![peer_a]);
2424        assert!(rig.fetcher.candidate_peers(&hashes[3]).is_empty());
2425        assert_eq!(rig.fetcher.candidate_peers(&hashes[4]), vec![peer_b]);
2426    }
2427
2428    #[test]
2429    fn later_announcers_are_asked_after_the_first_ones_failed() {
2430        let mut rig = Rig::new();
2431        let batch = hashes(0..3);
2432        let hash = batch[0];
2433        let peers =
2434            (1..=MAX_COUNT_CANDIDATE_PEERS_PER_HASH as u8 + 2).map(peer).collect::<Vec<_>>();
2435        for peer_id in &peers {
2436            rig.add_peer(*peer_id);
2437            rig.announce(*peer_id, &batch);
2438        }
2439
2440        // Keep the eager sources and rotate the oldest fallback sources out for later ones.
2441        let candidates = peers[..MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH]
2442            .iter()
2443            .chain(&peers[MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH + 2..])
2444            .copied()
2445            .collect::<Vec<_>>();
2446        assert_eq!(rig.fetcher.candidate_peers(&hash), candidates);
2447        for (i, peer_id) in candidates.iter().enumerate() {
2448            let eager = i < MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH;
2449            assert_eq!(rig.fetcher.queued_hashes(peer_id).contains(&hash), eager, "peer {i}");
2450        }
2451        assert!(rig.fetcher.queued_hashes(&peers[MAX_COUNT_CANDIDATE_PEERS_PER_HASH]).is_empty());
2452
2453        // the first announcer fetches the hash, retries go to the most recent announcers first
2454        assert_eq!(rig.dispatch(), 1);
2455        assert_eq!(rig.fetcher.fetching_peer(&hash), Some(peers[0]));
2456        rig.fail(peers[0], RequestError::Timeout);
2457        assert_eq!(rig.dispatch(), 1);
2458        assert_eq!(rig.fetcher.fetching_peer(&hash), Some(*candidates.last().unwrap()));
2459
2460        // the hash is given up on once all candidates failed
2461        let mut order = vec![peers[0]];
2462        while let Some(fetching) = rig.fetcher.fetching_peer(&hash) {
2463            rig.fail(fetching, RequestError::Timeout);
2464            order.push(fetching);
2465            rig.dispatch();
2466        }
2467        let expected = std::iter::once(candidates[0])
2468            .chain(candidates[1..].iter().rev().copied())
2469            .collect::<Vec<_>>();
2470        assert_eq!(order, expected);
2471        assert_eq!(rig.fetcher.num_hashes(), 0);
2472    }
2473
2474    #[test]
2475    fn old_request_error_does_not_settle_a_new_request_to_the_same_peer() {
2476        let config =
2477            TransactionFetcherConfig { max_inflight_requests_per_peer: 2, ..Default::default() };
2478        let mut rig = Rig::with_config(config);
2479        let p = peer(1);
2480        let h = hash(1);
2481        rig.add_peer(p);
2482        rig.announce(p, &[h]);
2483        rig.dispatch();
2484        let (_, first) = rig.take_request(p).unwrap();
2485        rig.fetcher.on_transactions_received([&h]);
2486        rig.announce(p, &[h]);
2487        rig.dispatch();
2488        let (_, second) = rig.take_request(p).unwrap();
2489        first.send(Err(RequestError::Timeout)).unwrap();
2490        rig.next_event().unwrap();
2491        assert_eq!(rig.fetcher.num_fetching_hashes(), 1);
2492        assert_eq!(rig.fetcher.fetching_peer(&h), Some(p));
2493        assert_eq!(rig.fetcher.candidate_peers(&h), vec![p]);
2494        second.send(Ok(PooledTransactions(vec![]))).unwrap();
2495        rig.next_event().unwrap();
2496        assert_eq!(rig.fetcher.num_hashes(), 0);
2497    }
2498
2499    #[test]
2500    fn first_timeout_retries_the_only_source_once() {
2501        let mut rig = Rig::new();
2502        let p = peer(1);
2503        let h = hash(1);
2504        rig.add_peer(p);
2505        rig.announce(p, &[h]);
2506        rig.dispatch();
2507        rig.fail(p, RequestError::Timeout);
2508        assert_eq!(rig.fetcher.candidate_peers(&h), vec![p]);
2509        assert_eq!(rig.dispatch(), 1);
2510        rig.fail(p, RequestError::Timeout);
2511        assert_eq!(rig.fetcher.num_hashes(), 0);
2512        assert_eq!(rig.dispatch(), 0);
2513    }
2514
2515    #[test]
2516    fn replacing_candidates_cannot_extend_the_fetch_attempt_budget() {
2517        let mut rig = Rig::new();
2518        let h = hash(1);
2519        for n in 1..=MAX_COUNT_CANDIDATE_PEERS_PER_HASH as u8 {
2520            rig.add_peer(peer(n));
2521            rig.announce(peer(n), &[h]);
2522        }
2523        for n in 0..MAX_FETCH_ATTEMPTS_PER_HASH {
2524            let newcomer = peer((n + MAX_COUNT_CANDIDATE_PEERS_PER_HASH + 1) as u8);
2525            rig.add_peer(newcomer);
2526            rig.announce(newcomer, &[h]);
2527            assert_eq!(rig.dispatch(), 1);
2528            let fetching = rig.fetcher.fetching_peer(&h).unwrap();
2529            rig.fail(fetching, RequestError::Timeout);
2530        }
2531        assert_eq!(rig.fetcher.num_hashes(), 0);
2532    }
2533
2534    #[test]
2535    fn self_eviction_skips_shared_and_stale_announcement_entries() {
2536        let mut rig = Rig::with_config(TransactionFetcherConfig {
2537            max_capacity_cache_txns_pending_fetch: 4,
2538            ..Default::default()
2539        });
2540        let honest = peer(1);
2541        let flooder = peer(2);
2542        for p in [honest, flooder] {
2543            rig.add_peer(p);
2544        }
2545        rig.announce(honest, &hashes(0..2));
2546        rig.announce(flooder, &hashes(10..12));
2547        // The shared cursor entry must not hide newly queued exclusive victims.
2548        rig.announce(flooder, &[hash(0), hash(12), hash(13), hash(14), hash(15), hash(16)]);
2549        assert_eq!(rig.fetcher.candidate_peers(&hash(1)), vec![honest]);
2550        assert_eq!(rig.fetcher.candidate_peers(&hash(0)), vec![honest, flooder]);
2551        assert_eq!(rig.fetcher.num_hashes(), 4);
2552    }
2553
2554    #[test]
2555    fn stale_queue_entries_do_not_hide_exclusive_eviction_victims() {
2556        let mut rig = Rig::with_config(TransactionFetcherConfig {
2557            max_capacity_cache_txns_pending_fetch: 16,
2558            ..Default::default()
2559        });
2560        let honest = peer(1);
2561        let flooder = peer(2);
2562        let newcomer = peer(3);
2563        for p in [honest, flooder, newcomer] {
2564            rig.add_peer(p);
2565        }
2566        rig.announce(honest, &[hash(0)]);
2567        rig.announce(flooder, &hashes(1..16));
2568        rig.fetcher.on_transactions_received(hashes(1..9).iter());
2569        rig.announce(flooder, &hashes(16..24));
2570        rig.announce(newcomer, &[hash(24)]);
2571        assert_eq!(rig.fetcher.candidate_peers(&hash(0)), vec![honest]);
2572        assert!(rig.fetcher.candidate_peers(&hash(9)).is_empty());
2573    }
2574
2575    #[test]
2576    fn capacity_eviction_targets_the_peer_with_the_most_hashes() {
2577        let config = TransactionFetcherConfig {
2578            max_capacity_cache_txns_pending_fetch: 100,
2579            max_announced_hashes_per_peer: 60,
2580            ..Default::default()
2581        };
2582        let mut rig = Rig::with_config(config);
2583        let honest = peer(1);
2584        let flooders = [peer(2), peer(3)];
2585        rig.add_peer(honest);
2586        for peer_id in flooders {
2587            rig.add_peer(peer_id);
2588        }
2589
2590        // the honest peer's hashes are the oldest when the flood fills the fetcher
2591        let honest_hashes = hashes(0..10);
2592        rig.announce(honest, &honest_hashes);
2593        rig.announce(flooders[0], &hashes(100..160));
2594        rig.announce(flooders[1], &hashes(200..260));
2595
2596        assert_eq!(rig.fetcher.num_hashes(), 100);
2597        for hash in &honest_hashes {
2598            assert_eq!(rig.fetcher.candidate_peers(hash), vec![honest], "{hash} was evicted");
2599        }
2600        assert_eq!(rig.fetcher.queued_hashes(&honest), honest_hashes);
2601
2602        // the flooders gave up their oldest hashes
2603        assert!(rig.fetcher.candidate_peers(&hashes(100..101)[0]).is_empty());
2604        assert_eq!(rig.fetcher.candidate_peers(&hashes(259..260)[0]), vec![flooders[1]]);
2605    }
2606
2607    #[test]
2608    fn shared_queue_prefix_does_not_hide_exclusive_eviction_victim() {
2609        let mut rig = Rig::with_config(TransactionFetcherConfig {
2610            max_capacity_cache_txns_pending_fetch: 10,
2611            ..Default::default()
2612        });
2613        let honest = peer(1);
2614        let flooder = peer(2);
2615        let newcomer = peer(3);
2616        for p in [honest, flooder, newcomer] {
2617            rig.add_peer(p);
2618        }
2619        rig.announce(honest, &hashes(0..9));
2620        rig.announce(flooder, &hashes(0..8));
2621        rig.announce(flooder, &[hash(9)]);
2622        rig.announce(newcomer, &[hash(10)]);
2623        for h in hashes(0..8) {
2624            assert_eq!(rig.fetcher.candidate_peers(&h), vec![honest, flooder]);
2625        }
2626        assert!(rig.fetcher.candidate_peers(&hash(9)).is_empty());
2627        assert_eq!(rig.fetcher.candidate_peers(&hash(10)), vec![newcomer]);
2628    }
2629
2630    #[test]
2631    fn capacity_fallback_keeps_the_announcer_ready() {
2632        let mut rig = Rig::with_config(TransactionFetcherConfig {
2633            max_capacity_cache_txns_pending_fetch: 9,
2634            ..Default::default()
2635        });
2636        let stalled = peer(1);
2637        let source = peer(2);
2638        let announcer = peer(3);
2639        for p in [stalled, source, announcer] {
2640            rig.add_peer(p);
2641        }
2642        rig.announce(stalled, &hashes(0..8));
2643        rig.dispatch();
2644        rig.announce(source, &[hash(8)]);
2645        // The global scan sees only fetching hashes. The last new hash is dropped after
2646        // the shared scratch entries have been moved into the announcer's real queue.
2647        rig.announce(announcer, &hashes(0..10));
2648        rig.disconnect(source);
2649        assert_eq!(rig.dispatch(), 1);
2650        assert_eq!(rig.take_request(announcer).unwrap().0, vec![hash(8)]);
2651    }
2652
2653    #[test]
2654    fn capacity_eviction_preserves_coannounced_hashes() {
2655        let config = TransactionFetcherConfig {
2656            max_capacity_cache_txns_pending_fetch: 4,
2657            ..Default::default()
2658        };
2659        let mut rig = Rig::with_config(config);
2660        let honest = peer(1);
2661        let flooder = peer(2);
2662        let newcomer = peer(3);
2663        for peer_id in [honest, flooder, newcomer] {
2664            rig.add_peer(peer_id);
2665        }
2666        let shared = hash(0);
2667        rig.announce(honest, &[shared]);
2668        rig.announce(flooder, &hashes(0..4));
2669        rig.announce(newcomer, &[hash(4)]);
2670        assert_eq!(rig.fetcher.num_hashes(), 4);
2671        assert_eq!(rig.fetcher.candidate_peers(&shared), vec![honest, flooder]);
2672        assert!(rig.fetcher.candidate_peers(&hash(1)).is_empty());
2673        assert_eq!(rig.fetcher.candidate_peers(&hash(4)), vec![newcomer]);
2674        rig.dispatch();
2675        assert_eq!(rig.fetcher.fetching_peer(&shared), Some(honest));
2676        assert_eq!(rig.take_request(flooder).unwrap().0, vec![hash(2), hash(3)]);
2677    }
2678
2679    #[test]
2680    fn capacity_fallback_moves_past_fetching_hashes() {
2681        let mut rig = Rig::with_config(TransactionFetcherConfig {
2682            max_capacity_cache_txns_pending_fetch: 24,
2683            ..Default::default()
2684        });
2685        let [fetching, first, second, coannouncer, honest] = [1, 2, 3, 4, 5].map(peer);
2686        for p in [fetching, first, second, coannouncer, honest] {
2687            rig.add_peer(p);
2688        }
2689        // the oldest hashes are inflight and the busiest peer has no exclusive hashes
2690        rig.announce(fetching, &hashes(0..8));
2691        rig.dispatch();
2692        rig.announce(first, &hashes(8..16));
2693        rig.announce(second, &hashes(16..24));
2694        rig.announce(coannouncer, &hashes(8..24));
2695
2696        // the first search only gets past the fetching hashes, later ones evict pending hashes
2697        rig.announce(honest, &hashes(24..28));
2698        assert!(rig.fetcher.candidate_peers(&hash(24)).is_empty());
2699        for h in hashes(25..28) {
2700            assert_eq!(rig.fetcher.candidate_peers(&h), vec![honest]);
2701        }
2702        for h in hashes(8..11) {
2703            assert!(rig.fetcher.candidate_peers(&h).is_empty());
2704        }
2705        assert_eq!(rig.fetcher.num_fetching_hashes(), 8);
2706        rig.dispatch();
2707        assert_eq!(rig.take_request(honest).unwrap().0, hashes(25..28));
2708    }
2709
2710    #[test]
2711    fn capacity_with_only_shared_hashes_admits_new_announcements() {
2712        let config = TransactionFetcherConfig {
2713            max_capacity_cache_txns_pending_fetch: 2,
2714            ..Default::default()
2715        };
2716        let mut rig = Rig::with_config(config);
2717        for peer_id in [peer(1), peer(2), peer(3)] {
2718            rig.add_peer(peer_id);
2719        }
2720        for peer_id in [peer(1), peer(2)] {
2721            rig.announce(peer_id, &hashes(0..2));
2722        }
2723        rig.announce(peer(3), &[hash(2)]);
2724        assert_eq!(rig.fetcher.num_hashes(), 2);
2725        assert_eq!(rig.fetcher.candidate_peers(&hash(2)), vec![peer(3)]);
2726        assert!(rig.fetcher.candidate_peers(&hash(0)).is_empty());
2727        assert_eq!(rig.fetcher.candidate_peers(&hash(1)), vec![peer(1), peer(2)]);
2728        rig.dispatch();
2729        assert_eq!(rig.fetcher.num_fetching_hashes(), 2);
2730    }
2731
2732    #[test]
2733    fn retracked_hash_is_not_evicted_at_its_stale_queue_position() {
2734        let mut rig = Rig::with_config(TransactionFetcherConfig {
2735            max_capacity_cache_txns_pending_fetch: 3,
2736            ..Default::default()
2737        });
2738        let p = peer(1);
2739        rig.add_peer(p);
2740        rig.announce(p, &hashes(0..3));
2741        rig.fetcher.on_transactions_received([&hash(0)]);
2742        rig.announce(p, &[hash(0)]);
2743        rig.announce(p, &[hash(3)]);
2744        assert_eq!(rig.fetcher.candidate_peers(&hash(0)), vec![p]);
2745        assert!(rig.fetcher.candidate_peers(&hash(1)).is_empty());
2746        rig.dispatch();
2747        assert_eq!(rig.take_request(p).unwrap().0, vec![hash(2), hash(0), hash(3)]);
2748    }
2749
2750    #[test]
2751    fn shared_fallback_ignores_stale_tracking_generations() {
2752        let mut rig = Rig::with_config(TransactionFetcherConfig {
2753            max_capacity_cache_txns_pending_fetch: 3,
2754            ..Default::default()
2755        });
2756        for p in [peer(1), peer(2), peer(3)] {
2757            rig.add_peer(p);
2758        }
2759        for p in [peer(1), peer(2)] {
2760            rig.announce(p, &hashes(0..3));
2761        }
2762        rig.fetcher.on_transactions_received([&hash(0)]);
2763        for p in [peer(1), peer(2)] {
2764            rig.announce(p, &[hash(0)]);
2765        }
2766        rig.announce(peer(3), &[hash(3)]);
2767        assert_eq!(rig.fetcher.candidate_peers(&hash(0)), vec![peer(1), peer(2)]);
2768        assert!(rig.fetcher.candidate_peers(&hash(1)).is_empty());
2769    }
2770
2771    #[test]
2772    fn eviction_order_stays_bounded_when_hashes_are_tracked_again() {
2773        let config = TransactionFetcherConfig {
2774            max_capacity_cache_txns_pending_fetch: 8,
2775            ..Default::default()
2776        };
2777        let mut rig = Rig::with_config(config);
2778        let peer_a = peer(1);
2779        rig.add_peer(peer_a);
2780        let batch = hashes(0..8);
2781
2782        // the same hashes are given up on and announced again over and over, every round leaves
2783        // stale entries in the eviction order behind
2784        for _ in 0..10 {
2785            rig.announce(peer_a, &batch);
2786            assert_eq!(rig.fetcher.num_hashes(), 8);
2787            rig.dispatch();
2788            rig.fail(peer_a, RequestError::BadResponse);
2789            assert_eq!(rig.fetcher.num_hashes(), 0);
2790        }
2791        rig.announce(peer_a, &batch);
2792        assert_eq!(rig.fetcher.num_hashes(), 8);
2793
2794        // a new hash still evicts the oldest one rather than getting dropped
2795        rig.announce(peer_a, &hashes(8..9));
2796        assert_eq!(rig.fetcher.num_hashes(), 8);
2797        assert!(rig.fetcher.candidate_peers(&batch[0]).is_empty());
2798    }
2799
2800    #[test]
2801    fn disconnected_remembered_candidates_are_forgotten() {
2802        let mut rig = Rig::new();
2803        let hash = hash(1);
2804        let peers = (1..=MAX_COUNT_CANDIDATE_PEERS_PER_HASH as u8).map(peer).collect::<Vec<_>>();
2805        for peer_id in &peers {
2806            rig.add_peer(*peer_id);
2807            rig.announce(*peer_id, &[hash]);
2808        }
2809        let (queued, remembered) = peers.split_at(MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH);
2810
2811        // remembered candidates have no queue entry, they are forgotten nonetheless
2812        for peer_id in remembered {
2813            rig.disconnect(*peer_id);
2814        }
2815        assert_eq!(rig.fetcher.candidate_peers(&hash), queued);
2816
2817        // which frees their slots for later announcers
2818        let newcomer = peer(42);
2819        rig.add_peer(newcomer);
2820        rig.announce(newcomer, &[hash]);
2821        assert!(rig.fetcher.candidate_peers(&hash).contains(&newcomer));
2822
2823        // and a hash whose last connected candidate leaves is dropped
2824        for peer_id in queued {
2825            rig.disconnect(*peer_id);
2826        }
2827        rig.disconnect(newcomer);
2828        assert_eq!(rig.fetcher.num_hashes(), 0);
2829    }
2830
2831    #[test]
2832    fn remembered_candidates_take_over_when_queued_ones_disconnect() {
2833        let mut rig = Rig::new();
2834        let hash = hash(1);
2835        let peers =
2836            (1..=MAX_COUNT_EAGER_CANDIDATE_PEERS_PER_HASH as u8 + 1).map(peer).collect::<Vec<_>>();
2837        for peer_id in &peers {
2838            rig.add_peer(*peer_id);
2839            rig.announce(*peer_id, &[hash]);
2840        }
2841        let last = *peers.last().unwrap();
2842        assert!(rig.fetcher.queued_hashes(&last).is_empty());
2843
2844        // all peers that had the hash queued disconnect before fetching it
2845        for peer_id in &peers[..peers.len() - 1] {
2846            rig.disconnect(*peer_id);
2847        }
2848        assert_eq!(rig.fetcher.candidate_peers(&hash), vec![last]);
2849        assert_eq!(rig.fetcher.queued_hashes(&last), vec![hash]);
2850        assert_eq!(rig.dispatch(), 1);
2851        assert_eq!(rig.fetcher.fetching_peer(&hash), Some(last));
2852    }
2853
2854    #[test]
2855    fn global_inflight_limit_defers_ready_peers() {
2856        let config = TransactionFetcherConfig { max_inflight_requests: 1, ..Default::default() };
2857        let mut rig = Rig::with_config(config);
2858        let peer_a = peer(1);
2859        let peer_b = peer(2);
2860        rig.add_peer(peer_a);
2861        rig.add_peer(peer_b);
2862
2863        rig.announce(peer_a, &hashes(0..2));
2864        rig.announce(peer_b, &hashes(2..4));
2865
2866        assert_eq!(rig.dispatch(), 1);
2867        let (_, response) = rig.take_request(peer_a).unwrap();
2868        assert!(rig.take_request(peer_b).is_none());
2869        assert_eq!(rig.dispatch(), 0);
2870
2871        // the deferred peer is served once a request slot frees up
2872        rig.announce(peer_a, &hashes(4..5));
2873        drop(response);
2874        rig.next_event().unwrap();
2875        assert_eq!(rig.dispatch(), 1);
2876        assert!(rig.take_request(peer_b).is_some());
2877        assert!(rig.take_request(peer_a).is_none(), "peer_b was ready first");
2878    }
2879
2880    #[test]
2881    fn dispatch_applies_the_request_limit_independently_to_each_peer() {
2882        let mut rig = Rig::new();
2883        let peer_a = peer(1);
2884        let peer_b = peer(2);
2885        rig.add_peer(peer_a);
2886        rig.add_peer(peer_b);
2887
2888        rig.announce(peer_a, &hashes(0..100));
2889        rig.announce(peer_b, &hashes(100..200));
2890
2891        assert_eq!(rig.dispatch_with_budget(0), 0);
2892
2893        // Each peer can use the full request limit regardless of other inflight requests.
2894        assert_eq!(rig.dispatch_with_budget(40), 2);
2895        let (requested, response_a) = rig.take_request(peer_a).unwrap();
2896        assert_eq!(requested, hashes(0..40));
2897        let (requested, _) = rig.take_request(peer_b).unwrap();
2898        assert_eq!(requested, hashes(100..140));
2899        assert_eq!(rig.fetcher.num_fetching_hashes(), 80);
2900
2901        // A smaller request limit is respected too.
2902        response_a.send(Err(RequestError::BadResponse)).unwrap();
2903        rig.next_event().unwrap();
2904        assert_eq!(rig.dispatch_with_budget(10), 1);
2905        let (requested, _) = rig.take_request(peer_a).unwrap();
2906        assert_eq!(requested, hashes(40..50));
2907    }
2908
2909    #[test]
2910    fn full_session_channel_rolls_back_request() {
2911        let mut rig = Rig::new();
2912        let peer_a = peer(1);
2913        rig.add_peer_with_capacity(peer_a, 1);
2914        let hashes = hashes(0..3);
2915
2916        // occupy the only slot of the session channel
2917        let (blocker, _rx) = oneshot::channel();
2918        rig.peers[&peer_a]
2919            .request_tx()
2920            .try_send(PeerRequest::GetPooledTransactions {
2921                request: GetPooledTransactions(vec![]),
2922                response: blocker,
2923            })
2924            .unwrap();
2925
2926        rig.announce(peer_a, &hashes);
2927        assert_eq!(rig.dispatch(), 0);
2928        assert_eq!(rig.fetcher.num_pending_hashes(), 3);
2929        assert_eq!(rig.fetcher.num_inflight_requests(), 0);
2930        assert!(rig.fetcher.is_idle(&peer_a));
2931        assert_eq!(rig.fetcher.queued_hashes(&peer_a), hashes);
2932
2933        // drain the blocker, the peer is retried on the next dispatch
2934        let (blocked, _) = rig.take_request(peer_a).unwrap();
2935        assert!(blocked.is_empty());
2936        assert_eq!(rig.dispatch(), 1);
2937        let (requested, _) = rig.take_request(peer_a).unwrap();
2938        assert_eq!(requested, hashes);
2939    }
2940
2941    #[test]
2942    fn closed_session_channel_disconnects_peer() {
2943        let mut rig = Rig::new();
2944        let peer_a = peer(1);
2945        let peer_b = peer(2);
2946        rig.add_peer(peer_a);
2947        rig.add_peer(peer_b);
2948        let hashes = hashes(0..2);
2949
2950        rig.announce(peer_a, &hashes);
2951        rig.announce(peer_b, &hashes[..1]);
2952        // the session task is gone, but the manager didn't process the disconnect yet
2953        rig.sessions.remove(&peer_a);
2954
2955        assert_eq!(rig.dispatch(), 1);
2956        assert!(rig.fetcher.candidate_peers(&hashes[0]).contains(&peer_b));
2957        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_b]);
2958        assert_eq!(rig.fetcher.num_hashes(), 1, "hash only announced by the gone peer is dropped");
2959        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_b));
2960    }
2961
2962    #[test]
2963    fn busy_peer_queue_is_compacted() {
2964        let config =
2965            TransactionFetcherConfig { max_announced_hashes_per_peer: 4, ..Default::default() };
2966        let mut rig = Rig::with_config(config);
2967        let peer_a = peer(1);
2968        let peer_b = peer(2);
2969        rig.add_peer(peer_a);
2970        rig.add_peer(peer_b);
2971
2972        // keep peer_a busy
2973        rig.announce(peer_a, &hashes(0..1));
2974        rig.dispatch();
2975
2976        // hashes announced by the busy peer are delivered by others over and over
2977        for round in 1..20u64 {
2978            let hashes = hashes(round * 10..round * 10 + 4);
2979            rig.announce(peer_a, &hashes);
2980            rig.fetcher.on_transactions_received(&hashes);
2981            rig.fetcher.assert_invariants();
2982        }
2983        assert!(rig.fetcher.queued_hashes(&peer_a).len() <= 8);
2984    }
2985
2986    #[test]
2987    fn late_response_for_reassigned_hash_is_ignored() {
2988        let mut rig = Rig::new();
2989        let peer_a = peer(1);
2990        let peer_b = peer(2);
2991        rig.add_peer(peer_a);
2992        rig.add_peer(peer_b);
2993        let txs = pooled_txs(1);
2994        let hashes = hashes_of(&txs);
2995
2996        rig.announce(peer_a, &hashes);
2997        rig.dispatch();
2998        // arrives over broadcast, gets announced again and is assigned to another peer
2999        rig.fetcher.on_transactions_received(&hashes);
3000        rig.announce(peer_b, &hashes);
3001        rig.dispatch();
3002        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_b));
3003
3004        // the original request resolves without the hash, which must not touch the new fetch
3005        rig.respond(peer_a, vec![]);
3006        assert_eq!(rig.fetcher.fetching_peer(&hashes[0]), Some(peer_b));
3007        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_b]);
3008
3009        rig.respond(peer_b, txs);
3010        assert_eq!(rig.fetcher.num_hashes(), 0);
3011    }
3012
3013    #[test]
3014    fn random_operations_keep_invariants() {
3015        let mut rng = StdRng::seed_from_u64(0x5eed);
3016        let txs = pooled_txs(150);
3017        let all_hashes = hashes_of(&txs);
3018        let by_hash = txs.iter().map(|tx| (*tx.tx_hash(), tx.clone())).collect::<B256Map<_>>();
3019        // more peers than a hash has candidate slots, so announcers get remembered and rejected
3020        let peer_ids = (1..=24).map(peer).collect::<Vec<_>>();
3021
3022        let config = TransactionFetcherConfig {
3023            max_inflight_requests: 8,
3024            max_inflight_requests_per_peer: 2,
3025            max_capacity_cache_txns_pending_fetch: 120,
3026            max_announced_hashes_per_peer: 40,
3027            ..Default::default()
3028        };
3029        let mut rig = Rig::with_config(config);
3030        for peer_id in &peer_ids {
3031            rig.add_peer_with_capacity(*peer_id, 4);
3032        }
3033        let mut connected = peer_ids.clone();
3034        // requests taken from the sessions that weren't answered yet
3035        let mut outstanding: Vec<(PeerId, Vec<TxHash>, ResponseSender)> = Vec::new();
3036
3037        for _ in 0..5000 {
3038            match rng.random_range(0..100u32) {
3039                0..=39 => {
3040                    let Some(&peer_id) = connected.choose(&mut rng) else { continue };
3041                    let count = rng.random_range(1..=30);
3042                    let entries = all_hashes
3043                        .choose_multiple(&mut rng, count)
3044                        .map(|hash| {
3045                            let size = match rng.random_range(0..10) {
3046                                0 => 0,
3047                                1 => 200 * KIB,
3048                                _ => rng.random_range(100..1500),
3049                            };
3050                            (*hash, size)
3051                        })
3052                        .collect::<Vec<_>>();
3053                    rig.announce_with_sizes(peer_id, entries);
3054                }
3055                40..=59 => {
3056                    let budget =
3057                        if rng.random_bool(0.2) { rng.random_range(0..60) } else { usize::MAX };
3058                    rig.dispatch_with_budget(budget);
3059                    for peer_id in &connected {
3060                        while let Some((requested, response)) = rig.take_request(*peer_id) {
3061                            assert!(!requested.is_empty());
3062                            assert!(
3063                                requested.len() <=
3064                                    SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST
3065                            );
3066                            let unique = requested.iter().copied().collect::<B256Set>();
3067                            assert_eq!(unique.len(), requested.len(), "request has duplicates");
3068                            outstanding.push((*peer_id, requested, response));
3069                        }
3070                    }
3071                }
3072                60..=84 => {
3073                    if outstanding.is_empty() {
3074                        continue
3075                    }
3076                    let (_, requested, response) =
3077                        outstanding.swap_remove(rng.random_range(0..outstanding.len()));
3078                    match rng.random_range(0..10) {
3079                        0..=5 => {
3080                            let mut delivered = requested
3081                                .iter()
3082                                .filter(|_| rng.random_bool(0.7))
3083                                .map(|hash| by_hash[hash].clone())
3084                                .collect::<Vec<_>>();
3085                            if rng.random_bool(0.1) &&
3086                                let Some(duplicate) = delivered.first().cloned()
3087                            {
3088                                delivered.push(duplicate);
3089                            }
3090                            if rng.random_bool(0.1) {
3091                                delivered.push(txs.choose(&mut rng).unwrap().clone());
3092                            }
3093                            let _ = response.send(Ok(PooledTransactions(delivered)));
3094                        }
3095                        6..=7 => {
3096                            let _ = response.send(Ok(PooledTransactions(vec![])));
3097                        }
3098                        8 => {
3099                            let _ = response.send(Err(RequestError::Timeout));
3100                        }
3101                        _ => drop(response),
3102                    }
3103                    rig.drain_events();
3104                }
3105                85..=89 => {
3106                    let count = rng.random_range(1..=10);
3107                    let received =
3108                        all_hashes.choose_multiple(&mut rng, count).copied().collect::<Vec<_>>();
3109                    rig.fetcher.on_transactions_received(&received);
3110                    rig.fetcher.assert_invariants();
3111                }
3112                90..=94 => {
3113                    if connected.len() > 1 {
3114                        let peer_id = connected.swap_remove(rng.random_range(0..connected.len()));
3115                        rig.disconnect(peer_id);
3116                        // drops the response senders of the peer's outstanding requests
3117                        outstanding.retain(|(id, ..)| *id != peer_id);
3118                        rig.drain_events();
3119                    }
3120                }
3121                _ => {
3122                    if let Some(&peer_id) = peer_ids.iter().find(|id| !connected.contains(id)) {
3123                        rig.add_peer_with_capacity(peer_id, 4);
3124                        connected.push(peer_id);
3125                    }
3126                }
3127            }
3128        }
3129
3130        // settle everything that is still inflight
3131        drop(outstanding);
3132        for peer_id in &connected {
3133            rig.disconnect(*peer_id);
3134        }
3135        rig.drain_events();
3136        assert_eq!(rig.fetcher.num_inflight_requests(), 0);
3137        assert_eq!(rig.fetcher.num_fetching_hashes(), 0);
3138        assert_eq!(rig.fetcher.num_hashes(), 0);
3139        assert_eq!(rig.fetcher.num_peers(), 0);
3140    }
3141    #[test]
3142    fn resolved_requests_are_yielded_one_per_poll() {
3143        let mut rig = Rig::new();
3144        let peers = (1..=3).map(peer).collect::<Vec<_>>();
3145        for (i, peer_id) in peers.iter().enumerate() {
3146            rig.add_peer(*peer_id);
3147            rig.announce(*peer_id, &hashes(i as u64..i as u64 + 1));
3148        }
3149        assert_eq!(rig.dispatch(), 3);
3150        for peer_id in &peers {
3151            let (_, response) = rig.take_request(*peer_id).unwrap();
3152            response.send(Err(RequestError::Timeout)).unwrap();
3153        }
3154
3155        let events = rig.drain_events();
3156        assert_eq!(events.len(), 3);
3157        assert!(events.iter().all(|event| matches!(event, FetchEvent::FetchError { .. })));
3158        assert!(rig.next_event().is_none());
3159        assert_eq!(rig.fetcher.num_inflight_requests(), 0);
3160    }
3161
3162    #[test]
3163    fn global_capacity_bounds_tracked_hashes_across_peers() {
3164        let config = TransactionFetcherConfig {
3165            max_capacity_cache_txns_pending_fetch: 40,
3166            ..Default::default()
3167        };
3168        let mut rig = Rig::with_config(config);
3169        let peers = (1..=4).map(peer).collect::<Vec<_>>();
3170        for (i, peer_id) in peers.iter().enumerate() {
3171            rig.add_peer(*peer_id);
3172            rig.announce(*peer_id, &hashes(i as u64 * 16..(i as u64 + 1) * 16));
3173        }
3174
3175        // 24 of the 64 announced hashes were evicted, spread over the peers so that every
3176        // peer lost its oldest hashes and kept its newest
3177        assert_eq!(rig.fetcher.num_hashes(), 40);
3178        for (i, peer_id) in peers.iter().enumerate() {
3179            let first = i as u64 * 16;
3180            assert!(rig.fetcher.candidate_peers(&hash(first)).is_empty());
3181            assert!(rig.fetcher.candidate_peers(&hash(first + 3)).is_empty());
3182            assert_eq!(rig.fetcher.candidate_peers(&hash(first + 8)), vec![*peer_id]);
3183            assert_eq!(rig.fetcher.candidate_peers(&hash(first + 15)), vec![*peer_id]);
3184        }
3185        rig.fetcher.assert_invariants();
3186
3187        // every peer still has hashes to request, the evicted ones are skipped
3188        assert_eq!(rig.dispatch(), 4);
3189        let mut requested_total = 0;
3190        for peer_id in &peers {
3191            let (requested, _) = rig.take_request(*peer_id).unwrap();
3192            assert!(requested.len() <= 256);
3193            requested_total += requested.len();
3194        }
3195        assert_eq!(requested_total, 40, "every remaining hash is requested");
3196        rig.fetcher.assert_invariants();
3197    }
3198
3199    #[test]
3200    fn delivery_order_does_not_matter() {
3201        let mut rig = Rig::new();
3202        let peer_a = peer(1);
3203        let peer_b = peer(2);
3204        rig.add_peer(peer_a);
3205        rig.add_peer(peer_b);
3206        let txs = pooled_txs(4);
3207        let hashes = hashes_of(&txs);
3208
3209        rig.announce(peer_a, &hashes);
3210        rig.announce(peer_b, &hashes);
3211        rig.dispatch();
3212
3213        // the last and the first hash are delivered in reverse order, the two in between were
3214        // skipped by peer_a
3215        let event = rig.respond(peer_a, vec![txs[3].clone(), txs[0].clone()]);
3216        let FetchEvent::TransactionsFetched { transactions, .. } = event else { panic!() };
3217        assert_eq!(transactions.len(), 2);
3218        assert_eq!(rig.fetcher.num_hashes(), 2);
3219        assert_eq!(rig.fetcher.candidate_peers(&hashes[1]), vec![peer_b]);
3220        assert_eq!(rig.fetcher.candidate_peers(&hashes[2]), vec![peer_b]);
3221        assert_eq!(rig.fetcher.queued_hashes(&peer_b), hashes[1..3]);
3222    }
3223
3224    #[test]
3225    fn partial_delivery_with_concurrent_requests_per_peer() {
3226        let config =
3227            TransactionFetcherConfig { max_inflight_requests_per_peer: 2, ..Default::default() };
3228        let mut rig = Rig::with_config(config);
3229        let peer_a = peer(1);
3230        rig.add_peer(peer_a);
3231        let txs = pooled_txs(300);
3232        let hashes = hashes_of(&txs);
3233
3234        rig.announce(peer_a, &hashes);
3235        assert_eq!(rig.dispatch(), 2);
3236        let (first, response_first) = rig.take_request(peer_a).unwrap();
3237        let (second, response_second) = rig.take_request(peer_a).unwrap();
3238        assert_eq!(first, hashes[..256]);
3239        assert_eq!(second, hashes[256..]);
3240
3241        // only the last hash of the first request is delivered, the rest was skipped and has no
3242        // other candidate
3243        response_first.send(Ok(PooledTransactions(txs[255..256].to_vec()))).unwrap();
3244        rig.next_event().unwrap();
3245        assert_eq!(rig.fetcher.num_hashes(), 44);
3246        assert_eq!(rig.fetcher.num_fetching_hashes(), 44);
3247        assert!(!rig.fetcher.is_idle(&peer_a));
3248
3249        response_second.send(Ok(PooledTransactions(txs[256..].to_vec()))).unwrap();
3250        rig.next_event().unwrap();
3251        assert_eq!(rig.fetcher.num_hashes(), 0);
3252        assert!(rig.fetcher.is_idle(&peer_a));
3253    }
3254
3255    #[test]
3256    fn old_request_resolves_after_peer_reconnected_and_reannounced() {
3257        let mut rig = Rig::new();
3258        let peer_a = peer(1);
3259        rig.add_peer(peer_a);
3260        let txs = pooled_txs(2);
3261        let hashes = hashes_of(&txs);
3262
3263        rig.announce(peer_a, &hashes);
3264        rig.dispatch();
3265        let (_, response) = rig.take_request(peer_a).unwrap();
3266
3267        // the peer reconnects and announces the hashes again while the old request is pending
3268        rig.disconnect(peer_a);
3269        rig.add_peer(peer_a);
3270        rig.announce(peer_a, &hashes);
3271        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_a]);
3272        assert_eq!(rig.fetcher.num_fetching_hashes(), 2);
3273        assert_eq!(rig.dispatch(), 0, "the hashes are still being fetched");
3274
3275        // the old request delivers one hash and skips the other, which is retried with the new
3276        // session
3277        response.send(Ok(PooledTransactions(txs[1..].to_vec()))).unwrap();
3278        rig.next_event().unwrap();
3279        assert_eq!(rig.fetcher.num_hashes(), 1);
3280        assert_eq!(rig.fetcher.candidate_peers(&hashes[0]), vec![peer_a]);
3281        assert_eq!(rig.dispatch(), 1);
3282        let (requested, _) = rig.take_request(peer_a).unwrap();
3283        assert_eq!(requested, hashes[..1]);
3284    }
3285
3286    #[test]
3287    fn requeued_hashes_are_not_queued_twice() {
3288        let mut rig = Rig::new();
3289        let peer_a = peer(1);
3290        let peer_b = peer(2);
3291        rig.add_peer(peer_a);
3292        rig.add_peer(peer_b);
3293        let hashes = hashes(0..3);
3294
3295        // peer_b is busy while both announce the hashes, so they stay in its queue
3296        rig.announce(peer_b, &hashes[..1]);
3297        rig.dispatch();
3298        rig.announce(peer_a, &hashes[1..]);
3299        rig.announce(peer_b, &hashes[1..]);
3300        rig.dispatch();
3301        assert_eq!(rig.fetcher.fetching_peer(&hashes[1]), Some(peer_a));
3302        assert_eq!(rig.fetcher.queued_hashes(&peer_b), hashes[1..]);
3303
3304        rig.fail(peer_a, RequestError::Timeout);
3305        assert_eq!(rig.fetcher.queued_hashes(&peer_b), hashes[1..], "no duplicates");
3306    }
3307}