Skip to main content

reth_network/transactions/
mod.rs

1//! Transactions management for the p2p network.
2
3use alloy_consensus::transaction::TxHashRef;
4use rayon::iter::{IntoParallelIterator, ParallelIterator};
5
6/// Aggregation on configurable parameters for [`TransactionsManager`].
7pub mod config;
8/// Default and spec'd bounds.
9pub mod constants;
10/// Component responsible for fetching transactions from [`NewPooledTransactionHashes`].
11pub mod fetcher;
12/// Defines the traits for transaction-related policies.
13pub mod policy;
14
15pub use self::constants::{
16    tx_fetcher::DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
17    SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
18};
19use config::AnnouncementAcceptance;
20pub use config::{
21    AnnouncementFilteringPolicy, TransactionFetcherConfig, TransactionIngressPolicy,
22    TransactionPropagationMode, TransactionPropagationPolicy, TransactionsManagerConfig,
23};
24use policy::NetworkPolicies;
25
26pub(crate) use fetcher::{FetchEvent, TransactionFetcher};
27
28use self::constants::{tx_manager::*, DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE};
29use crate::{
30    budget::{
31        DEFAULT_BUDGET_TRY_DRAIN_NETWORK_TRANSACTION_EVENTS,
32        DEFAULT_BUDGET_TRY_DRAIN_PENDING_POOL_IMPORTS, DEFAULT_BUDGET_TRY_DRAIN_STREAM,
33    },
34    cache::LruCache,
35    duration_metered_exec, metered_poll_nested_stream_with_budget,
36    metrics::{
37        AnnouncedTxTypesMetrics, TransactionsManagerMetrics, NETWORK_POOL_TRANSACTIONS_SCOPE,
38    },
39    transactions::config::{StrictEthAnnouncementFilter, TransactionPropagationKind},
40    NetworkHandle, TxTypesCounter,
41};
42use alloy_primitives::{TxHash, B256};
43use constants::SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE;
44use futures::{stream::FuturesUnordered, Future, StreamExt};
45use reth_eth_wire::{
46    DedupPayload, EthNetworkPrimitives, EthVersion, GetPooledTransactions, HandleMempoolData,
47    HandleVersionedMempoolData, NetworkPrimitives, NewPooledTransactionHashes,
48    NewPooledTransactionHashes66, NewPooledTransactionHashes68, PooledTransactions,
49    RequestTxHashes, Transactions, ValidAnnouncementData,
50};
51use reth_ethereum_primitives::{TransactionSigned, TxType};
52use reth_metrics::common::mpsc::UnboundedMeteredReceiver;
53use reth_network_api::{
54    events::{PeerEvent, SessionInfo},
55    NetworkEvent, NetworkEventListenerProvider, PeerKind, PeerRequest, PeerRequestSender, Peers,
56};
57use reth_network_p2p::{
58    error::{RequestError, RequestResult},
59    sync::SyncStateProvider,
60};
61use reth_network_peers::PeerId;
62use reth_network_types::ReputationChangeKind;
63use reth_primitives_traits::SignedTransaction;
64use reth_tokio_util::EventStream;
65use reth_transaction_pool::{
66    error::{PoolError, PoolResult},
67    AddedTransactionOutcome, GetPooledTransactionLimit, PoolTransaction, PropagateKind,
68    PropagatedTransactions, TransactionPool, ValidPoolTransaction,
69};
70use std::{
71    collections::{hash_map::Entry, HashMap, HashSet},
72    pin::Pin,
73    sync::{
74        atomic::{AtomicUsize, Ordering},
75        Arc,
76    },
77    task::{Context, Poll},
78    time::{Duration, Instant},
79};
80use tokio::sync::{mpsc, oneshot, oneshot::error::RecvError};
81use tokio_stream::wrappers::UnboundedReceiverStream;
82use tracing::{debug, trace};
83
84/// The future for importing transactions into the pool.
85///
86/// Resolves with the result of each transaction import.
87pub type PoolImportFuture =
88    Pin<Box<dyn Future<Output = Vec<PoolResult<AddedTransactionOutcome>>> + Send + 'static>>;
89
90/// Api to interact with [`TransactionsManager`] task.
91///
92/// This can be obtained via [`TransactionsManager::handle`] and can be used to manually interact
93/// with the [`TransactionsManager`] task once it is spawned.
94///
95/// For example [`TransactionsHandle::get_peer_transaction_hashes`] returns the transaction hashes
96/// known by a specific peer.
97#[derive(Debug, Clone)]
98pub struct TransactionsHandle<N: NetworkPrimitives = EthNetworkPrimitives> {
99    /// Command channel to the [`TransactionsManager`]
100    manager_tx: mpsc::UnboundedSender<TransactionsCommand<N>>,
101}
102
103impl<N: NetworkPrimitives> TransactionsHandle<N> {
104    fn send(&self, cmd: TransactionsCommand<N>) {
105        let _ = self.manager_tx.send(cmd);
106    }
107
108    /// Fetch the [`PeerRequestSender`] for the given peer.
109    async fn peer_handle(
110        &self,
111        peer_id: PeerId,
112    ) -> Result<Option<PeerRequestSender<PeerRequest<N>>>, RecvError> {
113        let (tx, rx) = oneshot::channel();
114        self.send(TransactionsCommand::GetPeerSender { peer_id, peer_request_sender: tx });
115        rx.await
116    }
117
118    /// Manually propagate the transaction that belongs to the hash.
119    pub fn propagate(&self, hash: TxHash) {
120        self.send(TransactionsCommand::PropagateHash(hash))
121    }
122
123    /// Manually propagate the transaction hash to a specific peer.
124    ///
125    /// Note: this only propagates if the pool contains the transaction.
126    pub fn propagate_hash_to(&self, hash: TxHash, peer: PeerId) {
127        self.propagate_hashes_to(Some(hash), peer)
128    }
129
130    /// Manually propagate the transaction hashes to a specific peer.
131    ///
132    /// Note: this only propagates the transactions that are known to the pool.
133    pub fn propagate_hashes_to(&self, hash: impl IntoIterator<Item = TxHash>, peer: PeerId) {
134        let hashes = hash.into_iter().collect::<Vec<_>>();
135        if hashes.is_empty() {
136            return
137        }
138        self.send(TransactionsCommand::PropagateHashesTo(hashes, peer))
139    }
140
141    /// Request the active peer IDs from the [`TransactionsManager`].
142    pub async fn get_active_peers(&self) -> Result<HashSet<PeerId>, RecvError> {
143        let (tx, rx) = oneshot::channel();
144        self.send(TransactionsCommand::GetActivePeers(tx));
145        rx.await
146    }
147
148    /// Manually propagate full transaction hashes to a specific peer.
149    ///
150    /// Do nothing if transactions are empty.
151    pub fn propagate_transactions_to(&self, transactions: Vec<TxHash>, peer: PeerId) {
152        if transactions.is_empty() {
153            return
154        }
155        self.send(TransactionsCommand::PropagateTransactionsTo(transactions, peer))
156    }
157
158    /// Manually propagate the given transaction hashes to all peers.
159    ///
160    /// It's up to the [`TransactionsManager`] whether the transactions are sent as hashes or in
161    /// full.
162    pub fn propagate_transactions(&self, transactions: Vec<TxHash>) {
163        if transactions.is_empty() {
164            return
165        }
166        self.send(TransactionsCommand::PropagateTransactions(transactions))
167    }
168
169    /// Manually propagate the given transactions to all peers.
170    ///
171    /// It's up to the [`TransactionsManager`] whether the transactions are sent as hashes or in
172    /// full.
173    pub fn broadcast_transactions(
174        &self,
175        transactions: impl IntoIterator<Item = N::BroadcastedTransaction>,
176    ) {
177        let transactions =
178            transactions.into_iter().map(PropagateTransaction::new).collect::<Vec<_>>();
179        if transactions.is_empty() {
180            return
181        }
182        self.send(TransactionsCommand::BroadcastTransactions(transactions))
183    }
184
185    /// Request the transaction hashes known by specific peers.
186    pub async fn get_transaction_hashes(
187        &self,
188        peers: Vec<PeerId>,
189    ) -> Result<HashMap<PeerId, HashSet<TxHash>>, RecvError> {
190        if peers.is_empty() {
191            return Ok(Default::default())
192        }
193        let (tx, rx) = oneshot::channel();
194        self.send(TransactionsCommand::GetTransactionHashes { peers, tx });
195        rx.await
196    }
197
198    /// Request the transaction hashes known by a specific peer.
199    pub async fn get_peer_transaction_hashes(
200        &self,
201        peer: PeerId,
202    ) -> Result<HashSet<TxHash>, RecvError> {
203        let res = self.get_transaction_hashes(vec![peer]).await?;
204        Ok(res.into_values().next().unwrap_or_default())
205    }
206
207    /// Requests the transactions directly from the given peer.
208    ///
209    /// Returns `None` if the peer is not connected.
210    ///
211    /// **Note**: this returns the response from the peer as received.
212    pub async fn get_pooled_transactions_from(
213        &self,
214        peer_id: PeerId,
215        hashes: Vec<B256>,
216    ) -> Result<Option<Vec<N::PooledTransaction>>, RequestError> {
217        let Some(peer) = self.peer_handle(peer_id).await? else { return Ok(None) };
218
219        let (tx, rx) = oneshot::channel();
220        let request = PeerRequest::GetPooledTransactions { request: hashes.into(), response: tx };
221        peer.try_send(request).ok();
222
223        rx.await?.map(|res| Some(res.0))
224    }
225}
226
227/// Manages transactions on top of the p2p network.
228///
229/// This can be spawned to another task and is supposed to be run as background service.
230/// [`TransactionsHandle`] can be used as frontend to programmatically send commands to it and
231/// interact with it.
232///
233/// The [`TransactionsManager`] is responsible for:
234///    - handling incoming eth messages for transactions.
235///    - serving transaction requests.
236///    - propagate transactions
237///
238/// This type communicates with the [`NetworkManager`](crate::NetworkManager) in both directions.
239///   - receives incoming network messages.
240///   - sends messages to dispatch (responses, propagate tx)
241///
242/// It is directly connected to the [`TransactionPool`] to retrieve requested transactions and
243/// propagate new transactions over the network.
244///
245/// It can be configured with different policies for transaction propagation and announcement
246/// filtering. See [`NetworkPolicies`] for more details.
247///
248/// ## Network Transaction Processing
249///
250/// ### Message Types
251///
252/// - **`Transactions`**: Full transaction broadcasts (rejects blob transactions)
253/// - **`NewPooledTransactionHashes`**: Hash announcements
254///
255/// ### Peer Tracking
256///
257/// - Maintains per-peer transaction cache (default: 10,240 entries)
258/// - Prevents duplicate imports and enables efficient propagation
259///
260/// ### Bad Transaction Handling
261///
262/// Caches and rejects transactions with consensus violations (gas, signature, chain ID).
263/// Penalizes peers sending invalid transactions.
264///
265/// ### Import Management
266///
267/// Limits concurrent pool imports and backs off when approaching capacity.
268///
269/// ### Transaction Fetching
270///
271/// For announced transactions: filters known → queues unknown → fetches → imports
272///
273/// ### Propagation Rules
274///
275/// Based on: origin (Local/External/Private), peer capabilities, and network state.
276/// Disabled during initial sync.
277///
278/// ### Security
279///
280/// Rate limiting via reputation, bad transaction isolation, peer scoring.
281#[derive(Debug)]
282#[must_use = "Manager does nothing unless polled."]
283pub struct TransactionsManager<Pool, N: NetworkPrimitives = EthNetworkPrimitives> {
284    /// Access to the transaction pool.
285    pool: Pool,
286    /// Network access.
287    network: NetworkHandle<N>,
288    /// Subscriptions to all network related events.
289    ///
290    /// From which we get all new incoming transaction related messages.
291    network_events: EventStream<NetworkEvent<PeerRequest<N>>>,
292    /// Transaction fetcher to handle inflight and missing transaction requests.
293    transaction_fetcher: TransactionFetcher<N>,
294    /// All currently pending transactions grouped by peers.
295    ///
296    /// This way we can track incoming transactions and prevent multiple pool imports for the same
297    /// transaction
298    transactions_by_peers: HashMap<TxHash, HashSet<PeerId>>,
299    /// Transactions that are currently imported into the `Pool`.
300    ///
301    /// The import process includes:
302    ///  - validation of the transactions, e.g. transaction is well formed: valid tx type, fees are
303    ///    valid, or for 4844 transaction the blobs are valid. See also
304    ///    [`EthTransactionValidator`](reth_transaction_pool::validate::EthTransactionValidator)
305    /// - if the transaction is valid, it is added into the pool.
306    ///
307    /// Once the new transaction reaches the __pending__ state it will be emitted by the pool via
308    /// [`TransactionPool::pending_transactions_listener`] and arrive at the `pending_transactions`
309    /// receiver.
310    pool_imports: FuturesUnordered<PoolImportFuture>,
311    /// Stats on pending pool imports that help the node self-monitor.
312    pending_pool_imports_info: PendingPoolImportsInfo,
313    /// Bad imports.
314    bad_imports: LruCache<TxHash>,
315    /// All the connected peers.
316    peers: HashMap<PeerId, PeerMetadata<N>>,
317    /// Send half for the command channel.
318    ///
319    /// This is kept so that a new [`TransactionsHandle`] can be created at any time.
320    command_tx: mpsc::UnboundedSender<TransactionsCommand<N>>,
321    /// Incoming commands from [`TransactionsHandle`].
322    ///
323    /// This will only receive commands if a user manually sends a command to the manager through
324    /// the [`TransactionsHandle`] to interact with this type directly.
325    command_rx: UnboundedReceiverStream<TransactionsCommand<N>>,
326    /// A stream that yields new __pending__ transactions.
327    ///
328    /// A transaction is considered __pending__ if it is executable on the current state of the
329    /// chain. In other words, this only yields transactions that satisfy all consensus
330    /// requirements, these include:
331    ///   - no nonce gaps
332    ///   - all dynamic fee requirements are (currently) met
333    ///   - account has enough balance to cover the transaction's gas
334    pending_transactions: mpsc::Receiver<TxHash>,
335    /// Incoming events from the [`NetworkManager`](crate::NetworkManager).
336    transaction_events: UnboundedMeteredReceiver<NetworkTransactionEvent<N>>,
337    /// How the `TransactionsManager` is configured.
338    config: TransactionsManagerConfig,
339    /// Network Policies
340    policies: NetworkPolicies<N>,
341    /// `TransactionsManager` metrics
342    metrics: TransactionsManagerMetrics,
343    /// `AnnouncedTxTypes` metrics
344    announced_tx_types_metrics: AnnouncedTxTypesMetrics,
345}
346
347impl<Pool: TransactionPool, N: NetworkPrimitives> TransactionsManager<Pool, N> {
348    /// Sets up a new instance.
349    ///
350    /// Note: This expects an existing [`NetworkManager`](crate::NetworkManager) instance.
351    pub fn new(
352        network: NetworkHandle<N>,
353        pool: Pool,
354        from_network: mpsc::UnboundedReceiver<NetworkTransactionEvent<N>>,
355        transactions_manager_config: TransactionsManagerConfig,
356    ) -> Self {
357        Self::with_policy(
358            network,
359            pool,
360            from_network,
361            transactions_manager_config,
362            NetworkPolicies::new(
363                TransactionPropagationKind::default(),
364                StrictEthAnnouncementFilter::default(),
365            ),
366        )
367    }
368}
369
370impl<Pool: TransactionPool, N: NetworkPrimitives> TransactionsManager<Pool, N> {
371    /// Sets up a new instance with given the settings.
372    ///
373    /// Note: This expects an existing [`NetworkManager`](crate::NetworkManager) instance.
374    pub fn with_policy(
375        network: NetworkHandle<N>,
376        pool: Pool,
377        from_network: mpsc::UnboundedReceiver<NetworkTransactionEvent<N>>,
378        transactions_manager_config: TransactionsManagerConfig,
379        policies: NetworkPolicies<N>,
380    ) -> Self {
381        let network_events = network.event_listener();
382
383        let (command_tx, command_rx) = mpsc::unbounded_channel();
384
385        let transaction_fetcher = TransactionFetcher::with_transaction_fetcher_config(
386            &transactions_manager_config.transaction_fetcher_config,
387        );
388
389        // install a listener for new __pending__ transactions that are allowed to be propagated
390        // over the network
391        let pending = pool.pending_transactions_listener();
392        let pending_pool_imports_info = PendingPoolImportsInfo::default();
393        let metrics = TransactionsManagerMetrics::default();
394        metrics
395            .capacity_pending_pool_imports
396            .increment(pending_pool_imports_info.max_pending_pool_imports as u64);
397
398        Self {
399            pool,
400            network,
401            network_events,
402            transaction_fetcher,
403            transactions_by_peers: Default::default(),
404            pool_imports: Default::default(),
405            pending_pool_imports_info: PendingPoolImportsInfo::new(
406                DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
407            ),
408            bad_imports: LruCache::new(DEFAULT_MAX_COUNT_BAD_IMPORTS),
409            peers: Default::default(),
410            command_tx,
411            command_rx: UnboundedReceiverStream::new(command_rx),
412            pending_transactions: pending,
413            transaction_events: UnboundedMeteredReceiver::new(
414                from_network,
415                NETWORK_POOL_TRANSACTIONS_SCOPE,
416            ),
417            config: transactions_manager_config,
418            policies,
419            metrics,
420            announced_tx_types_metrics: AnnouncedTxTypesMetrics::default(),
421        }
422    }
423
424    /// Returns a new handle that can send commands to this type.
425    pub fn handle(&self) -> TransactionsHandle<N> {
426        TransactionsHandle { manager_tx: self.command_tx.clone() }
427    }
428
429    /// Returns `true` if [`TransactionsManager`] has capacity to request pending hashes. Returns
430    /// `false` if [`TransactionsManager`] is operating close to full capacity.
431    fn has_capacity_for_fetching_pending_hashes(&self) -> bool {
432        self.has_capacity_for_pending_pool_imports() &&
433            self.transaction_fetcher.has_capacity_for_fetching_pending_hashes()
434    }
435
436    /// Returns `true` if [`TransactionsManager`] has capacity for more pending pool imports.
437    fn has_capacity_for_pending_pool_imports(&self) -> bool {
438        self.remaining_pool_import_capacity() > 0
439    }
440
441    /// Returns the remaining capacity for pending pool imports.
442    fn remaining_pool_import_capacity(&self) -> usize {
443        self.pending_pool_imports_info.max_pending_pool_imports.saturating_sub(
444            self.pending_pool_imports_info.pending_pool_imports.load(Ordering::Relaxed),
445        )
446    }
447
448    fn report_peer_bad_transactions(&self, peer_id: PeerId) {
449        self.report_peer(peer_id, ReputationChangeKind::BadTransactions);
450        self.metrics.reported_bad_transactions.increment(1);
451    }
452
453    fn report_peer(&self, peer_id: PeerId, kind: ReputationChangeKind) {
454        trace!(target: "net::tx", ?peer_id, ?kind, "reporting reputation change");
455        self.network.reputation_change(peer_id, kind);
456    }
457
458    fn report_already_seen(&self, peer_id: PeerId) {
459        trace!(target: "net::tx", ?peer_id, "Penalizing peer for already seen transaction");
460        self.network.reputation_change(peer_id, ReputationChangeKind::AlreadySeenTransaction);
461    }
462
463    /// Clear the transaction
464    fn on_good_import(&mut self, hash: TxHash) {
465        self.transactions_by_peers.remove(&hash);
466    }
467
468    /// Penalize the peers that intentionally sent the bad transaction, and cache it to avoid
469    /// fetching or importing it again.
470    ///
471    /// Errors that count as bad transactions are:
472    ///
473    /// - intrinsic gas too low
474    /// - exceeds gas limit
475    /// - gas uint overflow
476    /// - exceeds max init code size
477    /// - oversized data
478    /// - signer account has bytecode
479    /// - chain id mismatch
480    /// - old legacy chain id
481    /// - tx type not supported
482    ///
483    /// (and additionally for blobs txns...)
484    ///
485    /// - no blobs
486    /// - too many blobs
487    /// - invalid kzg proof
488    /// - kzg error
489    /// - not blob transaction (tx type mismatch)
490    /// - wrong versioned kzg commitment hash
491    fn on_bad_import(&mut self, err: PoolError) {
492        let peers = self.transactions_by_peers.remove(&err.hash);
493
494        // if we're _currently_ syncing, we ignore a bad transaction
495        if !err.is_bad_transaction() || self.network.is_syncing() {
496            return
497        }
498        // otherwise we penalize the peer that sent the bad transaction, with the assumption that
499        // the peer should have known that this transaction is bad (e.g. violating consensus rules)
500        if let Some(peers) = peers {
501            for peer_id in peers {
502                self.report_peer_bad_transactions(peer_id);
503            }
504        }
505        self.metrics.bad_imports.increment(1);
506        self.bad_imports.insert(err.hash);
507    }
508
509    /// Runs an operation to fetch hashes that are cached in [`TransactionFetcher`].
510    ///
511    /// Returns `true` if a request was sent.
512    fn on_fetch_hashes_pending_fetch(&mut self) -> bool {
513        // try drain transaction hashes pending fetch
514        let info = &self.pending_pool_imports_info;
515        let max_pending_pool_imports = info.max_pending_pool_imports;
516        let has_capacity_wrt_pending_pool_imports =
517            |divisor| info.has_capacity(max_pending_pool_imports / divisor);
518
519        self.transaction_fetcher
520            .on_fetch_pending_hashes(&self.peers, has_capacity_wrt_pending_pool_imports)
521    }
522
523    fn on_request_error(&self, peer_id: PeerId, req_err: RequestError) {
524        let kind = match req_err {
525            RequestError::UnsupportedCapability => ReputationChangeKind::BadProtocol,
526            RequestError::Timeout => ReputationChangeKind::Timeout,
527            RequestError::ChannelClosed | RequestError::ConnectionDropped => {
528                // peer is already disconnected
529                return
530            }
531            RequestError::BadResponse => return self.report_peer_bad_transactions(peer_id),
532        };
533        self.report_peer(peer_id, kind);
534    }
535
536    #[inline]
537    fn update_poll_metrics(&self, start: Instant, poll_durations: TxManagerPollDurations) {
538        let metrics = &self.metrics;
539
540        let TxManagerPollDurations {
541            acc_network_events,
542            acc_pending_imports,
543            acc_tx_events,
544            acc_imported_txns,
545            acc_fetch_events,
546            acc_pending_fetch,
547            acc_cmds,
548        } = poll_durations;
549
550        // update metrics for whole poll function
551        metrics.duration_poll_tx_manager.set(start.elapsed().as_secs_f64());
552        // update metrics for nested expressions
553        metrics.acc_duration_poll_network_events.set(acc_network_events.as_secs_f64());
554        metrics.acc_duration_poll_pending_pool_imports.set(acc_pending_imports.as_secs_f64());
555        metrics.acc_duration_poll_transaction_events.set(acc_tx_events.as_secs_f64());
556        metrics.acc_duration_poll_imported_transactions.set(acc_imported_txns.as_secs_f64());
557        metrics.acc_duration_poll_fetch_events.set(acc_fetch_events.as_secs_f64());
558        metrics.acc_duration_fetch_pending_hashes.set(acc_pending_fetch.as_secs_f64());
559        metrics.acc_duration_poll_commands.set(acc_cmds.as_secs_f64());
560    }
561}
562
563impl<Pool: TransactionPool, N: NetworkPrimitives> TransactionsManager<Pool, N> {
564    /// Processes a batch import results.
565    fn on_batch_import_result(&mut self, batch_results: Vec<PoolResult<AddedTransactionOutcome>>) {
566        for res in batch_results {
567            match res {
568                Ok(AddedTransactionOutcome { hash, .. }) => {
569                    self.on_good_import(hash);
570                }
571                Err(err) => {
572                    self.on_bad_import(err);
573                }
574            }
575        }
576    }
577
578    /// Request handler for an incoming `NewPooledTransactionHashes`
579    fn on_new_pooled_transaction_hashes(
580        &mut self,
581        peer_id: PeerId,
582        msg: NewPooledTransactionHashes,
583    ) {
584        // If the node is initially syncing, ignore transactions
585        if self.network.is_initially_syncing() {
586            return
587        }
588        if self.network.tx_gossip_disabled() {
589            return
590        }
591
592        // get handle to peer's session, if the session is still active
593        let Some(peer) = self.peers.get_mut(&peer_id) else {
594            trace!(
595                peer_id = format!("{peer_id:#}"),
596                ?msg,
597                "discarding announcement from inactive peer"
598            );
599
600            return
601        };
602        let client = peer.client_version.clone();
603
604        // keep track of the transactions the peer knows
605        let mut count_txns_already_seen_by_peer = 0;
606        for tx in msg.iter_hashes().copied() {
607            if !peer.seen_transactions.insert(tx) {
608                count_txns_already_seen_by_peer += 1;
609            }
610        }
611        if count_txns_already_seen_by_peer > 0 {
612            // this may occur if transactions are sent or announced to a peer, at the same time as
613            // the peer sends/announces those hashes to us. this is because, marking
614            // txns as seen by a peer is done optimistically upon sending them to the
615            // peer.
616            self.metrics.messages_with_hashes_already_seen_by_peer.increment(1);
617            self.metrics
618                .occurrences_hash_already_seen_by_peer
619                .increment(count_txns_already_seen_by_peer);
620
621            trace!(target: "net::tx",
622                %count_txns_already_seen_by_peer,
623                peer_id=format!("{peer_id:#}"),
624                ?client,
625                "Peer sent hashes that have already been marked as seen by peer"
626            );
627
628            self.report_already_seen(peer_id);
629        }
630
631        // 1. filter out spam
632        if msg.is_empty() {
633            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
634            return;
635        }
636
637        let original_len = msg.len();
638        let mut partially_valid_msg = msg.dedup();
639
640        if partially_valid_msg.len() != original_len {
641            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
642        }
643
644        // 2. filter out transactions pending import to pool
645        partially_valid_msg.retain_by_hash(|hash| !self.transactions_by_peers.contains_key(hash));
646
647        // 3. filter out known hashes
648        //
649        // known txns have already been successfully fetched or received over gossip.
650        //
651        // most hashes will be filtered out here since the mempool protocol is a gossip
652        // protocol, healthy peers will send many of the same hashes.
653        //
654        let hashes_count_pre_pool_filter = partially_valid_msg.len();
655        self.pool.retain_unknown(&mut partially_valid_msg);
656        if hashes_count_pre_pool_filter > partially_valid_msg.len() {
657            let already_known_hashes_count =
658                hashes_count_pre_pool_filter - partially_valid_msg.len();
659            self.metrics
660                .occurrences_hashes_already_in_pool
661                .increment(already_known_hashes_count as u64);
662        }
663
664        if partially_valid_msg.is_empty() {
665            // nothing to request
666            return
667        }
668
669        // 4. filter out invalid entries (spam)
670        //
671        // validates messages with respect to the given network, e.g. allowed tx types
672        //
673        let mut should_report_peer = false;
674        let mut tx_types_counter = TxTypesCounter::default();
675
676        let is_eth68_message = partially_valid_msg
677            .msg_version()
678            .expect("partially valid announcement should have a version")
679            .is_eth68();
680
681        partially_valid_msg.retain(|tx_hash, metadata_ref_mut| {
682            let (ty_byte, size_val) = match *metadata_ref_mut {
683                Some((ty, size)) => {
684                    if !is_eth68_message {
685                        should_report_peer = true;
686                    }
687                    (ty, size)
688                }
689                None => {
690                    if is_eth68_message {
691                        should_report_peer = true;
692                        return false;
693                    }
694                    (0u8, 0)
695                }
696            };
697
698            if is_eth68_message &&
699                let Some((actual_ty_byte, _)) = *metadata_ref_mut &&
700                let Ok(parsed_tx_type) = TxType::try_from(actual_ty_byte)
701            {
702                tx_types_counter.increase_by_tx_type(parsed_tx_type);
703            }
704
705            let decision = self
706                .policies
707                .announcement_filter()
708                .decide_on_announcement(ty_byte, tx_hash, size_val);
709
710            match decision {
711                AnnouncementAcceptance::Accept => true,
712                AnnouncementAcceptance::Ignore => false,
713                AnnouncementAcceptance::Reject { penalize_peer } => {
714                    if penalize_peer {
715                        should_report_peer = true;
716                    }
717                    false
718                }
719            }
720        });
721
722        if is_eth68_message {
723            self.announced_tx_types_metrics.update_eth68_announcement_metrics(tx_types_counter);
724        }
725
726        if should_report_peer {
727            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
728        }
729
730        let mut valid_announcement_data =
731            ValidAnnouncementData::from_partially_valid_data(partially_valid_msg);
732
733        if valid_announcement_data.is_empty() {
734            // no valid announcement data
735            return
736        }
737
738        // 5. filter out already seen unknown hashes
739        //
740        // seen hashes are already in the tx fetcher, pending fetch.
741        //
742        // for any seen hashes add the peer as fallback. unseen hashes are loaded into the tx
743        // fetcher, hence they should be valid at this point.
744        let bad_imports = &self.bad_imports;
745        self.transaction_fetcher.filter_unseen_and_pending_hashes(
746            &mut valid_announcement_data,
747            |hash| bad_imports.contains(hash),
748            &peer_id,
749            &client,
750        );
751
752        if valid_announcement_data.is_empty() {
753            // nothing to request
754            return
755        }
756
757        trace!(target: "net::tx::propagation",
758            peer_id=format!("{peer_id:#}"),
759            hashes_len=valid_announcement_data.len(),
760            hashes=?valid_announcement_data.keys().collect::<Vec<_>>(),
761            msg_version=%valid_announcement_data.msg_version(),
762            client_version=%client,
763            "received previously unseen and pending hashes in announcement from peer"
764        );
765
766        // only send request for hashes to idle peer, otherwise buffer hashes storing peer as
767        // fallback
768        if !self.transaction_fetcher.is_idle(&peer_id) {
769            // load message version before announcement data is destructed in packing
770            let msg_version = valid_announcement_data.msg_version();
771            let (hashes, _version) = valid_announcement_data.into_request_hashes();
772
773            trace!(target: "net::tx",
774                peer_id=format!("{peer_id:#}"),
775                hashes=?*hashes,
776                %msg_version,
777                %client,
778                "buffering hashes announced by busy peer"
779            );
780
781            self.transaction_fetcher.buffer_hashes(hashes, Some(peer_id));
782
783            return
784        }
785
786        let mut hashes_to_request =
787            RequestTxHashes::with_capacity(valid_announcement_data.len() / 4);
788        let surplus_hashes =
789            self.transaction_fetcher.pack_request(&mut hashes_to_request, valid_announcement_data);
790
791        if !surplus_hashes.is_empty() {
792            trace!(target: "net::tx",
793                peer_id=format!("{peer_id:#}"),
794                surplus_hashes=?*surplus_hashes,
795                %client,
796                "some hashes in announcement from peer didn't fit in `GetPooledTransactions` request, buffering surplus hashes"
797            );
798
799            self.transaction_fetcher.buffer_hashes(surplus_hashes, Some(peer_id));
800        }
801
802        trace!(target: "net::tx",
803            peer_id=format!("{peer_id:#}"),
804            hashes=?*hashes_to_request,
805            %client,
806            "sending hashes in `GetPooledTransactions` request to peer's session"
807        );
808
809        // request the missing transactions
810        //
811        // get handle to peer's session again, at this point we know it exists
812        let Some(peer) = self.peers.get_mut(&peer_id) else { return };
813        if let Some(failed_to_request_hashes) =
814            self.transaction_fetcher.request_transactions_from_peer(hashes_to_request, peer)
815        {
816            let conn_eth_version = peer.version;
817
818            trace!(target: "net::tx",
819                peer_id=format!("{peer_id:#}"),
820                failed_to_request_hashes=?*failed_to_request_hashes,
821                %conn_eth_version,
822                %client,
823                "sending `GetPooledTransactions` request to peer's session failed, buffering hashes"
824            );
825            self.transaction_fetcher.buffer_hashes(failed_to_request_hashes, Some(peer_id));
826        }
827    }
828}
829
830impl<Pool, N> TransactionsManager<Pool, N>
831where
832    Pool: TransactionPool + Unpin + 'static,
833    N: NetworkPrimitives<
834            BroadcastedTransaction: SignedTransaction,
835            PooledTransaction: SignedTransaction,
836        > + Unpin,
837    Pool::Transaction:
838        PoolTransaction<Consensus = N::BroadcastedTransaction, Pooled = N::PooledTransaction>,
839{
840    /// Invoked when transactions in the local mempool are considered __pending__.
841    ///
842    /// When a transaction in the local mempool is moved to the pending pool, we propagate them to
843    /// connected peers over network using the `Transactions` and `NewPooledTransactionHashes`
844    /// messages. The Transactions message relays complete transaction objects and is typically
845    /// sent to a small, random fraction of connected peers.
846    ///
847    /// All other peers receive a notification of the transaction hash and can request the
848    /// complete transaction object if it is unknown to them. The dissemination of complete
849    /// transactions to a fraction of peers usually ensures that all nodes receive the transaction
850    /// and won't need to request it.
851    fn on_new_pending_transactions(&mut self, hashes: Vec<TxHash>) {
852        // Nothing to propagate while initially syncing
853        if self.network.is_initially_syncing() {
854            return
855        }
856        if self.network.tx_gossip_disabled() {
857            return
858        }
859
860        trace!(target: "net::tx", num_hashes=?hashes.len(), "Start propagating transactions");
861
862        self.propagate_all(hashes);
863    }
864
865    /// Propagate the full transactions to a specific peer.
866    ///
867    /// Returns the propagated transactions.
868    fn propagate_full_transactions_to_peer(
869        &mut self,
870        txs: Vec<TxHash>,
871        peer_id: PeerId,
872        propagation_mode: PropagationMode,
873    ) -> Option<PropagatedTransactions> {
874        let peer = self.peers.get_mut(&peer_id)?;
875        trace!(target: "net::tx", ?peer_id, "Propagating transactions to peer");
876        let mut propagated = PropagatedTransactions::default();
877
878        // filter all transactions unknown to the peer
879        let mut full_transactions = FullTransactionsBuilder::new(peer.version);
880
881        let to_propagate = self.pool.get_all(txs).into_iter().map(PropagateTransaction::pool_tx);
882
883        if propagation_mode.is_forced() {
884            // skip cache check if forced
885            full_transactions.extend(to_propagate);
886        } else {
887            // Iterate through the transactions to propagate and fill the hashes and full
888            // transaction
889            for tx in to_propagate {
890                if !peer.seen_transactions.contains(tx.tx_hash()) {
891                    // Only include if the peer hasn't seen the transaction
892                    full_transactions.push(&tx);
893                }
894            }
895        }
896
897        if full_transactions.is_empty() {
898            // nothing to propagate
899            return None
900        }
901
902        let PropagateTransactions { pooled, full } = full_transactions.build();
903
904        // send hashes if any
905        if let Some(new_pooled_hashes) = pooled {
906            for hash in new_pooled_hashes.iter_hashes().copied() {
907                propagated.0.entry(hash).or_default().push(PropagateKind::Hash(peer_id));
908                // mark transaction as seen by peer
909                peer.seen_transactions.insert(hash);
910            }
911
912            // send hashes of transactions
913            self.network.send_transactions_hashes(peer_id, new_pooled_hashes);
914        }
915
916        // send full transactions, if any
917        if let Some(new_full_transactions) = full {
918            for tx in &new_full_transactions {
919                propagated.0.entry(*tx.tx_hash()).or_default().push(PropagateKind::Full(peer_id));
920                // mark transaction as seen by peer
921                peer.seen_transactions.insert(*tx.tx_hash());
922            }
923
924            // send full transactions
925            self.network.send_transactions(peer_id, new_full_transactions);
926        }
927
928        // Update propagated transactions metrics
929        self.metrics.propagated_transactions.increment(propagated.0.len() as u64);
930
931        Some(propagated)
932    }
933
934    /// Propagate the transaction hashes to the given peer
935    ///
936    /// Note: This will only send the hashes for transactions that exist in the pool.
937    fn propagate_hashes_to(
938        &mut self,
939        hashes: Vec<TxHash>,
940        peer_id: PeerId,
941        propagation_mode: PropagationMode,
942    ) {
943        trace!(target: "net::tx", "Start propagating transactions as hashes");
944
945        // This fetches a transactions from the pool, including the blob transactions, which are
946        // only ever sent as hashes.
947        let propagated = {
948            let Some(peer) = self.peers.get_mut(&peer_id) else {
949                // no such peer
950                return
951            };
952
953            let to_propagate =
954                self.pool.get_all(hashes).into_iter().map(PropagateTransaction::pool_tx);
955
956            let mut propagated = PropagatedTransactions::default();
957
958            // check if transaction is known to peer
959            let mut hashes = PooledTransactionsHashesBuilder::new(peer.version);
960
961            if propagation_mode.is_forced() {
962                hashes.extend(to_propagate)
963            } else {
964                for tx in to_propagate {
965                    if !peer.seen_transactions.contains(tx.tx_hash()) {
966                        // Include if the peer hasn't seen it
967                        hashes.push(&tx);
968                    }
969                }
970            }
971
972            let new_pooled_hashes = hashes.build();
973
974            if new_pooled_hashes.is_empty() {
975                // nothing to propagate
976                return
977            }
978
979            for hash in new_pooled_hashes.iter_hashes().copied() {
980                propagated.0.entry(hash).or_default().push(PropagateKind::Hash(peer_id));
981            }
982
983            trace!(target: "net::tx::propagation", ?peer_id, ?new_pooled_hashes, "Propagating transactions to peer");
984
985            // send hashes of transactions
986            self.network.send_transactions_hashes(peer_id, new_pooled_hashes);
987
988            // Update propagated transactions metrics
989            self.metrics.propagated_transactions.increment(propagated.0.len() as u64);
990
991            propagated
992        };
993
994        // notify pool so events get fired
995        self.pool.on_propagated(propagated);
996    }
997
998    /// Propagate the transactions to all connected peers either as full objects or hashes.
999    ///
1000    /// The message for new pooled hashes depends on the negotiated version of the stream.
1001    /// See [`NewPooledTransactionHashes`]
1002    ///
1003    /// Note: EIP-4844 are disallowed from being broadcast in full and are only ever sent as hashes, see also <https://eips.ethereum.org/EIPS/eip-4844#networking>.
1004    fn propagate_transactions(
1005        &mut self,
1006        to_propagate: Vec<PropagateTransaction<N::BroadcastedTransaction>>,
1007        propagation_mode: PropagationMode,
1008    ) -> PropagatedTransactions {
1009        let mut propagated = PropagatedTransactions::default();
1010        if self.network.tx_gossip_disabled() {
1011            return propagated
1012        }
1013
1014        // send full transactions to a set of the connected peers based on the configured mode
1015        let max_num_full = self.config.propagation_mode.full_peer_count(self.peers.len());
1016
1017        // Note: Assuming ~random~ order due to random state of the peers map hasher
1018        for (peer_idx, (peer_id, peer)) in self.peers.iter_mut().enumerate() {
1019            if !self.policies.propagation_policy().can_propagate(peer) {
1020                // skip peers we should not propagate to
1021                continue
1022            }
1023            // determine whether to send full tx objects or hashes.
1024            let mut builder = if peer_idx > max_num_full {
1025                PropagateTransactionsBuilder::pooled(peer.version)
1026            } else {
1027                PropagateTransactionsBuilder::full(peer.version)
1028            };
1029
1030            if propagation_mode.is_forced() {
1031                builder.extend(to_propagate.iter());
1032            } else {
1033                // Iterate through the transactions to propagate and fill the hashes and full
1034                // transaction lists, before deciding whether or not to send full transactions to
1035                // the peer.
1036                for tx in &to_propagate {
1037                    // Only proceed if the transaction is not in the peer's list of seen
1038                    // transactions
1039                    if !peer.seen_transactions.contains(tx.tx_hash()) {
1040                        builder.push(tx);
1041                    }
1042                }
1043            }
1044
1045            if builder.is_empty() {
1046                trace!(target: "net::tx", ?peer_id, "Nothing to propagate to peer; has seen all transactions");
1047                continue
1048            }
1049
1050            let PropagateTransactions { pooled, full } = builder.build();
1051
1052            // send hashes if any
1053            if let Some(mut new_pooled_hashes) = pooled {
1054                // enforce tx soft limit per message for the (unlikely) event the number of
1055                // hashes exceeds it
1056                new_pooled_hashes
1057                    .truncate(SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE);
1058
1059                for hash in new_pooled_hashes.iter_hashes().copied() {
1060                    propagated.0.entry(hash).or_default().push(PropagateKind::Hash(*peer_id));
1061                    // mark transaction as seen by peer
1062                    peer.seen_transactions.insert(hash);
1063                }
1064
1065                trace!(target: "net::tx", ?peer_id, num_txs=?new_pooled_hashes.len(), "Propagating tx hashes to peer");
1066
1067                // send hashes of transactions
1068                self.network.send_transactions_hashes(*peer_id, new_pooled_hashes);
1069            }
1070
1071            // send full transactions, if any
1072            if let Some(new_full_transactions) = full {
1073                for tx in &new_full_transactions {
1074                    propagated
1075                        .0
1076                        .entry(*tx.tx_hash())
1077                        .or_default()
1078                        .push(PropagateKind::Full(*peer_id));
1079                    // mark transaction as seen by peer
1080                    peer.seen_transactions.insert(*tx.tx_hash());
1081                }
1082
1083                trace!(target: "net::tx", ?peer_id, num_txs=?new_full_transactions.len(), "Propagating full transactions to peer");
1084
1085                // send full transactions
1086                self.network.send_transactions(*peer_id, new_full_transactions);
1087            }
1088        }
1089
1090        // Update propagated transactions metrics
1091        self.metrics.propagated_transactions.increment(propagated.0.len() as u64);
1092
1093        propagated
1094    }
1095
1096    /// Propagates the given transactions to the peers
1097    ///
1098    /// This fetches all transaction from the pool, including the 4844 blob transactions but
1099    /// __without__ their sidecar, because 4844 transactions are only ever announced as hashes.
1100    fn propagate_all(&mut self, hashes: Vec<TxHash>) {
1101        if self.peers.is_empty() {
1102            // nothing to propagate
1103            return
1104        }
1105        let propagated = self.propagate_transactions(
1106            self.pool.get_all(hashes).into_iter().map(PropagateTransaction::pool_tx).collect(),
1107            PropagationMode::Basic,
1108        );
1109
1110        // notify pool so events get fired
1111        self.pool.on_propagated(propagated);
1112    }
1113
1114    /// Request handler for an incoming request for transactions
1115    fn on_get_pooled_transactions(
1116        &mut self,
1117        peer_id: PeerId,
1118        request: GetPooledTransactions,
1119        response: oneshot::Sender<RequestResult<PooledTransactions<N::PooledTransaction>>>,
1120    ) {
1121        if let Some(peer) = self.peers.get_mut(&peer_id) {
1122            if self.network.tx_gossip_disabled() {
1123                let _ = response.send(Ok(PooledTransactions::default()));
1124                return
1125            }
1126            let transactions = self.pool.get_pooled_transaction_elements(
1127                request.0,
1128                GetPooledTransactionLimit::ResponseSizeSoftLimit(
1129                    self.transaction_fetcher.info.soft_limit_byte_size_pooled_transactions_response,
1130                ),
1131            );
1132            trace!(target: "net::tx::propagation", sent_txs=?transactions.iter().map(|tx| tx.tx_hash()), "Sending requested transactions to peer");
1133
1134            // we sent a response at which point we assume that the peer is aware of the
1135            // transactions
1136            peer.seen_transactions.extend(transactions.iter().map(|tx| *tx.tx_hash()));
1137
1138            let resp = PooledTransactions(transactions);
1139            let _ = response.send(Ok(resp));
1140        }
1141    }
1142
1143    /// Handles a command received from a detached [`TransactionsHandle`]
1144    fn on_command(&mut self, cmd: TransactionsCommand<N>) {
1145        match cmd {
1146            TransactionsCommand::PropagateHash(hash) => {
1147                self.on_new_pending_transactions(vec![hash])
1148            }
1149            TransactionsCommand::PropagateHashesTo(hashes, peer) => {
1150                self.propagate_hashes_to(hashes, peer, PropagationMode::Forced)
1151            }
1152            TransactionsCommand::GetActivePeers(tx) => {
1153                let peers = self.peers.keys().copied().collect::<HashSet<_>>();
1154                tx.send(peers).ok();
1155            }
1156            TransactionsCommand::PropagateTransactionsTo(txs, peer) => {
1157                if let Some(propagated) =
1158                    self.propagate_full_transactions_to_peer(txs, peer, PropagationMode::Forced)
1159                {
1160                    self.pool.on_propagated(propagated);
1161                }
1162            }
1163            TransactionsCommand::PropagateTransactions(txs) => self.propagate_all(txs),
1164            TransactionsCommand::BroadcastTransactions(txs) => {
1165                let propagated = self.propagate_transactions(txs, PropagationMode::Forced);
1166                self.pool.on_propagated(propagated);
1167            }
1168            TransactionsCommand::GetTransactionHashes { peers, tx } => {
1169                let mut res = HashMap::with_capacity(peers.len());
1170                for peer_id in peers {
1171                    let hashes = self
1172                        .peers
1173                        .get(&peer_id)
1174                        .map(|peer| peer.seen_transactions.iter().copied().collect::<HashSet<_>>())
1175                        .unwrap_or_default();
1176                    res.insert(peer_id, hashes);
1177                }
1178                tx.send(res).ok();
1179            }
1180            TransactionsCommand::GetPeerSender { peer_id, peer_request_sender } => {
1181                let sender = self.peers.get(&peer_id).map(|peer| peer.request_tx.clone());
1182                peer_request_sender.send(sender).ok();
1183            }
1184        }
1185    }
1186
1187    /// Handles session establishment and peer transactions initialization.
1188    ///
1189    /// This is invoked when a new session is established.
1190    fn handle_peer_session(
1191        &mut self,
1192        info: SessionInfo,
1193        messages: PeerRequestSender<PeerRequest<N>>,
1194    ) {
1195        let SessionInfo { peer_id, client_version, version, .. } = info;
1196
1197        // Insert a new peer into the peerset.
1198        let peer = PeerMetadata::<N>::new(
1199            messages,
1200            version,
1201            client_version,
1202            self.config.max_transactions_seen_by_peer_history,
1203            info.peer_kind,
1204        );
1205        let peer = match self.peers.entry(peer_id) {
1206            Entry::Occupied(mut entry) => {
1207                entry.insert(peer);
1208                entry.into_mut()
1209            }
1210            Entry::Vacant(entry) => entry.insert(peer),
1211        };
1212
1213        self.policies.propagation_policy_mut().on_session_established(peer);
1214
1215        // Send a `NewPooledTransactionHashes` to the peer with up to
1216        // `SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE`
1217        // transactions in the pool.
1218        if self.network.is_initially_syncing() || self.network.tx_gossip_disabled() {
1219            trace!(target: "net::tx", ?peer_id, "Skipping transaction broadcast: node syncing or gossip disabled");
1220            return
1221        }
1222
1223        // Get transactions to broadcast
1224        let pooled_txs = self.pool.pooled_transactions_max(
1225            SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE,
1226        );
1227        if pooled_txs.is_empty() {
1228            trace!(target: "net::tx", ?peer_id, "No transactions in the pool to broadcast");
1229            return;
1230        }
1231
1232        // Build and send transaction hashes message
1233        let mut msg_builder = PooledTransactionsHashesBuilder::new(version);
1234        for pooled_tx in pooled_txs {
1235            peer.seen_transactions.insert(*pooled_tx.hash());
1236            msg_builder.push_pooled(pooled_tx);
1237        }
1238
1239        debug!(target: "net::tx", ?peer_id, tx_count = msg_builder.is_empty(), "Broadcasting transaction hashes");
1240        let msg = msg_builder.build();
1241        self.network.send_transactions_hashes(peer_id, msg);
1242    }
1243
1244    /// Handles a received event related to common network events.
1245    fn on_network_event(&mut self, event_result: NetworkEvent<PeerRequest<N>>) {
1246        match event_result {
1247            NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, .. }) => {
1248                // remove the peer
1249
1250                let peer = self.peers.remove(&peer_id);
1251                if let Some(mut peer) = peer {
1252                    self.policies.propagation_policy_mut().on_session_closed(&mut peer);
1253                }
1254                self.transaction_fetcher.remove_peer(&peer_id);
1255            }
1256            NetworkEvent::ActivePeerSession { info, messages } => {
1257                // process active peer session and broadcast available transaction from the pool
1258                self.handle_peer_session(info, messages);
1259            }
1260            NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {
1261                let peer_id = info.peer_id;
1262                // get messages from existing peer
1263                let messages = match self.peers.get(&peer_id) {
1264                    Some(p) => p.request_tx.clone(),
1265                    None => {
1266                        debug!(target: "net::tx", ?peer_id, "No peer request sender found");
1267                        return;
1268                    }
1269                };
1270                self.handle_peer_session(info, messages);
1271            }
1272            _ => {}
1273        }
1274    }
1275
1276    /// Returns true if the ingress policy allows processing messages from the given peer.
1277    fn accepts_incoming_from(&self, peer_id: &PeerId) -> bool {
1278        if self.config.ingress_policy.allows_all() {
1279            return true;
1280        }
1281        let Some(peer) = self.peers.get(peer_id) else {
1282            return false;
1283        };
1284        self.config.ingress_policy.allows(peer.peer_kind())
1285    }
1286
1287    /// Handles dedicated transaction events related to the `eth` protocol.
1288    fn on_network_tx_event(&mut self, event: NetworkTransactionEvent<N>) {
1289        match event {
1290            NetworkTransactionEvent::IncomingTransactions { peer_id, msg } => {
1291                if !self.accepts_incoming_from(&peer_id) {
1292                    trace!(target: "net::tx", peer_id=format!("{peer_id:#}"), policy=?self.config.ingress_policy, "Ignoring full transactions from peer blocked by ingress policy");
1293                    return;
1294                }
1295
1296                // ensure we didn't receive any blob transactions as these are disallowed to be
1297                // broadcasted in full
1298
1299                let has_blob_txs = msg.has_eip4844();
1300
1301                let non_blob_txs = msg
1302                    .0
1303                    .into_iter()
1304                    .map(N::PooledTransaction::try_from)
1305                    .filter_map(Result::ok)
1306                    .collect();
1307
1308                self.import_transactions(peer_id, non_blob_txs, TransactionSource::Broadcast);
1309
1310                if has_blob_txs {
1311                    debug!(target: "net::tx", ?peer_id, "received bad full blob transaction broadcast");
1312                    self.report_peer_bad_transactions(peer_id);
1313                }
1314            }
1315            NetworkTransactionEvent::IncomingPooledTransactionHashes { peer_id, msg } => {
1316                if !self.accepts_incoming_from(&peer_id) {
1317                    trace!(target: "net::tx", peer_id=format!("{peer_id:#}"), policy=?self.config.ingress_policy, "Ignoring transaction hashes from peer blocked by ingress policy");
1318                    return;
1319                }
1320                self.on_new_pooled_transaction_hashes(peer_id, msg)
1321            }
1322            NetworkTransactionEvent::GetPooledTransactions { peer_id, request, response } => {
1323                self.on_get_pooled_transactions(peer_id, request, response)
1324            }
1325            NetworkTransactionEvent::GetTransactionsHandle(response) => {
1326                let _ = response.send(Some(self.handle()));
1327            }
1328        }
1329    }
1330
1331    /// Starts the import process for the given transactions.
1332    fn import_transactions(
1333        &mut self,
1334        peer_id: PeerId,
1335        transactions: PooledTransactions<N::PooledTransaction>,
1336        source: TransactionSource,
1337    ) {
1338        // If the node is pipeline syncing, ignore transactions
1339        if self.network.is_initially_syncing() {
1340            return
1341        }
1342        if self.network.tx_gossip_disabled() {
1343            return
1344        }
1345
1346        // Early return if we don't have capacity for any imports
1347        if !self.has_capacity_for_pending_pool_imports() {
1348            return
1349        }
1350
1351        let Some(peer) = self.peers.get_mut(&peer_id) else { return };
1352        let client_version = peer.client_version.clone();
1353        let mut transactions = transactions.0;
1354
1355        let start = Instant::now();
1356
1357        // mark the transactions as received
1358        self.transaction_fetcher
1359            .remove_hashes_from_transaction_fetcher(transactions.iter().map(|tx| tx.tx_hash()));
1360
1361        // track that the peer knows these transaction, but only if this is a new broadcast.
1362        // If we received the transactions as the response to our `GetPooledTransactions``
1363        // requests (based on received `NewPooledTransactionHashes`) then we already
1364        // recorded the hashes as seen by this peer in `Self::on_new_pooled_transaction_hashes`.
1365        let mut num_already_seen_by_peer = 0;
1366        for tx in &transactions {
1367            if source.is_broadcast() && !peer.seen_transactions.insert(*tx.tx_hash()) {
1368                num_already_seen_by_peer += 1;
1369            }
1370        }
1371
1372        // 1. filter out txns already inserted into pool
1373        let txns_count_pre_pool_filter = transactions.len();
1374        self.pool.retain_unknown(&mut transactions);
1375        if txns_count_pre_pool_filter > transactions.len() {
1376            let already_known_txns_count = txns_count_pre_pool_filter - transactions.len();
1377            self.metrics
1378                .occurrences_transactions_already_in_pool
1379                .increment(already_known_txns_count as u64);
1380        }
1381
1382        // tracks the quality of the given transactions
1383        let mut has_bad_transactions = false;
1384
1385        // Remove known and invalid transactions
1386        transactions.retain(|tx| {
1387            if let Entry::Occupied(mut entry) = self.transactions_by_peers.entry(*tx.tx_hash()) {
1388                entry.get_mut().insert(peer_id);
1389                return false
1390            }
1391            if self.bad_imports.contains(tx.tx_hash()) {
1392                trace!(target: "net::tx",
1393                    peer_id=format!("{peer_id:#}"),
1394                    hash=%tx.tx_hash(),
1395                    %client_version,
1396                    "received a known bad transaction from peer"
1397                );
1398                has_bad_transactions = true;
1399                return false;
1400            }
1401            true
1402        });
1403
1404        // Truncate to remaining capacity before recovery to avoid wasting CPU on transactions
1405        // that won't be imported anyway.
1406        let capacity = self.remaining_pool_import_capacity();
1407        if transactions.len() > capacity {
1408            let skipped = transactions.len() - capacity;
1409            transactions.truncate(capacity);
1410            self.metrics
1411                .skipped_transactions_pending_pool_imports_at_capacity
1412                .increment(skipped as u64);
1413            trace!(target: "net::tx", skipped, capacity, "Truncated transactions batch to capacity");
1414        }
1415
1416        let txs_len = transactions.len();
1417
1418        let new_txs = transactions
1419            .into_par_iter()
1420            .filter_map(|tx| match tx.try_into_recovered() {
1421                Ok(tx) => Some(Pool::Transaction::from_pooled(tx)),
1422                Err(badtx) => {
1423                    trace!(target: "net::tx",
1424                        peer_id=format!("{peer_id:#}"),
1425                        hash=%badtx.tx_hash(),
1426                        client_version=%client_version,
1427                        "failed ecrecovery for transaction"
1428                    );
1429                    None
1430                }
1431            })
1432            .collect::<Vec<_>>();
1433
1434        has_bad_transactions |= new_txs.len() != txs_len;
1435
1436        // Record the transactions as seen by the peer
1437        for tx in &new_txs {
1438            self.transactions_by_peers.insert(*tx.hash(), HashSet::from([peer_id]));
1439        }
1440
1441        // 3. import new transactions as a batch to minimize lock contention on the underlying
1442        // pool
1443        if !new_txs.is_empty() {
1444            let pool = self.pool.clone();
1445            // update metrics
1446            let metric_pending_pool_imports = self.metrics.pending_pool_imports.clone();
1447            metric_pending_pool_imports.increment(new_txs.len() as f64);
1448
1449            // update self-monitoring info
1450            self.pending_pool_imports_info
1451                .pending_pool_imports
1452                .fetch_add(new_txs.len(), Ordering::Relaxed);
1453            let tx_manager_info_pending_pool_imports =
1454                self.pending_pool_imports_info.pending_pool_imports.clone();
1455
1456            trace!(target: "net::tx::propagation", new_txs_len=?new_txs.len(), "Importing new transactions");
1457            let import = Box::pin(async move {
1458                let added = new_txs.len();
1459                let res = pool.add_external_transactions(new_txs).await;
1460
1461                // update metrics
1462                metric_pending_pool_imports.decrement(added as f64);
1463                // update self-monitoring info
1464                tx_manager_info_pending_pool_imports.fetch_sub(added, Ordering::Relaxed);
1465
1466                res
1467            });
1468
1469            self.pool_imports.push(import);
1470        }
1471
1472        if num_already_seen_by_peer > 0 {
1473            self.metrics.messages_with_transactions_already_seen_by_peer.increment(1);
1474            self.metrics
1475                .occurrences_of_transaction_already_seen_by_peer
1476                .increment(num_already_seen_by_peer);
1477            trace!(target: "net::tx", num_txs=%num_already_seen_by_peer, ?peer_id, client=%client_version, "Peer sent already seen transactions");
1478        }
1479
1480        if has_bad_transactions {
1481            // peer sent us invalid transactions
1482            self.report_peer_bad_transactions(peer_id)
1483        }
1484
1485        if num_already_seen_by_peer > 0 {
1486            self.report_already_seen(peer_id);
1487        }
1488
1489        self.metrics.pool_import_prepare_duration.record(start.elapsed());
1490    }
1491
1492    /// Processes a [`FetchEvent`].
1493    fn on_fetch_event(&mut self, fetch_event: FetchEvent<N::PooledTransaction>) {
1494        match fetch_event {
1495            FetchEvent::TransactionsFetched { peer_id, transactions, report_peer } => {
1496                self.import_transactions(peer_id, transactions, TransactionSource::Response);
1497                if report_peer {
1498                    self.report_peer(peer_id, ReputationChangeKind::BadTransactions);
1499                }
1500            }
1501            FetchEvent::FetchError { peer_id, error } => {
1502                trace!(target: "net::tx", ?peer_id, %error, "requesting transactions from peer failed");
1503                self.on_request_error(peer_id, error);
1504            }
1505            FetchEvent::EmptyResponse { peer_id } => {
1506                trace!(target: "net::tx", ?peer_id, "peer returned empty response");
1507            }
1508        }
1509    }
1510}
1511
1512/// An endless future. Preemption ensure that future is non-blocking, nonetheless. See
1513/// [`crate::NetworkManager`] for more context on the design pattern.
1514///
1515/// This should be spawned or used as part of `tokio::select!`.
1516//
1517// spawned in `NodeConfig::start_network`(reth_node_core::NodeConfig) and
1518// `NetworkConfig::start_network`(reth_network::NetworkConfig)
1519impl<
1520        Pool: TransactionPool + Unpin + 'static,
1521        N: NetworkPrimitives<
1522                BroadcastedTransaction: SignedTransaction,
1523                PooledTransaction: SignedTransaction,
1524            > + Unpin,
1525    > Future for TransactionsManager<Pool, N>
1526where
1527    Pool::Transaction:
1528        PoolTransaction<Consensus = N::BroadcastedTransaction, Pooled = N::PooledTransaction>,
1529{
1530    type Output = ();
1531
1532    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1533        let start = Instant::now();
1534        let mut poll_durations = TxManagerPollDurations::default();
1535
1536        let this = self.get_mut();
1537
1538        // All streams are polled until their corresponding budget is exhausted, then we manually
1539        // yield back control to tokio. See `NetworkManager` for more context on the design
1540        // pattern.
1541
1542        // Advance network/peer related events (update peers map).
1543        let maybe_more_network_events = metered_poll_nested_stream_with_budget!(
1544            poll_durations.acc_network_events,
1545            "net::tx",
1546            "Network events stream",
1547            DEFAULT_BUDGET_TRY_DRAIN_STREAM,
1548            this.network_events.poll_next_unpin(cx),
1549            |event| this.on_network_event(event)
1550        );
1551
1552        // Advances new __pending__ transactions, transactions that were successfully inserted into
1553        // pending set in pool (are valid), and propagates them (inform peers which
1554        // transactions we have seen).
1555        //
1556        // We try to drain this to batch the transactions in a single message.
1557        //
1558        // We don't expect this buffer to be large, since only pending transactions are
1559        // emitted here.
1560        let mut new_txs = Vec::new();
1561        let maybe_more_pending_txns = match this.pending_transactions.poll_recv_many(
1562            cx,
1563            &mut new_txs,
1564            SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE,
1565        ) {
1566            Poll::Ready(count) => {
1567                if count == SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE {
1568                    // we filled the entire buffer capacity and need to try again on the next poll
1569                    // immediately
1570                    true
1571                } else {
1572                    // try once more, because mostlikely the channel is now empty and the waker is
1573                    // registered if this is pending, if we filled additional hashes, we poll again
1574                    // on the next iteration
1575                    let limit =
1576                        SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE -
1577                            new_txs.len();
1578                    this.pending_transactions.poll_recv_many(cx, &mut new_txs, limit).is_ready()
1579                }
1580            }
1581            Poll::Pending => false,
1582        };
1583        if !new_txs.is_empty() {
1584            this.on_new_pending_transactions(new_txs);
1585        }
1586
1587        // Advance incoming transaction events (stream new txns/announcements from
1588        // network manager and queue for import to pool/fetch txns).
1589        //
1590        // This will potentially remove hashes from hashes pending fetch, it the event
1591        // is an announcement (if same hashes are announced that didn't fit into a
1592        // previous request).
1593        //
1594        // The smallest decodable transaction is an empty legacy transaction, 10 bytes
1595        // (128 KiB / 10 bytes > 13k transactions).
1596        //
1597        // If this is an event with `Transactions` message, since transactions aren't
1598        // validated until they are inserted into the pool, this can potentially queue
1599        // >13k transactions for insertion to pool. More if the message size is bigger
1600        // than the soft limit on a `Transactions` broadcast message, which is 128 KiB.
1601        let maybe_more_tx_events = metered_poll_nested_stream_with_budget!(
1602            poll_durations.acc_tx_events,
1603            "net::tx",
1604            "Network transaction events stream",
1605            DEFAULT_BUDGET_TRY_DRAIN_NETWORK_TRANSACTION_EVENTS,
1606            this.transaction_events.poll_next_unpin(cx),
1607            |event| this.on_network_tx_event(event),
1608        );
1609
1610        // Advance inflight fetch requests (flush transaction fetcher and queue for
1611        // import to pool).
1612        //
1613        // The smallest decodable transaction is an empty legacy transaction, 10 bytes
1614        // (2 MiB / 10 bytes > 200k transactions).
1615        //
1616        // Since transactions aren't validated until they are inserted into the pool,
1617        // this can potentially queue >200k transactions for insertion to pool. More
1618        // if the message size is bigger than the soft limit on a `PooledTransactions`
1619        // response which is 2 MiB.
1620        let mut maybe_more_tx_fetch_events = metered_poll_nested_stream_with_budget!(
1621            poll_durations.acc_fetch_events,
1622            "net::tx",
1623            "Transaction fetch events stream",
1624            DEFAULT_BUDGET_TRY_DRAIN_STREAM,
1625            this.transaction_fetcher.poll_next_unpin(cx),
1626            |event| this.on_fetch_event(event),
1627        );
1628
1629        // Advance pool imports (flush txns to pool).
1630        //
1631        // Note, this is done in batches. A batch is filled from one `Transactions`
1632        // broadcast messages or one `PooledTransactions` response at a time. The
1633        // minimum batch size is 1 transaction (and might often be the case with blob
1634        // transactions).
1635        //
1636        // The smallest decodable transaction is an empty legacy transaction, 10 bytes
1637        // (2 MiB / 10 bytes > 200k transactions).
1638        //
1639        // Since transactions aren't validated until they are inserted into the pool,
1640        // this can potentially validate >200k transactions. More if the message size
1641        // is bigger than the soft limit on a `PooledTransactions` response which is
1642        // 2 MiB (`Transactions` broadcast messages is smaller, 128 KiB).
1643        let maybe_more_pool_imports = metered_poll_nested_stream_with_budget!(
1644            poll_durations.acc_pending_imports,
1645            "net::tx",
1646            "Batched pool imports stream",
1647            DEFAULT_BUDGET_TRY_DRAIN_PENDING_POOL_IMPORTS,
1648            this.pool_imports.poll_next_unpin(cx),
1649            |batch_results| this.on_batch_import_result(batch_results)
1650        );
1651
1652        // Tries to drain hashes pending fetch cache if the tx manager currently has
1653        // capacity for this (fetch txns).
1654        //
1655        // Sends at most one request.
1656        duration_metered_exec!(
1657            {
1658                if this.has_capacity_for_fetching_pending_hashes() &&
1659                    this.on_fetch_hashes_pending_fetch()
1660                {
1661                    maybe_more_tx_fetch_events = true;
1662                }
1663            },
1664            poll_durations.acc_pending_fetch
1665        );
1666
1667        // Advance commands (propagate/fetch/serve txns).
1668        let maybe_more_commands = metered_poll_nested_stream_with_budget!(
1669            poll_durations.acc_cmds,
1670            "net::tx",
1671            "Commands channel",
1672            DEFAULT_BUDGET_TRY_DRAIN_STREAM,
1673            this.command_rx.poll_next_unpin(cx),
1674            |cmd| this.on_command(cmd)
1675        );
1676
1677        this.transaction_fetcher.update_metrics();
1678
1679        // all channels are fully drained and import futures pending
1680        if maybe_more_network_events ||
1681            maybe_more_commands ||
1682            maybe_more_tx_events ||
1683            maybe_more_tx_fetch_events ||
1684            maybe_more_pool_imports ||
1685            maybe_more_pending_txns
1686        {
1687            // make sure we're woken up again
1688            cx.waker().wake_by_ref();
1689            return Poll::Pending
1690        }
1691
1692        this.update_poll_metrics(start, poll_durations);
1693
1694        Poll::Pending
1695    }
1696}
1697
1698/// Represents the different modes of transaction propagation.
1699///
1700/// This enum is used to determine how transactions are propagated to peers in the network.
1701#[derive(Debug, Copy, Clone, Eq, PartialEq)]
1702enum PropagationMode {
1703    /// Default propagation mode.
1704    ///
1705    /// Transactions are only sent to peers that haven't seen them yet.
1706    Basic,
1707    /// Forced propagation mode.
1708    ///
1709    /// Transactions are sent to all peers regardless of whether they have been sent or received
1710    /// before.
1711    Forced,
1712}
1713
1714impl PropagationMode {
1715    /// Returns `true` if the propagation kind is `Forced`.
1716    const fn is_forced(self) -> bool {
1717        matches!(self, Self::Forced)
1718    }
1719}
1720
1721/// A transaction that's about to be propagated to multiple peers.
1722#[derive(Debug, Clone)]
1723struct PropagateTransaction<T = TransactionSigned> {
1724    size: usize,
1725    transaction: Arc<T>,
1726}
1727
1728impl<T: SignedTransaction> PropagateTransaction<T> {
1729    /// Create a new instance from a transaction.
1730    pub fn new(transaction: T) -> Self {
1731        let size = transaction.length();
1732        Self { size, transaction: Arc::new(transaction) }
1733    }
1734
1735    /// Create a new instance from a pooled transaction
1736    fn pool_tx<P>(tx: Arc<ValidPoolTransaction<P>>) -> Self
1737    where
1738        P: PoolTransaction<Consensus = T>,
1739    {
1740        let size = tx.encoded_length();
1741        let transaction = tx.transaction.clone_into_consensus();
1742        let transaction = Arc::new(transaction.into_inner());
1743        Self { size, transaction }
1744    }
1745
1746    fn tx_hash(&self) -> &TxHash {
1747        self.transaction.tx_hash()
1748    }
1749}
1750
1751/// Helper type to construct the appropriate message to send to the peer based on whether the peer
1752/// should receive them in full or as pooled
1753#[derive(Debug, Clone)]
1754enum PropagateTransactionsBuilder<T> {
1755    Pooled(PooledTransactionsHashesBuilder),
1756    Full(FullTransactionsBuilder<T>),
1757}
1758
1759impl<T> PropagateTransactionsBuilder<T> {
1760    /// Create a builder for pooled transactions
1761    fn pooled(version: EthVersion) -> Self {
1762        Self::Pooled(PooledTransactionsHashesBuilder::new(version))
1763    }
1764
1765    /// Create a builder that sends transactions in full and records transactions that don't fit.
1766    fn full(version: EthVersion) -> Self {
1767        Self::Full(FullTransactionsBuilder::new(version))
1768    }
1769
1770    /// Returns true if no transactions are recorded.
1771    fn is_empty(&self) -> bool {
1772        match self {
1773            Self::Pooled(builder) => builder.is_empty(),
1774            Self::Full(builder) => builder.is_empty(),
1775        }
1776    }
1777
1778    /// Consumes the type and returns the built messages that should be sent to the peer.
1779    fn build(self) -> PropagateTransactions<T> {
1780        match self {
1781            Self::Pooled(pooled) => {
1782                PropagateTransactions { pooled: Some(pooled.build()), full: None }
1783            }
1784            Self::Full(full) => full.build(),
1785        }
1786    }
1787}
1788
1789impl<T: SignedTransaction> PropagateTransactionsBuilder<T> {
1790    /// Appends all transactions
1791    fn extend<'a>(&mut self, txs: impl IntoIterator<Item = &'a PropagateTransaction<T>>) {
1792        for tx in txs {
1793            self.push(tx);
1794        }
1795    }
1796
1797    /// Appends a transaction to the list.
1798    fn push(&mut self, transaction: &PropagateTransaction<T>) {
1799        match self {
1800            Self::Pooled(builder) => builder.push(transaction),
1801            Self::Full(builder) => builder.push(transaction),
1802        }
1803    }
1804}
1805
1806/// Represents how the transactions should be sent to a peer if any.
1807struct PropagateTransactions<T> {
1808    /// The pooled transaction hashes to send.
1809    pooled: Option<NewPooledTransactionHashes>,
1810    /// The transactions to send in full.
1811    full: Option<Vec<Arc<T>>>,
1812}
1813
1814/// Helper type for constructing the full transaction message that enforces the
1815/// [`DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE`] for full transaction broadcast
1816/// and enforces other propagation rules for EIP-4844 and tracks those transactions that can't be
1817/// broadcasted in full.
1818#[derive(Debug, Clone)]
1819struct FullTransactionsBuilder<T> {
1820    /// The soft limit to enforce for a single broadcast message of full transactions.
1821    total_size: usize,
1822    /// All transactions to be broadcasted.
1823    transactions: Vec<Arc<T>>,
1824    /// Transactions that didn't fit into the broadcast message
1825    pooled: PooledTransactionsHashesBuilder,
1826}
1827
1828impl<T> FullTransactionsBuilder<T> {
1829    /// Create a builder for the negotiated version of the peer's session
1830    fn new(version: EthVersion) -> Self {
1831        Self {
1832            total_size: 0,
1833            pooled: PooledTransactionsHashesBuilder::new(version),
1834            transactions: vec![],
1835        }
1836    }
1837
1838    /// Returns whether or not any transactions are in the [`FullTransactionsBuilder`].
1839    fn is_empty(&self) -> bool {
1840        self.transactions.is_empty() && self.pooled.is_empty()
1841    }
1842
1843    /// Returns the messages that should be propagated to the peer.
1844    fn build(self) -> PropagateTransactions<T> {
1845        let pooled = Some(self.pooled.build()).filter(|pooled| !pooled.is_empty());
1846        let full = Some(self.transactions).filter(|full| !full.is_empty());
1847        PropagateTransactions { pooled, full }
1848    }
1849}
1850
1851impl<T: SignedTransaction> FullTransactionsBuilder<T> {
1852    /// Appends all transactions.
1853    fn extend(&mut self, txs: impl IntoIterator<Item = PropagateTransaction<T>>) {
1854        for tx in txs {
1855            self.push(&tx)
1856        }
1857    }
1858
1859    /// Append a transaction to the list of full transaction if the total message bytes size doesn't
1860    /// exceed the soft maximum target byte size. The limit is soft, meaning if one single
1861    /// transaction goes over the limit, it will be broadcasted in its own [`Transactions`]
1862    /// message. The same pattern is followed in filling a [`GetPooledTransactions`] request in
1863    /// [`TransactionFetcher::fill_request_from_hashes_pending_fetch`].
1864    ///
1865    /// If the transaction is unsuitable for broadcast or would exceed the softlimit, it is appended
1866    /// to list of pooled transactions, (e.g. 4844 transactions).
1867    /// See also [`SignedTransaction::is_broadcastable_in_full`].
1868    fn push(&mut self, transaction: &PropagateTransaction<T>) {
1869        // Do not send full 4844 transaction hashes to peers.
1870        //
1871        //  Nodes MUST NOT automatically broadcast blob transactions to their peers.
1872        //  Instead, those transactions are only announced using
1873        //  `NewPooledTransactionHashes` messages, and can then be manually requested
1874        //  via `GetPooledTransactions`.
1875        //
1876        // From: <https://eips.ethereum.org/EIPS/eip-4844#networking>
1877        if !transaction.transaction.is_broadcastable_in_full() {
1878            self.pooled.push(transaction);
1879            return
1880        }
1881
1882        let new_size = self.total_size + transaction.size;
1883        if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE &&
1884            self.total_size > 0
1885        {
1886            // transaction does not fit into the message
1887            self.pooled.push(transaction);
1888            return
1889        }
1890
1891        self.total_size = new_size;
1892        self.transactions.push(Arc::clone(&transaction.transaction));
1893    }
1894}
1895
1896/// A helper type to create the pooled transactions message based on the negotiated version of the
1897/// session with the peer
1898#[derive(Debug, Clone)]
1899enum PooledTransactionsHashesBuilder {
1900    Eth66(NewPooledTransactionHashes66),
1901    Eth68(NewPooledTransactionHashes68),
1902}
1903
1904// === impl PooledTransactionsHashesBuilder ===
1905
1906impl PooledTransactionsHashesBuilder {
1907    /// Push a transaction from the pool to the list.
1908    fn push_pooled<T: PoolTransaction>(&mut self, pooled_tx: Arc<ValidPoolTransaction<T>>) {
1909        match self {
1910            Self::Eth66(msg) => msg.0.push(*pooled_tx.hash()),
1911            Self::Eth68(msg) => {
1912                msg.hashes.push(*pooled_tx.hash());
1913                msg.sizes.push(pooled_tx.encoded_length());
1914                msg.types.push(pooled_tx.transaction.ty());
1915            }
1916        }
1917    }
1918
1919    /// Returns whether or not any transactions are in the [`PooledTransactionsHashesBuilder`].
1920    fn is_empty(&self) -> bool {
1921        match self {
1922            Self::Eth66(hashes) => hashes.is_empty(),
1923            Self::Eth68(hashes) => hashes.is_empty(),
1924        }
1925    }
1926
1927    /// Appends all hashes
1928    fn extend<T: SignedTransaction>(
1929        &mut self,
1930        txs: impl IntoIterator<Item = PropagateTransaction<T>>,
1931    ) {
1932        for tx in txs {
1933            self.push(&tx);
1934        }
1935    }
1936
1937    fn push<T: SignedTransaction>(&mut self, tx: &PropagateTransaction<T>) {
1938        match self {
1939            Self::Eth66(msg) => msg.0.push(*tx.tx_hash()),
1940            Self::Eth68(msg) => {
1941                msg.hashes.push(*tx.tx_hash());
1942                msg.sizes.push(tx.size);
1943                msg.types.push(tx.transaction.ty());
1944            }
1945        }
1946    }
1947
1948    /// Create a builder for the negotiated version of the peer's session
1949    fn new(version: EthVersion) -> Self {
1950        match version {
1951            EthVersion::Eth66 | EthVersion::Eth67 => Self::Eth66(Default::default()),
1952            EthVersion::Eth68 | EthVersion::Eth69 | EthVersion::Eth70 => {
1953                Self::Eth68(Default::default())
1954            }
1955        }
1956    }
1957
1958    fn build(self) -> NewPooledTransactionHashes {
1959        match self {
1960            Self::Eth66(mut msg) => {
1961                msg.0.shrink_to_fit();
1962                msg.into()
1963            }
1964            Self::Eth68(mut msg) => {
1965                msg.shrink_to_fit();
1966                msg.into()
1967            }
1968        }
1969    }
1970}
1971
1972/// How we received the transactions.
1973enum TransactionSource {
1974    /// Transactions were broadcast to us via [`Transactions`] message.
1975    Broadcast,
1976    /// Transactions were sent as the response of [`fetcher::GetPooledTxRequest`] issued by us.
1977    Response,
1978}
1979
1980// === impl TransactionSource ===
1981
1982impl TransactionSource {
1983    /// Whether the transaction were sent as broadcast.
1984    const fn is_broadcast(&self) -> bool {
1985        matches!(self, Self::Broadcast)
1986    }
1987}
1988
1989/// Tracks a single peer in the context of [`TransactionsManager`].
1990#[derive(Debug)]
1991pub struct PeerMetadata<N: NetworkPrimitives = EthNetworkPrimitives> {
1992    /// Optimistically keeps track of transactions that we know the peer has seen. Optimistic, in
1993    /// the sense that transactions are preemptively marked as seen by peer when they are sent to
1994    /// the peer.
1995    seen_transactions: LruCache<TxHash>,
1996    /// A communication channel directly to the peer's session task.
1997    request_tx: PeerRequestSender<PeerRequest<N>>,
1998    /// negotiated version of the session.
1999    version: EthVersion,
2000    /// The peer's client version.
2001    client_version: Arc<str>,
2002    /// The kind of peer.
2003    peer_kind: PeerKind,
2004}
2005
2006impl<N: NetworkPrimitives> PeerMetadata<N> {
2007    /// Returns a new instance of [`PeerMetadata`].
2008    pub fn new(
2009        request_tx: PeerRequestSender<PeerRequest<N>>,
2010        version: EthVersion,
2011        client_version: Arc<str>,
2012        max_transactions_seen_by_peer: u32,
2013        peer_kind: PeerKind,
2014    ) -> Self {
2015        Self {
2016            seen_transactions: LruCache::new(max_transactions_seen_by_peer),
2017            request_tx,
2018            version,
2019            client_version,
2020            peer_kind,
2021        }
2022    }
2023
2024    /// Returns a reference to the peer's request sender channel.
2025    pub const fn request_tx(&self) -> &PeerRequestSender<PeerRequest<N>> {
2026        &self.request_tx
2027    }
2028
2029    /// Returns a mutable reference to the seen transactions LRU cache.
2030    pub const fn seen_transactions_mut(&mut self) -> &mut LruCache<TxHash> {
2031        &mut self.seen_transactions
2032    }
2033
2034    /// Returns the negotiated `EthVersion` of the session.
2035    pub const fn version(&self) -> EthVersion {
2036        self.version
2037    }
2038
2039    /// Returns a reference to the peer's client version string.
2040    pub fn client_version(&self) -> &str {
2041        &self.client_version
2042    }
2043
2044    /// Returns the peer's kind.
2045    pub const fn peer_kind(&self) -> PeerKind {
2046        self.peer_kind
2047    }
2048}
2049
2050/// Commands to send to the [`TransactionsManager`]
2051#[derive(Debug)]
2052enum TransactionsCommand<N: NetworkPrimitives = EthNetworkPrimitives> {
2053    /// Propagate a transaction hash to the network.
2054    PropagateHash(B256),
2055    /// Propagate transaction hashes to a specific peer.
2056    PropagateHashesTo(Vec<B256>, PeerId),
2057    /// Request the list of active peer IDs from the [`TransactionsManager`].
2058    GetActivePeers(oneshot::Sender<HashSet<PeerId>>),
2059    /// Propagate a collection of full transactions to a specific peer.
2060    PropagateTransactionsTo(Vec<TxHash>, PeerId),
2061    /// Propagate a collection of hashes to all peers.
2062    PropagateTransactions(Vec<TxHash>),
2063    /// Propagate a collection of broadcastable transactions in full to all peers.
2064    BroadcastTransactions(Vec<PropagateTransaction<N::BroadcastedTransaction>>),
2065    /// Request transaction hashes known by specific peers from the [`TransactionsManager`].
2066    GetTransactionHashes {
2067        peers: Vec<PeerId>,
2068        tx: oneshot::Sender<HashMap<PeerId, HashSet<TxHash>>>,
2069    },
2070    /// Requests a clone of the sender channel to the peer.
2071    GetPeerSender {
2072        peer_id: PeerId,
2073        peer_request_sender: oneshot::Sender<Option<PeerRequestSender<PeerRequest<N>>>>,
2074    },
2075}
2076
2077/// All events related to transactions emitted by the network.
2078#[derive(Debug)]
2079pub enum NetworkTransactionEvent<N: NetworkPrimitives = EthNetworkPrimitives> {
2080    /// Represents the event of receiving a list of transactions from a peer.
2081    ///
2082    /// This indicates transactions that were broadcasted to us from the peer.
2083    IncomingTransactions {
2084        /// The ID of the peer from which the transactions were received.
2085        peer_id: PeerId,
2086        /// The received transactions.
2087        msg: Transactions<N::BroadcastedTransaction>,
2088    },
2089    /// Represents the event of receiving a list of transaction hashes from a peer.
2090    IncomingPooledTransactionHashes {
2091        /// The ID of the peer from which the transaction hashes were received.
2092        peer_id: PeerId,
2093        /// The received new pooled transaction hashes.
2094        msg: NewPooledTransactionHashes,
2095    },
2096    /// Represents the event of receiving a `GetPooledTransactions` request from a peer.
2097    GetPooledTransactions {
2098        /// The ID of the peer from which the request was received.
2099        peer_id: PeerId,
2100        /// The received `GetPooledTransactions` request.
2101        request: GetPooledTransactions,
2102        /// The sender for responding to the request with a result of `PooledTransactions`.
2103        response: oneshot::Sender<RequestResult<PooledTransactions<N::PooledTransaction>>>,
2104    },
2105    /// Represents the event of receiving a `GetTransactionsHandle` request.
2106    GetTransactionsHandle(oneshot::Sender<Option<TransactionsHandle<N>>>),
2107}
2108
2109/// Tracks stats about the [`TransactionsManager`].
2110#[derive(Debug)]
2111pub struct PendingPoolImportsInfo {
2112    /// Number of transactions about to be inserted into the pool.
2113    pending_pool_imports: Arc<AtomicUsize>,
2114    /// Max number of transactions allowed to be imported concurrently.
2115    max_pending_pool_imports: usize,
2116}
2117
2118impl PendingPoolImportsInfo {
2119    /// Returns a new [`PendingPoolImportsInfo`].
2120    pub fn new(max_pending_pool_imports: usize) -> Self {
2121        Self { pending_pool_imports: Arc::new(AtomicUsize::default()), max_pending_pool_imports }
2122    }
2123
2124    /// Returns `true` if the number of pool imports is under a given tolerated max.
2125    pub fn has_capacity(&self, max_pending_pool_imports: usize) -> bool {
2126        self.pending_pool_imports.load(Ordering::Relaxed) < max_pending_pool_imports
2127    }
2128}
2129
2130impl Default for PendingPoolImportsInfo {
2131    fn default() -> Self {
2132        Self::new(DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS)
2133    }
2134}
2135
2136#[derive(Debug, Default)]
2137struct TxManagerPollDurations {
2138    acc_network_events: Duration,
2139    acc_pending_imports: Duration,
2140    acc_tx_events: Duration,
2141    acc_imported_txns: Duration,
2142    acc_fetch_events: Duration,
2143    acc_pending_fetch: Duration,
2144    acc_cmds: Duration,
2145}
2146
2147#[cfg(test)]
2148mod tests {
2149    use super::*;
2150    use crate::{
2151        test_utils::{
2152            transactions::{buffer_hash_to_tx_fetcher, new_mock_session, new_tx_manager},
2153            Testnet,
2154        },
2155        transactions::config::RelaxedEthAnnouncementFilter,
2156        NetworkConfigBuilder, NetworkManager,
2157    };
2158    use alloy_consensus::{TxEip1559, TxLegacy};
2159    use alloy_primitives::{hex, Signature, TxKind, U256};
2160    use alloy_rlp::Decodable;
2161    use futures::FutureExt;
2162    use reth_chainspec::MIN_TRANSACTION_GAS;
2163    use reth_ethereum_primitives::{PooledTransactionVariant, Transaction, TransactionSigned};
2164    use reth_network_api::{NetworkInfo, PeerKind};
2165    use reth_network_p2p::{
2166        error::{RequestError, RequestResult},
2167        sync::{NetworkSyncUpdater, SyncState},
2168    };
2169    use reth_storage_api::noop::NoopProvider;
2170    use reth_transaction_pool::test_utils::{
2171        testing_pool, MockTransaction, MockTransactionFactory, TestPool,
2172    };
2173    use secp256k1::SecretKey;
2174    use std::{
2175        future::poll_fn,
2176        net::{IpAddr, Ipv4Addr, SocketAddr},
2177        str::FromStr,
2178    };
2179    use tracing::error;
2180
2181    #[tokio::test(flavor = "multi_thread")]
2182    async fn test_ignored_tx_broadcasts_while_initially_syncing() {
2183        reth_tracing::init_test_tracing();
2184        let net = Testnet::create(3).await;
2185
2186        let mut handles = net.handles();
2187        let handle0 = handles.next().unwrap();
2188        let handle1 = handles.next().unwrap();
2189
2190        drop(handles);
2191        let handle = net.spawn();
2192
2193        let listener0 = handle0.event_listener();
2194        handle0.add_peer(*handle1.peer_id(), handle1.local_addr());
2195        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
2196
2197        let client = NoopProvider::default();
2198        let pool = testing_pool();
2199        let config = NetworkConfigBuilder::eth(secret_key)
2200            .disable_discovery()
2201            .listener_port(0)
2202            .build(client);
2203        let transactions_manager_config = config.transactions_manager_config.clone();
2204        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
2205            .await
2206            .unwrap()
2207            .into_builder()
2208            .transactions(pool.clone(), transactions_manager_config)
2209            .split_with_handle();
2210
2211        tokio::task::spawn(network);
2212
2213        // go to syncing (pipeline sync)
2214        network_handle.update_sync_state(SyncState::Syncing);
2215        assert!(NetworkInfo::is_syncing(&network_handle));
2216        assert!(NetworkInfo::is_initially_syncing(&network_handle));
2217
2218        // wait for all initiator connections
2219        let mut established = listener0.take(2);
2220        while let Some(ev) = established.next().await {
2221            match ev {
2222                NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {
2223                    // to insert a new peer in transactions peerset
2224                    transactions
2225                        .on_network_event(NetworkEvent::Peer(PeerEvent::SessionEstablished(info)))
2226                }
2227                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
2228                ev => {
2229                    error!("unexpected event {ev:?}")
2230                }
2231            }
2232        }
2233        // random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
2234        let input = hex!(
2235            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
2236        );
2237        let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
2238        transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
2239            peer_id: *handle1.peer_id(),
2240            msg: Transactions(vec![signed_tx.clone()]),
2241        });
2242        poll_fn(|cx| {
2243            let _ = transactions.poll_unpin(cx);
2244            Poll::Ready(())
2245        })
2246        .await;
2247        assert!(pool.is_empty());
2248        handle.terminate().await;
2249    }
2250
2251    #[tokio::test(flavor = "multi_thread")]
2252    async fn test_tx_broadcasts_through_two_syncs() {
2253        reth_tracing::init_test_tracing();
2254        let net = Testnet::create(3).await;
2255
2256        let mut handles = net.handles();
2257        let handle0 = handles.next().unwrap();
2258        let handle1 = handles.next().unwrap();
2259
2260        drop(handles);
2261        let handle = net.spawn();
2262
2263        let listener0 = handle0.event_listener();
2264        handle0.add_peer(*handle1.peer_id(), handle1.local_addr());
2265        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
2266
2267        let client = NoopProvider::default();
2268        let pool = testing_pool();
2269        let config = NetworkConfigBuilder::new(secret_key)
2270            .disable_discovery()
2271            .listener_port(0)
2272            .build(client);
2273        let transactions_manager_config = config.transactions_manager_config.clone();
2274        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
2275            .await
2276            .unwrap()
2277            .into_builder()
2278            .transactions(pool.clone(), transactions_manager_config)
2279            .split_with_handle();
2280
2281        tokio::task::spawn(network);
2282
2283        // go to syncing (pipeline sync) to idle and then to syncing (live)
2284        network_handle.update_sync_state(SyncState::Syncing);
2285        assert!(NetworkInfo::is_syncing(&network_handle));
2286        network_handle.update_sync_state(SyncState::Idle);
2287        assert!(!NetworkInfo::is_syncing(&network_handle));
2288        network_handle.update_sync_state(SyncState::Syncing);
2289        assert!(NetworkInfo::is_syncing(&network_handle));
2290
2291        // wait for all initiator connections
2292        let mut established = listener0.take(2);
2293        while let Some(ev) = established.next().await {
2294            match ev {
2295                NetworkEvent::ActivePeerSession { .. } |
2296                NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => {
2297                    // to insert a new peer in transactions peerset
2298                    transactions.on_network_event(ev);
2299                }
2300                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
2301                _ => {
2302                    error!("unexpected event {ev:?}")
2303                }
2304            }
2305        }
2306        // random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
2307        let input = hex!(
2308            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
2309        );
2310        let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
2311        transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
2312            peer_id: *handle1.peer_id(),
2313            msg: Transactions(vec![signed_tx.clone()]),
2314        });
2315        poll_fn(|cx| {
2316            let _ = transactions.poll_unpin(cx);
2317            Poll::Ready(())
2318        })
2319        .await;
2320        assert!(!NetworkInfo::is_initially_syncing(&network_handle));
2321        assert!(NetworkInfo::is_syncing(&network_handle));
2322        assert!(!pool.is_empty());
2323        handle.terminate().await;
2324    }
2325
2326    // Ensure that the transaction manager correctly handles the `IncomingPooledTransactionHashes`
2327    // event and is able to retrieve the corresponding transactions.
2328    #[tokio::test(flavor = "multi_thread")]
2329    async fn test_handle_incoming_transactions_hashes() {
2330        reth_tracing::init_test_tracing();
2331
2332        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
2333        let client = NoopProvider::default();
2334
2335        let config = NetworkConfigBuilder::new(secret_key)
2336            // let OS choose port
2337            .listener_port(0)
2338            .disable_discovery()
2339            .build(client);
2340
2341        let pool = testing_pool();
2342
2343        let transactions_manager_config = config.transactions_manager_config.clone();
2344        let (_network_handle, _network, mut tx_manager, _) = NetworkManager::new(config)
2345            .await
2346            .unwrap()
2347            .into_builder()
2348            .transactions(pool.clone(), transactions_manager_config)
2349            .split_with_handle();
2350
2351        let peer_id_1 = PeerId::new([1; 64]);
2352        let eth_version = EthVersion::Eth66;
2353
2354        let txs = vec![TransactionSigned::new_unhashed(
2355            Transaction::Legacy(TxLegacy {
2356                chain_id: Some(4),
2357                nonce: 15u64,
2358                gas_price: 2200000000,
2359                gas_limit: 34811,
2360                to: TxKind::Call(hex!("cf7f9e66af820a19257a2108375b180b0ec49167").into()),
2361                value: U256::from(1234u64),
2362                input: Default::default(),
2363            }),
2364            Signature::new(
2365                U256::from_str(
2366                    "0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981",
2367                )
2368                .unwrap(),
2369                U256::from_str(
2370                    "0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860",
2371                )
2372                .unwrap(),
2373                true,
2374            ),
2375        )];
2376
2377        let txs_hashes: Vec<B256> = txs.iter().map(|tx| *tx.hash()).collect();
2378
2379        let (peer_1, mut to_mock_session_rx) = new_mock_session(peer_id_1, eth_version);
2380        tx_manager.peers.insert(peer_id_1, peer_1);
2381
2382        assert!(pool.is_empty());
2383
2384        tx_manager.on_network_tx_event(NetworkTransactionEvent::IncomingPooledTransactionHashes {
2385            peer_id: peer_id_1,
2386            msg: NewPooledTransactionHashes::from(NewPooledTransactionHashes66::from(
2387                txs_hashes.clone(),
2388            )),
2389        });
2390
2391        // mock session of peer_1 receives request
2392        let req = to_mock_session_rx
2393            .recv()
2394            .await
2395            .expect("peer_1 session should receive request with buffered hashes");
2396        let PeerRequest::GetPooledTransactions { request, response } = req else { unreachable!() };
2397        assert_eq!(request, GetPooledTransactions::from(txs_hashes.clone()));
2398
2399        let message: Vec<PooledTransactionVariant> = txs
2400            .into_iter()
2401            .map(|tx| {
2402                PooledTransactionVariant::try_from(tx)
2403                    .expect("Failed to convert MockTransaction to PooledTransaction")
2404            })
2405            .collect();
2406
2407        // return the transactions corresponding to the transaction hashes.
2408        response
2409            .send(Ok(PooledTransactions(message)))
2410            .expect("should send peer_1 response to tx manager");
2411
2412        // adance the transaction manager future
2413        poll_fn(|cx| {
2414            let _ = tx_manager.poll_unpin(cx);
2415            Poll::Ready(())
2416        })
2417        .await;
2418
2419        // ensure that the transactions corresponding to the transaction hashes have been
2420        // successfully retrieved and stored in the Pool.
2421        assert_eq!(pool.get_all(txs_hashes.clone()).len(), txs_hashes.len());
2422    }
2423
2424    #[tokio::test(flavor = "multi_thread")]
2425    async fn test_handle_incoming_transactions() {
2426        reth_tracing::init_test_tracing();
2427        let net = Testnet::create(3).await;
2428
2429        let mut handles = net.handles();
2430        let handle0 = handles.next().unwrap();
2431        let handle1 = handles.next().unwrap();
2432
2433        drop(handles);
2434        let handle = net.spawn();
2435
2436        let listener0 = handle0.event_listener();
2437
2438        handle0.add_peer(*handle1.peer_id(), handle1.local_addr());
2439        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
2440
2441        let client = NoopProvider::default();
2442        let pool = testing_pool();
2443        let config = NetworkConfigBuilder::new(secret_key)
2444            .disable_discovery()
2445            .listener_port(0)
2446            .build(client);
2447        let transactions_manager_config = config.transactions_manager_config.clone();
2448        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
2449            .await
2450            .unwrap()
2451            .into_builder()
2452            .transactions(pool.clone(), transactions_manager_config)
2453            .split_with_handle();
2454        tokio::task::spawn(network);
2455
2456        network_handle.update_sync_state(SyncState::Idle);
2457
2458        assert!(!NetworkInfo::is_syncing(&network_handle));
2459
2460        // wait for all initiator connections
2461        let mut established = listener0.take(2);
2462        while let Some(ev) = established.next().await {
2463            match ev {
2464                NetworkEvent::ActivePeerSession { .. } |
2465                NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => {
2466                    // to insert a new peer in transactions peerset
2467                    transactions.on_network_event(ev);
2468                }
2469                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
2470                ev => {
2471                    error!("unexpected event {ev:?}")
2472                }
2473            }
2474        }
2475        // random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
2476        let input = hex!(
2477            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
2478        );
2479        let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
2480        transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
2481            peer_id: *handle1.peer_id(),
2482            msg: Transactions(vec![signed_tx.clone()]),
2483        });
2484        assert!(transactions
2485            .transactions_by_peers
2486            .get(signed_tx.tx_hash())
2487            .unwrap()
2488            .contains(handle1.peer_id()));
2489
2490        // advance the transaction manager future
2491        poll_fn(|cx| {
2492            let _ = transactions.poll_unpin(cx);
2493            Poll::Ready(())
2494        })
2495        .await;
2496
2497        assert!(!pool.is_empty());
2498        assert!(pool.get(signed_tx.tx_hash()).is_some());
2499        handle.terminate().await;
2500    }
2501
2502    #[tokio::test(flavor = "multi_thread")]
2503    async fn test_on_get_pooled_transactions_network() {
2504        reth_tracing::init_test_tracing();
2505        let net = Testnet::create(2).await;
2506
2507        let mut handles = net.handles();
2508        let handle0 = handles.next().unwrap();
2509        let handle1 = handles.next().unwrap();
2510
2511        drop(handles);
2512        let handle = net.spawn();
2513
2514        let listener0 = handle0.event_listener();
2515
2516        handle0.add_peer(*handle1.peer_id(), handle1.local_addr());
2517        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
2518
2519        let client = NoopProvider::default();
2520        let pool = testing_pool();
2521        let config = NetworkConfigBuilder::new(secret_key)
2522            .disable_discovery()
2523            .listener_port(0)
2524            .build(client);
2525        let transactions_manager_config = config.transactions_manager_config.clone();
2526        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
2527            .await
2528            .unwrap()
2529            .into_builder()
2530            .transactions(pool.clone(), transactions_manager_config)
2531            .split_with_handle();
2532        tokio::task::spawn(network);
2533
2534        network_handle.update_sync_state(SyncState::Idle);
2535
2536        assert!(!NetworkInfo::is_syncing(&network_handle));
2537
2538        // wait for all initiator connections
2539        let mut established = listener0.take(2);
2540        while let Some(ev) = established.next().await {
2541            match ev {
2542                NetworkEvent::ActivePeerSession { .. } |
2543                NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => {
2544                    transactions.on_network_event(ev);
2545                }
2546                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
2547                ev => {
2548                    error!("unexpected event {ev:?}")
2549                }
2550            }
2551        }
2552        handle.terminate().await;
2553
2554        let tx = MockTransaction::eip1559();
2555        let _ = transactions
2556            .pool
2557            .add_transaction(reth_transaction_pool::TransactionOrigin::External, tx.clone())
2558            .await;
2559
2560        let request = GetPooledTransactions(vec![*tx.get_hash()]);
2561
2562        let (send, receive) =
2563            oneshot::channel::<RequestResult<PooledTransactions<PooledTransactionVariant>>>();
2564
2565        transactions.on_network_tx_event(NetworkTransactionEvent::GetPooledTransactions {
2566            peer_id: *handle1.peer_id(),
2567            request,
2568            response: send,
2569        });
2570
2571        match receive.await.unwrap() {
2572            Ok(PooledTransactions(transactions)) => {
2573                assert_eq!(transactions.len(), 1);
2574            }
2575            Err(e) => {
2576                panic!("error: {e:?}");
2577            }
2578        }
2579    }
2580
2581    // Ensure that when the remote peer only returns part of the requested transactions, the
2582    // replied transactions are removed from the `tx_fetcher`, while the unresponsive ones are
2583    // re-buffered.
2584    #[tokio::test]
2585    async fn test_partially_tx_response() {
2586        reth_tracing::init_test_tracing();
2587
2588        let mut tx_manager = new_tx_manager().await.0;
2589        let tx_fetcher = &mut tx_manager.transaction_fetcher;
2590
2591        let peer_id_1 = PeerId::new([1; 64]);
2592        let eth_version = EthVersion::Eth66;
2593
2594        let txs = vec![
2595            TransactionSigned::new_unhashed(
2596                Transaction::Legacy(TxLegacy {
2597                    chain_id: Some(4),
2598                    nonce: 15u64,
2599                    gas_price: 2200000000,
2600                    gas_limit: 34811,
2601                    to: TxKind::Call(hex!("cf7f9e66af820a19257a2108375b180b0ec49167").into()),
2602                    value: U256::from(1234u64),
2603                    input: Default::default(),
2604                }),
2605                Signature::new(
2606                    U256::from_str(
2607                        "0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981",
2608                    )
2609                    .unwrap(),
2610                    U256::from_str(
2611                        "0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860",
2612                    )
2613                    .unwrap(),
2614                    true,
2615                ),
2616            ),
2617            TransactionSigned::new_unhashed(
2618                Transaction::Eip1559(TxEip1559 {
2619                    chain_id: 4,
2620                    nonce: 26u64,
2621                    max_priority_fee_per_gas: 1500000000,
2622                    max_fee_per_gas: 1500000013,
2623                    gas_limit: MIN_TRANSACTION_GAS,
2624                    to: TxKind::Call(hex!("61815774383099e24810ab832a5b2a5425c154d5").into()),
2625                    value: U256::from(3000000000000000000u64),
2626                    input: Default::default(),
2627                    access_list: Default::default(),
2628                }),
2629                Signature::new(
2630                    U256::from_str(
2631                        "0x59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd",
2632                    )
2633                    .unwrap(),
2634                    U256::from_str(
2635                        "0x016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469",
2636                    )
2637                    .unwrap(),
2638                    true,
2639                ),
2640            ),
2641        ];
2642
2643        let txs_hashes: Vec<B256> = txs.iter().map(|tx| *tx.hash()).collect();
2644
2645        let (mut peer_1, mut to_mock_session_rx) = new_mock_session(peer_id_1, eth_version);
2646        // mark hashes as seen by peer so it can fish them out from the cache for hashes pending
2647        // fetch
2648        peer_1.seen_transactions.insert(txs_hashes[0]);
2649        peer_1.seen_transactions.insert(txs_hashes[1]);
2650        tx_manager.peers.insert(peer_id_1, peer_1);
2651
2652        buffer_hash_to_tx_fetcher(tx_fetcher, txs_hashes[0], peer_id_1, 0, None);
2653        buffer_hash_to_tx_fetcher(tx_fetcher, txs_hashes[1], peer_id_1, 0, None);
2654
2655        // peer_1 is idle
2656        assert!(tx_fetcher.is_idle(&peer_id_1));
2657        assert_eq!(tx_fetcher.active_peers.len(), 0);
2658
2659        // sends requests for buffered hashes to peer_1
2660        tx_fetcher.on_fetch_pending_hashes(&tx_manager.peers, |_| true);
2661
2662        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
2663        // as long as request is in flight peer_1 is not idle
2664        assert!(!tx_fetcher.is_idle(&peer_id_1));
2665        assert_eq!(tx_fetcher.active_peers.len(), 1);
2666
2667        // mock session of peer_1 receives request
2668        let req = to_mock_session_rx
2669            .recv()
2670            .await
2671            .expect("peer_1 session should receive request with buffered hashes");
2672        let PeerRequest::GetPooledTransactions { response, .. } = req else { unreachable!() };
2673
2674        let message: Vec<PooledTransactionVariant> = txs
2675            .into_iter()
2676            .take(1)
2677            .map(|tx| {
2678                PooledTransactionVariant::try_from(tx)
2679                    .expect("Failed to convert MockTransaction to PooledTransaction")
2680            })
2681            .collect();
2682        // response partial request
2683        response
2684            .send(Ok(PooledTransactions(message)))
2685            .expect("should send peer_1 response to tx manager");
2686        let Some(FetchEvent::TransactionsFetched { peer_id, .. }) = tx_fetcher.next().await else {
2687            unreachable!()
2688        };
2689
2690        // request has resolved, peer_1 is idle again
2691        assert!(tx_fetcher.is_idle(&peer_id));
2692        assert_eq!(tx_fetcher.active_peers.len(), 0);
2693        // failing peer_1's request buffers requested hashes for retry.
2694        assert_eq!(tx_fetcher.num_pending_hashes(), 1);
2695    }
2696
2697    #[tokio::test]
2698    async fn test_max_retries_tx_request() {
2699        reth_tracing::init_test_tracing();
2700
2701        let mut tx_manager = new_tx_manager().await.0;
2702        let tx_fetcher = &mut tx_manager.transaction_fetcher;
2703
2704        let peer_id_1 = PeerId::new([1; 64]);
2705        let peer_id_2 = PeerId::new([2; 64]);
2706        let eth_version = EthVersion::Eth66;
2707        let seen_hashes = [B256::from_slice(&[1; 32]), B256::from_slice(&[2; 32])];
2708
2709        let (mut peer_1, mut to_mock_session_rx) = new_mock_session(peer_id_1, eth_version);
2710        // mark hashes as seen by peer so it can fish them out from the cache for hashes pending
2711        // fetch
2712        peer_1.seen_transactions.insert(seen_hashes[0]);
2713        peer_1.seen_transactions.insert(seen_hashes[1]);
2714        tx_manager.peers.insert(peer_id_1, peer_1);
2715
2716        // hashes are seen and currently not inflight, with one fallback peer, and are buffered
2717        // for first retry in reverse order to make index 0 lru
2718        let retries = 1;
2719        buffer_hash_to_tx_fetcher(tx_fetcher, seen_hashes[1], peer_id_1, retries, None);
2720        buffer_hash_to_tx_fetcher(tx_fetcher, seen_hashes[0], peer_id_1, retries, None);
2721
2722        // peer_1 is idle
2723        assert!(tx_fetcher.is_idle(&peer_id_1));
2724        assert_eq!(tx_fetcher.active_peers.len(), 0);
2725
2726        // sends request for buffered hashes to peer_1
2727        tx_fetcher.on_fetch_pending_hashes(&tx_manager.peers, |_| true);
2728
2729        let tx_fetcher = &mut tx_manager.transaction_fetcher;
2730
2731        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
2732        // as long as request is in inflight peer_1 is not idle
2733        assert!(!tx_fetcher.is_idle(&peer_id_1));
2734        assert_eq!(tx_fetcher.active_peers.len(), 1);
2735
2736        // mock session of peer_1 receives request
2737        let req = to_mock_session_rx
2738            .recv()
2739            .await
2740            .expect("peer_1 session should receive request with buffered hashes");
2741        let PeerRequest::GetPooledTransactions { request, response } = req else { unreachable!() };
2742        let GetPooledTransactions(hashes) = request;
2743
2744        let hashes = hashes.into_iter().collect::<HashSet<_>>();
2745
2746        assert_eq!(hashes, seen_hashes.into_iter().collect::<HashSet<_>>());
2747
2748        // fail request to peer_1
2749        response
2750            .send(Err(RequestError::BadResponse))
2751            .expect("should send peer_1 response to tx manager");
2752        let Some(FetchEvent::FetchError { peer_id, .. }) = tx_fetcher.next().await else {
2753            unreachable!()
2754        };
2755
2756        // request has resolved, peer_1 is idle again
2757        assert!(tx_fetcher.is_idle(&peer_id));
2758        assert_eq!(tx_fetcher.active_peers.len(), 0);
2759        // failing peer_1's request buffers requested hashes for retry
2760        assert_eq!(tx_fetcher.num_pending_hashes(), 2);
2761
2762        let (peer_2, mut to_mock_session_rx) = new_mock_session(peer_id_2, eth_version);
2763        tx_manager.peers.insert(peer_id_2, peer_2);
2764
2765        // peer_2 announces same hashes as peer_1
2766        let msg =
2767            NewPooledTransactionHashes::Eth66(NewPooledTransactionHashes66(seen_hashes.to_vec()));
2768        tx_manager.on_new_pooled_transaction_hashes(peer_id_2, msg);
2769
2770        let tx_fetcher = &mut tx_manager.transaction_fetcher;
2771
2772        // peer_2 should be in active_peers.
2773        assert_eq!(tx_fetcher.active_peers.len(), 1);
2774
2775        // since hashes are already seen, no changes to length of unknown hashes
2776        assert_eq!(tx_fetcher.num_all_hashes(), 2);
2777        // but hashes are taken out of buffer and packed into request to peer_2
2778        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
2779
2780        // mock session of peer_2 receives request
2781        let req = to_mock_session_rx
2782            .recv()
2783            .await
2784            .expect("peer_2 session should receive request with buffered hashes");
2785        let PeerRequest::GetPooledTransactions { response, .. } = req else { unreachable!() };
2786
2787        // report failed request to tx manager
2788        response
2789            .send(Err(RequestError::BadResponse))
2790            .expect("should send peer_2 response to tx manager");
2791        let Some(FetchEvent::FetchError { .. }) = tx_fetcher.next().await else { unreachable!() };
2792
2793        // `MAX_REQUEST_RETRIES_PER_TX_HASH`, 2, for hashes reached so this time won't be buffered
2794        // for retry
2795        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
2796        assert_eq!(tx_fetcher.active_peers.len(), 0);
2797    }
2798
2799    #[test]
2800    fn test_transaction_builder_empty() {
2801        let mut builder =
2802            PropagateTransactionsBuilder::<TransactionSigned>::pooled(EthVersion::Eth68);
2803        assert!(builder.is_empty());
2804
2805        let mut factory = MockTransactionFactory::default();
2806        let tx = PropagateTransaction::pool_tx(Arc::new(factory.create_eip1559()));
2807        builder.push(&tx);
2808        assert!(!builder.is_empty());
2809
2810        let txs = builder.build();
2811        assert!(txs.full.is_none());
2812        let txs = txs.pooled.unwrap();
2813        assert_eq!(txs.len(), 1);
2814    }
2815
2816    #[test]
2817    fn test_transaction_builder_large() {
2818        let mut builder =
2819            PropagateTransactionsBuilder::<TransactionSigned>::full(EthVersion::Eth68);
2820        assert!(builder.is_empty());
2821
2822        let mut factory = MockTransactionFactory::default();
2823        let mut tx = factory.create_eip1559();
2824        // create a transaction that still fits
2825        tx.transaction.set_size(DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE + 1);
2826        let tx = Arc::new(tx);
2827        let tx = PropagateTransaction::pool_tx(tx);
2828        builder.push(&tx);
2829        assert!(!builder.is_empty());
2830
2831        let txs = builder.clone().build();
2832        assert!(txs.pooled.is_none());
2833        let txs = txs.full.unwrap();
2834        assert_eq!(txs.len(), 1);
2835
2836        builder.push(&tx);
2837
2838        let txs = builder.clone().build();
2839        let pooled = txs.pooled.unwrap();
2840        assert_eq!(pooled.len(), 1);
2841        let txs = txs.full.unwrap();
2842        assert_eq!(txs.len(), 1);
2843    }
2844
2845    #[test]
2846    fn test_transaction_builder_eip4844() {
2847        let mut builder =
2848            PropagateTransactionsBuilder::<TransactionSigned>::full(EthVersion::Eth68);
2849        assert!(builder.is_empty());
2850
2851        let mut factory = MockTransactionFactory::default();
2852        let tx = PropagateTransaction::pool_tx(Arc::new(factory.create_eip4844()));
2853        builder.push(&tx);
2854        assert!(!builder.is_empty());
2855
2856        let txs = builder.clone().build();
2857        assert!(txs.full.is_none());
2858        let txs = txs.pooled.unwrap();
2859        assert_eq!(txs.len(), 1);
2860
2861        let tx = PropagateTransaction::pool_tx(Arc::new(factory.create_eip1559()));
2862        builder.push(&tx);
2863
2864        let txs = builder.clone().build();
2865        let pooled = txs.pooled.unwrap();
2866        assert_eq!(pooled.len(), 1);
2867        let txs = txs.full.unwrap();
2868        assert_eq!(txs.len(), 1);
2869    }
2870
2871    #[tokio::test]
2872    async fn test_propagate_full() {
2873        reth_tracing::init_test_tracing();
2874
2875        let (mut tx_manager, network) = new_tx_manager().await;
2876        let peer_id = PeerId::random();
2877
2878        // ensure not syncing
2879        network.handle().update_sync_state(SyncState::Idle);
2880
2881        // mock a peer
2882        let (tx, _rx) = mpsc::channel::<PeerRequest>(1);
2883
2884        let session_info = SessionInfo {
2885            peer_id,
2886            remote_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
2887            client_version: Arc::from(""),
2888            capabilities: Arc::new(vec![].into()),
2889            status: Arc::new(Default::default()),
2890            version: EthVersion::Eth68,
2891            peer_kind: PeerKind::Basic,
2892        };
2893        let messages: PeerRequestSender<PeerRequest> = PeerRequestSender::new(peer_id, tx);
2894        tx_manager
2895            .on_network_event(NetworkEvent::ActivePeerSession { info: session_info, messages });
2896        let mut propagate = vec![];
2897        let mut factory = MockTransactionFactory::default();
2898        let eip1559_tx = Arc::new(factory.create_eip1559());
2899        propagate.push(PropagateTransaction::pool_tx(eip1559_tx.clone()));
2900        let eip4844_tx = Arc::new(factory.create_eip4844());
2901        propagate.push(PropagateTransaction::pool_tx(eip4844_tx.clone()));
2902
2903        let propagated =
2904            tx_manager.propagate_transactions(propagate.clone(), PropagationMode::Basic);
2905        assert_eq!(propagated.0.len(), 2);
2906        let prop_txs = propagated.0.get(eip1559_tx.transaction.hash()).unwrap();
2907        assert_eq!(prop_txs.len(), 1);
2908        assert!(prop_txs[0].is_full());
2909
2910        let prop_txs = propagated.0.get(eip4844_tx.transaction.hash()).unwrap();
2911        assert_eq!(prop_txs.len(), 1);
2912        assert!(prop_txs[0].is_hash());
2913
2914        let peer = tx_manager.peers.get(&peer_id).unwrap();
2915        assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash()));
2916        assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash()));
2917        peer.seen_transactions.contains(eip4844_tx.transaction.hash());
2918
2919        // propagate again
2920        let propagated = tx_manager.propagate_transactions(propagate, PropagationMode::Basic);
2921        assert!(propagated.0.is_empty());
2922    }
2923
2924    #[tokio::test]
2925    async fn test_relaxed_filter_ignores_unknown_tx_types() {
2926        reth_tracing::init_test_tracing();
2927
2928        let transactions_manager_config = TransactionsManagerConfig::default();
2929
2930        let propagation_policy = TransactionPropagationKind::default();
2931        let announcement_policy = RelaxedEthAnnouncementFilter::default();
2932
2933        let policy_bundle = NetworkPolicies::new(propagation_policy, announcement_policy);
2934
2935        let pool = testing_pool();
2936        let secret_key = SecretKey::new(&mut rand_08::thread_rng());
2937        let client = NoopProvider::default();
2938
2939        let network_config = NetworkConfigBuilder::new(secret_key)
2940            .listener_port(0)
2941            .disable_discovery()
2942            .build(client.clone());
2943
2944        let mut network_manager = NetworkManager::new(network_config).await.unwrap();
2945        let (to_tx_manager_tx, from_network_rx) =
2946            mpsc::unbounded_channel::<NetworkTransactionEvent<EthNetworkPrimitives>>();
2947        network_manager.set_transactions(to_tx_manager_tx);
2948        let network_handle = network_manager.handle().clone();
2949        let network_service_handle = tokio::spawn(network_manager);
2950
2951        let mut tx_manager = TransactionsManager::<TestPool, EthNetworkPrimitives>::with_policy(
2952            network_handle.clone(),
2953            pool.clone(),
2954            from_network_rx,
2955            transactions_manager_config,
2956            policy_bundle,
2957        );
2958
2959        let peer_id = PeerId::random();
2960        let eth_version = EthVersion::Eth68;
2961        let (mock_peer_metadata, mut mock_session_rx) = new_mock_session(peer_id, eth_version);
2962        tx_manager.peers.insert(peer_id, mock_peer_metadata);
2963
2964        let mut tx_factory = MockTransactionFactory::default();
2965
2966        let valid_known_tx = tx_factory.create_eip1559();
2967        let known_tx_signed: Arc<ValidPoolTransaction<MockTransaction>> = Arc::new(valid_known_tx);
2968
2969        let known_tx_hash = *known_tx_signed.hash();
2970        let known_tx_type_byte = known_tx_signed.transaction.tx_type();
2971        let known_tx_size = known_tx_signed.encoded_length();
2972
2973        let unknown_tx_hash = B256::random();
2974        let unknown_tx_type_byte = 0xff_u8;
2975        let unknown_tx_size = 150;
2976
2977        let announcement_msg = NewPooledTransactionHashes::Eth68(NewPooledTransactionHashes68 {
2978            types: vec![known_tx_type_byte, unknown_tx_type_byte],
2979            sizes: vec![known_tx_size, unknown_tx_size],
2980            hashes: vec![known_tx_hash, unknown_tx_hash],
2981        });
2982
2983        tx_manager.on_new_pooled_transaction_hashes(peer_id, announcement_msg);
2984
2985        poll_fn(|cx| {
2986            let _ = tx_manager.poll_unpin(cx);
2987            Poll::Ready(())
2988        })
2989        .await;
2990
2991        let mut requested_hashes_in_getpooled = HashSet::new();
2992        let mut unexpected_request_received = false;
2993
2994        match tokio::time::timeout(std::time::Duration::from_millis(200), mock_session_rx.recv())
2995            .await
2996        {
2997            Ok(Some(PeerRequest::GetPooledTransactions { request, response: tx_response_ch })) => {
2998                let GetPooledTransactions(hashes) = request;
2999                for hash in hashes {
3000                    requested_hashes_in_getpooled.insert(hash);
3001                }
3002                let _ = tx_response_ch.send(Ok(PooledTransactions(vec![])));
3003            }
3004            Ok(Some(other_request)) => {
3005                tracing::error!(?other_request, "Received unexpected PeerRequest type");
3006                unexpected_request_received = true;
3007            }
3008            Ok(None) => tracing::info!("Mock session channel closed or no request received."),
3009            Err(_timeout_err) => {
3010                tracing::info!("Timeout: No GetPooledTransactions request received.")
3011            }
3012        }
3013
3014        assert!(
3015            requested_hashes_in_getpooled.contains(&known_tx_hash),
3016            "Should have requested the known EIP-1559 transaction. Requested: {requested_hashes_in_getpooled:?}"
3017        );
3018        assert!(
3019            !requested_hashes_in_getpooled.contains(&unknown_tx_hash),
3020            "Should NOT have requested the unknown transaction type. Requested: {requested_hashes_in_getpooled:?}"
3021        );
3022        assert!(
3023            !unexpected_request_received,
3024            "An unexpected P2P request was received by the mock peer."
3025        );
3026
3027        network_service_handle.abort();
3028    }
3029}