Skip to main content

reth_network/transactions/
config.rs

1use core::fmt;
2use std::{fmt::Debug, str::FromStr};
3
4use super::{
5    PeerMetadata, DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER,
6    DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
7    SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
8};
9use crate::transactions::constants::{
10    tx_fetcher::{
11        DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH, DEFAULT_MAX_COUNT_ANNOUNCED_HASHES_PER_PEER,
12        DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS, DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
13    },
14    tx_manager::{
15        DEFAULT_MAX_BYTE_SIZE_PENDING_POOL_IMPORTS, DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
16        DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
17    },
18};
19use alloy_eips::eip2718::IsTyped2718;
20use alloy_primitives::B256;
21use derive_more::Display;
22use reth_eth_wire::NetworkPrimitives;
23use reth_network_types::peers::kind::PeerKind;
24
25/// Configuration for managing transactions within the network.
26#[derive(Debug, Clone)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub struct TransactionsManagerConfig {
29    /// Configuration for fetching transactions.
30    pub transaction_fetcher_config: TransactionFetcherConfig,
31    /// Max number of seen transactions to store for each peer.
32    pub max_transactions_seen_by_peer_history: u32,
33    /// Soft limit on concurrent transaction imports. A fetched response admitted while capacity
34    /// remains may exceed this limit by at most 255 transactions; broadcasts are truncated to fit.
35    #[cfg_attr(feature = "serde", serde(default = "default_max_pending_pool_imports"))]
36    pub max_pending_pool_imports: usize,
37    /// Soft limit on the encoded byte size of concurrent transaction imports, including blob
38    /// sidecars. A fetched response admitted while capacity remains may exceed this limit by one
39    /// response message; broadcasts are truncated to fit.
40    #[cfg_attr(feature = "serde", serde(default = "default_max_pending_pool_imports_bytes"))]
41    pub max_pending_pool_imports_bytes: usize,
42    /// How new pending transactions are propagated.
43    #[cfg_attr(feature = "serde", serde(default))]
44    pub propagation_mode: TransactionPropagationMode,
45    /// Which peers we accept incoming transactions or announcements from.
46    #[cfg_attr(feature = "serde", serde(default))]
47    pub ingress_policy: TransactionIngressPolicy,
48    /// Memory limit (in bytes) for the channel that carries
49    /// `NetworkTransactionEvent`s from the `NetworkManager` to the `TransactionsManager`.
50    ///
51    /// When the budget is exhausted, new events are dropped.
52    #[cfg_attr(feature = "serde", serde(default = "default_tx_channel_memory_limit_bytes"))]
53    pub tx_channel_memory_limit_bytes: usize,
54}
55
56#[cfg(feature = "serde")]
57const fn default_max_pending_pool_imports() -> usize {
58    DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS
59}
60
61#[cfg(feature = "serde")]
62const fn default_max_pending_pool_imports_bytes() -> usize {
63    DEFAULT_MAX_BYTE_SIZE_PENDING_POOL_IMPORTS
64}
65
66#[cfg(feature = "serde")]
67const fn default_tx_channel_memory_limit_bytes() -> usize {
68    DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES
69}
70
71impl Default for TransactionsManagerConfig {
72    fn default() -> Self {
73        Self {
74            transaction_fetcher_config: TransactionFetcherConfig::default(),
75            max_transactions_seen_by_peer_history: DEFAULT_MAX_COUNT_TRANSACTIONS_SEEN_BY_PEER,
76            max_pending_pool_imports: DEFAULT_MAX_COUNT_PENDING_POOL_IMPORTS,
77            max_pending_pool_imports_bytes: DEFAULT_MAX_BYTE_SIZE_PENDING_POOL_IMPORTS,
78            propagation_mode: TransactionPropagationMode::default(),
79            ingress_policy: TransactionIngressPolicy::default(),
80            tx_channel_memory_limit_bytes: DEFAULT_TX_MANAGER_CHANNEL_MEMORY_LIMIT_BYTES,
81        }
82    }
83}
84
85/// Determines how new pending transactions are propagated to other peers in full.
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88pub enum TransactionPropagationMode {
89    /// Send full transactions to sqrt of current peers.
90    #[default]
91    Sqrt,
92    /// Always send transactions in full.
93    All,
94    /// Send full transactions to a maximum number of peers
95    Max(usize),
96}
97
98impl TransactionPropagationMode {
99    /// Returns the number of peers full transactions should be propagated to.
100    pub(crate) fn full_peer_count(&self, peer_count: usize) -> usize {
101        match self {
102            Self::Sqrt => (peer_count as f64).sqrt().round() as usize,
103            Self::All => peer_count,
104            Self::Max(max) => peer_count.min(*max),
105        }
106    }
107}
108impl std::fmt::Display for TransactionPropagationMode {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        match self {
111            Self::Sqrt => write!(f, "sqrt"),
112            Self::All => write!(f, "all"),
113            Self::Max(max) => write!(f, "max:{max}"),
114        }
115    }
116}
117
118impl FromStr for TransactionPropagationMode {
119    type Err = String;
120
121    fn from_str(s: &str) -> Result<Self, Self::Err> {
122        let s = s.to_lowercase();
123        match s.as_str() {
124            "sqrt" => Ok(Self::Sqrt),
125            "all" => Ok(Self::All),
126            s => {
127                if let Some(num) = s.strip_prefix("max:") {
128                    num.parse::<usize>()
129                        .map(TransactionPropagationMode::Max)
130                        .map_err(|_| format!("Invalid number for Max variant: {num}"))
131                } else {
132                    Err(format!("Invalid transaction propagation mode: {s}"))
133                }
134            }
135        }
136    }
137}
138
139/// Configuration for fetching transactions.
140#[derive(Debug, Clone)]
141#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
142pub struct TransactionFetcherConfig {
143    /// Max inflight [`GetPooledTransactions`](reth_eth_wire::GetPooledTransactions) requests.
144    pub max_inflight_requests: u32,
145    /// Max inflight [`GetPooledTransactions`](reth_eth_wire::GetPooledTransactions) requests per
146    /// peer.
147    pub max_inflight_requests_per_peer: u8,
148    /// Soft limit for the byte size of a
149    /// [`PooledTransactions`](reth_eth_wire::PooledTransactions) response on assembling a
150    /// [`GetPooledTransactions`](reth_eth_wire::GetPooledTransactions) request. Spec'd at 2
151    /// MiB.
152    pub soft_limit_byte_size_pooled_transactions_response: usize,
153    /// Soft limit for the byte size of the expected
154    /// [`PooledTransactions`](reth_eth_wire::PooledTransactions) response on packing a
155    /// [`GetPooledTransactions`](reth_eth_wire::GetPooledTransactions) request with hashes.
156    pub soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
157    /// Max number of announced transaction hashes to keep track of, i.e. hashes that were
158    /// announced but not fetched yet, both pending and inflight. Once reached, the peer tracking
159    /// the most hashes gives up its oldest unshared pending hash for a newly announced one.
160    /// If none is found, the oldest pending hash (including shared hashes) is evicted instead.
161    /// Inflight hashes are preserved; if no victim is found, the announcement is dropped.
162    pub max_capacity_cache_txns_pending_fetch: u32,
163    /// Max number of tracked hashes a single peer can be a candidate for. Announcements from a
164    /// peer that exceed this limit are dropped.
165    #[cfg_attr(feature = "serde", serde(default = "default_max_announced_hashes_per_peer"))]
166    pub max_announced_hashes_per_peer: u32,
167}
168
169#[cfg(feature = "serde")]
170const fn default_max_announced_hashes_per_peer() -> u32 {
171    DEFAULT_MAX_COUNT_ANNOUNCED_HASHES_PER_PEER
172}
173
174impl TransactionFetcherConfig {
175    /// Creates a new config with the default limit on announced hashes per peer.
176    pub const fn new(
177        max_inflight_requests: u32,
178        max_inflight_requests_per_peer: u8,
179        soft_limit_byte_size_pooled_transactions_response: usize,
180        soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
181        max_capacity_cache_txns_pending_fetch: u32,
182    ) -> Self {
183        Self {
184            max_inflight_requests,
185            max_inflight_requests_per_peer,
186            soft_limit_byte_size_pooled_transactions_response,
187            soft_limit_byte_size_pooled_transactions_response_on_pack_request,
188            max_capacity_cache_txns_pending_fetch,
189            max_announced_hashes_per_peer: DEFAULT_MAX_COUNT_ANNOUNCED_HASHES_PER_PEER,
190        }
191    }
192}
193
194impl Default for TransactionFetcherConfig {
195    fn default() -> Self {
196        Self::new(
197            DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS,
198            DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER,
199            SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE,
200            DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ,
201            DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH,
202        )
203    }
204}
205
206/// A policy defining which peers pending transactions are gossiped to.
207pub trait TransactionPropagationPolicy<N: NetworkPrimitives>:
208    Send + Sync + Unpin + fmt::Debug + 'static
209{
210    /// Filter a given peer based on the policy.
211    ///
212    /// This determines whether transactions can be propagated to this peer. Peers that are
213    /// filtered out also don't receive the pending pool announcement on session establishment and
214    /// are served empty responses to `GetPooledTransactions` requests.
215    fn can_propagate(&self, peer: &mut PeerMetadata<N>) -> bool;
216
217    /// A callback on the policy when a new peer session is established.
218    fn on_session_established(&mut self, peer: &mut PeerMetadata<N>);
219
220    /// A callback on the policy when a peer session is closed.
221    fn on_session_closed(&mut self, peer: &mut PeerMetadata<N>);
222}
223
224/// Determines which peers pending transactions are propagated to.
225#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Display)]
226#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
227pub enum TransactionPropagationKind {
228    /// Propagate transactions to all peers.
229    ///
230    /// No restrictions
231    #[default]
232    All,
233    /// Propagate transactions to only trusted peers.
234    Trusted,
235    /// Do not propagate transactions
236    None,
237}
238
239impl<N: NetworkPrimitives> TransactionPropagationPolicy<N> for TransactionPropagationKind {
240    fn can_propagate(&self, peer: &mut PeerMetadata<N>) -> bool {
241        match self {
242            Self::All => true,
243            Self::Trusted => peer.peer_kind.is_trusted(),
244            Self::None => false,
245        }
246    }
247
248    fn on_session_established(&mut self, _peer: &mut PeerMetadata<N>) {}
249
250    fn on_session_closed(&mut self, _peer: &mut PeerMetadata<N>) {}
251}
252
253impl FromStr for TransactionPropagationKind {
254    type Err = String;
255
256    fn from_str(s: &str) -> Result<Self, Self::Err> {
257        match s {
258            "All" | "all" => Ok(Self::All),
259            "Trusted" | "trusted" => Ok(Self::Trusted),
260            "None" | "none" => Ok(Self::None),
261            _ => Err(format!("Invalid transaction propagation policy: {s}")),
262        }
263    }
264}
265
266/// Determines which peers we will accept incoming transactions or announcements from.
267#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Display)]
268#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
269pub enum TransactionIngressPolicy {
270    /// Accept transactions from any peer.
271    #[default]
272    All,
273    /// Accept transactions only from trusted peers.
274    Trusted,
275    /// Drop all incoming transactions.
276    None,
277}
278
279impl TransactionIngressPolicy {
280    /// Returns true if the ingress policy allows the provided peer kind.
281    pub const fn allows(&self, peer_kind: PeerKind) -> bool {
282        match self {
283            Self::All => true,
284            Self::Trusted => peer_kind.is_trusted(),
285            Self::None => false,
286        }
287    }
288
289    /// Returns true if the ingress policy accepts transactions from any peer.
290    pub const fn allows_all(&self) -> bool {
291        matches!(self, Self::All)
292    }
293}
294
295impl FromStr for TransactionIngressPolicy {
296    type Err = String;
297
298    fn from_str(s: &str) -> Result<Self, Self::Err> {
299        match s {
300            "All" | "all" => Ok(Self::All),
301            "Trusted" | "trusted" => Ok(Self::Trusted),
302            "None" | "none" => Ok(Self::None),
303            _ => Err(format!("Invalid transaction ingress policy: {s}")),
304        }
305    }
306}
307
308/// Defines the outcome of evaluating a transaction against an `AnnouncementFilteringPolicy`.
309///
310/// Dictates how the `TransactionManager` should proceed on an announced transaction.
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub enum AnnouncementAcceptance {
313    /// Accept the transaction announcement.
314    Accept,
315    /// Log the transaction but not fetching the transaction or penalizing the peer.
316    Ignore,
317    /// Reject
318    Reject {
319        /// If true, the peer sending this announcement should be penalized.
320        penalize_peer: bool,
321    },
322}
323
324/// A policy that defines how to handle incoming transaction announcements,
325/// particularly concerning transaction types and other announcement metadata.
326pub trait AnnouncementFilteringPolicy<N: NetworkPrimitives>:
327    Send + Sync + Unpin + fmt::Debug + 'static
328{
329    /// Decides how to handle a transaction announcement based on its type, hash, and size.
330    fn decide_on_announcement(&self, ty: u8, hash: &B256, size: usize) -> AnnouncementAcceptance;
331}
332
333/// A generic `AnnouncementFilteringPolicy` that enforces strict validation
334/// of transaction type based on a generic type `T`.
335#[derive(Debug, Clone, Default)]
336#[non_exhaustive]
337pub struct TypedStrictFilter;
338
339impl<N: NetworkPrimitives> AnnouncementFilteringPolicy<N> for TypedStrictFilter {
340    fn decide_on_announcement(&self, ty: u8, hash: &B256, size: usize) -> AnnouncementAcceptance {
341        if N::PooledTransaction::is_type(ty) {
342            AnnouncementAcceptance::Accept
343        } else {
344            tracing::trace!(target: "net::tx::policy::strict_typed",
345                %ty,
346                %size,
347                %hash,
348                "Invalid or unrecognized transaction type byte. Rejecting entry and recommending peer penalization."
349            );
350            AnnouncementAcceptance::Reject { penalize_peer: true }
351        }
352    }
353}
354
355/// Type alias for a `TypedStrictFilter`. This is the default strict announcement filter.
356pub type StrictEthAnnouncementFilter = TypedStrictFilter;
357
358/// An [`AnnouncementFilteringPolicy`] that permissively handles unknown type bytes
359/// based on a given type `T` using `T::try_from(u8)`.
360///
361/// If `T::try_from(ty)` succeeds, the announcement is accepted. Otherwise, it's ignored.
362#[derive(Debug, Clone, Default)]
363#[non_exhaustive]
364pub struct TypedRelaxedFilter;
365
366impl<N: NetworkPrimitives> AnnouncementFilteringPolicy<N> for TypedRelaxedFilter {
367    fn decide_on_announcement(&self, ty: u8, hash: &B256, size: usize) -> AnnouncementAcceptance {
368        if N::PooledTransaction::is_type(ty) {
369            AnnouncementAcceptance::Accept
370        } else {
371            tracing::trace!(target: "net::tx::policy::relaxed_typed",
372                %ty,
373                %size,
374                %hash,
375                "Unknown transaction type byte. Ignoring entry."
376            );
377            AnnouncementAcceptance::Ignore
378        }
379    }
380}
381
382/// Type alias for `TypedRelaxedFilter`. This filter accepts known Ethereum transaction types and
383/// ignores unknown ones without penalizing the peer.
384pub type RelaxedEthAnnouncementFilter = TypedRelaxedFilter;
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn test_transaction_propagation_mode_from_str() {
392        // Test "sqrt" variant
393        assert_eq!(
394            TransactionPropagationMode::from_str("sqrt").unwrap(),
395            TransactionPropagationMode::Sqrt
396        );
397        assert_eq!(
398            TransactionPropagationMode::from_str("SQRT").unwrap(),
399            TransactionPropagationMode::Sqrt
400        );
401        assert_eq!(
402            TransactionPropagationMode::from_str("Sqrt").unwrap(),
403            TransactionPropagationMode::Sqrt
404        );
405
406        // Test "all" variant
407        assert_eq!(
408            TransactionPropagationMode::from_str("all").unwrap(),
409            TransactionPropagationMode::All
410        );
411        assert_eq!(
412            TransactionPropagationMode::from_str("ALL").unwrap(),
413            TransactionPropagationMode::All
414        );
415        assert_eq!(
416            TransactionPropagationMode::from_str("All").unwrap(),
417            TransactionPropagationMode::All
418        );
419
420        // Test "max:N" variant
421        assert_eq!(
422            TransactionPropagationMode::from_str("max:10").unwrap(),
423            TransactionPropagationMode::Max(10)
424        );
425        assert_eq!(
426            TransactionPropagationMode::from_str("MAX:42").unwrap(),
427            TransactionPropagationMode::Max(42)
428        );
429        assert_eq!(
430            TransactionPropagationMode::from_str("Max:100").unwrap(),
431            TransactionPropagationMode::Max(100)
432        );
433
434        // Test invalid inputs
435        assert!(TransactionPropagationMode::from_str("invalid").is_err());
436        assert!(TransactionPropagationMode::from_str("max:not_a_number").is_err());
437        assert!(TransactionPropagationMode::from_str("max:").is_err());
438        assert!(TransactionPropagationMode::from_str("max").is_err());
439        assert!(TransactionPropagationMode::from_str("").is_err());
440    }
441}