reth_network/transactions/
config.rs1use 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#[derive(Debug, Clone)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub struct TransactionsManagerConfig {
29 pub transaction_fetcher_config: TransactionFetcherConfig,
31 pub max_transactions_seen_by_peer_history: u32,
33 #[cfg_attr(feature = "serde", serde(default = "default_max_pending_pool_imports"))]
36 pub max_pending_pool_imports: usize,
37 #[cfg_attr(feature = "serde", serde(default = "default_max_pending_pool_imports_bytes"))]
41 pub max_pending_pool_imports_bytes: usize,
42 #[cfg_attr(feature = "serde", serde(default))]
44 pub propagation_mode: TransactionPropagationMode,
45 #[cfg_attr(feature = "serde", serde(default))]
47 pub ingress_policy: TransactionIngressPolicy,
48 #[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
88pub enum TransactionPropagationMode {
89 #[default]
91 Sqrt,
92 All,
94 Max(usize),
96}
97
98impl TransactionPropagationMode {
99 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#[derive(Debug, Clone)]
141#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
142pub struct TransactionFetcherConfig {
143 pub max_inflight_requests: u32,
145 pub max_inflight_requests_per_peer: u8,
148 pub soft_limit_byte_size_pooled_transactions_response: usize,
153 pub soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize,
157 pub max_capacity_cache_txns_pending_fetch: u32,
163 #[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 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
206pub trait TransactionPropagationPolicy<N: NetworkPrimitives>:
208 Send + Sync + Unpin + fmt::Debug + 'static
209{
210 fn can_propagate(&self, peer: &mut PeerMetadata<N>) -> bool;
216
217 fn on_session_established(&mut self, peer: &mut PeerMetadata<N>);
219
220 fn on_session_closed(&mut self, peer: &mut PeerMetadata<N>);
222}
223
224#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Display)]
226#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
227pub enum TransactionPropagationKind {
228 #[default]
232 All,
233 Trusted,
235 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Display)]
268#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
269pub enum TransactionIngressPolicy {
270 #[default]
272 All,
273 Trusted,
275 None,
277}
278
279impl TransactionIngressPolicy {
280 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312pub enum AnnouncementAcceptance {
313 Accept,
315 Ignore,
317 Reject {
319 penalize_peer: bool,
321 },
322}
323
324pub trait AnnouncementFilteringPolicy<N: NetworkPrimitives>:
327 Send + Sync + Unpin + fmt::Debug + 'static
328{
329 fn decide_on_announcement(&self, ty: u8, hash: &B256, size: usize) -> AnnouncementAcceptance;
331}
332
333#[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
355pub type StrictEthAnnouncementFilter = TypedStrictFilter;
357
358#[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
382pub type RelaxedEthAnnouncementFilter = TypedRelaxedFilter;
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn test_transaction_propagation_mode_from_str() {
392 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 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 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 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}