reth_network/transactions/
fetcher.rs

1//! `TransactionFetcher` is responsible for rate limiting and retry logic for fetching
2//! transactions. Upon receiving an announcement, functionality of the `TransactionFetcher` is
3//! used for filtering out hashes 1) for which the tx is already known and 2) unknown but the hash
4//! is already seen in a previous announcement. The hashes that remain from an announcement are
5//! then packed into a request with respect to the [`EthVersion`] of the announcement. Any hashes
6//! that don't fit into the request, are buffered in the `TransactionFetcher`. If on the other
7//! hand, space remains, hashes that the peer has previously announced are taken out of buffered
8//! hashes to fill the request up. The [`GetPooledTransactions`] request is then sent to the
9//! peer's session, this marks the peer as active with respect to
10//! `MAX_CONCURRENT_TX_REQUESTS_PER_PEER`.
11//!
12//! When a peer buffers hashes in the `TransactionsManager::on_new_pooled_transaction_hashes`
13//! pipeline, it is stored as fallback peer for those hashes. When [`TransactionsManager`] is
14//! polled, it checks if any of fallback peer is idle. If so, it packs a request for that peer,
15//! filling it from the buffered hashes. It does so until there are no more idle peers or until
16//! the hashes buffer is empty.
17//!
18//! If a [`GetPooledTransactions`] request resolves with an error, the hashes in the request are
19//! buffered with respect to `MAX_REQUEST_RETRIES_PER_TX_HASH`. So is the case if the request
20//! resolves with partial success, that is some of the requested hashes are not in the response,
21//! these are then buffered.
22//!
23//! Most healthy peers will send the same hashes in their announcements, as RLPx is a gossip
24//! protocol. This means it's unlikely, that a valid hash, will be buffered for very long
25//! before it's re-tried. Nonetheless, the capacity of the buffered hashes cache must be large
26//! enough to buffer many hashes during network failure, to allow for recovery.
27
28use super::{
29    config::TransactionFetcherConfig,
30    constants::{tx_fetcher::*, SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST},
31    PeerMetadata, PooledTransactions, SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
32};
33use crate::{
34    cache::{LruCache, LruMap},
35    duration_metered_exec,
36    metrics::TransactionFetcherMetrics,
37};
38use alloy_consensus::transaction::PooledTransaction;
39use alloy_primitives::TxHash;
40use derive_more::{Constructor, Deref};
41use futures::{stream::FuturesUnordered, Future, FutureExt, Stream, StreamExt};
42use pin_project::pin_project;
43use reth_eth_wire::{
44    DedupPayload, GetPooledTransactions, HandleMempoolData, HandleVersionedMempoolData,
45    PartiallyValidData, RequestTxHashes, ValidAnnouncementData,
46};
47use reth_eth_wire_types::{EthNetworkPrimitives, NetworkPrimitives};
48use reth_network_api::PeerRequest;
49use reth_network_p2p::error::{RequestError, RequestResult};
50use reth_network_peers::PeerId;
51use reth_primitives_traits::SignedTransaction;
52use schnellru::ByLength;
53use std::{
54    collections::HashMap,
55    pin::Pin,
56    task::{ready, Context, Poll},
57    time::Duration,
58};
59use tokio::sync::{mpsc::error::TrySendError, oneshot, oneshot::error::RecvError};
60use tracing::trace;
61
62/// The type responsible for fetching missing transactions from peers.
63///
64/// This will keep track of unique transaction hashes that are currently being fetched and submits
65/// new requests on announced hashes.
66#[derive(Debug)]
67#[pin_project]
68pub struct TransactionFetcher<N: NetworkPrimitives = EthNetworkPrimitives> {
69    /// All peers with to which a [`GetPooledTransactions`] request is inflight.
70    pub active_peers: LruMap<PeerId, u8, ByLength>,
71    /// All currently active [`GetPooledTransactions`] requests.
72    ///
73    /// The set of hashes encompassed by these requests are a subset of all hashes in the fetcher.
74    /// It's disjoint from the set of hashes which are awaiting an idle fallback peer in order to
75    /// be fetched.
76    #[pin]
77    pub inflight_requests: FuturesUnordered<GetPooledTxRequestFut<N::PooledTransaction>>,
78    /// Hashes that are awaiting an idle fallback peer so they can be fetched.
79    ///
80    /// This is a subset of all hashes in the fetcher, and is disjoint from the set of hashes for
81    /// which a [`GetPooledTransactions`] request is inflight.
82    pub hashes_pending_fetch: LruCache<TxHash>,
83    /// Tracks all hashes in the transaction fetcher.
84    pub hashes_fetch_inflight_and_pending_fetch: LruMap<TxHash, TxFetchMetadata, ByLength>,
85    /// Info on capacity of the transaction fetcher.
86    pub info: TransactionFetcherInfo,
87    #[doc(hidden)]
88    metrics: TransactionFetcherMetrics,
89}
90
91impl<N: NetworkPrimitives> TransactionFetcher<N> {
92    /// Removes the peer from the active set.
93    pub(crate) fn remove_peer(&mut self, peer_id: &PeerId) {
94        self.active_peers.remove(peer_id);
95    }
96
97    /// Updates metrics.
98    #[inline]
99    pub fn update_metrics(&self) {
100        let metrics = &self.metrics;
101
102        metrics.inflight_transaction_requests.set(self.inflight_requests.len() as f64);
103
104        let hashes_pending_fetch = self.hashes_pending_fetch.len() as f64;
105        let total_hashes = self.hashes_fetch_inflight_and_pending_fetch.len() as f64;
106
107        metrics.hashes_pending_fetch.set(hashes_pending_fetch);
108        metrics.hashes_inflight_transaction_requests.set(total_hashes - hashes_pending_fetch);
109    }
110
111    #[inline]
112    fn update_pending_fetch_cache_search_metrics(&self, durations: TxFetcherSearchDurations) {
113        let metrics = &self.metrics;
114
115        let TxFetcherSearchDurations { find_idle_peer, fill_request } = durations;
116        metrics
117            .duration_find_idle_fallback_peer_for_any_pending_hash
118            .set(find_idle_peer.as_secs_f64());
119        metrics.duration_fill_request_from_hashes_pending_fetch.set(fill_request.as_secs_f64());
120    }
121
122    /// Sets up transaction fetcher with config
123    pub fn with_transaction_fetcher_config(config: &TransactionFetcherConfig) -> Self {
124        let TransactionFetcherConfig {
125            max_inflight_requests,
126            max_capacity_cache_txns_pending_fetch,
127            ..
128        } = *config;
129
130        let info = config.clone().into();
131
132        let metrics = TransactionFetcherMetrics::default();
133        metrics.capacity_inflight_requests.increment(max_inflight_requests as u64);
134
135        Self {
136            active_peers: LruMap::new(max_inflight_requests),
137            hashes_pending_fetch: LruCache::new(max_capacity_cache_txns_pending_fetch),
138            hashes_fetch_inflight_and_pending_fetch: LruMap::new(
139                max_inflight_requests + max_capacity_cache_txns_pending_fetch,
140            ),
141            info,
142            metrics,
143            ..Default::default()
144        }
145    }
146
147    /// Removes the specified hashes from inflight tracking.
148    #[inline]
149    pub fn remove_hashes_from_transaction_fetcher<'a, I>(&mut self, hashes: I)
150    where
151        I: IntoIterator<Item = &'a TxHash>,
152    {
153        for hash in hashes {
154            self.hashes_fetch_inflight_and_pending_fetch.remove(hash);
155            self.hashes_pending_fetch.remove(hash);
156        }
157    }
158
159    /// Updates peer's activity status upon a resolved [`GetPooledTxRequest`].
160    fn decrement_inflight_request_count_for(&mut self, peer_id: &PeerId) {
161        let remove = || -> bool {
162            if let Some(inflight_count) = self.active_peers.get(peer_id) {
163                *inflight_count = inflight_count.saturating_sub(1);
164                if *inflight_count == 0 {
165                    return true
166                }
167            }
168            false
169        }();
170
171        if remove {
172            self.active_peers.remove(peer_id);
173        }
174    }
175
176    /// Returns `true` if peer is idle with respect to `self.inflight_requests`.
177    #[inline]
178    pub fn is_idle(&self, peer_id: &PeerId) -> bool {
179        let Some(inflight_count) = self.active_peers.peek(peer_id) else { return true };
180        if *inflight_count < self.info.max_inflight_requests_per_peer {
181            return true
182        }
183        false
184    }
185
186    /// Returns any idle peer for the given hash.
187    pub fn get_idle_peer_for(&self, hash: TxHash) -> Option<&PeerId> {
188        let TxFetchMetadata { fallback_peers, .. } =
189            self.hashes_fetch_inflight_and_pending_fetch.peek(&hash)?;
190
191        for peer_id in fallback_peers.iter() {
192            if self.is_idle(peer_id) {
193                return Some(peer_id)
194            }
195        }
196
197        None
198    }
199
200    /// Returns any idle peer for any hash pending fetch. If one is found, the corresponding
201    /// hash is written to the request buffer that is passed as parameter.
202    ///
203    /// Loops through the hashes pending fetch in lru order until one is found with an idle
204    /// fallback peer, or the budget passed as parameter is depleted, whatever happens first.
205    pub fn find_any_idle_fallback_peer_for_any_pending_hash(
206        &mut self,
207        hashes_to_request: &mut RequestTxHashes,
208        mut budget: Option<usize>, // search fallback peers for max `budget` lru pending hashes
209    ) -> Option<PeerId> {
210        let mut hashes_pending_fetch_iter = self.hashes_pending_fetch.iter();
211
212        let idle_peer = loop {
213            let &hash = hashes_pending_fetch_iter.next()?;
214
215            let idle_peer = self.get_idle_peer_for(hash);
216
217            if idle_peer.is_some() {
218                hashes_to_request.insert(hash);
219                break idle_peer.copied()
220            }
221
222            if let Some(ref mut bud) = budget {
223                *bud = bud.saturating_sub(1);
224                if *bud == 0 {
225                    return None
226                }
227            }
228        };
229        let hash = hashes_to_request.iter().next()?;
230
231        // pop hash that is loaded in request buffer from cache of hashes pending fetch
232        drop(hashes_pending_fetch_iter);
233        _ = self.hashes_pending_fetch.remove(hash);
234
235        idle_peer
236    }
237
238    /// Packages hashes for a [`GetPooledTxRequest`] up to limit. Returns left over hashes. Takes
239    /// a [`RequestTxHashes`] buffer as parameter for filling with hashes to request.
240    ///
241    /// Returns left over hashes.
242    pub fn pack_request(
243        &self,
244        hashes_to_request: &mut RequestTxHashes,
245        hashes_from_announcement: ValidAnnouncementData,
246    ) -> RequestTxHashes {
247        if hashes_from_announcement.msg_version().is_eth68() {
248            return self.pack_request_eth68(hashes_to_request, hashes_from_announcement)
249        }
250        self.pack_request_eth66(hashes_to_request, hashes_from_announcement)
251    }
252
253    /// Packages hashes for a [`GetPooledTxRequest`] from an
254    /// [`Eth68`](reth_eth_wire::EthVersion::Eth68) announcement up to limit as defined by protocol
255    /// version 68. Takes a [`RequestTxHashes`] buffer as parameter for filling with hashes to
256    /// request.
257    ///
258    /// Returns left over hashes.
259    ///
260    /// Loops through hashes passed as parameter and checks if a hash fits in the expected
261    /// response. If no, it's added to surplus hashes. If yes, it's added to hashes to the request
262    /// and expected response size is accumulated.
263    pub fn pack_request_eth68(
264        &self,
265        hashes_to_request: &mut RequestTxHashes,
266        hashes_from_announcement: impl HandleMempoolData
267            + IntoIterator<Item = (TxHash, Option<(u8, usize)>)>,
268    ) -> RequestTxHashes {
269        let mut acc_size_response = 0;
270
271        let mut hashes_from_announcement_iter = hashes_from_announcement.into_iter();
272
273        if let Some((hash, Some((_ty, size)))) = hashes_from_announcement_iter.next() {
274            hashes_to_request.insert(hash);
275
276            // tx is really big, pack request with single tx
277            if size >= self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request {
278                return hashes_from_announcement_iter.collect()
279            }
280            acc_size_response = size;
281        }
282
283        let mut surplus_hashes = RequestTxHashes::default();
284
285        // folds size based on expected response size  and adds selected hashes to the request
286        // list and the other hashes to the surplus list
287        for (hash, metadata) in hashes_from_announcement_iter.by_ref() {
288            let Some((_ty, size)) = metadata else {
289                unreachable!("this method is called upon reception of an eth68 announcement")
290            };
291
292            let next_acc_size = acc_size_response + size;
293
294            if next_acc_size <=
295                self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request
296            {
297                // only update accumulated size of tx response if tx will fit in without exceeding
298                // soft limit
299                acc_size_response = next_acc_size;
300                _ = hashes_to_request.insert(hash)
301            } else {
302                _ = surplus_hashes.insert(hash)
303            }
304
305            let free_space =
306                self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request -
307                    acc_size_response;
308
309            if free_space < MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED {
310                break
311            }
312        }
313
314        surplus_hashes.extend(hashes_from_announcement_iter.map(|(hash, _metadata)| hash));
315
316        surplus_hashes
317    }
318
319    /// Packages hashes for a [`GetPooledTxRequest`] from an
320    /// [`Eth66`](reth_eth_wire::EthVersion::Eth66) announcement up to limit as defined by
321    /// protocol version 66. Takes a [`RequestTxHashes`] buffer as parameter for filling with
322    /// hashes to request.
323    ///
324    /// Returns left over hashes.
325    pub fn pack_request_eth66(
326        &self,
327        hashes_to_request: &mut RequestTxHashes,
328        hashes_from_announcement: ValidAnnouncementData,
329    ) -> RequestTxHashes {
330        let (mut hashes, _version) = hashes_from_announcement.into_request_hashes();
331        if hashes.len() <= SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST {
332            *hashes_to_request = hashes;
333            hashes_to_request.shrink_to_fit();
334
335            RequestTxHashes::default()
336        } else {
337            let surplus_hashes =
338                hashes.retain_count(SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST);
339            *hashes_to_request = hashes;
340            hashes_to_request.shrink_to_fit();
341
342            surplus_hashes
343        }
344    }
345
346    /// Tries to buffer hashes for retry.
347    pub fn try_buffer_hashes_for_retry(
348        &mut self,
349        mut hashes: RequestTxHashes,
350        peer_failed_to_serve: &PeerId,
351    ) {
352        // It could be that the txns have been received over broadcast in the time being. Remove
353        // the peer as fallback peer so it isn't request again for these hashes.
354        hashes.retain(|hash| {
355            if let Some(entry) = self.hashes_fetch_inflight_and_pending_fetch.get(hash) {
356                entry.fallback_peers_mut().remove(peer_failed_to_serve);
357                return true
358            }
359            // tx has been seen over broadcast in the time it took for the request to resolve
360            false
361        });
362
363        self.buffer_hashes(hashes, None)
364    }
365
366    /// Number of hashes pending fetch.
367    pub fn num_pending_hashes(&self) -> usize {
368        self.hashes_pending_fetch.len()
369    }
370
371    /// Number of all transaction hashes in the fetcher.
372    pub fn num_all_hashes(&self) -> usize {
373        self.hashes_fetch_inflight_and_pending_fetch.len()
374    }
375
376    /// Buffers hashes. Note: Only peers that haven't yet tried to request the hashes should be
377    /// passed as `fallback_peer` parameter! For re-buffering hashes on failed request, use
378    /// [`TransactionFetcher::try_buffer_hashes_for_retry`]. Hashes that have been re-requested
379    /// [`DEFAULT_MAX_RETRIES`], are dropped.
380    pub fn buffer_hashes(&mut self, hashes: RequestTxHashes, fallback_peer: Option<PeerId>) {
381        for hash in hashes {
382            // hash could have been evicted from bounded lru map
383            if self.hashes_fetch_inflight_and_pending_fetch.peek(&hash).is_none() {
384                continue
385            }
386
387            let Some(TxFetchMetadata { retries, fallback_peers, .. }) =
388                self.hashes_fetch_inflight_and_pending_fetch.get(&hash)
389            else {
390                return
391            };
392
393            if let Some(peer_id) = fallback_peer {
394                // peer has not yet requested hash
395                fallback_peers.insert(peer_id);
396            } else {
397                if *retries >= DEFAULT_MAX_RETRIES {
398                    trace!(target: "net::tx",
399                        %hash,
400                        retries,
401                        "retry limit for `GetPooledTransactions` requests reached for hash, dropping hash"
402                    );
403
404                    self.hashes_fetch_inflight_and_pending_fetch.remove(&hash);
405                    self.hashes_pending_fetch.remove(&hash);
406                    continue
407                }
408                *retries += 1;
409            }
410
411            if let (_, Some(evicted_hash)) = self.hashes_pending_fetch.insert_and_get_evicted(hash)
412            {
413                self.hashes_fetch_inflight_and_pending_fetch.remove(&evicted_hash);
414            }
415        }
416    }
417
418    /// Tries to request hashes pending fetch.
419    ///
420    /// Finds the first buffered hash with a fallback peer that is idle, if any. Fills the rest of
421    /// the request by checking the transactions seen by the peer against the buffer.
422    pub fn on_fetch_pending_hashes(
423        &mut self,
424        peers: &HashMap<PeerId, PeerMetadata<N>>,
425        has_capacity_wrt_pending_pool_imports: impl Fn(usize) -> bool,
426    ) {
427        let mut hashes_to_request = RequestTxHashes::with_capacity(
428            DEFAULT_MARGINAL_COUNT_HASHES_GET_POOLED_TRANSACTIONS_REQUEST,
429        );
430        let mut search_durations = TxFetcherSearchDurations::default();
431
432        // budget to look for an idle peer before giving up
433        let budget_find_idle_fallback_peer = self
434            .search_breadth_budget_find_idle_fallback_peer(&has_capacity_wrt_pending_pool_imports);
435
436        let peer_id = duration_metered_exec!(
437            {
438                let Some(peer_id) = self.find_any_idle_fallback_peer_for_any_pending_hash(
439                    &mut hashes_to_request,
440                    budget_find_idle_fallback_peer,
441                ) else {
442                    // no peers are idle or budget is depleted
443                    return
444                };
445
446                peer_id
447            },
448            search_durations.find_idle_peer
449        );
450
451        // peer should always exist since `is_session_active` already checked
452        let Some(peer) = peers.get(&peer_id) else { return };
453        let conn_eth_version = peer.version;
454
455        // fill the request with more hashes pending fetch that have been announced by the peer.
456        // the search for more hashes is done with respect to the given budget, which determines
457        // how many hashes to loop through before giving up. if no more hashes are found wrt to
458        // the budget, the single hash that was taken out of the cache above is sent in a request.
459        let budget_fill_request = self
460            .search_breadth_budget_find_intersection_pending_hashes_and_hashes_seen_by_peer(
461                &has_capacity_wrt_pending_pool_imports,
462            );
463
464        duration_metered_exec!(
465            {
466                self.fill_request_from_hashes_pending_fetch(
467                    &mut hashes_to_request,
468                    &peer.seen_transactions,
469                    budget_fill_request,
470                )
471            },
472            search_durations.fill_request
473        );
474
475        self.update_pending_fetch_cache_search_metrics(search_durations);
476
477        trace!(target: "net::tx",
478            peer_id=format!("{peer_id:#}"),
479            hashes=?*hashes_to_request,
480            %conn_eth_version,
481            "requesting hashes that were stored pending fetch from peer"
482        );
483
484        // request the buffered missing transactions
485        if let Some(failed_to_request_hashes) =
486            self.request_transactions_from_peer(hashes_to_request, peer)
487        {
488            trace!(target: "net::tx",
489                peer_id=format!("{peer_id:#}"),
490                ?failed_to_request_hashes,
491                %conn_eth_version,
492                "failed sending request to peer's session, buffering hashes"
493            );
494
495            self.buffer_hashes(failed_to_request_hashes, Some(peer_id));
496        }
497    }
498
499    /// Filters out hashes that have been seen before. For hashes that have already been seen, the
500    /// peer is added as fallback peer.
501    pub fn filter_unseen_and_pending_hashes(
502        &mut self,
503        new_announced_hashes: &mut ValidAnnouncementData,
504        is_tx_bad_import: impl Fn(&TxHash) -> bool,
505        peer_id: &PeerId,
506        client_version: &str,
507    ) {
508        let mut previously_unseen_hashes_count = 0;
509
510        let msg_version = new_announced_hashes.msg_version();
511
512        // filter out inflight hashes, and register the peer as fallback for all inflight hashes
513        new_announced_hashes.retain(|hash, metadata| {
514
515            // occupied entry
516            if let Some(TxFetchMetadata{ tx_encoded_length: previously_seen_size, ..}) = self.hashes_fetch_inflight_and_pending_fetch.peek_mut(hash) {
517                // update size metadata if available
518                if let Some((_ty, size)) = metadata {
519                    if let Some(prev_size) = previously_seen_size {
520                        // check if this peer is announcing a different size than a previous peer
521                        if size != prev_size {
522                            trace!(target: "net::tx",
523                                peer_id=format!("{peer_id:#}"),
524                                %hash,
525                                size,
526                                previously_seen_size,
527                                %client_version,
528                                "peer announced a different size for tx, this is especially worrying if one size is much bigger..."
529                            );
530                        }
531                    }
532                    // believe the most recent peer to announce tx
533                    *previously_seen_size = Some(*size);
534                }
535
536                // hash has been seen but is not inflight
537                if self.hashes_pending_fetch.remove(hash) {
538                    return true
539                }
540
541                return false
542            }
543
544            // vacant entry
545
546            if is_tx_bad_import(hash) {
547                return false
548            }
549
550            previously_unseen_hashes_count += 1;
551
552            if self.hashes_fetch_inflight_and_pending_fetch.get_or_insert(*hash, ||
553                TxFetchMetadata{retries: 0, fallback_peers: LruCache::new(DEFAULT_MAX_COUNT_FALLBACK_PEERS as u32), tx_encoded_length: None}
554            ).is_none() {
555
556                trace!(target: "net::tx",
557                    peer_id=format!("{peer_id:#}"),
558                    %hash,
559                    ?msg_version,
560                    %client_version,
561                    "failed to cache new announced hash from peer in schnellru::LruMap, dropping hash"
562                );
563
564                return false
565            }
566            true
567        });
568
569        trace!(target: "net::tx",
570            peer_id=format!("{peer_id:#}"),
571            previously_unseen_hashes_count=previously_unseen_hashes_count,
572            msg_version=?msg_version,
573            client_version=%client_version,
574            "received previously unseen hashes in announcement from peer"
575        );
576    }
577
578    /// Requests the missing transactions from the previously unseen announced hashes of the peer.
579    /// Returns the requested hashes if the request concurrency limit is reached or if the request
580    /// fails to send over the channel to the peer's session task.
581    ///
582    /// This filters all announced hashes that are already in flight, and requests the missing,
583    /// while marking the given peer as an alternative peer for the hashes that are already in
584    /// flight.
585    pub fn request_transactions_from_peer(
586        &mut self,
587        new_announced_hashes: RequestTxHashes,
588        peer: &PeerMetadata<N>,
589    ) -> Option<RequestTxHashes> {
590        let peer_id: PeerId = peer.request_tx.peer_id;
591        let conn_eth_version = peer.version;
592
593        if self.active_peers.len() >= self.info.max_inflight_requests {
594            trace!(target: "net::tx",
595                peer_id=format!("{peer_id:#}"),
596                hashes=?*new_announced_hashes,
597                %conn_eth_version,
598                max_inflight_transaction_requests=self.info.max_inflight_requests,
599                "limit for concurrent `GetPooledTransactions` requests reached, dropping request for hashes to peer"
600            );
601            return Some(new_announced_hashes)
602        }
603
604        let Some(inflight_count) = self.active_peers.get_or_insert(peer_id, || 0) else {
605            trace!(target: "net::tx",
606                peer_id=format!("{peer_id:#}"),
607                hashes=?*new_announced_hashes,
608                conn_eth_version=%conn_eth_version,
609                "failed to cache active peer in schnellru::LruMap, dropping request to peer"
610            );
611            return Some(new_announced_hashes)
612        };
613
614        if *inflight_count >= self.info.max_inflight_requests_per_peer {
615            trace!(target: "net::tx",
616                peer_id=format!("{peer_id:#}"),
617                hashes=?*new_announced_hashes,
618                %conn_eth_version,
619                max_concurrent_tx_reqs_per_peer=self.info.max_inflight_requests_per_peer,
620                "limit for concurrent `GetPooledTransactions` requests per peer reached"
621            );
622            return Some(new_announced_hashes)
623        }
624
625        #[cfg(debug_assertions)]
626        {
627            for hash in &new_announced_hashes {
628                if self.hashes_pending_fetch.contains(hash) {
629                    tracing::debug!(target: "net::tx", "`{}` should have been taken out of buffer before packing in a request, breaks invariant `@hashes_pending_fetch` and `@inflight_requests`, `@hashes_fetch_inflight_and_pending_fetch` for `{}`: {:?}",
630                        format!("{:?}", new_announced_hashes), // Assuming new_announced_hashes can be debug-printed directly
631                        format!("{:?}", new_announced_hashes),
632                        new_announced_hashes.iter().map(|hash| {
633                            let metadata = self.hashes_fetch_inflight_and_pending_fetch.get(hash);
634                            // Assuming you only need `retries` and `tx_encoded_length` for debugging
635                            (*hash, metadata.map(|m| (m.retries, m.tx_encoded_length)))
636                        }).collect::<Vec<(TxHash, Option<(u8, Option<usize>)>)>>())
637                }
638            }
639        }
640
641        let (response, rx) = oneshot::channel();
642        let req = PeerRequest::GetPooledTransactions {
643            request: GetPooledTransactions(new_announced_hashes.iter().copied().collect()),
644            response,
645        };
646
647        // try to send the request to the peer
648        if let Err(err) = peer.request_tx.try_send(req) {
649            // peer channel is full
650            return match err {
651                TrySendError::Full(_) | TrySendError::Closed(_) => {
652                    self.metrics.egress_peer_channel_full.increment(1);
653                    Some(new_announced_hashes)
654                }
655            }
656        }
657
658        *inflight_count += 1;
659        // stores a new request future for the request
660        self.inflight_requests.push(GetPooledTxRequestFut::new(peer_id, new_announced_hashes, rx));
661
662        None
663    }
664
665    /// Tries to fill request with hashes pending fetch so that the expected [`PooledTransactions`]
666    /// response is full enough. A mutable reference to a list of hashes to request is passed as
667    /// parameter. A budget is passed as parameter, this ensures that the node stops searching
668    /// for more hashes after the budget is depleted. Under bad network conditions, the cache of
669    /// hashes pending fetch may become very full for a while. As the node recovers, the hashes
670    /// pending fetch cache should get smaller. The budget should aim to be big enough to loop
671    /// through all buffered hashes in good network conditions.
672    ///
673    /// The request hashes buffer is filled as if it's an eth68 request, i.e. smartly assemble
674    /// the request based on expected response size. For any hash missing size metadata, it is
675    /// guessed at [`AVERAGE_BYTE_SIZE_TX_ENCODED`].
676    ///
677    /// Loops through hashes pending fetch and does:
678    ///
679    /// 1. Check if a hash pending fetch is seen by peer.
680    /// 2. Optimistically include the hash in the request.
681    /// 3. Accumulate expected total response size.
682    /// 4. Check if acc size and hashes count is at limit, if so stop looping.
683    /// 5. Remove hashes to request from cache of hashes pending fetch.
684    pub fn fill_request_from_hashes_pending_fetch(
685        &mut self,
686        hashes_to_request: &mut RequestTxHashes,
687        seen_hashes: &LruCache<TxHash>,
688        mut budget_fill_request: Option<usize>, // check max `budget` lru pending hashes
689    ) {
690        let Some(hash) = hashes_to_request.iter().next() else { return };
691
692        let mut acc_size_response = self
693            .hashes_fetch_inflight_and_pending_fetch
694            .get(hash)
695            .and_then(|entry| entry.tx_encoded_len())
696            .unwrap_or(AVERAGE_BYTE_SIZE_TX_ENCODED);
697
698        // if request full enough already, we're satisfied, send request for single tx
699        if acc_size_response >=
700            DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES
701        {
702            return
703        }
704
705        // try to fill request by checking if any other hashes pending fetch (in lru order) are
706        // also seen by peer
707        for hash in self.hashes_pending_fetch.iter() {
708            // 1. Check if a hash pending fetch is seen by peer.
709            if !seen_hashes.contains(hash) {
710                continue
711            };
712
713            // 2. Optimistically include the hash in the request.
714            hashes_to_request.insert(*hash);
715
716            // 3. Accumulate expected total response size.
717            let size = self
718                .hashes_fetch_inflight_and_pending_fetch
719                .get(hash)
720                .and_then(|entry| entry.tx_encoded_len())
721                .unwrap_or(AVERAGE_BYTE_SIZE_TX_ENCODED);
722
723            acc_size_response += size;
724
725            // 4. Check if acc size or hashes count is at limit, if so stop looping.
726            // if expected response is full enough or the number of hashes in the request is
727            // enough, we're satisfied
728            if acc_size_response >=
729                DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES ||
730                hashes_to_request.len() >
731                    DEFAULT_SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST_ON_FETCH_PENDING_HASHES
732            {
733                break
734            }
735
736            if let Some(ref mut bud) = budget_fill_request {
737                *bud -= 1;
738                if *bud == 0 {
739                    break
740                }
741            }
742        }
743
744        // 5. Remove hashes to request from cache of hashes pending fetch.
745        for hash in hashes_to_request.iter() {
746            self.hashes_pending_fetch.remove(hash);
747        }
748    }
749
750    /// Returns `true` if [`TransactionFetcher`] has capacity to request pending hashes. Returns
751    /// `false` if [`TransactionFetcher`] is operating close to full capacity.
752    pub fn has_capacity_for_fetching_pending_hashes(&self) -> bool {
753        let info = &self.info;
754
755        self.has_capacity(info.max_inflight_requests)
756    }
757
758    /// Returns `true` if the number of inflight requests are under a given tolerated max.
759    fn has_capacity(&self, max_inflight_requests: usize) -> bool {
760        self.inflight_requests.len() <= max_inflight_requests
761    }
762
763    /// Returns the limit to enforce when looking for any pending hash with an idle fallback peer.
764    ///
765    /// Returns `Some(limit)` if [`TransactionFetcher`] and the
766    /// [`TransactionPool`](reth_transaction_pool::TransactionPool) are operating close to full
767    /// capacity. Returns `None`, unlimited, if they are not that busy.
768    pub fn search_breadth_budget_find_idle_fallback_peer(
769        &self,
770        has_capacity_wrt_pending_pool_imports: impl Fn(usize) -> bool,
771    ) -> Option<usize> {
772        let info = &self.info;
773
774        let tx_fetcher_has_capacity = self.has_capacity(
775            info.max_inflight_requests /
776                DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_IDLE_PEER,
777        );
778        let tx_pool_has_capacity = has_capacity_wrt_pending_pool_imports(
779            DEFAULT_DIVISOR_MAX_COUNT_PENDING_POOL_IMPORTS_ON_FIND_IDLE_PEER,
780        );
781
782        if tx_fetcher_has_capacity && tx_pool_has_capacity {
783            // unlimited search breadth
784            None
785        } else {
786            // limited breadth of search for idle peer
787            let limit = DEFAULT_BUDGET_FIND_IDLE_FALLBACK_PEER;
788
789            trace!(target: "net::tx",
790                inflight_requests=self.inflight_requests.len(),
791                max_inflight_transaction_requests=info.max_inflight_requests,
792                hashes_pending_fetch=self.hashes_pending_fetch.len(),
793                limit,
794                "search breadth limited in search for idle fallback peer for some hash pending fetch"
795            );
796
797            Some(limit)
798        }
799    }
800
801    /// Returns the limit to enforce when looking for the intersection between hashes announced by
802    /// peer and hashes pending fetch.
803    ///
804    /// Returns `Some(limit)` if [`TransactionFetcher`] and the
805    /// [`TransactionPool`](reth_transaction_pool::TransactionPool) are operating close to full
806    /// capacity. Returns `None`, unlimited, if they are not that busy.
807    pub fn search_breadth_budget_find_intersection_pending_hashes_and_hashes_seen_by_peer(
808        &self,
809        has_capacity_wrt_pending_pool_imports: impl Fn(usize) -> bool,
810    ) -> Option<usize> {
811        let info = &self.info;
812
813        let tx_fetcher_has_capacity = self.has_capacity(
814            info.max_inflight_requests /
815                DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_INTERSECTION,
816        );
817        let tx_pool_has_capacity = has_capacity_wrt_pending_pool_imports(
818            DEFAULT_DIVISOR_MAX_COUNT_PENDING_POOL_IMPORTS_ON_FIND_INTERSECTION,
819        );
820
821        if tx_fetcher_has_capacity && tx_pool_has_capacity {
822            // unlimited search breadth
823            None
824        } else {
825            // limited breadth of search for idle peer
826            let limit = DEFAULT_BUDGET_FIND_INTERSECTION_ANNOUNCED_BY_PEER_AND_PENDING_FETCH;
827
828            trace!(target: "net::tx",
829                inflight_requests=self.inflight_requests.len(),
830                max_inflight_transaction_requests=self.info.max_inflight_requests,
831                hashes_pending_fetch=self.hashes_pending_fetch.len(),
832                limit=limit,
833                "search breadth limited in search for intersection of hashes announced by peer and hashes pending fetch"
834            );
835
836            Some(limit)
837        }
838    }
839
840    /// Processes a resolved [`GetPooledTransactions`] request. Queues the outcome as a
841    /// [`FetchEvent`], which will then be streamed by
842    /// [`TransactionsManager`](super::TransactionsManager).
843    pub fn on_resolved_get_pooled_transactions_request_fut(
844        &mut self,
845        response: GetPooledTxResponse<N::PooledTransaction>,
846    ) -> FetchEvent<N::PooledTransaction> {
847        // update peer activity, requests for buffered hashes can only be made to idle
848        // fallback peers
849        let GetPooledTxResponse { peer_id, mut requested_hashes, result } = response;
850
851        self.decrement_inflight_request_count_for(&peer_id);
852
853        match result {
854            Ok(Ok(transactions)) => {
855                //
856                // 1. peer has failed to serve any of the hashes it has announced to us that we,
857                // as a follow, have requested
858                //
859                if transactions.is_empty() {
860                    trace!(target: "net::tx",
861                        peer_id=format!("{peer_id:#}"),
862                        requested_hashes_len=requested_hashes.len(),
863                        "received empty `PooledTransactions` response from peer, peer failed to serve hashes it announced"
864                    );
865
866                    return FetchEvent::EmptyResponse { peer_id }
867                }
868
869                //
870                // 2. filter out hashes that we didn't request
871                //
872                let payload = UnverifiedPooledTransactions::new(transactions);
873
874                let unverified_len = payload.len();
875                let (verification_outcome, verified_payload) =
876                    payload.verify(&requested_hashes, &peer_id);
877
878                let unsolicited = unverified_len - verified_payload.len();
879                if unsolicited > 0 {
880                    self.metrics.unsolicited_transactions.increment(unsolicited as u64);
881                }
882
883                let report_peer = if verification_outcome == VerificationOutcome::ReportPeer {
884                    trace!(target: "net::tx",
885                        peer_id=format!("{peer_id:#}"),
886                        unverified_len,
887                        verified_payload_len=verified_payload.len(),
888                        "received `PooledTransactions` response from peer with entries that didn't verify against request, filtered out transactions"
889                    );
890                    true
891                } else {
892                    false
893                };
894
895                // peer has only sent hashes that we didn't request
896                if verified_payload.is_empty() {
897                    return FetchEvent::FetchError { peer_id, error: RequestError::BadResponse }
898                }
899
900                //
901                // 3. stateless validation of payload, e.g. dedup
902                //
903                let unvalidated_payload_len = verified_payload.len();
904
905                let valid_payload = verified_payload.dedup();
906
907                // todo: validate based on announced tx size/type and report peer for sending
908                // invalid response <https://github.com/paradigmxyz/reth/issues/6529>. requires
909                // passing the rlp encoded length down from active session along with the decoded
910                // tx.
911
912                if valid_payload.len() != unvalidated_payload_len {
913                    trace!(target: "net::tx",
914                    peer_id=format!("{peer_id:#}"),
915                    unvalidated_payload_len,
916                    valid_payload_len=valid_payload.len(),
917                    "received `PooledTransactions` response from peer with duplicate entries, filtered them out"
918                    );
919                }
920                // valid payload will have at least one transaction at this point. even if the tx
921                // size/type announced by the peer is different to the actual tx size/type, pass on
922                // to pending pool imports pipeline for validation.
923
924                //
925                // 4. clear received hashes
926                //
927                let requested_hashes_len = requested_hashes.len();
928                let mut fetched = Vec::with_capacity(valid_payload.len());
929                requested_hashes.retain(|requested_hash| {
930                    if valid_payload.contains_key(requested_hash) {
931                        // hash is now known, stop tracking
932                        fetched.push(*requested_hash);
933                        return false
934                    }
935                    true
936                });
937                fetched.shrink_to_fit();
938                self.metrics.fetched_transactions.increment(fetched.len() as u64);
939
940                if fetched.len() < requested_hashes_len {
941                    trace!(target: "net::tx",
942                        peer_id=format!("{peer_id:#}"),
943                        requested_hashes_len=requested_hashes_len,
944                        fetched_len=fetched.len(),
945                        "peer failed to serve hashes it announced"
946                    );
947                }
948
949                //
950                // 5. buffer left over hashes
951                //
952                self.try_buffer_hashes_for_retry(requested_hashes, &peer_id);
953
954                let transactions = valid_payload.into_data().into_values().collect();
955
956                FetchEvent::TransactionsFetched { peer_id, transactions, report_peer }
957            }
958            Ok(Err(req_err)) => {
959                self.try_buffer_hashes_for_retry(requested_hashes, &peer_id);
960                FetchEvent::FetchError { peer_id, error: req_err }
961            }
962            Err(_) => {
963                self.try_buffer_hashes_for_retry(requested_hashes, &peer_id);
964                // request channel closed/dropped
965                FetchEvent::FetchError { peer_id, error: RequestError::ChannelClosed }
966            }
967        }
968    }
969}
970
971impl<N: NetworkPrimitives> Stream for TransactionFetcher<N> {
972    type Item = FetchEvent<N::PooledTransaction>;
973
974    /// Advances all inflight requests and returns the next event.
975    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
976        // `FuturesUnordered` doesn't close when `None` is returned. so just return pending.
977        // <https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=815be2b6c8003303757c3ced135f363e>
978        if self.inflight_requests.is_empty() {
979            return Poll::Pending
980        }
981
982        if let Some(resp) = ready!(self.inflight_requests.poll_next_unpin(cx)) {
983            return Poll::Ready(Some(self.on_resolved_get_pooled_transactions_request_fut(resp)))
984        }
985
986        Poll::Pending
987    }
988}
989
990impl<T: NetworkPrimitives> Default for TransactionFetcher<T> {
991    fn default() -> Self {
992        Self {
993            active_peers: LruMap::new(DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS),
994            inflight_requests: Default::default(),
995            hashes_pending_fetch: LruCache::new(DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH),
996            hashes_fetch_inflight_and_pending_fetch: LruMap::new(
997                DEFAULT_MAX_CAPACITY_CACHE_INFLIGHT_AND_PENDING_FETCH,
998            ),
999            info: TransactionFetcherInfo::default(),
1000            metrics: Default::default(),
1001        }
1002    }
1003}
1004
1005/// Metadata of a transaction hash that is yet to be fetched.
1006#[derive(Debug, Constructor)]
1007pub struct TxFetchMetadata {
1008    /// The number of times a request attempt has been made for the hash.
1009    retries: u8,
1010    /// Peers that have announced the hash, but to which a request attempt has not yet been made.
1011    fallback_peers: LruCache<PeerId>,
1012    /// Size metadata of the transaction if it has been seen in an eth68 announcement.
1013    // todo: store all seen sizes as a `(size, peer_id)` tuple to catch peers that respond with
1014    // another size tx than they announced. alt enter in request (won't catch peers announcing
1015    // wrong size for requests assembled from hashes pending fetch if stored in request fut)
1016    tx_encoded_length: Option<usize>,
1017}
1018
1019impl TxFetchMetadata {
1020    /// Returns a mutable reference to the fallback peers cache for this transaction hash.
1021    pub const fn fallback_peers_mut(&mut self) -> &mut LruCache<PeerId> {
1022        &mut self.fallback_peers
1023    }
1024
1025    /// Returns the size of the transaction, if its hash has been received in any
1026    /// [`Eth68`](reth_eth_wire::EthVersion::Eth68) announcement. If the transaction hash has only
1027    /// been seen in [`Eth66`](reth_eth_wire::EthVersion::Eth66) announcements so far, this will
1028    /// return `None`.
1029    pub const fn tx_encoded_len(&self) -> Option<usize> {
1030        self.tx_encoded_length
1031    }
1032}
1033
1034/// Represents possible events from fetching transactions.
1035#[derive(Debug)]
1036pub enum FetchEvent<T = PooledTransaction> {
1037    /// Triggered when transactions are successfully fetched.
1038    TransactionsFetched {
1039        /// The ID of the peer from which transactions were fetched.
1040        peer_id: PeerId,
1041        /// The transactions that were fetched, if available.
1042        transactions: PooledTransactions<T>,
1043        /// Whether the peer should be penalized for sending unsolicited transactions or for
1044        /// misbehavior.
1045        report_peer: bool,
1046    },
1047    /// Triggered when there is an error in fetching transactions.
1048    FetchError {
1049        /// The ID of the peer from which an attempt to fetch transactions resulted in an error.
1050        peer_id: PeerId,
1051        /// The specific error that occurred while fetching.
1052        error: RequestError,
1053    },
1054    /// An empty response was received.
1055    EmptyResponse {
1056        /// The ID of the sender.
1057        peer_id: PeerId,
1058    },
1059}
1060
1061/// An inflight request for [`PooledTransactions`] from a peer.
1062#[derive(Debug)]
1063pub struct GetPooledTxRequest<T = PooledTransaction> {
1064    peer_id: PeerId,
1065    /// Transaction hashes that were requested, for cleanup purposes
1066    requested_hashes: RequestTxHashes,
1067    response: oneshot::Receiver<RequestResult<PooledTransactions<T>>>,
1068}
1069
1070/// Upon reception of a response, a [`GetPooledTxRequest`] is deconstructed to form a
1071/// [`GetPooledTxResponse`].
1072#[derive(Debug)]
1073pub struct GetPooledTxResponse<T = PooledTransaction> {
1074    peer_id: PeerId,
1075    /// Transaction hashes that were requested, for cleanup purposes, since peer may only return a
1076    /// subset of requested hashes.
1077    requested_hashes: RequestTxHashes,
1078    result: Result<RequestResult<PooledTransactions<T>>, RecvError>,
1079}
1080
1081/// Stores the response receiver made by sending a [`GetPooledTransactions`] request to a peer's
1082/// session.
1083#[must_use = "futures do nothing unless polled"]
1084#[pin_project::pin_project]
1085#[derive(Debug)]
1086pub struct GetPooledTxRequestFut<T = PooledTransaction> {
1087    #[pin]
1088    inner: Option<GetPooledTxRequest<T>>,
1089}
1090
1091impl<T> GetPooledTxRequestFut<T> {
1092    #[inline]
1093    const fn new(
1094        peer_id: PeerId,
1095        requested_hashes: RequestTxHashes,
1096        response: oneshot::Receiver<RequestResult<PooledTransactions<T>>>,
1097    ) -> Self {
1098        Self { inner: Some(GetPooledTxRequest { peer_id, requested_hashes, response }) }
1099    }
1100}
1101
1102impl<T> Future for GetPooledTxRequestFut<T> {
1103    type Output = GetPooledTxResponse<T>;
1104
1105    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1106        let mut req = self.as_mut().project().inner.take().expect("polled after completion");
1107        match req.response.poll_unpin(cx) {
1108            Poll::Ready(result) => Poll::Ready(GetPooledTxResponse {
1109                peer_id: req.peer_id,
1110                requested_hashes: req.requested_hashes,
1111                result,
1112            }),
1113            Poll::Pending => {
1114                self.project().inner.set(Some(req));
1115                Poll::Pending
1116            }
1117        }
1118    }
1119}
1120
1121/// Wrapper of unverified [`PooledTransactions`].
1122#[derive(Debug, Constructor, Deref)]
1123pub struct UnverifiedPooledTransactions<T> {
1124    txns: PooledTransactions<T>,
1125}
1126
1127/// [`PooledTransactions`] that have been successfully verified.
1128#[derive(Debug, Constructor, Deref)]
1129pub struct VerifiedPooledTransactions<T> {
1130    txns: PooledTransactions<T>,
1131}
1132
1133impl<T: SignedTransaction> DedupPayload for VerifiedPooledTransactions<T> {
1134    type Value = T;
1135
1136    fn is_empty(&self) -> bool {
1137        self.txns.is_empty()
1138    }
1139
1140    fn len(&self) -> usize {
1141        self.txns.len()
1142    }
1143
1144    fn dedup(self) -> PartiallyValidData<Self::Value> {
1145        PartiallyValidData::from_raw_data(
1146            self.txns.into_iter().map(|tx| (*tx.tx_hash(), tx)).collect(),
1147            None,
1148        )
1149    }
1150}
1151
1152trait VerifyPooledTransactionsResponse {
1153    type Transaction: SignedTransaction;
1154
1155    fn verify(
1156        self,
1157        requested_hashes: &RequestTxHashes,
1158        peer_id: &PeerId,
1159    ) -> (VerificationOutcome, VerifiedPooledTransactions<Self::Transaction>);
1160}
1161
1162impl<T: SignedTransaction> VerifyPooledTransactionsResponse for UnverifiedPooledTransactions<T> {
1163    type Transaction = T;
1164
1165    fn verify(
1166        self,
1167        requested_hashes: &RequestTxHashes,
1168        _peer_id: &PeerId,
1169    ) -> (VerificationOutcome, VerifiedPooledTransactions<T>) {
1170        let mut verification_outcome = VerificationOutcome::Ok;
1171
1172        let Self { mut txns } = self;
1173
1174        #[cfg(debug_assertions)]
1175        let mut tx_hashes_not_requested: smallvec::SmallVec<[TxHash; 16]> = smallvec::smallvec!();
1176        #[cfg(not(debug_assertions))]
1177        let mut tx_hashes_not_requested_count = 0;
1178
1179        txns.0.retain(|tx| {
1180            if !requested_hashes.contains(tx.tx_hash()) {
1181                verification_outcome = VerificationOutcome::ReportPeer;
1182
1183                #[cfg(debug_assertions)]
1184                tx_hashes_not_requested.push(*tx.tx_hash());
1185                #[cfg(not(debug_assertions))]
1186                {
1187                    tx_hashes_not_requested_count += 1;
1188                }
1189
1190                return false
1191            }
1192            true
1193        });
1194
1195        #[cfg(debug_assertions)]
1196        if !tx_hashes_not_requested.is_empty() {
1197            trace!(target: "net::tx",
1198                peer_id=format!("{_peer_id:#}"),
1199                ?tx_hashes_not_requested,
1200                "transactions in `PooledTransactions` response from peer were not requested"
1201            );
1202        }
1203        #[cfg(not(debug_assertions))]
1204        if tx_hashes_not_requested_count != 0 {
1205            trace!(target: "net::tx",
1206                peer_id=format!("{_peer_id:#}"),
1207                tx_hashes_not_requested_count,
1208                "transactions in `PooledTransactions` response from peer were not requested"
1209            );
1210        }
1211
1212        (verification_outcome, VerifiedPooledTransactions::new(txns))
1213    }
1214}
1215
1216/// Outcome from verifying a [`PooledTransactions`] response. Signals to caller whether to penalize
1217/// the sender of the response or not.
1218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1219pub enum VerificationOutcome {
1220    /// Peer behaves appropriately.
1221    Ok,
1222    /// A penalty should be flagged for the peer. Peer sent a response with unacceptably
1223    /// invalid entries.
1224    ReportPeer,
1225}
1226
1227/// Tracks stats about the [`TransactionFetcher`].
1228#[derive(Debug, Constructor)]
1229pub struct TransactionFetcherInfo {
1230    /// Max inflight [`GetPooledTransactions`] requests.
1231    pub max_inflight_requests: usize,
1232    /// Max inflight [`GetPooledTransactions`] requests per peer.
1233    pub max_inflight_requests_per_peer: u8,
1234    /// Soft limit for the byte size of the expected [`PooledTransactions`] response, upon packing
1235    /// a [`GetPooledTransactions`] request with hashes (by default less than 2 MiB worth of
1236    /// transactions is requested).
1237    pub soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
1238    /// Soft limit for the byte size of a [`PooledTransactions`] response, upon assembling the
1239    /// response. Spec'd at 2 MiB, but can be adjusted for research purpose.
1240    pub soft_limit_byte_size_pooled_transactions_response: usize,
1241    /// Max capacity of the cache of transaction hashes, for transactions that weren't yet fetched.
1242    /// A transaction is pending fetch if its hash didn't fit into a [`GetPooledTransactions`] yet,
1243    /// or it wasn't returned upon request to peers.
1244    pub max_capacity_cache_txns_pending_fetch: u32,
1245}
1246
1247impl Default for TransactionFetcherInfo {
1248    fn default() -> Self {
1249        Self::new(
1250            DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS as usize,
1251            DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
1252            DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
1253            SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
1254            DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH,
1255        )
1256    }
1257}
1258
1259impl From<TransactionFetcherConfig> for TransactionFetcherInfo {
1260    fn from(config: TransactionFetcherConfig) -> Self {
1261        let TransactionFetcherConfig {
1262            max_inflight_requests,
1263            max_inflight_requests_per_peer,
1264            soft_limit_byte_size_pooled_transactions_response,
1265            soft_limit_byte_size_pooled_transactions_response_on_pack_request,
1266            max_capacity_cache_txns_pending_fetch,
1267        } = config;
1268
1269        Self::new(
1270            max_inflight_requests as usize,
1271            max_inflight_requests_per_peer,
1272            soft_limit_byte_size_pooled_transactions_response_on_pack_request,
1273            soft_limit_byte_size_pooled_transactions_response,
1274            max_capacity_cache_txns_pending_fetch,
1275        )
1276    }
1277}
1278
1279#[derive(Debug, Default)]
1280struct TxFetcherSearchDurations {
1281    find_idle_peer: Duration,
1282    fill_request: Duration,
1283}
1284
1285#[cfg(test)]
1286mod test {
1287    use super::*;
1288    use crate::test_utils::transactions::{buffer_hash_to_tx_fetcher, new_mock_session};
1289    use alloy_primitives::{hex, B256};
1290    use alloy_rlp::Decodable;
1291    use derive_more::IntoIterator;
1292    use reth_eth_wire_types::EthVersion;
1293    use reth_ethereum_primitives::TransactionSigned;
1294    use std::{collections::HashSet, str::FromStr};
1295
1296    #[derive(IntoIterator)]
1297    struct TestValidAnnouncementData(Vec<(TxHash, Option<(u8, usize)>)>);
1298
1299    impl HandleMempoolData for TestValidAnnouncementData {
1300        fn is_empty(&self) -> bool {
1301            self.0.is_empty()
1302        }
1303
1304        fn len(&self) -> usize {
1305            self.0.len()
1306        }
1307
1308        fn retain_by_hash(&mut self, mut f: impl FnMut(&TxHash) -> bool) {
1309            self.0.retain(|(hash, _)| f(hash))
1310        }
1311    }
1312
1313    impl HandleVersionedMempoolData for TestValidAnnouncementData {
1314        fn msg_version(&self) -> EthVersion {
1315            EthVersion::Eth68
1316        }
1317    }
1318
1319    #[test]
1320    fn pack_eth68_request() {
1321        reth_tracing::init_test_tracing();
1322
1323        // RIG TEST
1324
1325        let tx_fetcher = &mut TransactionFetcher::<EthNetworkPrimitives>::default();
1326
1327        let eth68_hashes = [
1328            B256::from_slice(&[1; 32]),
1329            B256::from_slice(&[2; 32]),
1330            B256::from_slice(&[3; 32]),
1331            B256::from_slice(&[4; 32]),
1332            B256::from_slice(&[5; 32]),
1333        ];
1334        let eth68_sizes = [
1335            DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ - MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED - 1, // first will fit
1336            DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ, // second won't
1337            2, // free space > `MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED`, third will fit, no more after this
1338            9,
1339            0,
1340        ];
1341
1342        let expected_request_hashes =
1343            [eth68_hashes[0], eth68_hashes[2]].into_iter().collect::<HashSet<_>>();
1344
1345        let expected_surplus_hashes =
1346            [eth68_hashes[1], eth68_hashes[3], eth68_hashes[4]].into_iter().collect::<HashSet<_>>();
1347
1348        let mut eth68_hashes_to_request = RequestTxHashes::with_capacity(3);
1349
1350        let valid_announcement_data = TestValidAnnouncementData(
1351            eth68_hashes
1352                .into_iter()
1353                .zip(eth68_sizes)
1354                .map(|(hash, size)| (hash, Some((0u8, size))))
1355                .collect::<Vec<_>>(),
1356        );
1357
1358        // TEST
1359
1360        let surplus_eth68_hashes =
1361            tx_fetcher.pack_request_eth68(&mut eth68_hashes_to_request, valid_announcement_data);
1362
1363        let eth68_hashes_to_request = eth68_hashes_to_request.into_iter().collect::<HashSet<_>>();
1364        let surplus_eth68_hashes = surplus_eth68_hashes.into_iter().collect::<HashSet<_>>();
1365
1366        assert_eq!(expected_request_hashes, eth68_hashes_to_request);
1367        assert_eq!(expected_surplus_hashes, surplus_eth68_hashes);
1368    }
1369
1370    #[tokio::test]
1371    async fn test_on_fetch_pending_hashes() {
1372        reth_tracing::init_test_tracing();
1373
1374        let tx_fetcher = &mut TransactionFetcher::default();
1375
1376        // RIG TEST
1377
1378        // hashes that will be fetched because they are stored as pending fetch
1379        let seen_hashes = [
1380            B256::from_slice(&[1; 32]),
1381            B256::from_slice(&[2; 32]),
1382            B256::from_slice(&[3; 32]),
1383            B256::from_slice(&[4; 32]),
1384        ];
1385        //
1386        // txns 1-3 are small, all will fit in request. no metadata has been made available for
1387        // hash 4, it has only been seen over eth66 conn, so average tx size will be assumed in
1388        // filling request.
1389        let seen_eth68_hashes_sizes = [120, 158, 116];
1390
1391        // peer that will fetch seen hashes because they are pending fetch
1392        let peer_1 = PeerId::new([1; 64]);
1393        // second peer, won't do anything in this test
1394        let peer_2 = PeerId::new([2; 64]);
1395
1396        // add seen hashes to peers seen transactions
1397        //
1398        // get handle for peer_1's session to receive request for pending hashes
1399        let (mut peer_1_data, mut peer_1_mock_session_rx) =
1400            new_mock_session(peer_1, EthVersion::Eth66);
1401        for hash in &seen_hashes {
1402            peer_1_data.seen_transactions.insert(*hash);
1403        }
1404        let (mut peer_2_data, _) = new_mock_session(peer_2, EthVersion::Eth66);
1405        for hash in &seen_hashes {
1406            peer_2_data.seen_transactions.insert(*hash);
1407        }
1408        let mut peers = HashMap::default();
1409        peers.insert(peer_1, peer_1_data);
1410        peers.insert(peer_2, peer_2_data);
1411
1412        // insert seen_hashes into tx fetcher
1413        for i in 0..3 {
1414            // insert peer_2 as fallback peer for seen_hashes
1415            buffer_hash_to_tx_fetcher(
1416                tx_fetcher,
1417                seen_hashes[i],
1418                peer_2,
1419                0,
1420                Some(seen_eth68_hashes_sizes[i]),
1421            );
1422        }
1423        buffer_hash_to_tx_fetcher(tx_fetcher, seen_hashes[3], peer_2, 0, None);
1424
1425        // insert pending hash without peer_1 as fallback peer, only with peer_2 as fallback peer
1426        let hash_other = B256::from_slice(&[5; 32]);
1427        buffer_hash_to_tx_fetcher(tx_fetcher, hash_other, peer_2, 0, None);
1428
1429        // add peer_1 as lru fallback peer for seen hashes
1430        for hash in &seen_hashes {
1431            buffer_hash_to_tx_fetcher(tx_fetcher, *hash, peer_1, 0, None);
1432        }
1433
1434        // seen hashes and the random hash from peer_2 are pending fetch
1435        assert_eq!(tx_fetcher.num_pending_hashes(), 5);
1436
1437        // TEST
1438
1439        tx_fetcher.on_fetch_pending_hashes(&peers, |_| true);
1440
1441        // mock session of peer_1 receives request
1442        let req = peer_1_mock_session_rx
1443            .recv()
1444            .await
1445            .expect("peer session should receive request with buffered hashes");
1446        let PeerRequest::GetPooledTransactions { request, .. } = req else { unreachable!() };
1447        let GetPooledTransactions(requested_hashes) = request;
1448
1449        assert_eq!(
1450            requested_hashes.into_iter().collect::<HashSet<_>>(),
1451            seen_hashes.into_iter().collect::<HashSet<_>>()
1452        )
1453    }
1454
1455    #[test]
1456    fn verify_response_hashes() {
1457        let input = hex!(
1458            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598daa"
1459        );
1460        let signed_tx_1: PooledTransaction =
1461            TransactionSigned::decode(&mut &input[..]).unwrap().try_into().unwrap();
1462        let input = hex!(
1463            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
1464        );
1465        let signed_tx_2: PooledTransaction =
1466            TransactionSigned::decode(&mut &input[..]).unwrap().try_into().unwrap();
1467
1468        // only tx 1 is requested
1469        let request_hashes = [
1470            B256::from_str("0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e67890")
1471                .unwrap(),
1472            *signed_tx_1.hash(),
1473            B256::from_str("0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4e12345")
1474                .unwrap(),
1475            B256::from_str("0x3b9aca00f0671c9a2a1b817a0a78d3fe0c0f776cccb2a8c3c1b412a4f4edabe3")
1476                .unwrap(),
1477        ];
1478
1479        for hash in &request_hashes {
1480            assert_ne!(hash, signed_tx_2.hash())
1481        }
1482
1483        let request_hashes = RequestTxHashes::new(request_hashes.into_iter().collect());
1484
1485        // but response contains tx 1 + another tx
1486        let response_txns = PooledTransactions(vec![signed_tx_1.clone(), signed_tx_2]);
1487        let payload = UnverifiedPooledTransactions::new(response_txns);
1488
1489        let (outcome, verified_payload) = payload.verify(&request_hashes, &PeerId::ZERO);
1490
1491        assert_eq!(VerificationOutcome::ReportPeer, outcome);
1492        assert_eq!(1, verified_payload.len());
1493        assert!(verified_payload.contains(&signed_tx_1));
1494    }
1495}