Skip to main content

reth_network/transactions/
mod.rs

1//! Transactions management for the p2p network.
2
3use alloy_consensus::{constants::EIP4844_TX_TYPE_ID, transaction::TxHashRef, Transaction as _};
4use reth_concurrency::sync::rayon::iter::{IntoParallelIterator, ParallelIterator};
5use smallvec::SmallVec;
6
7/// Normalized transaction announcements.
8pub mod announcement;
9mod blob;
10
11/// Aggregation on configurable parameters for [`TransactionsManager`].
12pub mod config;
13/// Default and spec'd bounds.
14pub mod constants;
15/// Component responsible for fetching transactions from [`NewPooledTransactionHashes`].
16pub mod fetcher;
17/// Defines the traits for transaction-related policies.
18pub mod policy;
19#[cfg(test)]
20mod test_harness;
21
22pub use self::constants::{
23    tx_fetcher::DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
24    SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
25};
26use announcement::TransactionAnnouncement;
27use blob::BlobFetcher;
28use config::AnnouncementAcceptance;
29pub use config::{
30    AnnouncementFilteringPolicy, TransactionFetcherConfig, TransactionIngressPolicy,
31    TransactionPropagationMode, TransactionPropagationPolicy, TransactionsManagerConfig,
32};
33use policy::NetworkPolicies;
34
35pub(crate) use fetcher::{FetchEvent, TransactionFetcher};
36
37use self::constants::{
38    tx_manager::*, DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE,
39    SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST,
40};
41use crate::{
42    budget::{
43        DEFAULT_BUDGET_TRY_DRAIN_NETWORK_TRANSACTION_EVENTS,
44        DEFAULT_BUDGET_TRY_DRAIN_PENDING_POOL_IMPORTS, DEFAULT_BUDGET_TRY_DRAIN_STREAM,
45    },
46    cache::{LruCache, LruMap},
47    duration_metered_exec, metered_poll_nested_stream_with_budget,
48    metrics::{AnnouncedTxTypesMetrics, TransactionsManagerMetrics},
49    network::NetworkHandleMessage,
50    transactions::config::{StrictEthAnnouncementFilter, TransactionPropagationKind},
51    NetworkHandle, TxTypesCounter,
52};
53use alloy_eips::{
54    eip2718::{Encodable2718, Typed2718},
55    eip7594::BlobCellMask,
56};
57use alloy_primitives::{
58    bytes::BufMut,
59    map::{hash_map::Entry, B256Map, B256Set, FbBuildHasher, HashMap, HashSet},
60    Address, TxHash, B128, B256,
61};
62use alloy_rlp::Encodable;
63use constants::SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE;
64use futures::{stream::FuturesUnordered, Future, StreamExt};
65use reth_eth_wire::{
66    BroadcastPoolTransactions, Cells, DisconnectReason, EthNetworkPrimitives, EthVersion, GetCells,
67    GetPooledTransactions, LazyEncoded, LazyEncodedTransaction, NetworkPrimitives,
68    NewPooledTransactionHashes, NewPooledTransactionHashes66, NewPooledTransactionHashes68,
69    NewPooledTransactionHashes72, PooledTransactions, Transactions,
70};
71use reth_ethereum_primitives::TxType;
72use reth_evm::SenderRecoveryCache;
73use reth_metrics::common::mpsc::MemoryBoundedReceiver;
74use reth_network_api::{
75    events::{PeerEvent, SessionInfo},
76    NetworkEvent, NetworkEventListenerProvider, PeerKind, PeerRequest, PeerRequestSender, Peers,
77};
78use reth_network_p2p::{
79    error::{RequestError, RequestResult},
80    sync::SyncStateProvider,
81};
82use reth_network_peers::PeerId;
83use reth_network_types::ReputationChangeKind;
84use reth_primitives_traits::{InMemorySize, SignedTransaction};
85use reth_tokio_util::EventStream;
86use reth_transaction_pool::{
87    blobstore::BlobCellAvailability,
88    error::{
89        Eip4844PoolTransactionError, InvalidPoolTransactionError, PoolError, PoolErrorKind,
90        PoolResult,
91    },
92    AddedTransactionOutcome, GetPooledTransactionLimit, PoolTransaction, PropagateKind,
93    PropagatedTransactions, TransactionPool, ValidPoolTransaction,
94};
95use std::{
96    pin::Pin,
97    sync::{
98        atomic::{AtomicUsize, Ordering},
99        Arc,
100    },
101    task::{Context, Poll},
102    time::{Duration, Instant},
103};
104use tokio::sync::{mpsc, oneshot, oneshot::error::RecvError};
105use tokio_stream::wrappers::UnboundedReceiverStream;
106use tracing::{debug, trace};
107
108/// The future for importing transactions into the pool.
109///
110/// Resolves with the result of each transaction import.
111pub type PoolImportFuture =
112    Pin<Box<dyn Future<Output = Vec<PoolResult<AddedTransactionOutcome>>> + Send + 'static>>;
113
114/// A blob transaction whose cells passed the check, with the peer that sent its body. Boxed, as
115/// pool transactions needn't be `Unpin`.
116type VerifiedBlobTx<T> = (PeerId, Box<T>);
117
118/// Api to interact with [`TransactionsManager`] task.
119///
120/// This can be obtained via [`TransactionsManager::handle`] and can be used to manually interact
121/// with the [`TransactionsManager`] task once it is spawned.
122///
123/// For example [`TransactionsHandle::get_peer_transaction_hashes`] returns the transaction hashes
124/// known by a specific peer.
125#[derive(Debug, Clone)]
126pub struct TransactionsHandle<N: NetworkPrimitives = EthNetworkPrimitives> {
127    /// Command channel to the [`TransactionsManager`]
128    manager_tx: mpsc::UnboundedSender<TransactionsCommand<N>>,
129}
130
131impl<N: NetworkPrimitives> TransactionsHandle<N> {
132    fn send(&self, cmd: TransactionsCommand<N>) {
133        let _ = self.manager_tx.send(cmd);
134    }
135
136    /// Fetch the [`PeerRequestSender`] for the given peer.
137    async fn peer_handle(
138        &self,
139        peer_id: PeerId,
140    ) -> Result<Option<PeerRequestSender<PeerRequest<N>>>, RecvError> {
141        let (tx, rx) = oneshot::channel();
142        self.send(TransactionsCommand::GetPeerSender { peer_id, peer_request_sender: tx });
143        rx.await
144    }
145
146    /// Manually propagate the transaction that belongs to the hash.
147    pub fn propagate(&self, hash: TxHash) {
148        self.send(TransactionsCommand::PropagateHash(hash))
149    }
150
151    /// Manually propagate the transaction hash to a specific peer.
152    ///
153    /// Note: this only propagates if the pool contains the transaction.
154    pub fn propagate_hash_to(&self, hash: TxHash, peer: PeerId) {
155        self.propagate_hashes_to(Some(hash), peer)
156    }
157
158    /// Manually propagate the transaction hashes to a specific peer.
159    ///
160    /// Note: this only propagates the transactions that are known to the pool.
161    pub fn propagate_hashes_to(&self, hash: impl IntoIterator<Item = TxHash>, peer: PeerId) {
162        let hashes = hash.into_iter().collect::<Vec<_>>();
163        if hashes.is_empty() {
164            return
165        }
166        self.send(TransactionsCommand::PropagateHashesTo(hashes, peer))
167    }
168
169    /// Request the active peer IDs from the [`TransactionsManager`].
170    pub async fn get_active_peers(&self) -> Result<HashSet<PeerId>, RecvError> {
171        let (tx, rx) = oneshot::channel();
172        self.send(TransactionsCommand::GetActivePeers(tx));
173        rx.await
174    }
175
176    /// Manually propagate full transaction hashes to a specific peer.
177    ///
178    /// Do nothing if transactions are empty.
179    pub fn propagate_transactions_to(&self, transactions: Vec<TxHash>, peer: PeerId) {
180        if transactions.is_empty() {
181            return
182        }
183        self.send(TransactionsCommand::PropagateTransactionsTo(transactions, peer))
184    }
185
186    /// Manually propagate the given transaction hashes to all peers.
187    ///
188    /// It's up to the [`TransactionsManager`] whether the transactions are sent as hashes or in
189    /// full.
190    pub fn propagate_transactions(&self, transactions: Vec<TxHash>) {
191        if transactions.is_empty() {
192            return
193        }
194        self.send(TransactionsCommand::PropagateTransactions(transactions))
195    }
196
197    /// Manually propagate the given transactions to all peers.
198    ///
199    /// It's up to the [`TransactionsManager`] whether the transactions are sent as hashes or in
200    /// full. Blob announcements require a propagatable pool entry.
201    pub fn broadcast_transactions(
202        &self,
203        transactions: impl IntoIterator<Item = N::BroadcastedTransaction>,
204    ) {
205        let transactions =
206            transactions.into_iter().map(PropagateTransaction::new).collect::<Vec<_>>();
207        if transactions.is_empty() {
208            return
209        }
210        self.send(TransactionsCommand::BroadcastTransactions(transactions))
211    }
212
213    /// Request the transaction hashes known by specific peers.
214    pub async fn get_transaction_hashes(
215        &self,
216        peers: Vec<PeerId>,
217    ) -> Result<HashMap<PeerId, B256Set>, RecvError> {
218        if peers.is_empty() {
219            return Ok(Default::default())
220        }
221        let (tx, rx) = oneshot::channel();
222        self.send(TransactionsCommand::GetTransactionHashes { peers, tx });
223        rx.await
224    }
225
226    /// Request the transaction hashes known by a specific peer.
227    pub async fn get_peer_transaction_hashes(&self, peer: PeerId) -> Result<B256Set, RecvError> {
228        let res = self.get_transaction_hashes(vec![peer]).await?;
229        Ok(res.into_values().next().unwrap_or_default())
230    }
231
232    /// Requests the transactions directly from the given peer.
233    ///
234    /// Returns `None` if the peer is not connected.
235    ///
236    /// **Note**: this returns the response from the peer as received.
237    pub async fn get_pooled_transactions_from(
238        &self,
239        peer_id: PeerId,
240        hashes: Vec<B256>,
241    ) -> Result<Option<Vec<N::PooledTransaction>>, RequestError> {
242        let Some(peer) = self.peer_handle(peer_id).await? else { return Ok(None) };
243
244        let (tx, rx) = oneshot::channel();
245        let request = PeerRequest::GetPooledTransactions { request: hashes.into(), response: tx };
246        peer.try_send(request).ok();
247
248        rx.await?.map(|res| Some(res.0))
249    }
250
251    /// Requests cells from a specific eth/72 peer.
252    ///
253    /// This is the transport-level client primitive for EIP-8070. The caller supplies the
254    /// transaction hashes and the common cell mask for the request. Announcement-driven batching,
255    /// retries, cell verification, and blob reconstruction are layered above this method.
256    ///
257    /// Returns `None` if the peer is no longer connected.
258    pub async fn get_cells_from(
259        &self,
260        peer_id: PeerId,
261        hashes: Vec<B256>,
262        cell_mask: B128,
263    ) -> Result<Option<Cells>, RequestError> {
264        if hashes.is_empty() {
265            return Ok(Some(Cells { cell_mask: cell_mask.into(), ..Default::default() }))
266        }
267
268        self.request_cells_from(peer_id, GetCells { hashes, cell_mask: cell_mask.into() }).await
269    }
270
271    /// Requests cells with one little-endian mask per transaction hash.
272    /// Uniform batches use shared encoding; heterogeneous batches require an eth/73 peer and
273    /// contain at most 64 unique hashes. Invalid batches return `InvalidRequest` without sending.
274    /// Returns `None` if the peer disconnected. Callers must verify returned cells against the
275    /// transaction commitments and proofs before using them, as with `get_cells_from`.
276    pub async fn get_cells_with_masks_from(
277        &self,
278        peer_id: PeerId,
279        hashes: Vec<B256>,
280        masks: Vec<B128>,
281    ) -> Result<Option<Cells>, RequestError> {
282        let request =
283            GetCells::from_masks(hashes, masks).map_err(|_| RequestError::InvalidRequest)?;
284        self.request_cells_from(peer_id, request).await
285    }
286
287    async fn request_cells_from(
288        &self,
289        peer_id: PeerId,
290        request: GetCells,
291    ) -> Result<Option<Cells>, RequestError> {
292        let Some(peer) = self.peer_handle(peer_id).await? else { return Ok(None) };
293        let (tx, rx) = oneshot::channel();
294        peer.try_send(PeerRequest::GetCells { request, response: tx })
295            .map_err(|_| RequestError::ChannelClosed)?;
296        rx.await?.map(Some)
297    }
298}
299
300/// Manages transactions on top of the p2p network.
301///
302/// This can be spawned to another task and is supposed to be run as background service.
303/// [`TransactionsHandle`] can be used as frontend to programmatically send commands to it and
304/// interact with it.
305///
306/// The [`TransactionsManager`] is responsible for:
307///    - handling incoming eth messages for transactions.
308///    - serving transaction requests.
309///    - propagate transactions
310///
311/// This type communicates with the [`NetworkManager`](crate::NetworkManager) in both directions.
312///   - receives incoming network messages.
313///   - sends messages to dispatch (responses, propagate tx)
314///
315/// It is directly connected to the [`TransactionPool`] to retrieve requested transactions and
316/// propagate new transactions over the network.
317///
318/// It can be configured with different policies for transaction propagation and announcement
319/// filtering. See [`NetworkPolicies`] for more details.
320///
321/// ## Network Transaction Processing
322///
323/// ### Message Types
324///
325/// - **`Transactions`**: Full transaction broadcasts (rejects blob transactions)
326/// - **`NewPooledTransactionHashes`**: Hash announcements
327///
328/// ### Peer Tracking
329///
330/// - Maintains per-peer transaction cache (default: 10,240 entries)
331/// - Prevents duplicate imports and enables efficient propagation
332///
333/// ### Bad Transaction Handling
334///
335/// Caches and rejects transactions with consensus violations (gas, signature, chain ID).
336/// Penalizes peers sending invalid transactions.
337///
338/// ### Import Management
339///
340/// Limits concurrent pool imports and backs off when approaching capacity.
341///
342/// ### Transaction Fetching
343///
344/// For announced transactions: filters known → queues unknown → fetches → imports
345///
346/// ### Propagation Rules
347///
348/// Based on: origin (Local/External/Private), peer capabilities, and network state.
349/// Disabled during initial sync.
350///
351/// ### Security
352///
353/// Rate limiting via reputation, bad transaction isolation, peer scoring.
354#[derive(Debug)]
355#[must_use = "Manager does nothing unless polled."]
356pub struct TransactionsManager<Pool: TransactionPool, N: NetworkPrimitives = EthNetworkPrimitives> {
357    /// Access to the transaction pool.
358    pool: Pool,
359    /// Cache of recovered transaction senders shared with payload execution, if enabled.
360    sender_recovery_cache: Option<SenderRecoveryCache>,
361    /// Network access.
362    network: NetworkHandle<N>,
363    /// Subscriptions to all network related events.
364    ///
365    /// From which we get all new incoming transaction related messages.
366    network_events: EventStream<NetworkEvent<PeerRequest<N>>>,
367    /// Transaction fetcher to handle inflight and missing transaction requests.
368    transaction_fetcher: TransactionFetcher<N>,
369    /// Fetches the cells of blob transactions whose bodies eth/72 peers send without blobs.
370    blob_fetcher: BlobFetcher<Pool::Transaction>,
371    /// All currently pending transactions grouped by peers.
372    ///
373    /// This way we can track incoming transactions and prevent multiple pool imports for the same
374    /// transaction
375    transactions_by_peers: B256Map<SmallVec<[PeerId; 1]>>,
376    /// Scratch hashes reused when deduplicating announcements.
377    announcement_hashes: B256Set,
378    /// Transactions that are currently imported into the `Pool`.
379    ///
380    /// The import process includes:
381    ///  - validation of the transactions, e.g. transaction is well formed: valid tx type, fees are
382    ///    valid, or for 4844 transaction the blobs are valid. See also
383    ///    [`EthTransactionValidator`](reth_transaction_pool::validate::EthTransactionValidator)
384    /// - if the transaction is valid, it is added into the pool.
385    ///
386    /// Once the new transaction reaches the __pending__ state it will be emitted by the pool via
387    /// [`TransactionPool::pending_transactions_listener`] and arrive at the `pending_transactions`
388    /// receiver.
389    pool_imports: FuturesUnordered<PoolImportFuture>,
390    /// Stats on pending pool imports that help the node self-monitor.
391    pending_pool_imports_info: PendingPoolImportsInfo,
392    /// Bad imports.
393    bad_imports: LruCache<TxHash, FbBuildHasher<32>>,
394    /// Blob transactions whose sender's previous nonce wasn't pooled, kept while their import runs
395    /// so a nonce gap can be retried.
396    importing_blob_txs: B256Map<VerifiedBlobTx<Pool::Transaction>>,
397    /// Blob transactions turned away for a nonce gap, by sender and nonce, imported again once the
398    /// previous nonce is, since cell checks finish in any order.
399    nonce_gapped_blob_txs: LruMap<(Address, u64), VerifiedBlobTx<Pool::Transaction>>,
400    /// All the connected peers.
401    peers: HashMap<PeerId, PeerMetadata<N>, FbBuildHasher<64>>,
402    /// Send half for the command channel.
403    ///
404    /// This is kept so that a new [`TransactionsHandle`] can be created at any time.
405    command_tx: mpsc::UnboundedSender<TransactionsCommand<N>>,
406    /// Incoming commands from [`TransactionsHandle`].
407    ///
408    /// This will only receive commands if a user manually sends a command to the manager through
409    /// the [`TransactionsHandle`] to interact with this type directly.
410    command_rx: UnboundedReceiverStream<TransactionsCommand<N>>,
411    /// A stream that yields new __pending__ transactions.
412    ///
413    /// A transaction is considered __pending__ if it is executable on the current state of the
414    /// chain. In other words, this only yields transactions that satisfy all consensus
415    /// requirements, these include:
416    ///   - no nonce gaps
417    ///   - all dynamic fee requirements are (currently) met
418    ///   - account has enough balance to cover the transaction's gas
419    pending_transactions: mpsc::Receiver<TxHash>,
420    /// Incoming events from the [`NetworkManager`](crate::NetworkManager).
421    transaction_events: MemoryBoundedReceiver<NetworkTransactionEvent<N>>,
422    /// How the `TransactionsManager` is configured.
423    config: TransactionsManagerConfig,
424    /// Network Policies
425    policies: NetworkPolicies<N>,
426    /// `TransactionsManager` metrics
427    metrics: TransactionsManagerMetrics,
428    /// `AnnouncedTxTypes` metrics
429    announced_tx_types_metrics: AnnouncedTxTypesMetrics,
430}
431
432impl<Pool: TransactionPool, N: NetworkPrimitives> TransactionsManager<Pool, N> {
433    /// Sets up a new instance.
434    ///
435    /// Note: This expects an existing [`NetworkManager`](crate::NetworkManager) instance.
436    pub fn new(
437        network: NetworkHandle<N>,
438        pool: Pool,
439        from_network: MemoryBoundedReceiver<NetworkTransactionEvent<N>>,
440        transactions_manager_config: TransactionsManagerConfig,
441    ) -> Self {
442        Self::with_policy(
443            network,
444            pool,
445            from_network,
446            transactions_manager_config,
447            NetworkPolicies::new(
448                TransactionPropagationKind::default(),
449                StrictEthAnnouncementFilter::default(),
450            ),
451        )
452    }
453}
454
455impl<Pool: TransactionPool, N: NetworkPrimitives> TransactionsManager<Pool, N> {
456    /// Sets up a new instance with given the settings.
457    ///
458    /// Note: This expects an existing [`NetworkManager`](crate::NetworkManager) instance.
459    pub fn with_policy(
460        network: NetworkHandle<N>,
461        pool: Pool,
462        from_network: MemoryBoundedReceiver<NetworkTransactionEvent<N>>,
463        transactions_manager_config: TransactionsManagerConfig,
464        policies: NetworkPolicies<N>,
465    ) -> Self {
466        let network_events = network.event_listener();
467
468        let (command_tx, command_rx) = mpsc::unbounded_channel();
469
470        let transaction_fetcher =
471            TransactionFetcher::new(transactions_manager_config.transaction_fetcher_config.clone());
472
473        // install a listener for new __pending__ transactions that are allowed to be propagated
474        // over the network
475        let pending = pool.pending_transactions_listener();
476        let pending_pool_imports_info = PendingPoolImportsInfo::new(
477            transactions_manager_config.max_pending_pool_imports,
478            transactions_manager_config.max_pending_pool_imports_bytes,
479        );
480        let metrics = TransactionsManagerMetrics::default();
481        metrics
482            .capacity_pending_pool_imports
483            .increment(pending_pool_imports_info.max_pending_pool_imports as u64);
484        metrics
485            .capacity_pending_pool_imports_bytes
486            .increment(pending_pool_imports_info.max_pending_pool_imports_bytes as u64);
487
488        // Called by path: importing `NetworkInfo` would make `is_syncing` ambiguous with
489        // `SyncStateProvider`'s.
490        let blob_fetcher = BlobFetcher::new(
491            reth_network_api::NetworkInfo::cell_custody(&network).clone(),
492            transactions_manager_config.blob_fetch_probability,
493        );
494
495        Self {
496            pool,
497            sender_recovery_cache: None,
498            network,
499            network_events,
500            transaction_fetcher,
501            blob_fetcher,
502            transactions_by_peers: Default::default(),
503            announcement_hashes: B256Set::default(),
504            pool_imports: Default::default(),
505            pending_pool_imports_info,
506            bad_imports: LruCache::with_hasher(DEFAULT_MAX_COUNT_BAD_IMPORTS, Default::default()),
507            importing_blob_txs: Default::default(),
508            nonce_gapped_blob_txs: LruMap::new(MAX_NONCE_GAPPED_BLOB_TXS),
509            peers: Default::default(),
510            command_tx,
511            command_rx: UnboundedReceiverStream::new(command_rx),
512            pending_transactions: pending,
513            transaction_events: from_network,
514            config: transactions_manager_config,
515            policies,
516            metrics,
517            announced_tx_types_metrics: AnnouncedTxTypesMetrics::default(),
518        }
519    }
520
521    /// Returns a new handle that can send commands to this type.
522    pub fn handle(&self) -> TransactionsHandle<N> {
523        TransactionsHandle { manager_tx: self.command_tx.clone() }
524    }
525
526    /// Uses the provided sender recovery cache.
527    pub fn with_sender_recovery_cache(mut self, cache: SenderRecoveryCache) -> Self {
528        self.sender_recovery_cache = Some(cache);
529        self
530    }
531
532    /// Returns whether pending pool imports are below the soft limit.
533    ///
534    /// Fetch responses are admitted in full when capacity remains, so one response can exceed
535    /// the limit by at most 255 transactions (the 256-hash request cap minus one free slot), or
536    /// the byte limit by one response message. Further responses and requests wait until imports
537    /// fall below both limits again.
538    fn has_capacity_for_pending_pool_imports(&self) -> bool {
539        self.remaining_pool_import_capacity() > 0
540    }
541
542    /// Returns the remaining capacity below the soft limit for pending pool imports.
543    ///
544    /// Outstanding requests do not reserve capacity. A fetched response is admitted in full
545    /// if any capacity remains; while imports exceed the count or byte limit, this returns zero.
546    fn remaining_pool_import_capacity(&self) -> usize {
547        let info = &self.pending_pool_imports_info;
548        if info.pending_pool_imports_bytes.load(Ordering::Relaxed) >=
549            info.max_pending_pool_imports_bytes
550        {
551            return 0
552        }
553        info.max_pending_pool_imports
554            .saturating_sub(info.pending_pool_imports.load(Ordering::Relaxed))
555    }
556
557    /// Returns the transaction count and encoded byte size available to broadcasts, after
558    /// reserving space for fetched hashes.
559    fn remaining_broadcast_import_capacity(&self) -> (usize, usize) {
560        let capacity = self.remaining_pool_import_capacity();
561        let info = &self.pending_pool_imports_info;
562        let bytes = info
563            .max_pending_pool_imports_bytes
564            .saturating_sub(info.pending_pool_imports_bytes.load(Ordering::Relaxed));
565        if self.transaction_fetcher.num_hashes() == 0 {
566            return (capacity, bytes)
567        }
568        // Reserve one batch (or half a small import budget) for fetched transactions.
569        // Broadcasts are processed first and must not consume every newly freed slot.
570        let reserved = info
571            .max_pending_pool_imports
572            .div_ceil(2)
573            .min(SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST);
574        // Likewise reserve one response worth of bytes, so broadcasts can't fill the byte limit
575        // that pauses fetching.
576        let reserved_bytes = info
577            .max_pending_pool_imports_bytes
578            .div_ceil(2)
579            .min(SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE);
580        (capacity.saturating_sub(reserved), bytes.saturating_sub(reserved_bytes))
581    }
582
583    fn report_peer_bad_transactions(&self, peer_id: PeerId) {
584        self.report_peer(peer_id, ReputationChangeKind::BadTransactions);
585        self.metrics.reported_bad_transactions.increment(1);
586    }
587
588    fn report_peer(&self, peer_id: PeerId, kind: ReputationChangeKind) {
589        trace!(target: "net::tx", ?peer_id, ?kind, "reporting reputation change");
590        self.network.reputation_change(peer_id, kind);
591    }
592
593    fn report_already_seen(&self, peer_id: PeerId) {
594        trace!(target: "net::tx", ?peer_id, "Penalizing peer for already seen transaction");
595        self.network.reputation_change(peer_id, ReputationChangeKind::AlreadySeenTransaction);
596    }
597
598    /// Handles a closed peer session, removing the peer from transaction-local tracking state.
599    fn on_peer_session_closed(&mut self, peer_id: &PeerId) {
600        if let Some(mut peer) = self.peers.remove(peer_id) {
601            self.policies.propagation_policy_mut().on_session_closed(&mut peer);
602        }
603        self.transaction_fetcher.on_peer_disconnected(peer_id);
604        self.blob_fetcher.drop_peer(peer_id);
605    }
606
607    /// Clear the transaction
608    fn on_good_import(&mut self, hash: TxHash) {
609        self.transactions_by_peers.remove(&hash);
610        // An imported blob transaction no longer needs the cells eth/72 peers announced.
611        self.blob_fetcher.remove(&hash);
612    }
613
614    /// Handles a failed transaction import.
615    ///
616    /// Blob sidecar errors (e.g. invalid proof, missing sidecar) are penalized via
617    /// `report_peer_bad_transactions` but NOT cached in `bad_imports` — the transaction itself
618    /// may be valid when fetched from another peer with correct sidecar data.
619    ///
620    /// Other bad transactions are penalized and cached in `bad_imports` to avoid fetching or
621    /// importing them again.
622    ///
623    /// Errors that count as bad transactions are:
624    ///
625    /// - intrinsic gas too low
626    /// - exceeds gas limit
627    /// - gas uint overflow
628    /// - exceeds max init code size
629    /// - signer account has bytecode
630    /// - chain id mismatch
631    /// - old legacy chain id
632    /// - tx type not supported
633    ///
634    /// (and additionally for blobs txns...)
635    ///
636    /// - no blobs
637    /// - too many blobs
638    /// - invalid kzg proof
639    /// - kzg error
640    /// - not blob transaction (tx type mismatch)
641    /// - wrong versioned kzg commitment hash
642    fn on_bad_import(&mut self, err: PoolError) {
643        let peers = self.transactions_by_peers.remove(&err.hash);
644
645        if err.is_bad_blob_sidecar() {
646            // Only the first peer's copy was imported, so only it is penalized, and repeated
647            // offenders get banned. The hash isn't cached as bad, since another copy may be valid.
648            //
649            // Eth/72 peers cannot reach this path with an elided sidecar: their blob
650            // transactions wait in the blob fetcher until their cells pass a check, so any
651            // sidecar failure here means actual blob data failed validation.
652            if let Some(&peer_id) = peers.as_ref().and_then(|peers| peers.first()) {
653                self.report_peer_bad_transactions(peer_id);
654            }
655            return
656        }
657
658        // if we're _currently_ syncing, we ignore a bad transaction
659        if !err.is_bad_transaction() || self.network.is_syncing() {
660            return
661        }
662        // otherwise we penalize the peer that sent the bad transaction, with the assumption that
663        // the peer should have known that this transaction is bad (e.g. violating consensus rules)
664        if let Some(peers) = peers {
665            for peer_id in peers {
666                self.report_peer_bad_transactions(peer_id);
667            }
668        }
669        self.metrics.bad_imports.increment(1);
670        self.bad_imports.insert(err.hash);
671    }
672
673    fn on_request_error(&self, peer_id: PeerId, req_err: RequestError) {
674        let kind = match req_err {
675            RequestError::UnsupportedCapability => ReputationChangeKind::BadProtocol,
676            RequestError::Timeout => ReputationChangeKind::Timeout,
677            RequestError::ChannelClosed | RequestError::ConnectionDropped => {
678                // peer is already disconnected
679                return
680            }
681            RequestError::BadResponse => return self.report_peer_bad_transactions(peer_id),
682            RequestError::InvalidRequest => return,
683        };
684        self.report_peer(peer_id, kind);
685    }
686
687    #[inline]
688    fn update_poll_metrics(&self, start: Instant, poll_durations: TxManagerPollDurations) {
689        let metrics = &self.metrics;
690
691        let TxManagerPollDurations {
692            acc_network_events,
693            acc_pending_imports,
694            acc_tx_events,
695            acc_imported_txns,
696            acc_fetch_events,
697            acc_pending_fetch,
698            acc_cmds,
699        } = poll_durations;
700
701        // update metrics for whole poll function
702        metrics.duration_poll_tx_manager.set(start.elapsed().as_secs_f64());
703        // update metrics for nested expressions
704        metrics.acc_duration_poll_network_events.set(acc_network_events.as_secs_f64());
705        metrics.acc_duration_poll_pending_pool_imports.set(acc_pending_imports.as_secs_f64());
706        metrics.acc_duration_poll_transaction_events.set(acc_tx_events.as_secs_f64());
707        metrics.acc_duration_poll_imported_transactions.set(acc_imported_txns.as_secs_f64());
708        metrics.acc_duration_poll_fetch_events.set(acc_fetch_events.as_secs_f64());
709        metrics.acc_duration_fetch_pending_hashes.set(acc_pending_fetch.as_secs_f64());
710        metrics.acc_duration_poll_commands.set(acc_cmds.as_secs_f64());
711    }
712}
713
714impl<Pool: TransactionPool, N: NetworkPrimitives> TransactionsManager<Pool, N> {
715    /// Request handler for an incoming `NewPooledTransactionHashes`
716    fn on_new_pooled_transaction_hashes(
717        &mut self,
718        peer_id: PeerId,
719        msg: NewPooledTransactionHashes,
720    ) {
721        // If the node is initially syncing, ignore transactions
722        if self.network.is_initially_syncing() {
723            return
724        }
725        if self.network.tx_gossip_disabled() {
726            return
727        }
728
729        // get handle to peer's session, if the session is still active
730        let Some(peer) = self.peers.get_mut(&peer_id) else {
731            trace!(
732                peer_id = format!("{peer_id:#}"),
733                ?msg,
734                "discarding announcement from inactive peer"
735            );
736
737            return
738        };
739        // A session only decodes announcements of its own version, so another format was queued
740        // by an earlier session of the peer and must not be checked against this one.
741        if !msg.is_valid_for_version(peer.version) {
742            trace!(
743                peer_id = format!("{peer_id:#}"),
744                msg_version = ?msg.version(),
745                version = ?peer.version,
746                "discarding announcement from an earlier session"
747            );
748            return
749        }
750        let client = peer.client_version.clone();
751
752        if msg.is_empty() {
753            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
754            return
755        }
756
757        let Ok(mut announcement) =
758            TransactionAnnouncement::from_message(&msg, &mut self.announcement_hashes)
759        else {
760            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
761            return
762        };
763        let has_duplicates = announcement.len() != msg.len();
764
765        // keep track of the transactions the peer knows
766        let count_txns_already_seen_by_peer =
767            msg.iter_hashes().filter(|hash| !peer.seen_transactions.insert(**hash)).count();
768        drop(msg);
769        if count_txns_already_seen_by_peer > 0 {
770            // this may occur if transactions are sent or announced to a peer, at the same time as
771            // the peer sends/announces those hashes to us. this is because, marking
772            // txns as seen by a peer is done optimistically upon sending them to the
773            // peer.
774            self.metrics.messages_with_hashes_already_seen_by_peer.increment(1);
775            self.metrics
776                .occurrences_hash_already_seen_by_peer
777                .increment(count_txns_already_seen_by_peer as u64);
778
779            trace!(target: "net::tx",
780                %count_txns_already_seen_by_peer,
781                peer_id=format!("{peer_id:#}"),
782                ?client,
783                "Peer sent hashes that have already been marked as seen by peer"
784            );
785
786            self.report_already_seen(peer_id);
787        }
788
789        if has_duplicates {
790            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
791        }
792
793        // Exclude pending imports and known bad transactions before counting types and applying
794        // policy. These cheap checks shrink the batch before acquiring the pool lock.
795        let mut should_report_peer = false;
796        let mut tx_types_counter = TxTypesCounter::default();
797        let has_eth68_metadata = announcement.version().has_eth68_metadata();
798
799        announcement.retain(|tx| {
800            if self.transactions_by_peers.contains_key(&tx.hash) ||
801                self.bad_imports.contains(&tx.hash)
802            {
803                return false
804            }
805            let (ty_byte, size_val) = tx.metadata.map_or((0, 0), |metadata| {
806                match TxType::try_from(metadata.tx_type) {
807                    Ok(tx_type) => tx_types_counter.increase_by_tx_type(tx_type),
808                    Err(_) => tx_types_counter.increase_other(),
809                }
810                (metadata.tx_type, metadata.size)
811            });
812
813            let decision = self
814                .policies
815                .announcement_filter()
816                .decide_on_announcement(ty_byte, &tx.hash, size_val);
817
818            match decision {
819                AnnouncementAcceptance::Accept => true,
820                AnnouncementAcceptance::Ignore => false,
821                AnnouncementAcceptance::Reject { penalize_peer } => {
822                    if penalize_peer {
823                        should_report_peer = true;
824                    }
825                    false
826                }
827            }
828        });
829
830        if has_eth68_metadata {
831            self.announced_tx_types_metrics.update_eth68_announcement_metrics(tx_types_counter);
832        }
833
834        if should_report_peer {
835            self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
836        }
837
838        // Filter out hashes already in the pool.
839        //
840        // known txns have already been successfully fetched or received over gossip.
841        //
842        // most hashes will be filtered out here since the mempool protocol is a gossip
843        // protocol, healthy peers will send many of the same hashes.
844        //
845        let hashes_count_pre_pool_filter = announcement.len();
846        self.pool.retain_unknown(&mut announcement);
847        if hashes_count_pre_pool_filter > announcement.len() {
848            let already_known_hashes_count = hashes_count_pre_pool_filter - announcement.len();
849            self.metrics
850                .occurrences_hashes_already_in_pool
851                .increment(already_known_hashes_count as u64);
852        }
853
854        if announcement.is_empty() {
855            // nothing to request
856            return
857        }
858
859        // eth/72 peers announce the cells they keep of each blob transaction.
860        self.blob_fetcher.on_announcement(peer_id, &mut announcement);
861
862        trace!(target: "net::tx::propagation",
863            peer_id=format!("{peer_id:#}"),
864            hashes_len=announcement.len(),
865            msg_version=%announcement.version(),
866            client_version=%client,
867            "received unknown hashes in announcement from peer"
868        );
869
870        // Queue hashes for fetching; requests are sent when the manager is polled.
871        self.transaction_fetcher.on_announcement(peer_id, announcement);
872    }
873}
874
875impl<Pool, N> TransactionsManager<Pool, N>
876where
877    Pool: TransactionPool + Unpin + 'static,
878    N: NetworkPrimitives<
879        BroadcastedTransaction: SignedTransaction,
880        PooledTransaction: SignedTransaction,
881    >,
882    Pool::Transaction:
883        PoolTransaction<Consensus = N::BroadcastedTransaction, Pooled = N::PooledTransaction>,
884{
885    /// Invoked when transactions in the local mempool are considered __pending__.
886    ///
887    /// When a transaction in the local mempool is moved to the pending pool, we propagate them to
888    /// connected peers over network using the `Transactions` and `NewPooledTransactionHashes`
889    /// messages. The Transactions message relays complete transaction objects and is typically
890    /// sent to a small, random fraction of connected peers.
891    ///
892    /// All other peers receive a notification of the transaction hash and can request the
893    /// complete transaction object if it is unknown to them. The dissemination of complete
894    /// transactions to a fraction of peers usually ensures that all nodes receive the transaction
895    /// and won't need to request it.
896    fn on_new_pending_transactions(&mut self, hashes: Vec<TxHash>) {
897        // We intentionally do not gate this on initial sync.
898        // During initial sync we skip importing tx announcements from peers in
899        // `on_new_pooled_transaction_hashes`, so transactions reaching this path are local.
900        if self.network.tx_gossip_disabled() {
901            return
902        }
903
904        trace!(target: "net::tx", num_hashes=?hashes.len(), "Start propagating transactions");
905
906        self.propagate_all(hashes);
907    }
908
909    /// Propagate the full transactions to a specific peer.
910    ///
911    /// Returns the propagated transactions.
912    fn propagate_full_transactions_to_peer(
913        &mut self,
914        txs: Vec<TxHash>,
915        peer_id: PeerId,
916        propagation_mode: PropagationMode,
917    ) -> Option<PropagatedTransactions> {
918        let peer = self.peers.get_mut(&peer_id)?;
919        trace!(target: "net::tx", ?peer_id, "Propagating transactions to peer");
920        let mut propagated = PropagatedTransactions::default();
921
922        // filter all transactions unknown to the peer
923        let mut full_transactions = FullTransactionsBuilder::new(peer.version);
924
925        let to_propagate = self.pool.get_all(txs).into_iter().map(PropagateTransaction::pool_tx);
926
927        if propagation_mode.is_forced() {
928            // skip cache check if forced
929            full_transactions.extend(to_propagate);
930        } else {
931            // Iterate through the transactions to propagate and fill the hashes and full
932            // transaction
933            for tx in to_propagate {
934                if !peer.seen_transactions.contains(tx.tx_hash()) {
935                    // Only include if the peer hasn't seen the transaction
936                    full_transactions.push(&tx);
937                }
938            }
939        }
940
941        if full_transactions.is_empty() {
942            // nothing to propagate
943            return None
944        }
945
946        let PropagateTransactions { pooled, full } = full_transactions.build();
947
948        // send hashes if any
949        for new_pooled_hashes in pooled {
950            for hash in new_pooled_hashes.iter_hashes().copied() {
951                propagated.record(hash, PropagateKind::Hash(peer_id));
952                // mark transaction as seen by peer
953                peer.seen_transactions.insert(hash);
954            }
955
956            // send hashes of transactions
957            self.network.send_transactions_hashes(peer_id, new_pooled_hashes);
958        }
959
960        // send full transactions, if any
961        if let Some(new_full_transactions) = full {
962            for hash in new_full_transactions.iter_hashes() {
963                propagated.record(*hash, PropagateKind::Full(peer_id));
964                // mark transaction as seen by peer
965                peer.seen_transactions.insert(*hash);
966            }
967
968            // send full transactions
969            self.network.send_broadcast_pool_transactions(peer_id, new_full_transactions);
970        }
971
972        // Update propagated transactions metrics
973        self.metrics.propagated_transactions.increment(propagated.len() as u64);
974
975        Some(propagated)
976    }
977
978    /// Propagate the transaction hashes to the given peer
979    ///
980    /// Note: This will only send the hashes for transactions that exist in the pool.
981    fn propagate_hashes_to(
982        &mut self,
983        hashes: Vec<TxHash>,
984        peer_id: PeerId,
985        propagation_mode: PropagationMode,
986    ) {
987        trace!(target: "net::tx", "Start propagating transactions as hashes");
988
989        // This fetches a transactions from the pool, including the blob transactions, which are
990        // only ever sent as hashes.
991        let propagated = {
992            let Some(peer) = self.peers.get_mut(&peer_id) else {
993                // no such peer
994                return
995            };
996
997            let to_propagate =
998                self.pool.get_all(hashes).into_iter().map(PropagateTransaction::pool_tx);
999
1000            let mut propagated = PropagatedTransactions::default();
1001
1002            // check if transaction is known to peer
1003            let mut hashes = PooledTransactionsHashesBuilder::new(peer.version);
1004
1005            if propagation_mode.is_forced() {
1006                hashes.extend(to_propagate)
1007            } else {
1008                for tx in to_propagate {
1009                    if !peer.seen_transactions.contains(tx.tx_hash()) {
1010                        // Include if the peer hasn't seen it
1011                        hashes.push(&tx);
1012                    }
1013                }
1014            }
1015
1016            let messages = hashes.build();
1017
1018            if messages.is_empty() {
1019                // nothing to propagate
1020                return
1021            }
1022
1023            for new_pooled_hashes in messages {
1024                for hash in new_pooled_hashes.iter_hashes().copied() {
1025                    propagated.record(hash, PropagateKind::Hash(peer_id));
1026                    peer.seen_transactions.insert(hash);
1027                }
1028
1029                trace!(target: "net::tx::propagation", ?peer_id, ?new_pooled_hashes, "Propagating transactions to peer");
1030
1031                // send hashes of transactions
1032                self.network.send_transactions_hashes(peer_id, new_pooled_hashes);
1033            }
1034
1035            // Update propagated transactions metrics
1036            self.metrics.propagated_transactions.increment(propagated.len() as u64);
1037
1038            propagated
1039        };
1040
1041        // notify pool so events get fired
1042        self.pool.on_propagated(propagated);
1043    }
1044
1045    /// Propagate the transactions to all connected peers either as full objects or hashes.
1046    ///
1047    /// The message for new pooled hashes depends on the negotiated version of the stream.
1048    /// See [`NewPooledTransactionHashes`]
1049    ///
1050    /// 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>.
1051    fn propagate_transactions(
1052        &mut self,
1053        to_propagate: Vec<PropagateTransaction>,
1054        propagation_mode: PropagationMode,
1055    ) -> PropagatedTransactions {
1056        let mut propagated = PropagatedTransactions::default();
1057        if self.network.tx_gossip_disabled() {
1058            return propagated
1059        }
1060
1061        // send full transactions to a set of the connected peers based on the configured mode
1062        let max_num_full = self.config.propagation_mode.full_peer_count(self.peers.len());
1063
1064        // Note: Assuming ~random~ order due to random state of the peers map hasher
1065        let mut num_full_peers = 0;
1066        for (peer_id, peer) in &mut self.peers {
1067            if !self.policies.propagation_policy().can_propagate(peer) {
1068                // skip peers we should not propagate to
1069                continue
1070            }
1071
1072            // determine whether to send full tx objects or hashes.
1073            let mut builder = if num_full_peers < max_num_full {
1074                num_full_peers += 1;
1075                PropagateTransactionsBuilder::full(peer.version, to_propagate.len())
1076            } else {
1077                PropagateTransactionsBuilder::pooled(peer.version, to_propagate.len())
1078            };
1079
1080            // Transactions are optimistically marked as seen by the peer when included in the
1081            // message, see `PeerMetadata::seen_transactions`, so filter out those the peer's
1082            // version can't carry before marking them.
1083            let eligible = to_propagate.iter().filter(|tx| tx.can_announce_to(peer.version));
1084            if propagation_mode.is_forced() {
1085                for tx in eligible {
1086                    peer.seen_transactions.insert(*tx.tx_hash());
1087                    builder.push(tx);
1088                }
1089            } else {
1090                // Iterate through the transactions to propagate and fill the hashes and full
1091                // transaction lists, before deciding whether or not to send full transactions to
1092                // the peer.
1093                for tx in eligible {
1094                    // Only include the transaction if the peer hasn't seen it yet
1095                    if peer.seen_transactions.insert(*tx.tx_hash()) {
1096                        builder.push(tx);
1097                    }
1098                }
1099            }
1100
1101            if builder.is_empty() {
1102                trace!(target: "net::tx", ?peer_id, "Nothing to propagate to peer; has seen all transactions");
1103                continue
1104            }
1105
1106            let PropagateTransactions { pooled, full } = builder.build();
1107
1108            // send hashes if any
1109            for mut new_pooled_hashes in pooled {
1110                // Unhappy path: too many hashes for a single message. This should not happen
1111                // during regular propagation, which is capped at the soft limit per batch, and
1112                // is only reachable via manual propagation commands with oversized batches.
1113                if new_pooled_hashes.len() >
1114                    SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE
1115                {
1116                    // hashes that exceed the limit are not sent, so they must not be tracked as
1117                    // seen by the peer
1118                    for hash in new_pooled_hashes
1119                        .iter_hashes()
1120                        .skip(SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE)
1121                    {
1122                        peer.seen_transactions.remove(hash);
1123                    }
1124                    new_pooled_hashes.truncate(
1125                        SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE,
1126                    );
1127                }
1128
1129                for hash in new_pooled_hashes.iter_hashes().copied() {
1130                    propagated.record(hash, PropagateKind::Hash(*peer_id));
1131                }
1132
1133                trace!(target: "net::tx", ?peer_id, num_txs=?new_pooled_hashes.len(), "Propagating tx hashes to peer");
1134
1135                // send hashes of transactions
1136                self.network.send_transactions_hashes(*peer_id, new_pooled_hashes);
1137            }
1138
1139            // send full transactions, if any
1140            if let Some(new_full_transactions) = full {
1141                for hash in new_full_transactions.iter_hashes() {
1142                    propagated.record(*hash, PropagateKind::Full(*peer_id));
1143                }
1144
1145                trace!(target: "net::tx", ?peer_id, num_txs=?new_full_transactions.len(), "Propagating full transactions to peer");
1146
1147                // send full transactions
1148                self.network.send_broadcast_pool_transactions(*peer_id, new_full_transactions);
1149            }
1150        }
1151
1152        // Update propagated transactions metrics
1153        self.metrics.propagated_transactions.increment(propagated.len() as u64);
1154
1155        propagated
1156    }
1157
1158    /// Propagates the given transactions to the peers
1159    ///
1160    /// This fetches all transaction from the pool, including the 4844 blob transactions but
1161    /// __without__ their sidecar, because 4844 transactions are only ever announced as hashes.
1162    fn propagate_all(&mut self, hashes: Vec<TxHash>) {
1163        if self.peers.is_empty() {
1164            // nothing to propagate
1165            return
1166        }
1167        let propagated = self.propagate_transactions(
1168            self.pool.get_all(hashes).into_iter().map(PropagateTransaction::pool_tx).collect(),
1169            PropagationMode::Basic,
1170        );
1171
1172        // notify pool so events get fired
1173        self.pool.on_propagated(propagated);
1174    }
1175
1176    /// Request handler for an incoming request for transactions
1177    fn on_get_pooled_transactions(
1178        &mut self,
1179        peer_id: PeerId,
1180        mut request: GetPooledTransactions,
1181        response: oneshot::Sender<RequestResult<PooledTransactions<N::PooledTransaction>>>,
1182    ) {
1183        // fast exit if gossip is disabled
1184        if self.network.tx_gossip_disabled() {
1185            let _ = response.send(Ok(PooledTransactions::default()));
1186            return
1187        }
1188        if let Some(peer) = self.peers.get_mut(&peer_id) {
1189            // don't serve pending transactions to peers the policy doesn't propagate to
1190            if !self.policies.propagation_policy().can_propagate(peer) {
1191                let _ = response.send(Ok(PooledTransactions::default()));
1192                return
1193            }
1194
1195            let limit = GetPooledTransactionLimit::ResponseSizeSoftLimit(
1196                self.config
1197                    .transaction_fetcher_config
1198                    .soft_limit_byte_size_pooled_transactions_response,
1199            );
1200            // serve at most the soft limit of hashes, partial responses are allowed
1201            request.0.truncate(SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST);
1202            // eth/72 peers fetch blobs with `GetCells`.
1203            let transactions = if peer.version.is_eth72_or_newer() {
1204                self.pool.get_pooled_transaction_elements_without_blobs(request.0, limit)
1205            } else {
1206                self.pool.get_pooled_transaction_elements(request.0, limit)
1207            };
1208            trace!(target: "net::tx::propagation", sent_txs=?transactions.iter().map(|tx| tx.tx_hash()), "Sending requested transactions to peer");
1209
1210            // we sent a response at which point we assume that the peer is aware of the
1211            // transactions
1212            peer.seen_transactions.extend(transactions.iter().map(|tx| *tx.tx_hash()));
1213
1214            let resp = PooledTransactions(transactions);
1215            let _ = response.send(Ok(resp));
1216        }
1217    }
1218
1219    /// Handles a command received from a detached [`TransactionsHandle`]
1220    fn on_command(&mut self, cmd: TransactionsCommand<N>) {
1221        match cmd {
1222            TransactionsCommand::PropagateHash(hash) => {
1223                self.on_new_pending_transactions(vec![hash])
1224            }
1225            TransactionsCommand::PropagateHashesTo(hashes, peer) => {
1226                self.propagate_hashes_to(hashes, peer, PropagationMode::Forced)
1227            }
1228            TransactionsCommand::GetActivePeers(tx) => {
1229                let peers = self.peers.keys().copied().collect::<HashSet<_>>();
1230                tx.send(peers).ok();
1231            }
1232            TransactionsCommand::PropagateTransactionsTo(txs, peer) => {
1233                if let Some(propagated) =
1234                    self.propagate_full_transactions_to_peer(txs, peer, PropagationMode::Forced)
1235                {
1236                    self.pool.on_propagated(propagated);
1237                }
1238            }
1239            TransactionsCommand::PropagateTransactions(txs) => self.propagate_all(txs),
1240            TransactionsCommand::BroadcastTransactions(mut txs) => {
1241                // Use the pooled sizes and only announce blobs the pool allows peers to fetch.
1242                let blob_txs = txs
1243                    .extract_if(.., |tx| tx.tx_type() == EIP4844_TX_TYPE_ID)
1244                    .map(|tx| *tx.tx_hash())
1245                    .collect();
1246                txs.extend(
1247                    self.pool
1248                        .get_all(blob_txs)
1249                        .into_iter()
1250                        .filter(|tx| tx.propagate)
1251                        .map(PropagateTransaction::pool_tx),
1252                );
1253                let propagated = self.propagate_transactions(txs, PropagationMode::Forced);
1254                self.pool.on_propagated(propagated);
1255            }
1256            TransactionsCommand::GetTransactionHashes { peers, tx } => {
1257                let mut res = HashMap::with_capacity_and_hasher(peers.len(), Default::default());
1258                for peer_id in peers {
1259                    let hashes = self
1260                        .peers
1261                        .get(&peer_id)
1262                        .map(|peer| peer.seen_transactions.iter().copied().collect::<B256Set>())
1263                        .unwrap_or_default();
1264                    res.insert(peer_id, hashes);
1265                }
1266                tx.send(res).ok();
1267            }
1268            TransactionsCommand::GetPeerSender { peer_id, peer_request_sender } => {
1269                let sender = self.peers.get(&peer_id).map(|peer| peer.request_tx.clone());
1270                peer_request_sender.send(sender).ok();
1271            }
1272        }
1273    }
1274
1275    /// Handles session establishment and peer transactions initialization.
1276    ///
1277    /// This is invoked when a new session is established.
1278    fn handle_peer_session(
1279        &mut self,
1280        info: SessionInfo,
1281        messages: PeerRequestSender<PeerRequest<N>>,
1282    ) {
1283        let SessionInfo { peer_id, client_version, version, .. } = info;
1284
1285        // Insert a new peer into the peerset.
1286        let peer = PeerMetadata::<N>::new(
1287            messages,
1288            version,
1289            client_version,
1290            self.config.max_transactions_seen_by_peer_history,
1291            info.peer_kind,
1292        );
1293        let peer = match self.peers.entry(peer_id) {
1294            Entry::Occupied(mut entry) => {
1295                entry.insert(peer);
1296                entry.into_mut()
1297            }
1298            Entry::Vacant(entry) => entry.insert(peer),
1299        };
1300
1301        self.policies.propagation_policy_mut().on_session_established(peer);
1302
1303        // Send a `NewPooledTransactionHashes` to the peer with up to
1304        // `SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE`
1305        // transactions in the pool.
1306        if self.network.is_initially_syncing() || self.network.tx_gossip_disabled() {
1307            trace!(target: "net::tx", ?peer_id, "Skipping transaction broadcast: node syncing or gossip disabled");
1308            return
1309        }
1310
1311        // skip peers we should not propagate to
1312        if !self.policies.propagation_policy().can_propagate(peer) {
1313            return
1314        }
1315
1316        // Get transactions to broadcast
1317        let pooled_txs = self.pool.pooled_transactions_max(
1318            SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE,
1319        );
1320        if pooled_txs.is_empty() {
1321            trace!(target: "net::tx", ?peer_id, "No transactions in the pool to broadcast");
1322            return;
1323        }
1324
1325        // Build and send transaction hashes message
1326        let mut msg_builder = PooledTransactionsHashesBuilder::new(version);
1327        for pooled_tx in pooled_txs {
1328            msg_builder.push_pooled(pooled_tx);
1329        }
1330
1331        for msg in msg_builder.build() {
1332            peer.seen_transactions.extend(msg.iter_hashes().copied());
1333            debug!(target: "net::tx", ?peer_id, tx_count = msg.len(), "Broadcasting transaction hashes");
1334            self.network.send_transactions_hashes(peer_id, msg);
1335        }
1336    }
1337
1338    /// Handles a received event related to common network events.
1339    fn on_network_event(&mut self, event_result: NetworkEvent<PeerRequest<N>>) {
1340        match event_result {
1341            NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, .. }) => {
1342                self.on_peer_session_closed(&peer_id);
1343            }
1344            NetworkEvent::ActivePeerSession { info, messages } => {
1345                // process active peer session and broadcast available transaction from the pool
1346                self.handle_peer_session(info, messages);
1347            }
1348            NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {
1349                let peer_id = info.peer_id;
1350                // get messages from existing peer
1351                let messages = match self.peers.get(&peer_id) {
1352                    Some(p) => p.request_tx.clone(),
1353                    None => {
1354                        debug!(target: "net::tx", ?peer_id, "No peer request sender found");
1355                        return;
1356                    }
1357                };
1358                self.handle_peer_session(info, messages);
1359            }
1360            _ => {}
1361        }
1362    }
1363
1364    /// Returns true if the ingress policy allows processing messages from the given peer.
1365    fn accepts_incoming_from(&self, peer_id: &PeerId) -> bool {
1366        if self.config.ingress_policy.allows_all() {
1367            return true;
1368        }
1369        let Some(peer) = self.peers.get(peer_id) else {
1370            return false;
1371        };
1372        self.config.ingress_policy.allows(peer.peer_kind())
1373    }
1374
1375    /// Handles dedicated transaction events related to the `eth` protocol.
1376    fn on_network_tx_event(&mut self, event: NetworkTransactionEvent<N>) {
1377        match event {
1378            NetworkTransactionEvent::IncomingTransactions { peer_id, msg } => {
1379                if !self.accepts_incoming_from(&peer_id) {
1380                    trace!(target: "net::tx", peer_id=format!("{peer_id:#}"), policy=?self.config.ingress_policy, "Ignoring full transactions from peer blocked by ingress policy");
1381                    return;
1382                }
1383
1384                // ensure we didn't receive any blob transactions as these are disallowed to be
1385                // broadcasted in full
1386
1387                let has_blob_txs = msg.has_eip4844();
1388
1389                let non_blob_txs = msg
1390                    .into_iter()
1391                    .map(N::PooledTransaction::try_from)
1392                    .filter_map(Result::ok)
1393                    .collect();
1394
1395                self.import_transactions(peer_id, non_blob_txs, TransactionSource::Broadcast);
1396
1397                if has_blob_txs {
1398                    debug!(target: "net::tx", ?peer_id, "received bad full blob transaction broadcast");
1399                    self.report_peer_bad_transactions(peer_id);
1400                }
1401            }
1402            NetworkTransactionEvent::IncomingPooledTransactionHashes { peer_id, msg } => {
1403                if !self.accepts_incoming_from(&peer_id) {
1404                    trace!(target: "net::tx", peer_id=format!("{peer_id:#}"), policy=?self.config.ingress_policy, "Ignoring transaction hashes from peer blocked by ingress policy");
1405                    return;
1406                }
1407                self.on_new_pooled_transaction_hashes(peer_id, msg)
1408            }
1409            NetworkTransactionEvent::GetPooledTransactions { peer_id, request, response } => {
1410                self.on_get_pooled_transactions(peer_id, request, response)
1411            }
1412            NetworkTransactionEvent::GetTransactionsHandle(response) => {
1413                let _ = response.send(Some(self.handle()));
1414            }
1415        }
1416    }
1417
1418    /// Starts the import process for the given transactions.
1419    ///
1420    /// Callers must check import capacity before consuming a fetch response. Responses are
1421    /// admitted in full and may overshoot the soft limit by one bounded response; broadcasts
1422    /// are truncated to their available capacity.
1423    fn import_transactions(
1424        &mut self,
1425        peer_id: PeerId,
1426        transactions: PooledTransactions<N::PooledTransaction>,
1427        source: TransactionSource,
1428    ) {
1429        // If the node is pipeline syncing, ignore transactions
1430        if self.network.is_initially_syncing() {
1431            return
1432        }
1433        if self.network.tx_gossip_disabled() {
1434            return
1435        }
1436
1437        let (version, client_version) = match &source {
1438            TransactionSource::Broadcast => {
1439                let Some(peer) = self.peers.get(&peer_id) else { return };
1440                (peer.version(), peer.client_version.clone())
1441            }
1442            TransactionSource::Response { version, client_version } => {
1443                (*version, client_version.clone())
1444            }
1445        };
1446        let is_broadcast = source.is_broadcast();
1447        let mut transactions = transactions.0;
1448
1449        // Fetched batches may exceed the soft limit: their request size is bounded, and the
1450        // caller stops consuming responses until capacity becomes available again.
1451        if is_broadcast {
1452            let (capacity, byte_capacity) = self.remaining_broadcast_import_capacity();
1453            let mut bytes = 0usize;
1454            let admitted = transactions
1455                .iter()
1456                .take(capacity)
1457                .take_while(|tx| {
1458                    bytes = bytes.saturating_add(tx.encode_2718_len());
1459                    bytes <= byte_capacity
1460                })
1461                .count();
1462            if transactions.len() > admitted {
1463                self.metrics
1464                    .skipped_transactions_pending_pool_imports_at_capacity
1465                    .increment((transactions.len() - admitted) as u64);
1466                transactions.truncate(admitted);
1467            }
1468        }
1469
1470        if transactions.is_empty() {
1471            return
1472        }
1473
1474        let start = Instant::now();
1475
1476        // Stop fetching transactions received through either broadcasts or responses.
1477        self.transaction_fetcher
1478            .on_transactions_received(transactions.iter().map(|tx| tx.tx_hash()));
1479
1480        // track that the peer knows these transaction, but only if this is a new broadcast.
1481        // If we received the transactions as the response to our `GetPooledTransactions``
1482        // requests (based on received `NewPooledTransactionHashes`) then we already
1483        // recorded the hashes as seen by this peer in `Self::on_new_pooled_transaction_hashes`.
1484        let mut num_already_seen_by_peer = 0;
1485        if is_broadcast && let Some(peer) = self.peers.get_mut(&peer_id) {
1486            for tx in &transactions {
1487                if !peer.seen_transactions.insert(*tx.tx_hash()) {
1488                    num_already_seen_by_peer += 1;
1489                }
1490            }
1491        }
1492
1493        // tracks the quality of the given transactions
1494        let mut has_bad_transactions = false;
1495
1496        // 1. Remove known, already-tracked, and invalid transactions first since these are
1497        // cheap in-memory checks against local maps
1498        transactions.retain(|tx| {
1499            if let Entry::Occupied(mut entry) = self.transactions_by_peers.entry(*tx.tx_hash()) {
1500                let peers = entry.get_mut();
1501                if !peers.contains(&peer_id) {
1502                    peers.push(peer_id);
1503                }
1504                return false
1505            }
1506            if self.bad_imports.contains(tx.tx_hash()) {
1507                trace!(target: "net::tx",
1508                    peer_id=format!("{peer_id:#}"),
1509                    hash=%tx.tx_hash(),
1510                    %client_version,
1511                    "received a known bad transaction from peer"
1512                );
1513                has_bad_transactions = true;
1514                return false;
1515            }
1516            true
1517        });
1518
1519        // 2. filter out txns already inserted into pool
1520        let txns_count_pre_pool_filter = transactions.len();
1521        self.pool.retain_unknown(&mut transactions);
1522        if txns_count_pre_pool_filter > transactions.len() {
1523            let already_known_txns_count = txns_count_pre_pool_filter - transactions.len();
1524            self.metrics
1525                .occurrences_transactions_already_in_pool
1526                .increment(already_known_txns_count as u64);
1527        }
1528
1529        let txs_len = transactions.len();
1530
1531        let recover = |tx| {
1532            let recovered = Pool::Transaction::try_recover_with_cache_opt(
1533                tx,
1534                self.sender_recovery_cache.as_ref(),
1535            );
1536            match recovered {
1537                Ok(tx) => Some(tx),
1538                Err(badtx) => {
1539                    trace!(target: "net::tx",
1540                        peer_id=format!("{peer_id:#}"),
1541                        hash=%badtx.tx_hash(),
1542                        client_version=%client_version,
1543                        "failed ecrecovery for transaction"
1544                    );
1545                    None
1546                }
1547            }
1548        };
1549
1550        let mut new_txs = transactions.into_par_iter().filter_map(recover).collect::<Vec<_>>();
1551
1552        has_bad_transactions |= new_txs.len() != txs_len;
1553
1554        // eth/72 peers send blob transactions without their blobs, per EIP-8070. Their bodies
1555        // wait in the blob fetcher for their cells, which then hands them back for the import.
1556        if version.is_eth72_or_newer() {
1557            for tx in new_txs.extract_if(.., |tx| tx.is_eip4844()) {
1558                has_bad_transactions |= !self.blob_fetcher.body(peer_id, tx);
1559            }
1560        }
1561
1562        // Record the transactions as seen by the peer
1563        for tx in &new_txs {
1564            self.transactions_by_peers.insert(*tx.hash(), smallvec::smallvec![peer_id]);
1565        }
1566
1567        // 3. import new transactions as a batch to minimize lock contention on the underlying
1568        // pool
1569        self.import_recovered_transactions(new_txs);
1570
1571        if num_already_seen_by_peer > 0 {
1572            self.metrics.messages_with_transactions_already_seen_by_peer.increment(1);
1573            self.metrics
1574                .occurrences_of_transaction_already_seen_by_peer
1575                .increment(num_already_seen_by_peer);
1576            trace!(target: "net::tx", num_txs=%num_already_seen_by_peer, ?peer_id, client=%client_version, "Peer sent already seen transactions");
1577        }
1578
1579        if has_bad_transactions {
1580            // peer sent us invalid transactions
1581            self.report_peer_bad_transactions(peer_id)
1582        }
1583
1584        if num_already_seen_by_peer > 0 {
1585            self.report_already_seen(peer_id);
1586        }
1587
1588        self.metrics.pool_import_prepare_duration.record(start.elapsed());
1589    }
1590
1591    /// Queues recovered transactions for a batched pool import, counted against the import
1592    /// limits.
1593    fn import_recovered_transactions(&self, new_txs: Vec<Pool::Transaction>) {
1594        if !new_txs.is_empty() {
1595            let pool = self.pool.clone();
1596            // update metrics
1597            let metric_pending_pool_imports = self.metrics.pending_pool_imports.clone();
1598            metric_pending_pool_imports.increment(new_txs.len() as f64);
1599            // includes blob sidecars, which stay in memory until the import completes
1600            let bytes = new_txs.iter().map(PoolTransaction::encoded_length).sum::<usize>();
1601            let metric_pending_pool_imports_bytes = self.metrics.pending_pool_imports_bytes.clone();
1602            metric_pending_pool_imports_bytes.increment(bytes as f64);
1603
1604            // update self-monitoring info
1605            self.pending_pool_imports_info
1606                .pending_pool_imports
1607                .fetch_add(new_txs.len(), Ordering::Relaxed);
1608            let tx_manager_info_pending_pool_imports =
1609                self.pending_pool_imports_info.pending_pool_imports.clone();
1610            self.pending_pool_imports_info
1611                .pending_pool_imports_bytes
1612                .fetch_add(bytes, Ordering::Relaxed);
1613            let tx_manager_info_pending_pool_imports_bytes =
1614                self.pending_pool_imports_info.pending_pool_imports_bytes.clone();
1615
1616            trace!(target: "net::tx::propagation", new_txs_len=?new_txs.len(), "Importing new transactions");
1617            let import = Box::pin(async move {
1618                let added = new_txs.len();
1619                let res = pool.add_external_transactions(new_txs).await;
1620
1621                // update metrics
1622                metric_pending_pool_imports.decrement(added as f64);
1623                metric_pending_pool_imports_bytes.decrement(bytes as f64);
1624                // update self-monitoring info
1625                tx_manager_info_pending_pool_imports.fetch_sub(added, Ordering::Relaxed);
1626                tx_manager_info_pending_pool_imports_bytes.fetch_sub(bytes, Ordering::Relaxed);
1627
1628                res
1629            });
1630
1631            self.pool_imports.push(import);
1632        }
1633    }
1634
1635    /// Processes a batch import results.
1636    fn on_batch_import_result(&mut self, batch_results: Vec<PoolResult<AddedTransactionOutcome>>) {
1637        for res in batch_results {
1638            match res {
1639                Ok(AddedTransactionOutcome { hash, .. }) => {
1640                    let imported = self.importing_blob_txs.remove(&hash);
1641                    self.on_good_import(hash);
1642                    self.import_next_nonce_gapped(hash, imported);
1643                }
1644                Err(err) => {
1645                    let importing = self.importing_blob_txs.remove(&err.hash);
1646                    // A nonce too low has no previous nonce to wait for.
1647                    let nonce_gap = matches!(
1648                        &err.kind,
1649                        PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip4844(
1650                            Eip4844PoolTransactionError::Eip4844NonceGap
1651                        ))
1652                    );
1653                    self.on_bad_import(err);
1654                    if nonce_gap && let Some((peer_id, tx)) = importing {
1655                        self.on_blob_nonce_gap(peer_id, tx);
1656                    }
1657                }
1658            }
1659        }
1660    }
1661
1662    /// Keeps a verified blob transaction the pool turned away for a nonce gap until the previous
1663    /// nonce of its sender is imported, or imports it again if that nonce arrived since.
1664    fn on_blob_nonce_gap(&mut self, peer_id: PeerId, tx: Box<Pool::Transaction>) {
1665        let (sender, nonce) = (tx.sender(), tx.nonce());
1666        if nonce > 0 && self.pool.get_transaction_by_sender_and_nonce(sender, nonce - 1).is_some() {
1667            self.import_verified_blob_transactions(vec![(peer_id, *tx)]);
1668        } else {
1669            self.nonce_gapped_blob_txs.insert((sender, nonce), (peer_id, tx));
1670        }
1671    }
1672
1673    /// Imports the blob transaction waiting for the nonce after the imported transaction `hash`,
1674    /// if any. `imported` is the transaction if it came from the blob fetcher.
1675    fn import_next_nonce_gapped(
1676        &mut self,
1677        hash: TxHash,
1678        imported: Option<VerifiedBlobTx<Pool::Transaction>>,
1679    ) {
1680        if self.nonce_gapped_blob_txs.is_empty() {
1681            return
1682        }
1683        let Some((sender, nonce)) = imported
1684            .map(|(_, tx)| (tx.sender(), tx.nonce()))
1685            .or_else(|| self.pool.get(&hash).map(|tx| (tx.sender(), tx.nonce())))
1686        else {
1687            return
1688        };
1689        if let Some((peer_id, tx)) = self.nonce_gapped_blob_txs.remove(&(sender, nonce + 1)) {
1690            self.import_verified_blob_transactions(vec![(peer_id, *tx)]);
1691        }
1692    }
1693
1694    /// Queues the blob transactions whose cells passed their check, each with the peer that sent
1695    /// its body, skipping those with an import already in flight.
1696    fn import_verified_blob_transactions(&mut self, verified: Vec<(PeerId, Pool::Transaction)>) {
1697        let mut txs = Vec::with_capacity(verified.len());
1698        for (peer_id, tx) in verified {
1699            // An import of the same transaction already in flight decides it, as in
1700            // `import_transactions`, so each import keeps its own peer.
1701            if let Entry::Vacant(entry) = self.transactions_by_peers.entry(*tx.hash()) {
1702                entry.insert(smallvec::smallvec![peer_id]);
1703                // Only a transaction whose previous nonce isn't pooled yet can hit a nonce gap.
1704                let (sender, nonce) = (tx.sender(), tx.nonce());
1705                if nonce > 0 &&
1706                    self.pool.get_transaction_by_sender_and_nonce(sender, nonce - 1).is_none()
1707                {
1708                    self.importing_blob_txs.insert(*tx.hash(), (peer_id, Box::new(tx.clone())));
1709                }
1710                txs.push(tx);
1711            }
1712        }
1713        // A sender's transactions checked together reach the pool in nonce order.
1714        txs.sort_unstable_by_key(|tx| (tx.sender(), tx.nonce()));
1715        self.import_recovered_transactions(txs);
1716    }
1717
1718    /// Processes a [`FetchEvent`].
1719    fn on_fetch_event(&mut self, fetch_event: FetchEvent<N::PooledTransaction>) {
1720        match fetch_event {
1721            FetchEvent::TransactionsFetched {
1722                peer_id,
1723                transactions,
1724                report_peer,
1725                version,
1726                client_version,
1727            } => {
1728                self.import_transactions(
1729                    peer_id,
1730                    transactions,
1731                    TransactionSource::Response { version, client_version },
1732                );
1733                if report_peer {
1734                    self.report_peer(peer_id, ReputationChangeKind::BadTransactions);
1735                }
1736            }
1737            FetchEvent::FetchError { peer_id, error } => {
1738                trace!(target: "net::tx", ?peer_id, %error, "requesting transactions from peer failed");
1739                self.on_request_error(peer_id, error);
1740            }
1741            FetchEvent::EmptyResponse { peer_id } => {
1742                trace!(target: "net::tx", ?peer_id, "peer returned empty response");
1743            }
1744            FetchEvent::AnnouncementMismatch { peer_id } => {
1745                let Some(peer) = self.peers.get(&peer_id) else { return };
1746                let requests = peer.request_tx().clone();
1747                // Remove the session from transaction tracking before the transport disconnects.
1748                self.on_peer_session_closed(&peer_id);
1749                self.report_peer(peer_id, ReputationChangeKind::BadAnnouncement);
1750                self.network.send_message(NetworkHandleMessage::DisconnectSession(
1751                    requests,
1752                    DisconnectReason::ProtocolBreach,
1753                ));
1754            }
1755        }
1756    }
1757}
1758
1759/// An endless future. Preemption ensure that future is non-blocking, nonetheless. See
1760/// [`crate::NetworkManager`] for more context on the design pattern.
1761///
1762/// This should be spawned or used as part of `tokio::select!`.
1763//
1764// spawned in `NodeConfig::start_network`(reth_node_core::NodeConfig) and
1765// `NetworkConfig::start_network`(reth_network::NetworkConfig)
1766impl<
1767        Pool: TransactionPool + Unpin + 'static,
1768        N: NetworkPrimitives<
1769            BroadcastedTransaction: SignedTransaction,
1770            PooledTransaction: SignedTransaction,
1771        >,
1772    > Future for TransactionsManager<Pool, N>
1773where
1774    Pool::Transaction:
1775        PoolTransaction<Consensus = N::BroadcastedTransaction, Pooled = N::PooledTransaction>,
1776{
1777    type Output = ();
1778
1779    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1780        let start = Instant::now();
1781        let mut poll_durations = TxManagerPollDurations::default();
1782
1783        let this = self.get_mut();
1784
1785        // All streams are polled until their corresponding budget is exhausted, then we manually
1786        // yield back control to tokio. See `NetworkManager` for more context on the design
1787        // pattern.
1788
1789        // Advance network/peer related events (update peers map).
1790        let maybe_more_network_events = metered_poll_nested_stream_with_budget!(
1791            poll_durations.acc_network_events,
1792            "net::tx",
1793            "Network events stream",
1794            DEFAULT_BUDGET_TRY_DRAIN_STREAM,
1795            this.network_events.poll_next_unpin(cx),
1796            |event| this.on_network_event(event)
1797        );
1798
1799        // Advance incoming transaction events (stream new txns/announcements from
1800        // network manager and queue for import to pool/fetch txns).
1801        //
1802        // Announcements are queued in the transaction fetcher, requests for them are sent
1803        // further below.
1804        //
1805        // Decoded broadcasts may exceed the available import capacity. Admission truncates
1806        // them before filtering and sender recovery, reserving capacity for fetched transactions.
1807        let maybe_more_tx_events = metered_poll_nested_stream_with_budget!(
1808            poll_durations.acc_tx_events,
1809            "net::tx",
1810            "Network transaction events stream",
1811            DEFAULT_BUDGET_TRY_DRAIN_NETWORK_TRANSACTION_EVENTS,
1812            this.transaction_events.poll_next_unpin(cx),
1813            |event: NetworkTransactionEvent<N>| this.on_network_tx_event(event),
1814        );
1815
1816        // Advance inflight fetch requests (flush transaction fetcher and queue for
1817        // import to pool).
1818        //
1819        // Pace response consumption with the soft import limit. Dispatch checks capacity but
1820        // does not reserve it for outstanding requests, so concurrent responses can exceed it.
1821        // Admit one complete response while capacity remains (at most 256 transactions), then
1822        // pause here if it fills or overshoots the limit. Existing requests continue in flight;
1823        // completed responses wait in their channels until pool imports free capacity.
1824        let mut maybe_more_tx_fetch_events = metered_poll_nested_stream_with_budget!(
1825            poll_durations.acc_fetch_events,
1826            "net::tx",
1827            "Transaction fetch events stream",
1828            DEFAULT_BUDGET_TRY_DRAIN_STREAM,
1829            if this.has_capacity_for_pending_pool_imports() {
1830                this.transaction_fetcher.poll_next_unpin(cx)
1831            } else {
1832                Poll::Pending
1833            },
1834            |event| this.on_fetch_event(event),
1835        );
1836
1837        // Import blob transactions whose cells passed their check.
1838        if this.has_capacity_for_pending_pool_imports() &&
1839            let Poll::Ready(verified) = this.blob_fetcher.poll(cx, &this.peers)
1840        {
1841            this.import_verified_blob_transactions(verified);
1842        }
1843        // Bodies that had no room in the cell fetcher are fetched again once they have.
1844        for (peer_id, tx) in this.blob_fetcher.poll_refetches(cx) {
1845            this.transaction_fetcher.on_announcement(peer_id, [tx]);
1846        }
1847
1848        // Remember whether response polling stopped at capacity so imports completing below
1849        // can trigger another poll even if the waiting response has not registered a waker yet.
1850        let fetcher_paused_at_capacity = !this.has_capacity_for_pending_pool_imports();
1851
1852        // Advance admitted batches and free capacity for more responses.
1853        let maybe_more_pool_imports = metered_poll_nested_stream_with_budget!(
1854            poll_durations.acc_pending_imports,
1855            "net::tx",
1856            "Batched pool imports stream",
1857            DEFAULT_BUDGET_TRY_DRAIN_PENDING_POOL_IMPORTS,
1858            this.pool_imports.poll_next_unpin(cx),
1859            |batch_results| this.on_batch_import_result(batch_results)
1860        );
1861
1862        // Advances new __pending__ transactions, transactions that were successfully inserted into
1863        // pending set in pool (are valid), and propagates them (inform peers which
1864        // transactions we have seen).
1865        //
1866        // This is polled after pool imports so transactions that became pending in this poll
1867        // iteration are propagated immediately, instead of waiting for the task to be woken
1868        // again.
1869        //
1870        // We try to drain this to batch the transactions in a single message.
1871        //
1872        // We don't expect this buffer to be large, since only pending transactions are
1873        // emitted here.
1874        let mut new_txs = Vec::new();
1875        let mut maybe_more_pending_txns = match this.pending_transactions.poll_recv_many(
1876            cx,
1877            &mut new_txs,
1878            SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE,
1879        ) {
1880            Poll::Ready(count) => {
1881                if count == SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE {
1882                    // we filled the entire buffer capacity and need to try again on the next poll
1883                    // immediately
1884                    true
1885                } else {
1886                    // try once more, because mostlikely the channel is now empty and the waker is
1887                    // registered if this is pending, if we filled additional hashes, we poll again
1888                    // on the next iteration
1889                    let limit =
1890                        SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE -
1891                            new_txs.len();
1892                    this.pending_transactions.poll_recv_many(cx, &mut new_txs, limit).is_ready()
1893                }
1894            }
1895            Poll::Pending => false,
1896        };
1897        if !new_txs.is_empty() {
1898            // A previous nonce added outside this manager, e.g. over RPC, lets a blob transaction
1899            // waiting for it through too. Its import needs another poll to register its waker.
1900            let imports = this.pool_imports.len();
1901            for hash in &new_txs {
1902                this.import_next_nonce_gapped(*hash, None);
1903            }
1904            maybe_more_pending_txns |= this.pool_imports.len() > imports;
1905            this.on_new_pending_transactions(new_txs);
1906        }
1907
1908        // Dispatch only below the soft import limit. Each request is capped independently;
1909        // outstanding requests do not reserve capacity against other peers.
1910        duration_metered_exec!(
1911            {
1912                // Peers whose session channel was full are retried on the next poll, which any
1913                // other event triggers.
1914                let budget = this.remaining_pool_import_capacity();
1915                if budget > 0 && this.transaction_fetcher.dispatch(&this.peers, budget) > 0 {
1916                    // poll the fetcher again so the new inflight requests register their wakers
1917                    maybe_more_tx_fetch_events = true;
1918                }
1919            },
1920            poll_durations.acc_pending_fetch
1921        );
1922
1923        // Advance commands (propagate/fetch/serve txns).
1924        let maybe_more_commands = metered_poll_nested_stream_with_budget!(
1925            poll_durations.acc_cmds,
1926            "net::tx",
1927            "Commands channel",
1928            DEFAULT_BUDGET_TRY_DRAIN_STREAM,
1929            this.command_rx.poll_next_unpin(cx),
1930            |cmd| this.on_command(cmd)
1931        );
1932
1933        this.transaction_fetcher.update_metrics();
1934
1935        // Revisit the fetcher if imports freed capacity after response polling was paused.
1936        let resume_fetcher =
1937            fetcher_paused_at_capacity && this.has_capacity_for_pending_pool_imports();
1938
1939        // all channels are fully drained and import futures pending
1940        if maybe_more_network_events ||
1941            maybe_more_commands ||
1942            maybe_more_tx_events ||
1943            maybe_more_tx_fetch_events ||
1944            maybe_more_pool_imports ||
1945            maybe_more_pending_txns ||
1946            resume_fetcher
1947        {
1948            // make sure we're woken up again
1949            cx.waker().wake_by_ref();
1950            return Poll::Pending
1951        }
1952
1953        this.update_poll_metrics(start, poll_durations);
1954
1955        Poll::Pending
1956    }
1957}
1958
1959/// Represents the different modes of transaction propagation.
1960///
1961/// This enum is used to determine how transactions are propagated to peers in the network.
1962#[derive(Debug, Copy, Clone, Eq, PartialEq)]
1963enum PropagationMode {
1964    /// Default propagation mode.
1965    ///
1966    /// Transactions are only sent to peers that haven't seen them yet.
1967    Basic,
1968    /// Forced propagation mode.
1969    ///
1970    /// Transactions are sent to all peers regardless of whether they have been sent or received
1971    /// before.
1972    Forced,
1973}
1974
1975impl PropagationMode {
1976    /// Returns `true` if the propagation kind is `Forced`.
1977    const fn is_forced(self) -> bool {
1978        matches!(self, Self::Forced)
1979    }
1980}
1981
1982/// A transaction that's about to be propagated to multiple peers.
1983#[derive(Debug, Clone)]
1984struct PropagateTransaction {
1985    is_broadcastable_in_full: bool,
1986    /// Size advertised in eth/68 to eth/71 `NewPooledTransactionHashes` metadata and used for full
1987    /// broadcast soft-limit accounting.
1988    ///
1989    /// This is the network encoded transaction size. For pool-backed blob transactions, this is
1990    /// the pool's cached encoded length, which includes the sidecar returned by
1991    /// `PooledTransactions`.
1992    propagation_size: usize,
1993    /// Size advertised to eth/72 peers, which receive blob transactions without their blobs.
1994    propagation_size_without_blobs: Option<usize>,
1995    // Cells kept for every blob, or `None` if unknown, which is announced as all cells.
1996    cell_mask: Option<BlobCellMask>,
1997    transaction: LazyEncodedTransaction,
1998}
1999
2000impl PropagateTransaction {
2001    /// Create a new instance from a transaction supplied directly for propagation.
2002    ///
2003    /// Direct transactions use their EIP-2718 encoded length so eth/68+ hash announcements carry
2004    /// the same size metadata as [`NewPooledTransactionHashes68::push`] and
2005    /// [`NewPooledTransactionHashes72::push`].
2006    fn new<T: SignedTransaction>(transaction: T) -> Self {
2007        let is_broadcastable_in_full = transaction.is_broadcastable_in_full();
2008        let propagation_size = transaction.encode_2718_len();
2009
2010        Self {
2011            is_broadcastable_in_full,
2012            propagation_size,
2013            propagation_size_without_blobs: (!transaction.is_eip4844()).then_some(propagation_size),
2014            // Without its sidecar a blob transaction can't be served, so it's never announced.
2015            cell_mask: transaction.is_eip4844().then(BlobCellMask::default),
2016            transaction: LazyEncoded::new(transaction),
2017        }
2018    }
2019
2020    /// Create a new instance from a pooled transaction.
2021    ///
2022    /// Pool transactions already cache the network encoded size used by txpool admission and
2023    /// pooled hash announcements. For blob transactions, this includes the sidecar size expected in
2024    /// a `PooledTransactions` response.
2025    fn pool_tx<P: PoolTransaction>(tx: Arc<ValidPoolTransaction<P>>) -> Self {
2026        let is_broadcastable_in_full = tx.transaction.consensus_ref().is_broadcastable_in_full();
2027        let propagation_size = tx.encoded_length();
2028        let propagation_size_without_blobs = tx.transaction.encoded_length_eth72();
2029        let cell_mask = tx.transaction.blob_cell_availability().map(BlobCellAvailability::get);
2030        Self {
2031            is_broadcastable_in_full,
2032            propagation_size,
2033            propagation_size_without_blobs,
2034            cell_mask,
2035            transaction: LazyEncoded::new(PropagatePooledTransactionEncoder::new(tx)),
2036        }
2037    }
2038
2039    fn tx_hash(&self) -> &TxHash {
2040        self.transaction.tx_hash()
2041    }
2042
2043    /// Returns the network encoded size used for propagation limits and hash metadata.
2044    const fn propagation_size(&self) -> usize {
2045        self.propagation_size
2046    }
2047
2048    fn tx_type(&self) -> u8 {
2049        self.transaction.ty()
2050    }
2051
2052    const fn is_broadcastable_in_full(&self) -> bool {
2053        self.is_broadcastable_in_full
2054    }
2055
2056    fn shared(&self) -> LazyEncodedTransaction {
2057        self.transaction.clone()
2058    }
2059
2060    /// Returns whether the transaction can be announced to a peer on `version`.
2061    fn can_announce_to(&self, version: EthVersion) -> bool {
2062        if version.is_eth72_or_newer() {
2063            self.propagation_size_without_blobs.is_some()
2064        } else {
2065            can_serve_blobs(self.cell_mask)
2066        }
2067    }
2068}
2069
2070/// A pooled transaction encoder that avoids cloning into the consensus transaction for propagation.
2071#[derive(Debug)]
2072struct PropagatePooledTransactionEncoder<P: PoolTransaction> {
2073    transaction: Arc<ValidPoolTransaction<P>>,
2074}
2075
2076impl<P: PoolTransaction> PropagatePooledTransactionEncoder<P> {
2077    const fn new(transaction: Arc<ValidPoolTransaction<P>>) -> Self {
2078        Self { transaction }
2079    }
2080
2081    fn encode_uncached(&self, out: &mut dyn BufMut) {
2082        (*self.transaction.transaction.consensus_ref().inner()).encode(out);
2083    }
2084}
2085
2086impl<P: PoolTransaction> Encodable for PropagatePooledTransactionEncoder<P> {
2087    fn encode(&self, out: &mut dyn BufMut) {
2088        self.encode_uncached(out);
2089    }
2090
2091    fn length(&self) -> usize {
2092        (*self.transaction.transaction.consensus_ref().inner()).length()
2093    }
2094}
2095
2096impl<P: PoolTransaction> TxHashRef for PropagatePooledTransactionEncoder<P> {
2097    fn tx_hash(&self) -> &TxHash {
2098        self.transaction.hash()
2099    }
2100}
2101
2102impl<P: PoolTransaction> Typed2718 for PropagatePooledTransactionEncoder<P> {
2103    fn ty(&self) -> u8 {
2104        self.transaction.transaction.ty()
2105    }
2106}
2107
2108/// Helper type to construct the appropriate message to send to the peer based on whether the peer
2109/// should receive them in full or as pooled
2110#[derive(Debug, Clone)]
2111enum PropagateTransactionsBuilder {
2112    Pooled(PooledTransactionsHashesBuilder),
2113    Full(FullTransactionsBuilder),
2114}
2115
2116impl PropagateTransactionsBuilder {
2117    /// Create a builder for pooled transactions with capacity for the expected number of
2118    /// transactions.
2119    fn pooled(version: EthVersion, capacity: usize) -> Self {
2120        Self::Pooled(PooledTransactionsHashesBuilder::with_capacity(version, capacity))
2121    }
2122
2123    /// Create a builder that sends transactions in full and records transactions that don't fit,
2124    /// with capacity for the expected number of transactions.
2125    fn full(version: EthVersion, capacity: usize) -> Self {
2126        Self::Full(FullTransactionsBuilder::with_capacity(version, capacity))
2127    }
2128
2129    /// Returns true if no transactions are recorded.
2130    fn is_empty(&self) -> bool {
2131        match self {
2132            Self::Pooled(builder) => builder.is_empty(),
2133            Self::Full(builder) => builder.is_empty(),
2134        }
2135    }
2136
2137    /// Consumes the type and returns the built messages that should be sent to the peer.
2138    fn build(self) -> PropagateTransactions {
2139        match self {
2140            Self::Pooled(pooled) => PropagateTransactions { pooled: pooled.build(), full: None },
2141            Self::Full(full) => full.build(),
2142        }
2143    }
2144}
2145
2146impl PropagateTransactionsBuilder {
2147    /// Appends a transaction to the list.
2148    fn push(&mut self, transaction: &PropagateTransaction) {
2149        match self {
2150            Self::Pooled(builder) => builder.push(transaction),
2151            Self::Full(builder) => builder.push(transaction),
2152        }
2153    }
2154}
2155
2156/// Represents how the transactions should be sent to a peer if any.
2157struct PropagateTransactions {
2158    /// The pooled transaction hashes to send.
2159    pooled: SmallVec<[NewPooledTransactionHashes; 1]>,
2160    /// The transactions to send in full.
2161    full: Option<BroadcastPoolTransactions>,
2162}
2163
2164/// Helper type for constructing the full transaction message that enforces the
2165/// [`DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE`] for full transaction broadcast
2166/// and enforces other propagation rules for EIP-4844 and tracks those transactions that can't be
2167/// broadcasted in full.
2168#[derive(Debug, Clone)]
2169struct FullTransactionsBuilder {
2170    /// The soft limit to enforce for a single broadcast message of full transactions.
2171    total_size: usize,
2172    /// All transactions to be broadcasted.
2173    transactions: Vec<LazyEncodedTransaction>,
2174    /// Transactions that didn't fit into the broadcast message
2175    pooled: PooledTransactionsHashesBuilder,
2176}
2177
2178impl FullTransactionsBuilder {
2179    /// Create a builder for the negotiated version of the peer's session
2180    fn new(version: EthVersion) -> Self {
2181        Self {
2182            total_size: 0,
2183            pooled: PooledTransactionsHashesBuilder::new(version),
2184            transactions: vec![],
2185        }
2186    }
2187
2188    /// Create a builder with capacity for the expected number of full transactions.
2189    ///
2190    /// The overflow hashes builder remains lazily allocated since most transactions are expected
2191    /// to be broadcast in full.
2192    fn with_capacity(version: EthVersion, capacity: usize) -> Self {
2193        Self {
2194            total_size: 0,
2195            pooled: PooledTransactionsHashesBuilder::new(version),
2196            transactions: Vec::with_capacity(capacity),
2197        }
2198    }
2199
2200    /// Returns whether or not any transactions are in the [`FullTransactionsBuilder`].
2201    fn is_empty(&self) -> bool {
2202        self.transactions.is_empty() && self.pooled.is_empty()
2203    }
2204
2205    /// Returns the messages that should be propagated to the peer.
2206    fn build(self) -> PropagateTransactions {
2207        let pooled = self.pooled.build();
2208        let full =
2209            (!self.transactions.is_empty()).then_some(BroadcastPoolTransactions(self.transactions));
2210        PropagateTransactions { pooled, full }
2211    }
2212
2213    /// Appends all transactions.
2214    fn extend(&mut self, txs: impl IntoIterator<Item = PropagateTransaction>) {
2215        for tx in txs {
2216            self.push(&tx)
2217        }
2218    }
2219
2220    /// Append a transaction to the list of full transaction if the total message bytes size doesn't
2221    /// exceed the soft maximum target byte size. The limit is soft, meaning if one single
2222    /// transaction goes over the limit, it will be broadcasted in its own [`Transactions`]
2223    /// message. The same pattern is followed in filling a [`GetPooledTransactions`] request in
2224    /// [`TransactionFetcher::dispatch`].
2225    ///
2226    /// If the transaction is unsuitable for broadcast or would exceed the softlimit, it is appended
2227    /// to list of pooled transactions, (e.g. 4844 transactions).
2228    /// See also [`SignedTransaction::is_broadcastable_in_full`].
2229    fn push(&mut self, transaction: &PropagateTransaction) {
2230        // Do not send full 4844 transaction hashes to peers.
2231        //
2232        //  Nodes MUST NOT automatically broadcast blob transactions to their peers.
2233        //  Instead, those transactions are only announced using
2234        //  `NewPooledTransactionHashes` messages, and can then be manually requested
2235        //  via `GetPooledTransactions`.
2236        //
2237        // From: <https://eips.ethereum.org/EIPS/eip-4844#networking>
2238        if !transaction.is_broadcastable_in_full() {
2239            self.pooled.push(transaction);
2240            return
2241        }
2242
2243        let new_size = self.total_size + transaction.propagation_size();
2244        if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE &&
2245            self.total_size > 0
2246        {
2247            // transaction does not fit into the message
2248            self.pooled.push(transaction);
2249            return
2250        }
2251
2252        self.total_size = new_size;
2253        self.transactions.push(transaction.shared());
2254    }
2255}
2256
2257/// A helper type to create the pooled transactions message based on the negotiated version of the
2258/// session with the peer
2259#[derive(Debug, Clone)]
2260enum PooledTransactionsHashesBuilder {
2261    // Hashes only, for eth/66 and eth/67 peers.
2262    Eth66(NewPooledTransactionHashes66),
2263    // Hashes with types and sizes, for eth/68 to eth/71 peers.
2264    Eth68(NewPooledTransactionHashes68),
2265    // One announcement per cell mask for eth/72 and eth/73 peers, since each carries one mask.
2266    Eth72(SmallVec<[NewPooledTransactionHashes72; 1]>),
2267}
2268
2269// === impl PooledTransactionsHashesBuilder ===
2270
2271impl PooledTransactionsHashesBuilder {
2272    /// Push a transaction from the pool to the list.
2273    fn push_pooled<T: PoolTransaction>(&mut self, pooled_tx: Arc<ValidPoolTransaction<T>>) {
2274        self.push_hash(
2275            *pooled_tx.hash(),
2276            pooled_tx.transaction.ty(),
2277            pooled_tx.encoded_length(),
2278            pooled_tx.transaction.encoded_length_eth72(),
2279            pooled_tx.transaction.blob_cell_availability().map(BlobCellAvailability::get),
2280        );
2281    }
2282
2283    /// Returns whether the announcement is empty.
2284    fn is_empty(&self) -> bool {
2285        match self {
2286            Self::Eth66(hashes) => hashes.is_empty(),
2287            Self::Eth68(hashes) => hashes.is_empty(),
2288            Self::Eth72(messages) => messages.iter().all(|msg| msg.is_empty()),
2289        }
2290    }
2291
2292    /// Appends all hashes
2293    fn extend(&mut self, txs: impl IntoIterator<Item = PropagateTransaction>) {
2294        for tx in txs {
2295            self.push(&tx);
2296        }
2297    }
2298
2299    fn push(&mut self, tx: &PropagateTransaction) {
2300        self.push_hash(
2301            *tx.tx_hash(),
2302            tx.tx_type(),
2303            tx.propagation_size(),
2304            tx.propagation_size_without_blobs,
2305            tx.cell_mask,
2306        );
2307    }
2308
2309    // Appends a hash, skipping transactions that can't be served at the peer's version.
2310    fn push_hash(
2311        &mut self,
2312        hash: TxHash,
2313        ty: u8,
2314        size: usize,
2315        eth72_size: Option<usize>,
2316        cell_mask: Option<BlobCellMask>,
2317    ) {
2318        match self {
2319            Self::Eth66(msg) if can_serve_blobs(cell_mask) => msg.push(hash),
2320            Self::Eth68(msg) if can_serve_blobs(cell_mask) => {
2321                msg.hashes.push(hash);
2322                msg.sizes.push(size);
2323                msg.types.push(ty);
2324            }
2325            Self::Eth66(_) | Self::Eth68(_) => {}
2326            Self::Eth72(messages) => {
2327                let Some(size) = eth72_size else { return };
2328                // The mask only describes blob transactions, so others join any announcement.
2329                let cell_mask = (ty == EIP4844_TX_TYPE_ID).then(|| {
2330                    cell_mask
2331                        .map_or(NewPooledTransactionHashes72::ALL_CELLS_MASK, BlobCellMask::to_b128)
2332                });
2333                let index = messages
2334                    .iter()
2335                    .position(|msg| {
2336                        cell_mask.is_none() ||
2337                            msg.cell_mask.is_none_or(|mask| Some(mask) == cell_mask)
2338                    })
2339                    .unwrap_or_else(|| {
2340                        messages.push(Default::default());
2341                        messages.len() - 1
2342                    });
2343                let msg = &mut messages[index];
2344                msg.hashes.push(hash);
2345                msg.sizes.push(size);
2346                msg.types.push(ty);
2347                msg.cell_mask = msg.cell_mask.or(cell_mask);
2348            }
2349        }
2350    }
2351
2352    /// Create a builder for the negotiated version of the peer's session
2353    fn new(version: EthVersion) -> Self {
2354        match version {
2355            EthVersion::Eth66 | EthVersion::Eth67 => Self::Eth66(Default::default()),
2356            EthVersion::Eth68 | EthVersion::Eth69 | EthVersion::Eth70 | EthVersion::Eth71 => {
2357                Self::Eth68(Default::default())
2358            }
2359            EthVersion::Eth72 | EthVersion::Eth73 => Self::Eth72(Default::default()),
2360        }
2361    }
2362
2363    /// Create a builder for the negotiated version of the peer's session with capacity for the
2364    /// expected number of hashes.
2365    fn with_capacity(version: EthVersion, capacity: usize) -> Self {
2366        match version {
2367            EthVersion::Eth66 | EthVersion::Eth67 => {
2368                Self::Eth66(NewPooledTransactionHashes66::with_capacity(capacity))
2369            }
2370            EthVersion::Eth68 | EthVersion::Eth69 | EthVersion::Eth70 | EthVersion::Eth71 => {
2371                Self::Eth68(NewPooledTransactionHashes68::with_capacity(capacity))
2372            }
2373            EthVersion::Eth72 | EthVersion::Eth73 => {
2374                Self::Eth72(SmallVec::from_buf([NewPooledTransactionHashes72::with_capacity(
2375                    capacity,
2376                )]))
2377            }
2378        }
2379    }
2380
2381    // Returns the non-empty announcements to send.
2382    fn build(self) -> SmallVec<[NewPooledTransactionHashes; 1]> {
2383        let mut messages = match self {
2384            Self::Eth66(mut msg) => {
2385                msg.shrink_to_fit();
2386                SmallVec::from_buf([NewPooledTransactionHashes::from(msg)])
2387            }
2388            Self::Eth68(mut msg) => {
2389                msg.shrink_to_fit();
2390                SmallVec::from_buf([msg.into()])
2391            }
2392            Self::Eth72(messages) => messages
2393                .into_iter()
2394                .map(|mut msg| {
2395                    msg.shrink_to_fit();
2396                    msg.into()
2397                })
2398                .collect(),
2399        };
2400        messages.retain(|msg| !msg.is_empty());
2401        messages
2402    }
2403}
2404
2405/// Returns whether a transaction with `cell_mask` can be served with its blobs, as eth/66 to eth/71
2406/// peers need.
2407fn can_serve_blobs(cell_mask: Option<BlobCellMask>) -> bool {
2408    cell_mask.is_none_or(BlobCellMask::is_recoverable)
2409}
2410
2411/// How we received the transactions.
2412#[derive(Debug)]
2413enum TransactionSource {
2414    /// Transactions were broadcast to us via [`Transactions`] message.
2415    Broadcast,
2416    /// Transactions were sent as the response to a `GetPooledTransactions` request issued by us.
2417    Response {
2418        /// Session metadata remains available after the responding peer disconnects.
2419        version: EthVersion,
2420        client_version: Arc<str>,
2421    },
2422}
2423
2424// === impl TransactionSource ===
2425
2426impl TransactionSource {
2427    /// Whether the transaction were sent as broadcast.
2428    const fn is_broadcast(&self) -> bool {
2429        matches!(self, Self::Broadcast)
2430    }
2431}
2432
2433/// Tracks a single peer in the context of [`TransactionsManager`].
2434#[derive(Debug)]
2435pub struct PeerMetadata<N: NetworkPrimitives = EthNetworkPrimitives> {
2436    /// Optimistically keeps track of transactions that we know the peer has seen. Optimistic, in
2437    /// the sense that transactions are preemptively marked as seen by peer when they are sent to
2438    /// the peer.
2439    seen_transactions: LruCache<TxHash, FbBuildHasher<32>>,
2440    /// A communication channel directly to the peer's session task.
2441    request_tx: PeerRequestSender<PeerRequest<N>>,
2442    /// negotiated version of the session.
2443    version: EthVersion,
2444    /// The peer's client version.
2445    client_version: Arc<str>,
2446    /// The kind of peer.
2447    peer_kind: PeerKind,
2448}
2449
2450impl<N: NetworkPrimitives> PeerMetadata<N> {
2451    /// Returns a new instance of [`PeerMetadata`].
2452    pub fn new(
2453        request_tx: PeerRequestSender<PeerRequest<N>>,
2454        version: EthVersion,
2455        client_version: Arc<str>,
2456        max_transactions_seen_by_peer: u32,
2457        peer_kind: PeerKind,
2458    ) -> Self {
2459        Self {
2460            seen_transactions: LruCache::with_hasher(
2461                max_transactions_seen_by_peer,
2462                Default::default(),
2463            ),
2464            request_tx,
2465            version,
2466            client_version,
2467            peer_kind,
2468        }
2469    }
2470
2471    /// Returns a reference to the peer's request sender channel.
2472    pub const fn request_tx(&self) -> &PeerRequestSender<PeerRequest<N>> {
2473        &self.request_tx
2474    }
2475
2476    /// Returns a mutable reference to the seen transactions LRU cache.
2477    pub const fn seen_transactions_mut(&mut self) -> &mut LruCache<TxHash, FbBuildHasher<32>> {
2478        &mut self.seen_transactions
2479    }
2480
2481    /// Returns the negotiated `EthVersion` of the session.
2482    pub const fn version(&self) -> EthVersion {
2483        self.version
2484    }
2485
2486    /// Returns a reference to the peer's client version string.
2487    pub fn client_version(&self) -> &str {
2488        &self.client_version
2489    }
2490
2491    /// Returns the peer's kind.
2492    pub const fn peer_kind(&self) -> PeerKind {
2493        self.peer_kind
2494    }
2495}
2496
2497/// Commands to send to the [`TransactionsManager`]
2498#[derive(Debug)]
2499enum TransactionsCommand<N: NetworkPrimitives = EthNetworkPrimitives> {
2500    /// Propagate a transaction hash to the network.
2501    PropagateHash(B256),
2502    /// Propagate transaction hashes to a specific peer.
2503    PropagateHashesTo(Vec<B256>, PeerId),
2504    /// Request the list of active peer IDs from the [`TransactionsManager`].
2505    GetActivePeers(oneshot::Sender<HashSet<PeerId>>),
2506    /// Propagate a collection of full transactions to a specific peer.
2507    PropagateTransactionsTo(Vec<TxHash>, PeerId),
2508    /// Propagate a collection of hashes to all peers.
2509    PropagateTransactions(Vec<TxHash>),
2510    /// Propagate a collection of broadcastable transactions in full to all peers.
2511    BroadcastTransactions(Vec<PropagateTransaction>),
2512    /// Request transaction hashes known by specific peers from the [`TransactionsManager`].
2513    GetTransactionHashes { peers: Vec<PeerId>, tx: oneshot::Sender<HashMap<PeerId, B256Set>> },
2514    /// Requests a clone of the sender channel to the peer.
2515    GetPeerSender {
2516        peer_id: PeerId,
2517        peer_request_sender: oneshot::Sender<Option<PeerRequestSender<PeerRequest<N>>>>,
2518    },
2519}
2520
2521/// All events related to transactions emitted by the network.
2522#[derive(Debug)]
2523pub enum NetworkTransactionEvent<N: NetworkPrimitives = EthNetworkPrimitives> {
2524    /// Represents the event of receiving a list of transactions from a peer.
2525    ///
2526    /// This indicates transactions that were broadcasted to us from the peer.
2527    IncomingTransactions {
2528        /// The ID of the peer from which the transactions were received.
2529        peer_id: PeerId,
2530        /// The received transactions.
2531        msg: Transactions<N::BroadcastedTransaction>,
2532    },
2533    /// Represents the event of receiving a list of transaction hashes from a peer.
2534    IncomingPooledTransactionHashes {
2535        /// The ID of the peer from which the transaction hashes were received.
2536        peer_id: PeerId,
2537        /// The received new pooled transaction hashes.
2538        msg: NewPooledTransactionHashes,
2539    },
2540    /// Represents the event of receiving a `GetPooledTransactions` request from a peer.
2541    GetPooledTransactions {
2542        /// The ID of the peer from which the request was received.
2543        peer_id: PeerId,
2544        /// The received `GetPooledTransactions` request.
2545        request: GetPooledTransactions,
2546        /// The sender for responding to the request with a result of `PooledTransactions`.
2547        response: oneshot::Sender<RequestResult<PooledTransactions<N::PooledTransaction>>>,
2548    },
2549    /// Represents the event of receiving a `GetTransactionsHandle` request.
2550    GetTransactionsHandle(oneshot::Sender<Option<TransactionsHandle<N>>>),
2551}
2552
2553/// Tracks stats about the [`TransactionsManager`].
2554#[derive(Debug)]
2555pub struct PendingPoolImportsInfo {
2556    /// Number of transactions about to be inserted into the pool.
2557    pending_pool_imports: Arc<AtomicUsize>,
2558    /// Max number of transactions allowed to be imported concurrently.
2559    max_pending_pool_imports: usize,
2560    /// Encoded byte size of the transactions about to be inserted into the pool.
2561    pending_pool_imports_bytes: Arc<AtomicUsize>,
2562    /// Max encoded byte size of transactions allowed to be imported concurrently.
2563    max_pending_pool_imports_bytes: usize,
2564}
2565
2566impl PendingPoolImportsInfo {
2567    /// Returns a new [`PendingPoolImportsInfo`].
2568    pub fn new(max_pending_pool_imports: usize, max_pending_pool_imports_bytes: usize) -> Self {
2569        Self {
2570            pending_pool_imports: Arc::new(AtomicUsize::default()),
2571            max_pending_pool_imports,
2572            pending_pool_imports_bytes: Arc::new(AtomicUsize::default()),
2573            max_pending_pool_imports_bytes,
2574        }
2575    }
2576
2577    /// Returns `true` if the number of pool imports and their encoded byte size are both under
2578    /// the configured max.
2579    pub fn has_capacity(&self) -> bool {
2580        self.pending_pool_imports.load(Ordering::Relaxed) < self.max_pending_pool_imports &&
2581            self.pending_pool_imports_bytes.load(Ordering::Relaxed) <
2582                self.max_pending_pool_imports_bytes
2583    }
2584}
2585
2586impl Default for PendingPoolImportsInfo {
2587    fn default() -> Self {
2588        Self::new(
2589            DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
2590            DEFAULT_MAX_BYTE_SIZE_PENDING_POOL_IMPORTS,
2591        )
2592    }
2593}
2594
2595#[derive(Debug, Default)]
2596struct TxManagerPollDurations {
2597    acc_network_events: Duration,
2598    acc_pending_imports: Duration,
2599    acc_tx_events: Duration,
2600    acc_imported_txns: Duration,
2601    acc_fetch_events: Duration,
2602    acc_pending_fetch: Duration,
2603    acc_cmds: Duration,
2604}
2605
2606impl<N: NetworkPrimitives> InMemorySize for NetworkTransactionEvent<N> {
2607    // `N::BroadcastedTransaction` and `N::PooledTransaction` already implement
2608    // `InMemorySize` via `SignedTransaction: InMemorySize`, so no extra bound is needed.
2609    fn size(&self) -> usize {
2610        match self {
2611            Self::IncomingTransactions { peer_id, msg } => {
2612                core::mem::size_of_val(peer_id) +
2613                    msg.0.iter().map(InMemorySize::size).sum::<usize>()
2614            }
2615            Self::IncomingPooledTransactionHashes { peer_id, msg } => {
2616                core::mem::size_of_val(peer_id) + msg.size()
2617            }
2618            Self::GetPooledTransactions { peer_id, request, response } => {
2619                core::mem::size_of_val(peer_id) +
2620                    request.0.len() * core::mem::size_of::<TxHash>() +
2621                    core::mem::size_of_val(response)
2622            }
2623            Self::GetTransactionsHandle(_) => 0,
2624        }
2625    }
2626}
2627
2628#[cfg(test)]
2629mod tests {
2630    use super::*;
2631    use crate::{
2632        test_utils::{
2633            transactions::{buffer_hash_to_tx_fetcher, new_mock_session, new_tx_manager},
2634            Testnet,
2635        },
2636        transactions::config::RelaxedEthAnnouncementFilter,
2637        NetworkConfigBuilder, NetworkManager,
2638    };
2639    use alloy_consensus::{
2640        transaction::{Recovered, TxEip4844WithSidecar},
2641        SignableTransaction, TxEip1559, TxEip4844, TxLegacy,
2642    };
2643    use alloy_eips::{
2644        eip1559::MIN_PROTOCOL_BASE_FEE,
2645        eip2718::Encodable2718,
2646        eip4844::{Blob, BlobTransactionSidecar, BlobTransactionValidationError, Bytes48},
2647        eip7594::{BlobTransactionSidecarEip7594, CELLS_PER_EXT_BLOB},
2648    };
2649    use alloy_primitives::{address, hex, Address, Signature, TxKind, B256, U256};
2650    use alloy_rlp::Decodable;
2651    use futures::{task::noop_waker_ref, FutureExt};
2652    use reth_chainspec::MIN_TRANSACTION_GAS;
2653    use reth_ethereum_primitives::{PooledTransactionVariant, Transaction, TransactionSigned};
2654    use reth_network_api::{NetworkInfo, PeerKind};
2655    use reth_network_p2p::{
2656        error::{RequestError, RequestResult},
2657        sync::{NetworkSyncUpdater, SyncState},
2658    };
2659    use reth_primitives_traits::transaction::error::InvalidTransactionError;
2660    use reth_storage_api::noop::NoopProvider;
2661    use reth_tasks::Runtime;
2662    use reth_transaction_pool::{
2663        blobstore::{BlobStore, InMemoryBlobStore, DATA_COLUMNS},
2664        error::{Eip4844PoolTransactionError, InvalidPoolTransactionError, PoolError},
2665        identifier::SenderIdentifiers,
2666        test_utils::{
2667            blob_tx_without_blobs, testing_pool, MockTransaction, MockTransactionFactory,
2668            OkValidator, TestPool, TransactionGenerator,
2669        },
2670        CoinbaseTipOrdering, EthPooledTransaction, Pool, TransactionOrigin, ValidPoolTransaction,
2671    };
2672    use secp256k1::SecretKey;
2673    use std::{
2674        future::poll_fn,
2675        net::{IpAddr, Ipv4Addr, SocketAddr},
2676        str::FromStr,
2677        time::Instant,
2678    };
2679    use tracing::error;
2680
2681    type EthTestPool = Pool<
2682        OkValidator<EthPooledTransaction>,
2683        CoinbaseTipOrdering<EthPooledTransaction>,
2684        InMemoryBlobStore,
2685    >;
2686
2687    // Imports the verified blob transaction `tx` and handles the pool's result.
2688    async fn import_verified(tx_manager: &mut TransactionsManager<TestPool>, tx: MockTransaction) {
2689        tx_manager.import_verified_blob_transactions(vec![(PeerId::ZERO, tx)]);
2690        let results = tx_manager.pool_imports.next().await.unwrap();
2691        tx_manager.on_batch_import_result(results);
2692    }
2693
2694    #[tokio::test]
2695    async fn invalid_cell_batches_do_not_query_a_peer() {
2696        let (manager_tx, mut manager_rx) = mpsc::unbounded_channel();
2697        let handle = TransactionsHandle::<EthNetworkPrimitives> { manager_tx };
2698        for (hashes, masks) in [
2699            (vec![], vec![]),
2700            (vec![B256::ZERO], vec![]),
2701            (vec![B256::ZERO; 2], vec![B128::ZERO, B128::repeat_byte(1)]),
2702        ] {
2703            let result = tokio::time::timeout(
2704                Duration::from_secs(1),
2705                handle.get_cells_with_masks_from(PeerId::default(), hashes, masks),
2706            )
2707            .await
2708            .expect("invalid request should be rejected before looking up a peer");
2709            assert_eq!(result, Err(RequestError::InvalidRequest));
2710            assert!(matches!(manager_rx.try_recv(), Err(mpsc::error::TryRecvError::Empty)));
2711        }
2712    }
2713
2714    #[tokio::test]
2715    async fn announcement_policy_preserves_order_and_skips_pending_and_bad_imports() {
2716        #[derive(Debug, Clone, Default)]
2717        struct RecordingPolicy(Arc<parking_lot::Mutex<Vec<(u8, TxHash, usize)>>>);
2718
2719        impl AnnouncementFilteringPolicy<EthNetworkPrimitives> for RecordingPolicy {
2720            fn decide_on_announcement(
2721                &self,
2722                tx_type: u8,
2723                hash: &TxHash,
2724                size: usize,
2725            ) -> AnnouncementAcceptance {
2726                self.0.lock().push((tx_type, *hash, size));
2727                match tx_type {
2728                    0xff => AnnouncementAcceptance::Reject { penalize_peer: true },
2729                    1 => AnnouncementAcceptance::Ignore,
2730                    _ => AnnouncementAcceptance::Accept,
2731                }
2732            }
2733        }
2734
2735        let (mut manager, _network) = new_tx_manager().await;
2736        let policy = RecordingPolicy::default();
2737        manager.policies =
2738            NetworkPolicies::new(TransactionPropagationKind::default(), policy.clone());
2739        let peer_id = PeerId::repeat_byte(1);
2740        let (peer, mut rx) = new_mock_session(peer_id, EthVersion::Eth68);
2741        manager.peers.insert(peer_id, peer);
2742        let [pending, accepted, ignored, rejected, later, bad] =
2743            [1, 2, 3, 4, 5, 6].map(B256::repeat_byte);
2744        manager.transactions_by_peers.insert(pending, Default::default());
2745        manager.bad_imports.insert(bad);
2746        manager.on_new_pooled_transaction_hashes(
2747            peer_id,
2748            NewPooledTransactionHashes68 {
2749                hashes: vec![pending, accepted, accepted, ignored, rejected, later, bad],
2750                types: vec![0xff, 2, 0xff, 1, 0xff, 2, 0xff],
2751                sizes: vec![100, 200, 300, 400, 500, 600, 700],
2752            }
2753            .into(),
2754        );
2755
2756        assert_eq!(
2757            *policy.0.lock(),
2758            [(2, accepted, 200), (1, ignored, 400), (0xff, rejected, 500), (2, later, 600)]
2759        );
2760        poll_fn(|cx| {
2761            let _ = manager.poll_unpin(cx);
2762            Poll::Ready(())
2763        })
2764        .await;
2765        let PeerRequest::GetPooledTransactions { request, .. } = rx.try_recv().unwrap() else {
2766            panic!("expected transaction request")
2767        };
2768        assert_eq!(request.0, [accepted, later]);
2769    }
2770
2771    async fn new_eth_tx_manager(
2772        validator: OkValidator<EthPooledTransaction>,
2773    ) -> (
2774        TransactionsManager<EthTestPool, EthNetworkPrimitives>,
2775        NetworkManager<EthNetworkPrimitives>,
2776    ) {
2777        let secret_key = SecretKey::new(&mut rand::rng());
2778        let client = NoopProvider::default();
2779
2780        let config = NetworkConfigBuilder::new(secret_key, Runtime::test())
2781            .listener_port(0)
2782            .disable_discovery()
2783            .build(client);
2784
2785        let pool = Pool::new(
2786            validator,
2787            CoinbaseTipOrdering::default(),
2788            InMemoryBlobStore::default(),
2789            Default::default(),
2790        );
2791
2792        let transactions_manager_config = config.transactions_manager_config.clone();
2793        let (_network_handle, network, transactions, _) = NetworkManager::new(config)
2794            .await
2795            .unwrap()
2796            .into_builder()
2797            .transactions(pool.clone(), transactions_manager_config)
2798            .split_with_handle();
2799
2800        (transactions, network)
2801    }
2802
2803    #[tokio::test]
2804    async fn blob_fetcher_samples_the_custody_set_on_the_network_handle() {
2805        let (mut manager, _network) = new_eth_tx_manager(OkValidator::default()).await;
2806        let custody = BlobCellMask::from_bits(0b1111 << 70);
2807        NetworkInfo::cell_custody(&manager.network).set(custody);
2808        let (first, second) = (PeerId::repeat_byte(1), PeerId::repeat_byte(2));
2809        let (first_peer, mut first_rx) = new_mock_session(first, EthVersion::Eth72);
2810        let (second_peer, _second_rx) = new_mock_session(second, EthVersion::Eth72);
2811        manager.peers.insert(first, first_peer);
2812        manager.peers.insert(second, second_peer);
2813        let (tx, _) = blob_tx_without_blobs(1);
2814        let hash = *tx.hash();
2815        let msg = NewPooledTransactionHashes::Eth72(NewPooledTransactionHashes72 {
2816            types: vec![EIP4844_TX_TYPE_ID],
2817            sizes: vec![tx.encoded_length()],
2818            hashes: vec![hash],
2819            cell_mask: Some(NewPooledTransactionHashes72::ALL_CELLS_MASK),
2820        });
2821        let mut cx = Context::from_waker(noop_waker_ref());
2822
2823        // A transaction is fetched in full 15% of the time, which repeating the announcement
2824        // draws again, so 64 draws all fetching in full has a probability of about 1e-53.
2825        for _ in 0..64 {
2826            for peer in [first, second] {
2827                let mut announcement =
2828                    TransactionAnnouncement::from_message(&msg, &mut B256Set::default()).unwrap();
2829                manager.blob_fetcher.on_announcement(peer, &mut announcement);
2830            }
2831            assert!(manager.blob_fetcher.body(first, tx.clone()));
2832            assert!(manager.blob_fetcher.poll(&mut cx, &manager.peers).is_pending());
2833            let Ok(PeerRequest::GetCells { request, .. }) = first_rx.try_recv() else {
2834                panic!("expected a GetCells request")
2835            };
2836            let requested = request.cell_mask(0).unwrap();
2837            if requested != DATA_COLUMNS {
2838                // The custody columns and the sample's extra column.
2839                assert_eq!(requested.count(), custody.count() + 1);
2840                assert!(custody.is_subset_of(requested));
2841                return
2842            }
2843            manager.blob_fetcher.remove(&hash);
2844        }
2845        panic!("never sampled")
2846    }
2847
2848    fn valid_eth_pool_transaction(
2849        transaction: EthPooledTransaction,
2850    ) -> Arc<ValidPoolTransaction<EthPooledTransaction>> {
2851        let mut ids = SenderIdentifiers::default();
2852        let transaction_id =
2853            ids.sender_id_or_create(transaction.sender()).into_transaction_id(transaction.nonce());
2854
2855        Arc::new(ValidPoolTransaction {
2856            propagate: false,
2857            transaction_id,
2858            transaction,
2859            timestamp: Instant::now(),
2860            origin: TransactionOrigin::External,
2861            authority_ids: None,
2862        })
2863    }
2864
2865    fn gen_eip1559_pooled_with_nonce<R: rand::RngCore>(
2866        tx_gen: &mut TransactionGenerator<R>,
2867        nonce: u64,
2868    ) -> EthPooledTransaction {
2869        EthPooledTransaction::try_from_consensus(
2870            tx_gen.transaction().nonce(nonce).into_eip1559().try_into_recovered().unwrap(),
2871        )
2872        .unwrap()
2873    }
2874
2875    #[tokio::test(flavor = "multi_thread")]
2876    async fn test_ignored_tx_broadcasts_while_initially_syncing() {
2877        reth_tracing::init_test_tracing();
2878        let net = Testnet::create(3).await.spawn();
2879        let [peer0, peer1, _] = net.peers_array();
2880
2881        let listener0 = peer0.event_listener();
2882        peer0.add_peer(peer1);
2883        let secret_key = SecretKey::new(&mut rand::rng());
2884
2885        let client = NoopProvider::default();
2886        let pool = testing_pool();
2887        let config = NetworkConfigBuilder::eth(secret_key, Runtime::test())
2888            .disable_discovery()
2889            .listener_port(0)
2890            .build(client);
2891        let transactions_manager_config = config.transactions_manager_config.clone();
2892        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
2893            .await
2894            .unwrap()
2895            .into_builder()
2896            .transactions(pool.clone(), transactions_manager_config)
2897            .split_with_handle();
2898
2899        tokio::task::spawn(network);
2900
2901        // go to syncing (pipeline sync)
2902        network_handle.update_sync_state(SyncState::Syncing);
2903        assert!(NetworkInfo::is_syncing(&network_handle));
2904        assert!(NetworkInfo::is_initially_syncing(&network_handle));
2905
2906        // wait for all initiator connections
2907        let mut established = listener0.take(2);
2908        while let Some(ev) = established.next().await {
2909            match ev {
2910                NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => {
2911                    // to insert a new peer in transactions peerset
2912                    transactions
2913                        .on_network_event(NetworkEvent::Peer(PeerEvent::SessionEstablished(info)))
2914                }
2915                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
2916                ev => {
2917                    error!("unexpected event {ev:?}")
2918                }
2919            }
2920        }
2921        // random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
2922        let input = hex!(
2923            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
2924        );
2925        let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
2926        transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
2927            peer_id: *peer1.peer_id(),
2928            msg: Transactions(vec![signed_tx.clone()]),
2929        });
2930        poll_fn(|cx| {
2931            let _ = transactions.poll_unpin(cx);
2932            Poll::Ready(())
2933        })
2934        .await;
2935        assert!(pool.is_empty());
2936    }
2937
2938    #[tokio::test(flavor = "multi_thread")]
2939    async fn test_tx_broadcasts_through_two_syncs() {
2940        reth_tracing::init_test_tracing();
2941        let net = Testnet::create(3).await.spawn();
2942        let [peer0, peer1, _] = net.peers_array();
2943
2944        let listener0 = peer0.event_listener();
2945        peer0.add_peer(peer1);
2946        let secret_key = SecretKey::new(&mut rand::rng());
2947
2948        let client = NoopProvider::default();
2949        let pool = testing_pool();
2950        let config = NetworkConfigBuilder::new(secret_key, Runtime::test())
2951            .disable_discovery()
2952            .listener_port(0)
2953            .build(client);
2954        let transactions_manager_config = config.transactions_manager_config.clone();
2955        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
2956            .await
2957            .unwrap()
2958            .into_builder()
2959            .transactions(pool.clone(), transactions_manager_config)
2960            .split_with_handle();
2961
2962        tokio::task::spawn(network);
2963
2964        // go to syncing (pipeline sync) to idle and then to syncing (live)
2965        network_handle.update_sync_state(SyncState::Syncing);
2966        assert!(NetworkInfo::is_syncing(&network_handle));
2967        network_handle.update_sync_state(SyncState::Idle);
2968        assert!(!NetworkInfo::is_syncing(&network_handle));
2969        network_handle.update_sync_state(SyncState::Syncing);
2970        assert!(NetworkInfo::is_syncing(&network_handle));
2971
2972        // wait for all initiator connections
2973        let mut established = listener0.take(2);
2974        while let Some(ev) = established.next().await {
2975            match ev {
2976                NetworkEvent::ActivePeerSession { .. } |
2977                NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => {
2978                    // to insert a new peer in transactions peerset
2979                    transactions.on_network_event(ev);
2980                }
2981                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
2982                _ => {
2983                    error!("unexpected event {ev:?}")
2984                }
2985            }
2986        }
2987        // random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
2988        let input = hex!(
2989            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
2990        );
2991        let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
2992        transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
2993            peer_id: *peer1.peer_id(),
2994            msg: Transactions(vec![signed_tx.clone()]),
2995        });
2996        poll_fn(|cx| {
2997            let _ = transactions.poll_unpin(cx);
2998            Poll::Ready(())
2999        })
3000        .await;
3001        assert!(!NetworkInfo::is_initially_syncing(&network_handle));
3002        assert!(NetworkInfo::is_syncing(&network_handle));
3003        assert!(!pool.is_empty());
3004    }
3005
3006    // Ensure that the transaction manager correctly handles the `IncomingPooledTransactionHashes`
3007    // event and is able to retrieve the corresponding transactions.
3008    #[tokio::test(flavor = "multi_thread")]
3009    async fn test_handle_incoming_transactions_hashes() {
3010        reth_tracing::init_test_tracing();
3011
3012        let secret_key = SecretKey::new(&mut rand::rng());
3013        let client = NoopProvider::default();
3014
3015        let config = NetworkConfigBuilder::new(secret_key, Runtime::test())
3016            // let OS choose port
3017            .listener_port(0)
3018            .disable_discovery()
3019            .build(client);
3020
3021        let pool = testing_pool();
3022
3023        let transactions_manager_config = config.transactions_manager_config.clone();
3024        let (_network_handle, _network, mut tx_manager, _) = NetworkManager::new(config)
3025            .await
3026            .unwrap()
3027            .into_builder()
3028            .transactions(pool.clone(), transactions_manager_config)
3029            .split_with_handle();
3030
3031        let peer_id_1 = PeerId::repeat_byte(1);
3032        let eth_version = EthVersion::Eth66;
3033
3034        let txs = vec![TransactionSigned::new_unhashed(
3035            Transaction::Legacy(TxLegacy {
3036                chain_id: Some(4),
3037                nonce: 15u64,
3038                gas_price: 2200000000,
3039                gas_limit: 34811,
3040                to: TxKind::Call(address!("cf7f9e66af820a19257a2108375b180b0ec49167")),
3041                value: U256::from(1234u64),
3042                input: Default::default(),
3043            }),
3044            Signature::new(
3045                U256::from_str(
3046                    "0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981",
3047                )
3048                .unwrap(),
3049                U256::from_str(
3050                    "0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860",
3051                )
3052                .unwrap(),
3053                true,
3054            ),
3055        )];
3056
3057        let txs_hashes: Vec<B256> = txs.iter().map(|tx| *tx.hash()).collect();
3058
3059        let (peer_1, mut to_mock_session_rx) = new_mock_session(peer_id_1, eth_version);
3060        tx_manager.peers.insert(peer_id_1, peer_1);
3061
3062        assert!(pool.is_empty());
3063
3064        // An announcement in another version's format comes from an earlier session and is
3065        // dropped.
3066        tx_manager.on_network_tx_event(NetworkTransactionEvent::IncomingPooledTransactionHashes {
3067            peer_id: peer_id_1,
3068            msg: NewPooledTransactionHashes::Eth68(NewPooledTransactionHashes68 {
3069                types: vec![0],
3070                sizes: vec![txs[0].encode_2718_len()],
3071                hashes: txs_hashes.clone(),
3072            }),
3073        });
3074        assert_eq!(tx_manager.transaction_fetcher.num_hashes(), 0);
3075
3076        tx_manager.on_network_tx_event(NetworkTransactionEvent::IncomingPooledTransactionHashes {
3077            peer_id: peer_id_1,
3078            msg: NewPooledTransactionHashes::from(NewPooledTransactionHashes66::from(
3079                txs_hashes.clone(),
3080            )),
3081        });
3082
3083        // advance the transaction manager future to send the request
3084        poll_fn(|cx| {
3085            let _ = tx_manager.poll_unpin(cx);
3086            Poll::Ready(())
3087        })
3088        .await;
3089
3090        // mock session of peer_1 receives request
3091        let req = to_mock_session_rx
3092            .recv()
3093            .await
3094            .expect("peer_1 session should receive request with buffered hashes");
3095        let PeerRequest::GetPooledTransactions { request, response } = req else { unreachable!() };
3096        assert_eq!(request, GetPooledTransactions::from(txs_hashes.clone()));
3097
3098        let message: Vec<PooledTransactionVariant> = txs
3099            .into_iter()
3100            .map(|tx| {
3101                PooledTransactionVariant::try_from(tx)
3102                    .expect("Failed to convert MockTransaction to PooledTransaction")
3103            })
3104            .collect();
3105
3106        // return the transactions corresponding to the transaction hashes.
3107        response
3108            .send(Ok(PooledTransactions(message)))
3109            .expect("should send peer_1 response to tx manager");
3110
3111        // adance the transaction manager future
3112        poll_fn(|cx| {
3113            let _ = tx_manager.poll_unpin(cx);
3114            Poll::Ready(())
3115        })
3116        .await;
3117
3118        // ensure that the transactions corresponding to the transaction hashes have been
3119        // successfully retrieved and stored in the Pool.
3120        assert_eq!(pool.get_all(txs_hashes.clone()).len(), txs_hashes.len());
3121    }
3122
3123    #[tokio::test(flavor = "multi_thread")]
3124    async fn test_handle_incoming_transactions() {
3125        reth_tracing::init_test_tracing();
3126        let net = Testnet::create(3).await.spawn();
3127        let [peer0, peer1, _] = net.peers_array();
3128
3129        let listener0 = peer0.event_listener();
3130
3131        peer0.add_peer(peer1);
3132        let secret_key = SecretKey::new(&mut rand::rng());
3133
3134        let client = NoopProvider::default();
3135        let pool = testing_pool();
3136        let config = NetworkConfigBuilder::new(secret_key, Runtime::test())
3137            .disable_discovery()
3138            .listener_port(0)
3139            .build(client);
3140        let transactions_manager_config = config.transactions_manager_config.clone();
3141        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
3142            .await
3143            .unwrap()
3144            .into_builder()
3145            .transactions(pool.clone(), transactions_manager_config)
3146            .split_with_handle();
3147        tokio::task::spawn(network);
3148
3149        network_handle.update_sync_state(SyncState::Idle);
3150
3151        assert!(!NetworkInfo::is_syncing(&network_handle));
3152
3153        // wait for all initiator connections
3154        let mut established = listener0.take(2);
3155        while let Some(ev) = established.next().await {
3156            match ev {
3157                NetworkEvent::ActivePeerSession { .. } |
3158                NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => {
3159                    // to insert a new peer in transactions peerset
3160                    transactions.on_network_event(ev);
3161                }
3162                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
3163                ev => {
3164                    error!("unexpected event {ev:?}")
3165                }
3166            }
3167        }
3168        // random tx: <https://etherscan.io/getRawTx?tx=0x9448608d36e721ef403c53b00546068a6474d6cbab6816c3926de449898e7bce>
3169        let input = hex!(
3170            "02f871018302a90f808504890aef60826b6c94ddf4c5025d1a5742cf12f74eec246d4432c295e487e09c3bbcc12b2b80c080a0f21a4eacd0bf8fea9c5105c543be5a1d8c796516875710fafafdf16d16d8ee23a001280915021bb446d1973501a67f93d2b38894a514b976e7b46dc2fe54598d76"
3171        );
3172        let signed_tx = TransactionSigned::decode(&mut &input[..]).unwrap();
3173        transactions.on_network_tx_event(NetworkTransactionEvent::IncomingTransactions {
3174            peer_id: *peer1.peer_id(),
3175            msg: Transactions(vec![signed_tx.clone()]),
3176        });
3177        assert!(transactions
3178            .transactions_by_peers
3179            .get(signed_tx.tx_hash())
3180            .unwrap()
3181            .contains(peer1.peer_id()));
3182
3183        // advance the transaction manager future
3184        poll_fn(|cx| {
3185            let _ = transactions.poll_unpin(cx);
3186            Poll::Ready(())
3187        })
3188        .await;
3189
3190        assert!(!pool.is_empty());
3191        assert!(pool.get(signed_tx.tx_hash()).is_some());
3192    }
3193
3194    #[tokio::test(flavor = "multi_thread")]
3195    async fn test_session_closed_cleans_transaction_peer_state() {
3196        let (mut tx_manager, _network) = new_tx_manager().await;
3197        let peer_id = PeerId::repeat_byte(1);
3198        let fallback_peer = PeerId::repeat_byte(2);
3199        let (peer, _) = new_mock_session(peer_id, EthVersion::Eth66);
3200        let (fallback, _) = new_mock_session(fallback_peer, EthVersion::Eth66);
3201        let hash_shared = B256::from_slice(&[1; 32]);
3202
3203        tx_manager.peers.insert(peer_id, peer);
3204        tx_manager.peers.insert(fallback_peer, fallback);
3205        buffer_hash_to_tx_fetcher(&mut tx_manager.transaction_fetcher, hash_shared, peer_id, None);
3206        buffer_hash_to_tx_fetcher(
3207            &mut tx_manager.transaction_fetcher,
3208            hash_shared,
3209            fallback_peer,
3210            None,
3211        );
3212        assert_eq!(
3213            tx_manager.transaction_fetcher.candidate_peers(&hash_shared),
3214            vec![peer_id, fallback_peer]
3215        );
3216
3217        tx_manager.on_network_event(NetworkEvent::Peer(PeerEvent::SessionClosed {
3218            peer_id,
3219            reason: None,
3220        }));
3221
3222        // peer removed from peers map and from the fetcher
3223        assert!(!tx_manager.peers.contains_key(&peer_id));
3224        assert!(tx_manager.transaction_fetcher.queued_hashes(&peer_id).is_empty());
3225        // fallback peer is still available for the hash
3226        assert_eq!(
3227            tx_manager.transaction_fetcher.candidate_peers(&hash_shared),
3228            vec![fallback_peer]
3229        );
3230    }
3231
3232    #[tokio::test(flavor = "multi_thread")]
3233    async fn blob_tx_turned_away_for_a_nonce_gap_follows_its_previous_nonce() {
3234        let (mut tx_manager, _network) = new_tx_manager().await;
3235        let first = MockTransaction::eip4844();
3236        let second = first.next();
3237
3238        // The cells of the second transaction passed the check first.
3239        import_verified(&mut tx_manager, second.clone()).await;
3240        assert!(!tx_manager.pool.contains(second.hash()));
3241
3242        import_verified(&mut tx_manager, first.clone()).await;
3243        let results = tx_manager.pool_imports.next().await.unwrap();
3244        tx_manager.on_batch_import_result(results);
3245        assert!(tx_manager.pool.contains(second.hash()));
3246        assert!(tx_manager.nonce_gapped_blob_txs.is_empty());
3247        assert!(tx_manager.importing_blob_txs.is_empty());
3248    }
3249
3250    #[tokio::test(flavor = "multi_thread")]
3251    async fn blob_tx_turned_away_for_a_nonce_gap_follows_a_previous_nonce_added_elsewhere() {
3252        let (mut tx_manager, _network) = new_tx_manager().await;
3253        let first = MockTransaction::eip4844();
3254        let second = first.next();
3255        import_verified(&mut tx_manager, second.clone()).await;
3256        assert!(!tx_manager.nonce_gapped_blob_txs.is_empty());
3257
3258        // The previous nonce arrives over RPC, not through the manager's imports.
3259        let pool = tx_manager.pool.clone();
3260        let mut pending = pool.pending_transactions_listener();
3261        tokio::spawn(tx_manager);
3262        pool.add_external_transaction(first).await.unwrap();
3263        tokio::time::timeout(Duration::from_secs(10), async {
3264            while pending.recv().await.unwrap() != *second.hash() {}
3265        })
3266        .await
3267        .unwrap();
3268    }
3269
3270    #[tokio::test(flavor = "multi_thread")]
3271    async fn blob_tx_turned_away_for_a_nonce_gap_retries_if_its_previous_nonce_arrived() {
3272        let (mut tx_manager, _network) = new_tx_manager().await;
3273        let first = MockTransaction::eip4844();
3274        let second = first.next();
3275
3276        tx_manager.import_verified_blob_transactions(vec![(PeerId::ZERO, second.clone())]);
3277        let results = tx_manager.pool_imports.next().await.unwrap();
3278        // The previous nonce was imported before the result of the second one was handled.
3279        tx_manager.pool.add_external_transaction(first).await.unwrap();
3280        tx_manager.on_batch_import_result(results);
3281
3282        let results = tx_manager.pool_imports.next().await.unwrap();
3283        tx_manager.on_batch_import_result(results);
3284        assert!(tx_manager.pool.contains(second.hash()));
3285    }
3286
3287    #[tokio::test(flavor = "multi_thread")]
3288    async fn blob_tx_after_a_pooled_nonce_is_not_kept_for_a_retry() {
3289        let (mut tx_manager, _network) = new_tx_manager().await;
3290        let first = MockTransaction::eip4844();
3291        let second = first.next();
3292        tx_manager.pool.add_external_transaction(first).await.unwrap();
3293
3294        tx_manager.import_verified_blob_transactions(vec![(PeerId::ZERO, second)]);
3295        assert!(tx_manager.importing_blob_txs.is_empty());
3296    }
3297
3298    #[tokio::test(flavor = "multi_thread")]
3299    async fn blob_tx_with_a_nonce_too_low_is_not_kept_for_a_retry() {
3300        let (mut tx_manager, _network) = new_tx_manager().await;
3301        let second = MockTransaction::eip4844().next();
3302        tx_manager.import_verified_blob_transactions(vec![(PeerId::ZERO, second.clone())]);
3303        assert!(!tx_manager.importing_blob_txs.is_empty());
3304
3305        // Both nonces were mined while the cells of the second transaction were checked.
3306        let err = PoolError::new(
3307            *second.hash(),
3308            InvalidPoolTransactionError::Consensus(InvalidTransactionError::NonceNotConsistent {
3309                tx: second.nonce(),
3310                state: second.nonce() + 1,
3311            }),
3312        );
3313        tx_manager.on_batch_import_result(vec![Err(err)]);
3314        assert!(tx_manager.importing_blob_txs.is_empty());
3315        assert!(tx_manager.nonce_gapped_blob_txs.is_empty());
3316    }
3317
3318    #[tokio::test(flavor = "multi_thread")]
3319    async fn blob_txs_checked_together_are_imported_in_nonce_order() {
3320        let (mut tx_manager, _network) = new_tx_manager().await;
3321        let first = MockTransaction::eip4844();
3322        let second = first.next();
3323
3324        tx_manager.import_verified_blob_transactions(vec![
3325            (PeerId::ZERO, second.clone()),
3326            (PeerId::ZERO, first),
3327        ]);
3328        let results = tx_manager.pool_imports.next().await.unwrap();
3329        assert!(results.iter().all(Result::is_ok));
3330        tx_manager.on_batch_import_result(results);
3331        // Neither a retry nor a kept copy is left behind.
3332        assert!(tx_manager.pool_imports.is_empty());
3333        assert!(tx_manager.importing_blob_txs.is_empty());
3334        assert!(tx_manager.pool.contains(second.hash()));
3335    }
3336
3337    #[tokio::test(flavor = "multi_thread")]
3338    async fn test_bad_blob_sidecar_not_cached_as_bad_import() {
3339        let (mut tx_manager, mut network) = new_tx_manager().await;
3340        let (sender, duplicate) = (PeerId::repeat_byte(1), PeerId::repeat_byte(2));
3341        let hash = B256::from_slice(&[1; 32]);
3342        tx_manager.transactions_by_peers.insert(hash, smallvec::smallvec![sender, duplicate]);
3343
3344        let err = PoolError::new(
3345            hash,
3346            InvalidPoolTransactionError::Eip4844(Eip4844PoolTransactionError::InvalidEip4844Blob(
3347                BlobTransactionValidationError::InvalidProof,
3348            )),
3349        );
3350        tx_manager.on_bad_import(err);
3351
3352        assert!(!tx_manager.bad_imports.contains(&hash));
3353        assert!(matches!(
3354            network.try_recv_handle_message(),
3355            Ok(NetworkHandleMessage::ReputationChange(peer, ReputationChangeKind::BadTransactions))
3356                if peer == sender
3357        ));
3358        assert!(matches!(network.try_recv_handle_message(), Err(mpsc::error::TryRecvError::Empty)));
3359    }
3360
3361    #[tokio::test(flavor = "multi_thread")]
3362    async fn test_missing_blob_sidecar_not_cached_as_bad_import() {
3363        let (mut tx_manager, _network) = new_tx_manager().await;
3364        let peer_id = PeerId::repeat_byte(1);
3365        let hash = B256::from_slice(&[3; 32]);
3366
3367        tx_manager.network.update_sync_state(SyncState::Idle);
3368        tx_manager.transactions_by_peers.insert(hash, smallvec::smallvec![peer_id]);
3369
3370        let err = PoolError::new(
3371            hash,
3372            InvalidPoolTransactionError::Eip4844(
3373                Eip4844PoolTransactionError::MissingEip4844BlobSidecar,
3374            ),
3375        );
3376
3377        tx_manager.on_bad_import(err);
3378
3379        assert!(!tx_manager.bad_imports.contains(&hash));
3380    }
3381
3382    #[tokio::test(flavor = "multi_thread")]
3383    async fn test_non_blob_sidecar_error_still_cached_as_bad_import() {
3384        let (mut tx_manager, _network) = new_tx_manager().await;
3385        let peer_id = PeerId::repeat_byte(1);
3386        let hash = B256::from_slice(&[2; 32]);
3387
3388        tx_manager.network.update_sync_state(SyncState::Idle);
3389        tx_manager.transactions_by_peers.insert(hash, smallvec::smallvec![peer_id]);
3390
3391        let err = PoolError::new(
3392            hash,
3393            InvalidPoolTransactionError::Eip4844(Eip4844PoolTransactionError::NoEip4844Blobs),
3394        );
3395
3396        tx_manager.on_bad_import(err);
3397
3398        assert!(tx_manager.bad_imports.contains(&hash));
3399    }
3400
3401    #[tokio::test(flavor = "multi_thread")]
3402    async fn test_on_get_pooled_transactions_network() {
3403        reth_tracing::init_test_tracing();
3404        let net = Testnet::create(2).await.spawn();
3405        let [peer0, peer1] = net.peers_array();
3406
3407        let listener0 = peer0.event_listener();
3408
3409        peer0.add_peer(peer1);
3410        let secret_key = SecretKey::new(&mut rand::rng());
3411
3412        let client = NoopProvider::default();
3413        let pool = testing_pool();
3414        let config = NetworkConfigBuilder::new(secret_key, Runtime::test())
3415            .disable_discovery()
3416            .listener_port(0)
3417            .build(client);
3418        let transactions_manager_config = config.transactions_manager_config.clone();
3419        let (network_handle, network, mut transactions, _) = NetworkManager::new(config)
3420            .await
3421            .unwrap()
3422            .into_builder()
3423            .transactions(pool.clone(), transactions_manager_config)
3424            .split_with_handle();
3425        tokio::task::spawn(network);
3426
3427        network_handle.update_sync_state(SyncState::Idle);
3428
3429        assert!(!NetworkInfo::is_syncing(&network_handle));
3430
3431        // wait for all initiator connections
3432        let mut established = listener0.take(2);
3433        while let Some(ev) = established.next().await {
3434            match ev {
3435                NetworkEvent::ActivePeerSession { .. } |
3436                NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => {
3437                    transactions.on_network_event(ev);
3438                }
3439                NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {}
3440                ev => {
3441                    error!("unexpected event {ev:?}")
3442                }
3443            }
3444        }
3445
3446        let tx = MockTransaction::eip1559();
3447        let _ = transactions
3448            .pool
3449            .add_transaction(reth_transaction_pool::TransactionOrigin::External, tx.clone())
3450            .await;
3451
3452        let request = GetPooledTransactions(vec![*tx.get_hash()]);
3453
3454        let (send, receive) =
3455            oneshot::channel::<RequestResult<PooledTransactions<PooledTransactionVariant>>>();
3456
3457        transactions.on_network_tx_event(NetworkTransactionEvent::GetPooledTransactions {
3458            peer_id: *peer1.peer_id(),
3459            request,
3460            response: send,
3461        });
3462
3463        match receive.await.unwrap() {
3464            Ok(PooledTransactions(transactions)) => {
3465                assert_eq!(transactions.len(), 1);
3466            }
3467            Err(e) => {
3468                panic!("error: {e:?}");
3469            }
3470        }
3471
3472        // requests above the hash count soft limit are served up to the limit
3473        let mut hashes = vec![*tx.get_hash()];
3474        for _ in 0..SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST {
3475            let tx = MockTransaction::eip1559();
3476            hashes.push(*tx.get_hash());
3477            transactions
3478                .pool
3479                .add_transaction(reth_transaction_pool::TransactionOrigin::External, tx)
3480                .await
3481                .unwrap();
3482        }
3483
3484        let (send, receive) =
3485            oneshot::channel::<RequestResult<PooledTransactions<PooledTransactionVariant>>>();
3486        transactions.on_network_tx_event(NetworkTransactionEvent::GetPooledTransactions {
3487            peer_id: *peer1.peer_id(),
3488            request: GetPooledTransactions(hashes.clone()),
3489            response: send,
3490        });
3491
3492        let PooledTransactions(served) = receive.await.unwrap().unwrap();
3493        let served = served.iter().map(|tx| *tx.tx_hash()).collect::<Vec<_>>();
3494        assert_eq!(served, hashes[..SOFT_LIMIT_COUNT_HASHES_IN_GET_POOLED_TRANSACTIONS_REQUEST]);
3495    }
3496
3497    // Ensure that when the remote peer only returns part of the requested transactions, the
3498    // replied transactions are removed from the `tx_fetcher`, while the unresponsive ones are
3499    // re-buffered.
3500    #[tokio::test]
3501    async fn test_partially_tx_response() {
3502        reth_tracing::init_test_tracing();
3503
3504        let mut tx_manager = new_tx_manager().await.0;
3505        let tx_fetcher = &mut tx_manager.transaction_fetcher;
3506
3507        let peer_id_1 = PeerId::repeat_byte(1);
3508        let eth_version = EthVersion::Eth66;
3509
3510        let txs = vec![
3511            TransactionSigned::new_unhashed(
3512                Transaction::Legacy(TxLegacy {
3513                    chain_id: Some(4),
3514                    nonce: 15u64,
3515                    gas_price: 2200000000,
3516                    gas_limit: 34811,
3517                    to: TxKind::Call(address!("cf7f9e66af820a19257a2108375b180b0ec49167")),
3518                    value: U256::from(1234u64),
3519                    input: Default::default(),
3520                }),
3521                Signature::new(
3522                    U256::from_str(
3523                        "0x35b7bfeb9ad9ece2cbafaaf8e202e706b4cfaeb233f46198f00b44d4a566a981",
3524                    )
3525                    .unwrap(),
3526                    U256::from_str(
3527                        "0x612638fb29427ca33b9a3be2a0a561beecfe0269655be160d35e72d366a6a860",
3528                    )
3529                    .unwrap(),
3530                    true,
3531                ),
3532            ),
3533            TransactionSigned::new_unhashed(
3534                Transaction::Eip1559(TxEip1559 {
3535                    chain_id: 4,
3536                    nonce: 26u64,
3537                    max_priority_fee_per_gas: 1500000000,
3538                    max_fee_per_gas: 1500000013,
3539                    gas_limit: MIN_TRANSACTION_GAS,
3540                    to: TxKind::Call(address!("61815774383099e24810ab832a5b2a5425c154d5")),
3541                    value: U256::from(3000000000000000000u64),
3542                    input: Default::default(),
3543                    access_list: Default::default(),
3544                }),
3545                Signature::new(
3546                    U256::from_str(
3547                        "0x59e6b67f48fb32e7e570dfb11e042b5ad2e55e3ce3ce9cd989c7e06e07feeafd",
3548                    )
3549                    .unwrap(),
3550                    U256::from_str(
3551                        "0x016b83f4f980694ed2eee4d10667242b1f40dc406901b34125b008d334d47469",
3552                    )
3553                    .unwrap(),
3554                    true,
3555                ),
3556            ),
3557        ];
3558
3559        let txs_hashes: Vec<B256> = txs.iter().map(|tx| *tx.hash()).collect();
3560
3561        let (mut peer_1, mut to_mock_session_rx) = new_mock_session(peer_id_1, eth_version);
3562        // mark hashes as seen by peer so it can fish them out from the cache for hashes pending
3563        // fetch
3564        peer_1.seen_transactions.insert(txs_hashes[0]);
3565        peer_1.seen_transactions.insert(txs_hashes[1]);
3566        tx_manager.peers.insert(peer_id_1, peer_1);
3567
3568        buffer_hash_to_tx_fetcher(tx_fetcher, txs_hashes[0], peer_id_1, None);
3569        buffer_hash_to_tx_fetcher(tx_fetcher, txs_hashes[1], peer_id_1, None);
3570
3571        // peer_1 is idle
3572        assert!(tx_fetcher.is_idle(&peer_id_1));
3573        assert_eq!(tx_fetcher.num_inflight_requests(), 0);
3574
3575        // sends requests for buffered hashes to peer_1
3576        assert_eq!(tx_fetcher.dispatch(&tx_manager.peers, usize::MAX), 1);
3577
3578        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
3579        // as long as request is in flight peer_1 is not idle
3580        assert!(!tx_fetcher.is_idle(&peer_id_1));
3581        assert_eq!(tx_fetcher.num_inflight_requests(), 1);
3582
3583        // mock session of peer_1 receives request
3584        let req = to_mock_session_rx
3585            .recv()
3586            .await
3587            .expect("peer_1 session should receive request with buffered hashes");
3588        let PeerRequest::GetPooledTransactions { response, .. } = req else { unreachable!() };
3589
3590        let message: Vec<PooledTransactionVariant> = txs
3591            .into_iter()
3592            .take(1)
3593            .map(|tx| {
3594                PooledTransactionVariant::try_from(tx)
3595                    .expect("Failed to convert MockTransaction to PooledTransaction")
3596            })
3597            .collect();
3598        // response partial request
3599        response
3600            .send(Ok(PooledTransactions(message)))
3601            .expect("should send peer_1 response to tx manager");
3602        let Some(FetchEvent::TransactionsFetched { peer_id, .. }) = tx_fetcher.next().await else {
3603            unreachable!()
3604        };
3605
3606        // request has resolved, peer_1 is idle again
3607        assert!(tx_fetcher.is_idle(&peer_id));
3608        assert_eq!(tx_fetcher.num_inflight_requests(), 0);
3609        // the undelivered hash at the end of the request is retried with peer_1
3610        assert_eq!(tx_fetcher.num_pending_hashes(), 1);
3611        assert_eq!(tx_fetcher.candidate_peers(&txs_hashes[1]), vec![peer_id_1]);
3612    }
3613
3614    /// Tests that hashes of a failed request are retried with the alternate peer that announced
3615    /// them, and are given up on when no peer is left to fetch them from.
3616    #[tokio::test]
3617    async fn test_failed_request_retries_on_alternate_peer() {
3618        reth_tracing::init_test_tracing();
3619
3620        let mut tx_manager = new_tx_manager().await.0;
3621        let tx_fetcher = &mut tx_manager.transaction_fetcher;
3622
3623        let peer_id_1 = PeerId::repeat_byte(1);
3624        let peer_id_2 = PeerId::repeat_byte(2);
3625        let eth_version = EthVersion::Eth66;
3626        let seen_hashes = [B256::from_slice(&[1; 32]), B256::from_slice(&[2; 32])];
3627
3628        let (peer_1, mut to_mock_session_rx_1) = new_mock_session(peer_id_1, eth_version);
3629        let (peer_2, mut to_mock_session_rx_2) = new_mock_session(peer_id_2, eth_version);
3630        tx_manager.peers.insert(peer_id_1, peer_1);
3631        tx_manager.peers.insert(peer_id_2, peer_2);
3632
3633        // both peers announce the hashes, peer_1 first
3634        for hash in seen_hashes {
3635            buffer_hash_to_tx_fetcher(tx_fetcher, hash, peer_id_1, None);
3636            buffer_hash_to_tx_fetcher(tx_fetcher, hash, peer_id_2, None);
3637        }
3638        assert!(tx_fetcher.is_idle(&peer_id_1));
3639        assert!(tx_fetcher.is_idle(&peer_id_2));
3640
3641        // the hashes are requested from peer_1 only
3642        assert_eq!(tx_fetcher.dispatch(&tx_manager.peers, usize::MAX), 1);
3643        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
3644        assert!(!tx_fetcher.is_idle(&peer_id_1));
3645        assert!(tx_fetcher.is_idle(&peer_id_2));
3646
3647        let req = to_mock_session_rx_1
3648            .recv()
3649            .await
3650            .expect("peer_1 session should receive request with buffered hashes");
3651        let PeerRequest::GetPooledTransactions { request, response } = req else { unreachable!() };
3652        let GetPooledTransactions(hashes) = request;
3653        assert_eq!(
3654            hashes.into_iter().collect::<B256Set>(),
3655            seen_hashes.into_iter().collect::<B256Set>()
3656        );
3657
3658        // fail request to peer_1
3659        response
3660            .send(Err(RequestError::BadResponse))
3661            .expect("should send peer_1 response to tx manager");
3662        let Some(FetchEvent::FetchError { peer_id, .. }) = tx_fetcher.next().await else {
3663            unreachable!()
3664        };
3665        assert_eq!(peer_id, peer_id_1);
3666
3667        // request has resolved, peer_1 is idle again and the hashes are pending for peer_2 only
3668        assert!(tx_fetcher.is_idle(&peer_id_1));
3669        assert_eq!(tx_fetcher.num_inflight_requests(), 0);
3670        assert_eq!(tx_fetcher.num_pending_hashes(), 2);
3671        assert_eq!(tx_fetcher.candidate_peers(&seen_hashes[0]), vec![peer_id_2]);
3672
3673        // the hashes are retried with peer_2
3674        assert_eq!(tx_fetcher.dispatch(&tx_manager.peers, usize::MAX), 1);
3675        assert_eq!(tx_fetcher.num_pending_hashes(), 0);
3676        let req = to_mock_session_rx_2
3677            .recv()
3678            .await
3679            .expect("peer_2 session should receive request with buffered hashes");
3680        let PeerRequest::GetPooledTransactions { response, .. } = req else { unreachable!() };
3681
3682        // fail request to peer_2 as well
3683        response
3684            .send(Err(RequestError::BadResponse))
3685            .expect("should send peer_2 response to tx manager");
3686        let Some(FetchEvent::FetchError { .. }) = tx_fetcher.next().await else { unreachable!() };
3687
3688        // no peer is left to fetch the hashes from, they are dropped
3689        assert_eq!(tx_fetcher.num_hashes(), 0);
3690        assert_eq!(tx_fetcher.num_inflight_requests(), 0);
3691    }
3692
3693    #[test]
3694    fn test_direct_propagation_transaction_uses_2718_size() {
3695        let mut tx_gen = TransactionGenerator::new(rand::rng());
3696        let tx = tx_gen.gen_eip1559();
3697        let expected_size = tx.encode_2718_len();
3698
3699        let tx = PropagateTransaction::new(tx);
3700
3701        assert_eq!(tx.propagation_size(), expected_size);
3702    }
3703
3704    #[test]
3705    fn test_blob_transactions_are_announced_with_their_cells() {
3706        let sidecar = BlobTransactionSidecarEip7594::new(
3707            vec![Blob::repeat_byte(1)],
3708            vec![Bytes48::repeat_byte(2)],
3709            vec![Bytes48::repeat_byte(3); CELLS_PER_EXT_BLOB],
3710        );
3711        let blob_tx = |nonce, mask| {
3712            let tx = PooledTransactionVariant::Eip4844(
3713                TxEip4844WithSidecar {
3714                    tx: TxEip4844 {
3715                        nonce,
3716                        blob_versioned_hashes: vec![B256::ZERO],
3717                        ..Default::default()
3718                    },
3719                    sidecar: sidecar.clone().into(),
3720                }
3721                .into_signed(Signature::test_signature()),
3722            );
3723            let mut tx =
3724                EthPooledTransaction::from_pooled(Recovered::new_unchecked(tx, Address::ZERO));
3725            tx.blob_cell_availability = Some(BlobCellAvailability::new(mask));
3726            valid_eth_pool_transaction(tx)
3727        };
3728        let all = BlobCellMask::ALL;
3729        let custody = BlobCellMask::from_bits(0b11);
3730        let plain =
3731            valid_eth_pool_transaction(TransactionGenerator::new(rand::rng()).gen_eip1559_pooled());
3732        let provider = blob_tx(0, all);
3733        let sampler = blob_tx(1, custody);
3734
3735        // An eth/72 announcement has one mask for its blob transactions, so each mask gets its own
3736        // announcement, while other transactions join the first one.
3737        for push in [true, false] {
3738            let mut builder = PooledTransactionsHashesBuilder::new(EthVersion::Eth72);
3739            for tx in [&sampler, &plain, &provider] {
3740                if push {
3741                    builder.push(&PropagateTransaction::pool_tx(tx.clone()));
3742                } else {
3743                    builder.push_pooled(tx.clone());
3744                }
3745            }
3746            let announced: Vec<_> = builder
3747                .build()
3748                .iter()
3749                .map(|msg| {
3750                    let msg = msg.as_eth72().unwrap();
3751                    (msg.hashes.clone(), msg.cell_mask)
3752                })
3753                .collect();
3754            assert_eq!(
3755                announced,
3756                [
3757                    (vec![*sampler.hash(), *plain.hash()], Some(custody.to_b128())),
3758                    (vec![*provider.hash()], Some(NewPooledTransactionHashes72::ALL_CELLS_MASK)),
3759                ]
3760            );
3761        }
3762
3763        // Older peers need the blobs, which the sampler can't rebuild.
3764        let sampler = PropagateTransaction::pool_tx(sampler);
3765        assert!(sampler.can_announce_to(EthVersion::Eth72));
3766        assert!(!sampler.can_announce_to(EthVersion::Eth71));
3767        let mut builder = PooledTransactionsHashesBuilder::new(EthVersion::Eth68);
3768        builder.push(&PropagateTransaction::pool_tx(provider.clone()));
3769        builder.push(&sampler);
3770        let [NewPooledTransactionHashes::Eth68(msg)] = &builder.build()[..] else {
3771            panic!("expected one eth/68 announcement")
3772        };
3773        assert_eq!(msg.hashes, vec![*provider.hash()]);
3774    }
3775
3776    #[test]
3777    fn test_blob_transaction_announced_size_matches_served_body() {
3778        let sidecar = BlobTransactionSidecarEip7594::new(
3779            vec![Blob::repeat_byte(1); 2],
3780            vec![Bytes48::repeat_byte(2); 2],
3781            vec![Bytes48::repeat_byte(3); 2 * CELLS_PER_EXT_BLOB],
3782        );
3783        let full = PooledTransactionVariant::Eip4844(
3784            TxEip4844WithSidecar {
3785                tx: TxEip4844 { blob_versioned_hashes: vec![B256::ZERO; 2], ..Default::default() },
3786                sidecar: sidecar.into(),
3787            }
3788            .into_signed(Signature::test_signature()),
3789        );
3790        let mut without_blobs = full.clone();
3791        without_blobs.clear_eip7594_blobs();
3792        let pool_tx = valid_eth_pool_transaction(EthPooledTransaction::from_pooled(
3793            Recovered::new_unchecked(full.clone(), Address::ZERO),
3794        ));
3795        let tx = PropagateTransaction::pool_tx(pool_tx.clone());
3796
3797        // eth/72 peers are served blob transactions without their blobs, both in gossip and in the
3798        // announcement sent when a session is established.
3799        for (version, served) in [
3800            (EthVersion::Eth71, &full),
3801            (EthVersion::Eth72, &without_blobs),
3802            (EthVersion::Eth73, &without_blobs),
3803        ] {
3804            let mut builder = PooledTransactionsHashesBuilder::new(version);
3805            builder.push(&tx);
3806            builder.push_pooled(pool_tx.clone());
3807            let sizes = match &builder.build()[..] {
3808                [NewPooledTransactionHashes::Eth68(msg)] => msg.sizes.clone(),
3809                [NewPooledTransactionHashes::Eth72(msg)] => {
3810                    assert_eq!(msg.cell_mask, Some(NewPooledTransactionHashes72::ALL_CELLS_MASK));
3811                    msg.sizes.clone()
3812                }
3813                msgs => panic!("unexpected announcements {msgs:?}"),
3814            };
3815            assert_eq!(sizes, vec![served.encode_2718_len(); 2]);
3816        }
3817    }
3818
3819    #[test]
3820    fn test_transaction_builder_empty() {
3821        let mut builder = PropagateTransactionsBuilder::pooled(EthVersion::Eth68, 0);
3822        assert!(builder.is_empty());
3823
3824        let mut tx_gen = TransactionGenerator::new(rand::rng());
3825        let tx =
3826            PropagateTransaction::pool_tx(valid_eth_pool_transaction(tx_gen.gen_eip1559_pooled()));
3827        builder.push(&tx);
3828        assert!(!builder.is_empty());
3829
3830        let txs = builder.build();
3831        assert!(txs.full.is_none());
3832        let [txs] = &txs.pooled[..] else { panic!("expected one announcement") };
3833        assert_eq!(txs.len(), 1);
3834    }
3835
3836    #[test]
3837    fn test_pooled_propagation_transaction_encoder_length_matches_network_encoding() {
3838        let mut tx_gen = TransactionGenerator::new(rand::rng());
3839        let tx = valid_eth_pool_transaction(tx_gen.gen_eip1559_pooled());
3840        let pooled = PropagatePooledTransactionEncoder::new(tx);
3841
3842        let mut pooled_encoded = Vec::new();
3843        pooled.encode(&mut pooled_encoded);
3844        assert_eq!(pooled.length(), pooled_encoded.len());
3845
3846        let broadcast = BroadcastPoolTransactions(vec![LazyEncoded::new(pooled)]);
3847        let mut first_encoded = Vec::new();
3848        broadcast.encode(&mut first_encoded);
3849        let mut second_encoded = Vec::new();
3850        broadcast.encode(&mut second_encoded);
3851        assert_eq!(first_encoded, second_encoded);
3852
3853        let mut encoded = first_encoded.as_slice();
3854        let decoded = Transactions::<TransactionSigned>::decode(&mut encoded).unwrap();
3855        assert_eq!(decoded.len(), 1);
3856        assert!(encoded.is_empty());
3857    }
3858
3859    #[test]
3860    fn test_transaction_builder_large() {
3861        let mut builder = PropagateTransactionsBuilder::full(EthVersion::Eth68, 0);
3862        assert!(builder.is_empty());
3863
3864        let mut tx_gen = TransactionGenerator::new(rand::rng());
3865        let mut tx = tx_gen.gen_eip1559_pooled();
3866        // create a transaction that still fits
3867        tx.encoded_length = DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE + 1;
3868        let tx = PropagateTransaction::pool_tx(valid_eth_pool_transaction(tx));
3869        builder.push(&tx);
3870        assert!(!builder.is_empty());
3871
3872        let txs = builder.clone().build();
3873        assert!(txs.pooled.is_empty());
3874        let txs = txs.full.unwrap();
3875        assert_eq!(txs.len(), 1);
3876
3877        builder.push(&tx);
3878
3879        let txs = builder.clone().build();
3880        let [pooled] = &txs.pooled[..] else { panic!("expected one announcement") };
3881        assert_eq!(pooled.len(), 1);
3882        let txs = txs.full.unwrap();
3883        assert_eq!(txs.len(), 1);
3884    }
3885
3886    #[test]
3887    fn test_transaction_builder_eip4844() {
3888        let mut builder = PropagateTransactionsBuilder::full(EthVersion::Eth68, 0);
3889        assert!(builder.is_empty());
3890
3891        let mut tx_gen = TransactionGenerator::new(rand::rng());
3892        let tx =
3893            PropagateTransaction::pool_tx(valid_eth_pool_transaction(tx_gen.gen_eip4844_pooled()));
3894        builder.push(&tx);
3895        assert!(!builder.is_empty());
3896
3897        let txs = builder.clone().build();
3898        assert!(txs.full.is_none());
3899        let [txs] = &txs.pooled[..] else { panic!("expected one announcement") };
3900        assert_eq!(txs.len(), 1);
3901
3902        let tx =
3903            PropagateTransaction::pool_tx(valid_eth_pool_transaction(tx_gen.gen_eip1559_pooled()));
3904        builder.push(&tx);
3905
3906        let txs = builder.clone().build();
3907        let [pooled] = &txs.pooled[..] else { panic!("expected one announcement") };
3908        assert_eq!(pooled.len(), 1);
3909        let txs = txs.full.unwrap();
3910        assert_eq!(txs.len(), 1);
3911    }
3912
3913    #[tokio::test]
3914    async fn test_propagate_full() {
3915        reth_tracing::init_test_tracing();
3916
3917        let (mut tx_manager, network) = new_eth_tx_manager(OkValidator::default()).await;
3918        let peer_id = PeerId::random();
3919
3920        // ensure not syncing
3921        network.handle().update_sync_state(SyncState::Idle);
3922
3923        // mock a peer
3924        let (tx, _rx) = mpsc::channel::<PeerRequest>(1);
3925
3926        let session_info = SessionInfo {
3927            peer_id,
3928            remote_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
3929            client_version: Arc::from(""),
3930            capabilities: Arc::new(vec![].into()),
3931            status: Arc::new(Default::default()),
3932            version: EthVersion::Eth68,
3933            peer_kind: PeerKind::Basic,
3934        };
3935        let messages: PeerRequestSender<PeerRequest> = PeerRequestSender::new(peer_id, tx);
3936        tx_manager
3937            .on_network_event(NetworkEvent::ActivePeerSession { info: session_info, messages });
3938        let mut propagate = vec![];
3939        let mut tx_gen = TransactionGenerator::new(rand::rng());
3940        let eip1559_tx = valid_eth_pool_transaction(tx_gen.gen_eip1559_pooled());
3941        propagate.push(eip1559_tx.clone());
3942        let eip4844_tx = valid_eth_pool_transaction(tx_gen.gen_eip4844_pooled());
3943        propagate.push(eip4844_tx.clone());
3944
3945        let propagated = tx_manager.propagate_transactions(
3946            propagate.clone().into_iter().map(PropagateTransaction::pool_tx).collect(),
3947            PropagationMode::Basic,
3948        );
3949        assert_eq!(propagated.len(), 2);
3950        let prop_txs = propagated.get(eip1559_tx.transaction.hash()).unwrap();
3951        assert_eq!(prop_txs.len(), 1);
3952        assert!(prop_txs[0].is_full());
3953
3954        let prop_txs = propagated.get(eip4844_tx.transaction.hash()).unwrap();
3955        assert_eq!(prop_txs.len(), 1);
3956        assert!(prop_txs[0].is_hash());
3957
3958        let peer = tx_manager.peers.get(&peer_id).unwrap();
3959        assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash()));
3960        assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash()));
3961        peer.seen_transactions.contains(eip4844_tx.transaction.hash());
3962
3963        // propagate again
3964        let propagated = tx_manager.propagate_transactions(
3965            propagate.into_iter().map(PropagateTransaction::pool_tx).collect(),
3966            PropagationMode::Basic,
3967        );
3968        assert!(propagated.is_empty());
3969    }
3970
3971    #[tokio::test(flavor = "multi_thread")]
3972    async fn broadcast_announces_blob_transactions_from_the_pool() {
3973        let sidecar = BlobTransactionSidecarEip7594::new(
3974            vec![Blob::default()],
3975            vec![Bytes48::ZERO],
3976            vec![Bytes48::ZERO; CELLS_PER_EXT_BLOB],
3977        );
3978        let tx = TxEip4844 {
3979            max_fee_per_gas: MIN_PROTOCOL_BASE_FEE.into(),
3980            gas_limit: MIN_TRANSACTION_GAS,
3981            blob_versioned_hashes: sidecar.versioned_hashes().collect(),
3982            ..Default::default()
3983        };
3984        let tx = TxEip4844WithSidecar { tx, sidecar: sidecar.into() }
3985            .into_signed(Signature::test_signature());
3986        let pooled = EthPooledTransaction::from_pooled(Recovered::new_unchecked(
3987            PooledTransactionVariant::Eip4844(tx),
3988            Address::ZERO,
3989        ));
3990        let unpooled = TransactionGenerator::new(rand::rng()).gen_eip4844_pooled();
3991        for propagate in [true, false] {
3992            let validator = OkValidator::default().set_propagate_transactions(propagate);
3993            let (mut tx_manager, network) = new_eth_tx_manager(validator).await;
3994            network.handle().update_sync_state(SyncState::Idle);
3995            let peer_id = PeerId::random();
3996            let (peer, _rx) = new_mock_session(peer_id, EthVersion::Eth72);
3997            tx_manager.peers.insert(peer_id, peer);
3998            tx_manager.pool.add_external_transaction(pooled.clone()).await.unwrap();
3999            tx_manager
4000                .pool
4001                .blob_store()
4002                .insert(*pooled.hash(), pooled.blob_sidecar().unwrap().clone())
4003                .unwrap();
4004
4005            let txs = [&pooled, &unpooled]
4006                .map(|tx| PropagateTransaction::new(tx.clone_into_consensus().into_inner()));
4007            assert!(!txs[0].can_announce_to(EthVersion::Eth72));
4008            tx_manager.on_command(TransactionsCommand::BroadcastTransactions(txs.into()));
4009            let seen = &tx_manager.peers[&peer_id].seen_transactions;
4010            assert_eq!(seen.contains(pooled.hash()), propagate);
4011            assert!(!seen.contains(unpooled.hash()));
4012
4013            let (response, mut received) = oneshot::channel();
4014            tx_manager.on_get_pooled_transactions(
4015                peer_id,
4016                GetPooledTransactions(vec![*pooled.hash()]),
4017                response,
4018            );
4019            let served = received.try_recv().unwrap().unwrap();
4020            assert_eq!(served.first().map(|tx| tx.tx_hash()), propagate.then_some(pooled.hash()));
4021        }
4022    }
4023
4024    #[test]
4025    fn test_eth72_hashes_without_a_cell_sidecar() {
4026        let mut tx_gen = TransactionGenerator::new(rand::rng());
4027
4028        // no blob transactions: the mask stays unset and encodes as a zero mask
4029        let mut builder = PooledTransactionsHashesBuilder::new(EthVersion::Eth72);
4030        builder.push(&PropagateTransaction::pool_tx(valid_eth_pool_transaction(
4031            tx_gen.gen_eip1559_pooled(),
4032        )));
4033        let [msg] = &builder.build()[..] else { panic!("expected one announcement") };
4034        assert_eq!(msg.as_eth72().unwrap().cell_mask, None);
4035
4036        // A blob transaction without a known cell sidecar cannot be served over eth/72.
4037        let legacy = PooledTransactionVariant::Eip4844(
4038            TxEip4844WithSidecar {
4039                tx: TxEip4844 { blob_versioned_hashes: vec![B256::ZERO], ..Default::default() },
4040                sidecar: BlobTransactionSidecar::new(
4041                    vec![Blob::default()],
4042                    vec![Bytes48::ZERO],
4043                    vec![Bytes48::ZERO],
4044                )
4045                .into(),
4046            }
4047            .into_signed(Signature::test_signature()),
4048        );
4049        for blob in [
4050            tx_gen.gen_eip4844_pooled(),
4051            EthPooledTransaction::from_pooled(Recovered::new_unchecked(legacy, Address::ZERO)),
4052        ] {
4053            let blob = valid_eth_pool_transaction(blob);
4054            let mut builder = PooledTransactionsHashesBuilder::new(EthVersion::Eth72);
4055            builder.push(&PropagateTransaction::pool_tx(blob.clone()));
4056            builder.push_pooled(blob);
4057            assert!(builder.build().is_empty());
4058        }
4059    }
4060
4061    #[tokio::test]
4062    async fn test_truncated_hash_announcement_not_marked_seen() {
4063        reth_tracing::init_test_tracing();
4064
4065        let (mut tx_manager, network) = new_eth_tx_manager(OkValidator::default()).await;
4066        // all peers receive hash announcements only
4067        tx_manager.config.propagation_mode = TransactionPropagationMode::Max(0);
4068
4069        // ensure not syncing
4070        network.handle().update_sync_state(SyncState::Idle);
4071
4072        let peer_id = PeerId::random();
4073        let (peer, _rx) = new_mock_session(peer_id, EthVersion::Eth68);
4074        tx_manager.peers.insert(peer_id, peer);
4075
4076        // one more transaction than fits into a single hashes broadcast message
4077        let mut tx_gen = TransactionGenerator::new(rand::rng());
4078        let txs = (0..=SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE)
4079            .map(|nonce| {
4080                valid_eth_pool_transaction(gen_eip1559_pooled_with_nonce(&mut tx_gen, nonce as u64))
4081            })
4082            .collect::<Vec<_>>();
4083        let last_sent = *txs[txs.len() - 2].hash();
4084        let truncated = *txs[txs.len() - 1].hash();
4085
4086        let propagated = tx_manager.propagate_transactions(
4087            txs.into_iter().map(PropagateTransaction::pool_tx).collect(),
4088            PropagationMode::Basic,
4089        );
4090
4091        // the truncated hash was not sent, so it must not be tracked as seen by the peer
4092        assert!(propagated.get(&truncated).is_none());
4093        let peer = tx_manager.peers.get(&peer_id).unwrap();
4094        assert!(!peer.seen_transactions.contains(&truncated));
4095        assert!(peer.seen_transactions.contains(&last_sent));
4096    }
4097
4098    #[tokio::test]
4099    async fn test_propagate_pending_txs_while_initially_syncing() {
4100        reth_tracing::init_test_tracing();
4101
4102        let (mut tx_manager, network) = new_eth_tx_manager(OkValidator::default()).await;
4103        let peer_id = PeerId::random();
4104
4105        // Keep the node in initial sync mode.
4106        network.handle().update_sync_state(SyncState::Syncing);
4107        assert!(NetworkInfo::is_initially_syncing(&network.handle()));
4108
4109        // Add a peer so propagation has a destination.
4110        let (peer, _rx) = new_mock_session(peer_id, EthVersion::Eth68);
4111        tx_manager.peers.insert(peer_id, peer);
4112
4113        let mut tx_gen = TransactionGenerator::new(rand::rng());
4114        let tx = gen_eip1559_pooled_with_nonce(&mut tx_gen, 0);
4115        let tx_hash = *tx.hash();
4116        tx_manager
4117            .pool
4118            .add_transaction(reth_transaction_pool::TransactionOrigin::External, tx.clone())
4119            .await
4120            .expect("transaction should be accepted into the pool");
4121
4122        tx_manager.on_new_pending_transactions(vec![tx_hash]);
4123
4124        let peer = tx_manager.peers.get(&peer_id).expect("peer should exist");
4125        assert!(peer.seen_transactions.contains(&tx_hash));
4126    }
4127
4128    #[tokio::test]
4129    async fn test_relaxed_filter_ignores_unknown_tx_types() {
4130        reth_tracing::init_test_tracing();
4131
4132        let transactions_manager_config = TransactionsManagerConfig::default();
4133
4134        let propagation_policy = TransactionPropagationKind::default();
4135        let announcement_policy = RelaxedEthAnnouncementFilter::default();
4136
4137        let policy_bundle = NetworkPolicies::new(propagation_policy, announcement_policy);
4138
4139        let pool = testing_pool();
4140        let secret_key = SecretKey::new(&mut rand::rng());
4141        let client = NoopProvider::default();
4142
4143        let network_config = NetworkConfigBuilder::new(secret_key, Runtime::test())
4144            .listener_port(0)
4145            .disable_discovery()
4146            .build(client.clone());
4147
4148        let mut network_manager = NetworkManager::new(network_config).await.unwrap();
4149        let (to_tx_manager_tx, from_network_rx) =
4150            reth_metrics::common::mpsc::memory_bounded_channel::<
4151                NetworkTransactionEvent<EthNetworkPrimitives>,
4152            >(
4153                crate::transactions::constants::tx_manager::DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
4154                "test_tx_channel",
4155            );
4156        network_manager.set_transactions(to_tx_manager_tx);
4157        let network_handle = network_manager.handle().clone();
4158        let network_service_handle = tokio::spawn(network_manager);
4159
4160        let mut tx_manager = TransactionsManager::<TestPool, EthNetworkPrimitives>::with_policy(
4161            network_handle.clone(),
4162            pool.clone(),
4163            from_network_rx,
4164            transactions_manager_config,
4165            policy_bundle,
4166        );
4167
4168        let peer_id = PeerId::random();
4169        let eth_version = EthVersion::Eth68;
4170        let (mock_peer_metadata, mut mock_session_rx) = new_mock_session(peer_id, eth_version);
4171        tx_manager.peers.insert(peer_id, mock_peer_metadata);
4172
4173        let mut tx_factory = MockTransactionFactory::default();
4174
4175        let valid_known_tx = tx_factory.create_eip1559();
4176        let known_tx_signed: Arc<ValidPoolTransaction<MockTransaction>> = Arc::new(valid_known_tx);
4177
4178        let known_tx_hash = *known_tx_signed.hash();
4179        let known_tx_type_byte = known_tx_signed.transaction.tx_type();
4180        let known_tx_size = known_tx_signed.encoded_length();
4181
4182        let unknown_tx_hash = B256::random();
4183        let unknown_tx_type_byte = 0xff_u8;
4184        let unknown_tx_size = 150;
4185
4186        let announcement_msg = NewPooledTransactionHashes::Eth68(NewPooledTransactionHashes68 {
4187            types: vec![known_tx_type_byte, unknown_tx_type_byte],
4188            sizes: vec![known_tx_size, unknown_tx_size],
4189            hashes: vec![known_tx_hash, unknown_tx_hash],
4190        });
4191
4192        tx_manager.on_new_pooled_transaction_hashes(peer_id, announcement_msg);
4193
4194        poll_fn(|cx| {
4195            let _ = tx_manager.poll_unpin(cx);
4196            Poll::Ready(())
4197        })
4198        .await;
4199
4200        let mut requested_hashes_in_getpooled = B256Set::default();
4201        let mut unexpected_request_received = false;
4202
4203        match tokio::time::timeout(std::time::Duration::from_millis(200), mock_session_rx.recv())
4204            .await
4205        {
4206            Ok(Some(PeerRequest::GetPooledTransactions { request, response: tx_response_ch })) => {
4207                let GetPooledTransactions(hashes) = request;
4208                for hash in hashes {
4209                    requested_hashes_in_getpooled.insert(hash);
4210                }
4211                let _ = tx_response_ch.send(Ok(PooledTransactions(vec![])));
4212            }
4213            Ok(Some(other_request)) => {
4214                tracing::error!(?other_request, "Received unexpected PeerRequest type");
4215                unexpected_request_received = true;
4216            }
4217            Ok(None) => tracing::info!("Mock session channel closed or no request received."),
4218            Err(_timeout_err) => {
4219                tracing::info!("Timeout: No GetPooledTransactions request received.")
4220            }
4221        }
4222
4223        assert!(
4224            requested_hashes_in_getpooled.contains(&known_tx_hash),
4225            "Should have requested the known EIP-1559 transaction. Requested: {requested_hashes_in_getpooled:?}"
4226        );
4227        assert!(
4228            !requested_hashes_in_getpooled.contains(&unknown_tx_hash),
4229            "Should NOT have requested the unknown transaction type. Requested: {requested_hashes_in_getpooled:?}"
4230        );
4231        assert!(
4232            !unexpected_request_received,
4233            "An unexpected P2P request was received by the mock peer."
4234        );
4235
4236        network_service_handle.abort();
4237    }
4238}