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