reth_network/session/
active.rs

1//! Represents an established session.
2
3use core::sync::atomic::Ordering;
4use std::{
5    collections::VecDeque,
6    future::Future,
7    net::SocketAddr,
8    pin::Pin,
9    sync::{atomic::AtomicU64, Arc},
10    task::{ready, Context, Poll},
11    time::{Duration, Instant},
12};
13
14use crate::{
15    message::{NewBlockMessage, PeerMessage, PeerResponse, PeerResponseResult},
16    session::{
17        conn::EthRlpxConnection,
18        handle::{ActiveSessionMessage, SessionCommand},
19        BlockRangeInfo, EthVersion, SessionId,
20    },
21};
22use alloy_eips::merge::EPOCH_SLOTS;
23use alloy_primitives::Sealable;
24use futures::{stream::Fuse, SinkExt, StreamExt};
25use metrics::Gauge;
26use reth_eth_wire::{
27    errors::{EthHandshakeError, EthStreamError},
28    message::{EthBroadcastMessage, MessageError, RequestPair},
29    Capabilities, DisconnectP2P, DisconnectReason, EthMessage, NetworkPrimitives, NewBlockPayload,
30};
31use reth_eth_wire_types::RawCapabilityMessage;
32use reth_metrics::common::mpsc::MeteredPollSender;
33use reth_network_api::PeerRequest;
34use reth_network_p2p::error::RequestError;
35use reth_network_peers::PeerId;
36use reth_network_types::session::config::INITIAL_REQUEST_TIMEOUT;
37use reth_primitives_traits::Block;
38use rustc_hash::FxHashMap;
39use tokio::{
40    sync::{mpsc::error::TrySendError, oneshot},
41    time::Interval,
42};
43use tokio_stream::wrappers::ReceiverStream;
44use tokio_util::sync::PollSender;
45use tracing::{debug, trace};
46
47/// The recommended interval at which to check if a new range update should be sent to the remote
48/// peer.
49///
50/// Updates are only sent when the block height has advanced by at least one epoch (32 blocks)
51/// since the last update. The interval is set to one epoch duration in seconds.
52pub(super) const RANGE_UPDATE_INTERVAL: Duration = Duration::from_secs(EPOCH_SLOTS * 12);
53
54// Constants for timeout updating.
55
56/// Minimum timeout value
57const MINIMUM_TIMEOUT: Duration = Duration::from_secs(2);
58
59/// Maximum timeout value
60const MAXIMUM_TIMEOUT: Duration = INITIAL_REQUEST_TIMEOUT;
61/// How much the new measurements affect the current timeout (X percent)
62const SAMPLE_IMPACT: f64 = 0.1;
63/// Amount of RTTs before timeout
64const TIMEOUT_SCALING: u32 = 3;
65
66/// Restricts the number of queued outgoing messages for larger responses:
67///  - Block Bodies
68///  - Receipts
69///  - Headers
70///  - `PooledTransactions`
71///
72/// With proper softlimits in place (2MB) this targets 10MB (4+1 * 2MB) of outgoing response data.
73///
74/// This parameter serves as backpressure for reading additional requests from the remote.
75/// Once we've queued up more responses than this, the session should prioritize message flushing
76/// before reading any more messages from the remote peer, throttling the peer.
77const MAX_QUEUED_OUTGOING_RESPONSES: usize = 4;
78
79/// The type that advances an established session by listening for incoming messages (from local
80/// node or read from connection) and emitting events back to the
81/// [`SessionManager`](super::SessionManager).
82///
83/// It listens for
84///    - incoming commands from the [`SessionManager`](super::SessionManager)
85///    - incoming _internal_ requests/broadcasts via the request/command channel
86///    - incoming requests/broadcasts _from remote_ via the connection
87///    - responses for handled ETH requests received from the remote peer.
88#[expect(dead_code)]
89pub(crate) struct ActiveSession<N: NetworkPrimitives> {
90    /// Keeps track of request ids.
91    pub(crate) next_id: u64,
92    /// The underlying connection.
93    pub(crate) conn: EthRlpxConnection<N>,
94    /// Identifier of the node we're connected to.
95    pub(crate) remote_peer_id: PeerId,
96    /// The address we're connected to.
97    pub(crate) remote_addr: SocketAddr,
98    /// All capabilities the peer announced
99    pub(crate) remote_capabilities: Arc<Capabilities>,
100    /// Internal identifier of this session
101    pub(crate) session_id: SessionId,
102    /// Incoming commands from the manager
103    pub(crate) commands_rx: ReceiverStream<SessionCommand<N>>,
104    /// Sink to send messages to the [`SessionManager`](super::SessionManager).
105    pub(crate) to_session_manager: MeteredPollSender<ActiveSessionMessage<N>>,
106    /// A message that needs to be delivered to the session manager
107    pub(crate) pending_message_to_session: Option<ActiveSessionMessage<N>>,
108    /// Incoming internal requests which are delegated to the remote peer.
109    pub(crate) internal_request_rx: Fuse<ReceiverStream<PeerRequest<N>>>,
110    /// All requests sent to the remote peer we're waiting on a response
111    pub(crate) inflight_requests: FxHashMap<u64, InflightRequest<PeerRequest<N>>>,
112    /// All requests that were sent by the remote peer and we're waiting on an internal response
113    pub(crate) received_requests_from_remote: Vec<ReceivedRequest<N>>,
114    /// Buffered messages that should be handled and sent to the peer.
115    pub(crate) queued_outgoing: QueuedOutgoingMessages<N>,
116    /// The maximum time we wait for a response from a peer.
117    pub(crate) internal_request_timeout: Arc<AtomicU64>,
118    /// Interval when to check for timed out requests.
119    pub(crate) internal_request_timeout_interval: Interval,
120    /// If an [`ActiveSession`] does not receive a response at all within this duration then it is
121    /// considered a protocol violation and the session will initiate a drop.
122    pub(crate) protocol_breach_request_timeout: Duration,
123    /// Used to reserve a slot to guarantee that the termination message is delivered
124    pub(crate) terminate_message:
125        Option<(PollSender<ActiveSessionMessage<N>>, ActiveSessionMessage<N>)>,
126    /// The eth69 range info for the remote peer.
127    pub(crate) range_info: Option<BlockRangeInfo>,
128    /// The eth69 range info for the local node (this node).
129    /// This represents the range of blocks that this node can serve to other peers.
130    pub(crate) local_range_info: BlockRangeInfo,
131    /// Optional interval for sending periodic range updates to the remote peer (eth69+)
132    /// The interval is set to one epoch duration (~6.4 minutes), but updates are only sent when
133    /// the block height has advanced by at least one epoch (32 blocks) since the last update
134    pub(crate) range_update_interval: Option<Interval>,
135    /// The last latest block number we sent in a range update
136    /// Used to avoid sending unnecessary updates when block height hasn't changed significantly
137    pub(crate) last_sent_latest_block: Option<u64>,
138}
139
140impl<N: NetworkPrimitives> ActiveSession<N> {
141    /// Returns `true` if the session is currently in the process of disconnecting
142    fn is_disconnecting(&self) -> bool {
143        self.conn.inner().is_disconnecting()
144    }
145
146    /// Returns the next request id
147    const fn next_id(&mut self) -> u64 {
148        let id = self.next_id;
149        self.next_id += 1;
150        id
151    }
152
153    /// Shrinks the capacity of the internal buffers.
154    pub fn shrink_to_fit(&mut self) {
155        self.received_requests_from_remote.shrink_to_fit();
156        self.queued_outgoing.shrink_to_fit();
157    }
158
159    /// Returns how many responses we've currently queued up.
160    fn queued_response_count(&self) -> usize {
161        self.queued_outgoing.messages.iter().filter(|m| m.is_response()).count()
162    }
163
164    /// Handle a message read from the connection.
165    ///
166    /// Returns an error if the message is considered to be in violation of the protocol.
167    fn on_incoming_message(&mut self, msg: EthMessage<N>) -> OnIncomingMessageOutcome<N> {
168        /// A macro that handles an incoming request
169        /// This creates a new channel and tries to send the sender half to the session while
170        /// storing the receiver half internally so the pending response can be polled.
171        macro_rules! on_request {
172            ($req:ident, $resp_item:ident, $req_item:ident) => {{
173                let RequestPair { request_id, message: request } = $req;
174                let (tx, response) = oneshot::channel();
175                let received = ReceivedRequest {
176                    request_id,
177                    rx: PeerResponse::$resp_item { response },
178                    received: Instant::now(),
179                };
180                self.received_requests_from_remote.push(received);
181                self.try_emit_request(PeerMessage::EthRequest(PeerRequest::$req_item {
182                    request,
183                    response: tx,
184                }))
185                .into()
186            }};
187        }
188
189        /// Processes a response received from the peer
190        macro_rules! on_response {
191            ($resp:ident, $item:ident) => {{
192                let RequestPair { request_id, message } = $resp;
193                if let Some(req) = self.inflight_requests.remove(&request_id) {
194                    match req.request {
195                        RequestState::Waiting(PeerRequest::$item { response, .. }) => {
196                            trace!(peer_id=?self.remote_peer_id, ?request_id, "received response from peer");
197                            let _ = response.send(Ok(message));
198                            self.update_request_timeout(req.timestamp, Instant::now());
199                        }
200                        RequestState::Waiting(request) => {
201                            request.send_bad_response();
202                        }
203                        RequestState::TimedOut => {
204                            // request was already timed out internally
205                            self.update_request_timeout(req.timestamp, Instant::now());
206                        }
207                    }
208                } else {
209                    trace!(peer_id=?self.remote_peer_id, ?request_id, "received response to unknown request");
210                    // we received a response to a request we never sent
211                    self.on_bad_message();
212                }
213
214                OnIncomingMessageOutcome::Ok
215            }};
216        }
217
218        match msg {
219            message @ EthMessage::Status(_) => OnIncomingMessageOutcome::BadMessage {
220                error: EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake),
221                message,
222            },
223            EthMessage::NewBlockHashes(msg) => {
224                self.try_emit_broadcast(PeerMessage::NewBlockHashes(msg)).into()
225            }
226            EthMessage::NewBlock(msg) => {
227                let block = NewBlockMessage {
228                    hash: msg.block().header().hash_slow(),
229                    block: Arc::new(*msg),
230                };
231                self.try_emit_broadcast(PeerMessage::NewBlock(block)).into()
232            }
233            EthMessage::Transactions(msg) => {
234                self.try_emit_broadcast(PeerMessage::ReceivedTransaction(msg)).into()
235            }
236            EthMessage::NewPooledTransactionHashes66(msg) => {
237                self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
238            }
239            EthMessage::NewPooledTransactionHashes68(msg) => {
240                self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
241            }
242            EthMessage::GetBlockHeaders(req) => {
243                on_request!(req, BlockHeaders, GetBlockHeaders)
244            }
245            EthMessage::BlockHeaders(resp) => {
246                on_response!(resp, GetBlockHeaders)
247            }
248            EthMessage::GetBlockBodies(req) => {
249                on_request!(req, BlockBodies, GetBlockBodies)
250            }
251            EthMessage::BlockBodies(resp) => {
252                on_response!(resp, GetBlockBodies)
253            }
254            EthMessage::GetPooledTransactions(req) => {
255                on_request!(req, PooledTransactions, GetPooledTransactions)
256            }
257            EthMessage::PooledTransactions(resp) => {
258                on_response!(resp, GetPooledTransactions)
259            }
260            EthMessage::GetNodeData(req) => {
261                on_request!(req, NodeData, GetNodeData)
262            }
263            EthMessage::NodeData(resp) => {
264                on_response!(resp, GetNodeData)
265            }
266            EthMessage::GetReceipts(req) => {
267                if self.conn.version() >= EthVersion::Eth69 {
268                    on_request!(req, Receipts69, GetReceipts69)
269                } else {
270                    on_request!(req, Receipts, GetReceipts)
271                }
272            }
273            EthMessage::Receipts(resp) => {
274                on_response!(resp, GetReceipts)
275            }
276            EthMessage::Receipts69(resp) => {
277                on_response!(resp, GetReceipts69)
278            }
279            EthMessage::BlockRangeUpdate(msg) => {
280                // Validate that earliest <= latest according to the spec
281                if msg.earliest > msg.latest {
282                    return OnIncomingMessageOutcome::BadMessage {
283                        error: EthStreamError::InvalidMessage(MessageError::Other(format!(
284                            "invalid block range: earliest ({}) > latest ({})",
285                            msg.earliest, msg.latest
286                        ))),
287                        message: EthMessage::BlockRangeUpdate(msg),
288                    };
289                }
290
291                // Validate that the latest hash is not zero
292                if msg.latest_hash.is_zero() {
293                    return OnIncomingMessageOutcome::BadMessage {
294                        error: EthStreamError::InvalidMessage(MessageError::Other(
295                            "invalid block range: latest_hash cannot be zero".to_string(),
296                        )),
297                        message: EthMessage::BlockRangeUpdate(msg),
298                    };
299                }
300
301                if let Some(range_info) = self.range_info.as_ref() {
302                    range_info.update(msg.earliest, msg.latest, msg.latest_hash);
303                }
304
305                OnIncomingMessageOutcome::Ok
306            }
307            EthMessage::Other(bytes) => self.try_emit_broadcast(PeerMessage::Other(bytes)).into(),
308        }
309    }
310
311    /// Handle an internal peer request that will be sent to the remote.
312    fn on_internal_peer_request(&mut self, request: PeerRequest<N>, deadline: Instant) {
313        let request_id = self.next_id();
314
315        trace!(?request, peer_id=?self.remote_peer_id, ?request_id, "sending request to peer");
316        let msg = request.create_request_message(request_id);
317        self.queued_outgoing.push_back(msg.into());
318        let req = InflightRequest {
319            request: RequestState::Waiting(request),
320            timestamp: Instant::now(),
321            deadline,
322        };
323        self.inflight_requests.insert(request_id, req);
324    }
325
326    /// Handle a message received from the internal network
327    fn on_internal_peer_message(&mut self, msg: PeerMessage<N>) {
328        match msg {
329            PeerMessage::NewBlockHashes(msg) => {
330                self.queued_outgoing.push_back(EthMessage::NewBlockHashes(msg).into());
331            }
332            PeerMessage::NewBlock(msg) => {
333                self.queued_outgoing.push_back(EthBroadcastMessage::NewBlock(msg.block).into());
334            }
335            PeerMessage::PooledTransactions(msg) => {
336                if msg.is_valid_for_version(self.conn.version()) {
337                    self.queued_outgoing.push_back(EthMessage::from(msg).into());
338                } else {
339                    debug!(target: "net", ?msg,  version=?self.conn.version(), "Message is invalid for connection version, skipping");
340                }
341            }
342            PeerMessage::EthRequest(req) => {
343                let deadline = self.request_deadline();
344                self.on_internal_peer_request(req, deadline);
345            }
346            PeerMessage::SendTransactions(msg) => {
347                self.queued_outgoing.push_back(EthBroadcastMessage::Transactions(msg).into());
348            }
349            PeerMessage::BlockRangeUpdated(_) => {}
350            PeerMessage::ReceivedTransaction(_) => {
351                unreachable!("Not emitted by network")
352            }
353            PeerMessage::Other(other) => {
354                self.queued_outgoing.push_back(OutgoingMessage::Raw(other));
355            }
356        }
357    }
358
359    /// Returns the deadline timestamp at which the request times out
360    fn request_deadline(&self) -> Instant {
361        Instant::now() +
362            Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed))
363    }
364
365    /// Handle a Response to the peer
366    ///
367    /// This will queue the response to be sent to the peer
368    fn handle_outgoing_response(&mut self, id: u64, resp: PeerResponseResult<N>) {
369        match resp.try_into_message(id) {
370            Ok(msg) => {
371                self.queued_outgoing.push_back(msg.into());
372            }
373            Err(err) => {
374                debug!(target: "net", %err, "Failed to respond to received request");
375            }
376        }
377    }
378
379    /// Send a message back to the [`SessionManager`](super::SessionManager).
380    ///
381    /// Returns the message if the bounded channel is currently unable to handle this message.
382    #[expect(clippy::result_large_err)]
383    fn try_emit_broadcast(&self, message: PeerMessage<N>) -> Result<(), ActiveSessionMessage<N>> {
384        let Some(sender) = self.to_session_manager.inner().get_ref() else { return Ok(()) };
385
386        match sender
387            .try_send(ActiveSessionMessage::ValidMessage { peer_id: self.remote_peer_id, message })
388        {
389            Ok(_) => Ok(()),
390            Err(err) => {
391                trace!(
392                    target: "net",
393                    %err,
394                    "no capacity for incoming broadcast",
395                );
396                match err {
397                    TrySendError::Full(msg) => Err(msg),
398                    TrySendError::Closed(_) => Ok(()),
399                }
400            }
401        }
402    }
403
404    /// Send a message back to the [`SessionManager`](super::SessionManager)
405    /// covering both broadcasts and incoming requests.
406    ///
407    /// Returns the message if the bounded channel is currently unable to handle this message.
408    #[expect(clippy::result_large_err)]
409    fn try_emit_request(&self, message: PeerMessage<N>) -> Result<(), ActiveSessionMessage<N>> {
410        let Some(sender) = self.to_session_manager.inner().get_ref() else { return Ok(()) };
411
412        match sender
413            .try_send(ActiveSessionMessage::ValidMessage { peer_id: self.remote_peer_id, message })
414        {
415            Ok(_) => Ok(()),
416            Err(err) => {
417                trace!(
418                    target: "net",
419                    %err,
420                    "no capacity for incoming request",
421                );
422                match err {
423                    TrySendError::Full(msg) => Err(msg),
424                    TrySendError::Closed(_) => {
425                        // Note: this would mean the `SessionManager` was dropped, which is already
426                        // handled by checking if the command receiver channel has been closed.
427                        Ok(())
428                    }
429                }
430            }
431        }
432    }
433
434    /// Notify the manager that the peer sent a bad message
435    fn on_bad_message(&self) {
436        let Some(sender) = self.to_session_manager.inner().get_ref() else { return };
437        let _ = sender.try_send(ActiveSessionMessage::BadMessage { peer_id: self.remote_peer_id });
438    }
439
440    /// Report back that this session has been closed.
441    fn emit_disconnect(&mut self, cx: &mut Context<'_>) -> Poll<()> {
442        trace!(target: "net::session", remote_peer_id=?self.remote_peer_id, "emitting disconnect");
443        let msg = ActiveSessionMessage::Disconnected {
444            peer_id: self.remote_peer_id,
445            remote_addr: self.remote_addr,
446        };
447
448        self.terminate_message = Some((self.to_session_manager.inner().clone(), msg));
449        self.poll_terminate_message(cx).expect("message is set")
450    }
451
452    /// Report back that this session has been closed due to an error
453    fn close_on_error(&mut self, error: EthStreamError, cx: &mut Context<'_>) -> Poll<()> {
454        let msg = ActiveSessionMessage::ClosedOnConnectionError {
455            peer_id: self.remote_peer_id,
456            remote_addr: self.remote_addr,
457            error,
458        };
459        self.terminate_message = Some((self.to_session_manager.inner().clone(), msg));
460        self.poll_terminate_message(cx).expect("message is set")
461    }
462
463    /// Starts the disconnect process
464    fn start_disconnect(&mut self, reason: DisconnectReason) -> Result<(), EthStreamError> {
465        Ok(self.conn.inner_mut().start_disconnect(reason)?)
466    }
467
468    /// Flushes the disconnect message and emits the corresponding message
469    fn poll_disconnect(&mut self, cx: &mut Context<'_>) -> Poll<()> {
470        debug_assert!(self.is_disconnecting(), "not disconnecting");
471
472        // try to close the flush out the remaining Disconnect message
473        let _ = ready!(self.conn.poll_close_unpin(cx));
474        self.emit_disconnect(cx)
475    }
476
477    /// Attempts to disconnect by sending the given disconnect reason
478    fn try_disconnect(&mut self, reason: DisconnectReason, cx: &mut Context<'_>) -> Poll<()> {
479        match self.start_disconnect(reason) {
480            Ok(()) => {
481                // we're done
482                self.poll_disconnect(cx)
483            }
484            Err(err) => {
485                debug!(target: "net::session", %err, remote_peer_id=?self.remote_peer_id, "could not send disconnect");
486                self.close_on_error(err, cx)
487            }
488        }
489    }
490
491    /// Checks for _internally_ timed out requests.
492    ///
493    /// If a requests misses its deadline, then it is timed out internally.
494    /// If a request misses the `protocol_breach_request_timeout` then this session is considered in
495    /// protocol violation and will close.
496    ///
497    /// Returns `true` if a peer missed the `protocol_breach_request_timeout`, in which case the
498    /// session should be terminated.
499    #[must_use]
500    fn check_timed_out_requests(&mut self, now: Instant) -> bool {
501        for (id, req) in &mut self.inflight_requests {
502            if req.is_timed_out(now) {
503                if req.is_waiting() {
504                    debug!(target: "net::session", ?id, remote_peer_id=?self.remote_peer_id, "timed out outgoing request");
505                    req.timeout();
506                } else if now - req.timestamp > self.protocol_breach_request_timeout {
507                    return true
508                }
509            }
510        }
511
512        false
513    }
514
515    /// Updates the request timeout with a request's timestamps
516    fn update_request_timeout(&mut self, sent: Instant, received: Instant) {
517        let elapsed = received.saturating_duration_since(sent);
518
519        let current = Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed));
520        let request_timeout = calculate_new_timeout(current, elapsed);
521        self.internal_request_timeout.store(request_timeout.as_millis() as u64, Ordering::Relaxed);
522        self.internal_request_timeout_interval = tokio::time::interval(request_timeout);
523    }
524
525    /// If a termination message is queued this will try to send it
526    fn poll_terminate_message(&mut self, cx: &mut Context<'_>) -> Option<Poll<()>> {
527        let (mut tx, msg) = self.terminate_message.take()?;
528        match tx.poll_reserve(cx) {
529            Poll::Pending => {
530                self.terminate_message = Some((tx, msg));
531                return Some(Poll::Pending)
532            }
533            Poll::Ready(Ok(())) => {
534                let _ = tx.send_item(msg);
535            }
536            Poll::Ready(Err(_)) => {
537                // channel closed
538            }
539        }
540        // terminate the task
541        Some(Poll::Ready(()))
542    }
543}
544
545impl<N: NetworkPrimitives> Future for ActiveSession<N> {
546    type Output = ();
547
548    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
549        let this = self.get_mut();
550
551        // if the session is terminate we have to send the termination message before we can close
552        if let Some(terminate) = this.poll_terminate_message(cx) {
553            return terminate
554        }
555
556        if this.is_disconnecting() {
557            return this.poll_disconnect(cx)
558        }
559
560        // The receive loop can be CPU intensive since it involves message decoding which could take
561        // up a lot of resources and increase latencies for other sessions if not yielded manually.
562        // If the budget is exhausted we manually yield back control to the (coop) scheduler. This
563        // manual yield point should prevent situations where polling appears to be frozen. See also <https://tokio.rs/blog/2020-04-preemption>
564        // And tokio's docs on cooperative scheduling <https://docs.rs/tokio/latest/tokio/task/#cooperative-scheduling>
565        let mut budget = 4;
566
567        // The main poll loop that drives the session
568        'main: loop {
569            let mut progress = false;
570
571            // we prioritize incoming commands sent from the session manager
572            loop {
573                match this.commands_rx.poll_next_unpin(cx) {
574                    Poll::Pending => break,
575                    Poll::Ready(None) => {
576                        // this is only possible when the manager was dropped, in which case we also
577                        // terminate this session
578                        return Poll::Ready(())
579                    }
580                    Poll::Ready(Some(cmd)) => {
581                        progress = true;
582                        match cmd {
583                            SessionCommand::Disconnect { reason } => {
584                                debug!(
585                                    target: "net::session",
586                                    ?reason,
587                                    remote_peer_id=?this.remote_peer_id,
588                                    "Received disconnect command for session"
589                                );
590                                let reason =
591                                    reason.unwrap_or(DisconnectReason::DisconnectRequested);
592
593                                return this.try_disconnect(reason, cx)
594                            }
595                            SessionCommand::Message(msg) => {
596                                this.on_internal_peer_message(msg);
597                            }
598                        }
599                    }
600                }
601            }
602
603            let deadline = this.request_deadline();
604
605            while let Poll::Ready(Some(req)) = this.internal_request_rx.poll_next_unpin(cx) {
606                progress = true;
607                this.on_internal_peer_request(req, deadline);
608            }
609
610            // Advance all active requests.
611            // We remove each request one by one and add them back.
612            for idx in (0..this.received_requests_from_remote.len()).rev() {
613                let mut req = this.received_requests_from_remote.swap_remove(idx);
614                match req.rx.poll(cx) {
615                    Poll::Pending => {
616                        // not ready yet
617                        this.received_requests_from_remote.push(req);
618                    }
619                    Poll::Ready(resp) => {
620                        this.handle_outgoing_response(req.request_id, resp);
621                    }
622                }
623            }
624
625            // Send messages by advancing the sink and queuing in buffered messages
626            while this.conn.poll_ready_unpin(cx).is_ready() {
627                if let Some(msg) = this.queued_outgoing.pop_front() {
628                    progress = true;
629                    let res = match msg {
630                        OutgoingMessage::Eth(msg) => this.conn.start_send_unpin(msg),
631                        OutgoingMessage::Broadcast(msg) => this.conn.start_send_broadcast(msg),
632                        OutgoingMessage::Raw(msg) => this.conn.start_send_raw(msg),
633                    };
634                    if let Err(err) = res {
635                        debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to send message");
636                        // notify the manager
637                        return this.close_on_error(err, cx)
638                    }
639                } else {
640                    // no more messages to send over the wire
641                    break
642                }
643            }
644
645            // read incoming messages from the wire
646            'receive: loop {
647                // ensure we still have enough budget for another iteration
648                budget -= 1;
649                if budget == 0 {
650                    // make sure we're woken up again
651                    cx.waker().wake_by_ref();
652                    break 'main
653                }
654
655                // try to resend the pending message that we could not send because the channel was
656                // full. [`PollSender`] will ensure that we're woken up again when the channel is
657                // ready to receive the message, and will only error if the channel is closed.
658                if let Some(msg) = this.pending_message_to_session.take() {
659                    match this.to_session_manager.poll_reserve(cx) {
660                        Poll::Ready(Ok(_)) => {
661                            let _ = this.to_session_manager.send_item(msg);
662                        }
663                        Poll::Ready(Err(_)) => return Poll::Ready(()),
664                        Poll::Pending => {
665                            this.pending_message_to_session = Some(msg);
666                            break 'receive
667                        }
668                    };
669                }
670
671                // check whether we should throttle incoming messages
672                if this.received_requests_from_remote.len() > MAX_QUEUED_OUTGOING_RESPONSES {
673                    // we're currently waiting for the responses to the peer's requests which aren't
674                    // queued as outgoing yet
675                    //
676                    // Note: we don't need to register the waker here because we polled the requests
677                    // above
678                    break 'receive
679                }
680
681                // we also need to check if we have multiple responses queued up
682                if this.queued_outgoing.messages.len() > MAX_QUEUED_OUTGOING_RESPONSES &&
683                    this.queued_response_count() > MAX_QUEUED_OUTGOING_RESPONSES
684                {
685                    // if we've queued up more responses than allowed, we don't poll for new
686                    // messages and break the receive loop early
687                    //
688                    // Note: we don't need to register the waker here because we still have
689                    // queued messages and the sink impl registered the waker because we've
690                    // already advanced it to `Pending` earlier
691                    break 'receive
692                }
693
694                match this.conn.poll_next_unpin(cx) {
695                    Poll::Pending => break,
696                    Poll::Ready(None) => {
697                        if this.is_disconnecting() {
698                            break
699                        }
700                        debug!(target: "net::session", remote_peer_id=?this.remote_peer_id, "eth stream completed");
701                        return this.emit_disconnect(cx)
702                    }
703                    Poll::Ready(Some(res)) => {
704                        match res {
705                            Ok(msg) => {
706                                trace!(target: "net::session", msg_id=?msg.message_id(), remote_peer_id=?this.remote_peer_id, "received eth message");
707                                // decode and handle message
708                                match this.on_incoming_message(msg) {
709                                    OnIncomingMessageOutcome::Ok => {
710                                        // handled successfully
711                                        progress = true;
712                                    }
713                                    OnIncomingMessageOutcome::BadMessage { error, message } => {
714                                        debug!(target: "net::session", %error, msg=?message, remote_peer_id=?this.remote_peer_id, "received invalid protocol message");
715                                        return this.close_on_error(error, cx)
716                                    }
717                                    OnIncomingMessageOutcome::NoCapacity(msg) => {
718                                        // failed to send due to lack of capacity
719                                        this.pending_message_to_session = Some(msg);
720                                    }
721                                }
722                            }
723                            Err(err) => {
724                                debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to receive message");
725                                return this.close_on_error(err, cx)
726                            }
727                        }
728                    }
729                }
730            }
731
732            if !progress {
733                break 'main
734            }
735        }
736
737        if let Some(interval) = &mut this.range_update_interval {
738            // Check if we should send a range update based on block height changes
739            while interval.poll_tick(cx).is_ready() {
740                let current_latest = this.local_range_info.latest();
741                let should_send = if let Some(last_sent) = this.last_sent_latest_block {
742                    // Only send if block height has advanced by at least one epoch (32 blocks)
743                    current_latest.saturating_sub(last_sent) >= EPOCH_SLOTS
744                } else {
745                    true // First update, always send
746                };
747
748                if should_send {
749                    this.queued_outgoing.push_back(
750                        EthMessage::BlockRangeUpdate(this.local_range_info.to_message()).into(),
751                    );
752                    this.last_sent_latest_block = Some(current_latest);
753                }
754            }
755        }
756
757        while this.internal_request_timeout_interval.poll_tick(cx).is_ready() {
758            // check for timed out requests
759            if this.check_timed_out_requests(Instant::now()) &&
760                let Poll::Ready(Ok(_)) = this.to_session_manager.poll_reserve(cx)
761            {
762                let msg = ActiveSessionMessage::ProtocolBreach { peer_id: this.remote_peer_id };
763                this.pending_message_to_session = Some(msg);
764            }
765        }
766
767        this.shrink_to_fit();
768
769        Poll::Pending
770    }
771}
772
773/// Tracks a request received from the peer
774pub(crate) struct ReceivedRequest<N: NetworkPrimitives> {
775    /// Protocol Identifier
776    request_id: u64,
777    /// Receiver half of the channel that's supposed to receive the proper response.
778    rx: PeerResponse<N>,
779    /// Timestamp when we read this msg from the wire.
780    #[expect(dead_code)]
781    received: Instant,
782}
783
784/// A request that waits for a response from the peer
785pub(crate) struct InflightRequest<R> {
786    /// Request we sent to peer and the internal response channel
787    request: RequestState<R>,
788    /// Instant when the request was sent
789    timestamp: Instant,
790    /// Time limit for the response
791    deadline: Instant,
792}
793
794// === impl InflightRequest ===
795
796impl<N: NetworkPrimitives> InflightRequest<PeerRequest<N>> {
797    /// Returns true if the request is timedout
798    #[inline]
799    fn is_timed_out(&self, now: Instant) -> bool {
800        now > self.deadline
801    }
802
803    /// Returns true if we're still waiting for a response
804    #[inline]
805    const fn is_waiting(&self) -> bool {
806        matches!(self.request, RequestState::Waiting(_))
807    }
808
809    /// This will timeout the request by sending an error response to the internal channel
810    fn timeout(&mut self) {
811        let mut req = RequestState::TimedOut;
812        std::mem::swap(&mut self.request, &mut req);
813
814        if let RequestState::Waiting(req) = req {
815            req.send_err_response(RequestError::Timeout);
816        }
817    }
818}
819
820/// All outcome variants when handling an incoming message
821enum OnIncomingMessageOutcome<N: NetworkPrimitives> {
822    /// Message successfully handled.
823    Ok,
824    /// Message is considered to be in violation of the protocol
825    BadMessage { error: EthStreamError, message: EthMessage<N> },
826    /// Currently no capacity to handle the message
827    NoCapacity(ActiveSessionMessage<N>),
828}
829
830impl<N: NetworkPrimitives> From<Result<(), ActiveSessionMessage<N>>>
831    for OnIncomingMessageOutcome<N>
832{
833    fn from(res: Result<(), ActiveSessionMessage<N>>) -> Self {
834        match res {
835            Ok(_) => Self::Ok,
836            Err(msg) => Self::NoCapacity(msg),
837        }
838    }
839}
840
841enum RequestState<R> {
842    /// Waiting for the response
843    Waiting(R),
844    /// Request already timed out
845    TimedOut,
846}
847
848/// Outgoing messages that can be sent over the wire.
849#[derive(Debug)]
850pub(crate) enum OutgoingMessage<N: NetworkPrimitives> {
851    /// A message that is owned.
852    Eth(EthMessage<N>),
853    /// A message that may be shared by multiple sessions.
854    Broadcast(EthBroadcastMessage<N>),
855    /// A raw capability message
856    Raw(RawCapabilityMessage),
857}
858
859impl<N: NetworkPrimitives> OutgoingMessage<N> {
860    /// Returns true if this is a response.
861    const fn is_response(&self) -> bool {
862        match self {
863            Self::Eth(msg) => msg.is_response(),
864            _ => false,
865        }
866    }
867}
868
869impl<N: NetworkPrimitives> From<EthMessage<N>> for OutgoingMessage<N> {
870    fn from(value: EthMessage<N>) -> Self {
871        Self::Eth(value)
872    }
873}
874
875impl<N: NetworkPrimitives> From<EthBroadcastMessage<N>> for OutgoingMessage<N> {
876    fn from(value: EthBroadcastMessage<N>) -> Self {
877        Self::Broadcast(value)
878    }
879}
880
881/// Calculates a new timeout using an updated estimation of the RTT
882#[inline]
883fn calculate_new_timeout(current_timeout: Duration, estimated_rtt: Duration) -> Duration {
884    let new_timeout = estimated_rtt.mul_f64(SAMPLE_IMPACT) * TIMEOUT_SCALING;
885
886    // this dampens sudden changes by taking a weighted mean of the old and new values
887    let smoothened_timeout = current_timeout.mul_f64(1.0 - SAMPLE_IMPACT) + new_timeout;
888
889    smoothened_timeout.clamp(MINIMUM_TIMEOUT, MAXIMUM_TIMEOUT)
890}
891
892/// A helper struct that wraps the queue of outgoing messages and a metric to track their count
893pub(crate) struct QueuedOutgoingMessages<N: NetworkPrimitives> {
894    messages: VecDeque<OutgoingMessage<N>>,
895    count: Gauge,
896}
897
898impl<N: NetworkPrimitives> QueuedOutgoingMessages<N> {
899    pub(crate) const fn new(metric: Gauge) -> Self {
900        Self { messages: VecDeque::new(), count: metric }
901    }
902
903    pub(crate) fn push_back(&mut self, message: OutgoingMessage<N>) {
904        self.messages.push_back(message);
905        self.count.increment(1);
906    }
907
908    pub(crate) fn pop_front(&mut self) -> Option<OutgoingMessage<N>> {
909        self.messages.pop_front().inspect(|_| self.count.decrement(1))
910    }
911
912    pub(crate) fn shrink_to_fit(&mut self) {
913        self.messages.shrink_to_fit();
914    }
915}
916
917impl<N: NetworkPrimitives> Drop for QueuedOutgoingMessages<N> {
918    fn drop(&mut self) {
919        // Ensure gauge is decremented for any remaining items to avoid metric leak on teardown.
920        let remaining = self.messages.len();
921        if remaining > 0 {
922            self.count.decrement(remaining as f64);
923        }
924    }
925}
926
927#[cfg(test)]
928mod tests {
929    use super::*;
930    use crate::session::{handle::PendingSessionEvent, start_pending_incoming_session};
931    use alloy_eips::eip2124::ForkFilter;
932    use reth_chainspec::MAINNET;
933    use reth_ecies::stream::ECIESStream;
934    use reth_eth_wire::{
935        handshake::EthHandshake, EthNetworkPrimitives, EthStream, GetBlockBodies,
936        HelloMessageWithProtocols, P2PStream, StatusBuilder, UnauthedEthStream, UnauthedP2PStream,
937        UnifiedStatus,
938    };
939    use reth_ethereum_forks::EthereumHardfork;
940    use reth_network_peers::pk2id;
941    use reth_network_types::session::config::PROTOCOL_BREACH_REQUEST_TIMEOUT;
942    use secp256k1::{SecretKey, SECP256K1};
943    use tokio::{
944        net::{TcpListener, TcpStream},
945        sync::mpsc,
946    };
947
948    /// Returns a testing `HelloMessage` and new secretkey
949    fn eth_hello(server_key: &SecretKey) -> HelloMessageWithProtocols {
950        HelloMessageWithProtocols::builder(pk2id(&server_key.public_key(SECP256K1))).build()
951    }
952
953    struct SessionBuilder<N: NetworkPrimitives = EthNetworkPrimitives> {
954        _remote_capabilities: Arc<Capabilities>,
955        active_session_tx: mpsc::Sender<ActiveSessionMessage<N>>,
956        active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
957        to_sessions: Vec<mpsc::Sender<SessionCommand<N>>>,
958        secret_key: SecretKey,
959        local_peer_id: PeerId,
960        hello: HelloMessageWithProtocols,
961        status: UnifiedStatus,
962        fork_filter: ForkFilter,
963        next_id: usize,
964    }
965
966    impl<N: NetworkPrimitives> SessionBuilder<N> {
967        fn next_id(&mut self) -> SessionId {
968            let id = self.next_id;
969            self.next_id += 1;
970            SessionId(id)
971        }
972
973        /// Connects a new Eth stream and executes the given closure with that established stream
974        fn with_client_stream<F, O>(
975            &self,
976            local_addr: SocketAddr,
977            f: F,
978        ) -> Pin<Box<dyn Future<Output = ()> + Send>>
979        where
980            F: FnOnce(EthStream<P2PStream<ECIESStream<TcpStream>>, N>) -> O + Send + 'static,
981            O: Future<Output = ()> + Send + Sync,
982        {
983            let mut status = self.status;
984            let fork_filter = self.fork_filter.clone();
985            let local_peer_id = self.local_peer_id;
986            let mut hello = self.hello.clone();
987            let key = SecretKey::new(&mut rand_08::thread_rng());
988            hello.id = pk2id(&key.public_key(SECP256K1));
989            Box::pin(async move {
990                let outgoing = TcpStream::connect(local_addr).await.unwrap();
991                let sink = ECIESStream::connect(outgoing, key, local_peer_id).await.unwrap();
992
993                let (p2p_stream, _) = UnauthedP2PStream::new(sink).handshake(hello).await.unwrap();
994
995                let eth_version = p2p_stream.shared_capabilities().eth_version().unwrap();
996                status.set_eth_version(eth_version);
997
998                let (client_stream, _) = UnauthedEthStream::new(p2p_stream)
999                    .handshake(status, fork_filter)
1000                    .await
1001                    .unwrap();
1002                f(client_stream).await
1003            })
1004        }
1005
1006        async fn connect_incoming(&mut self, stream: TcpStream) -> ActiveSession<N> {
1007            let remote_addr = stream.local_addr().unwrap();
1008            let session_id = self.next_id();
1009            let (_disconnect_tx, disconnect_rx) = oneshot::channel();
1010            let (pending_sessions_tx, pending_sessions_rx) = mpsc::channel(1);
1011
1012            tokio::task::spawn(start_pending_incoming_session(
1013                Arc::new(EthHandshake::default()),
1014                disconnect_rx,
1015                session_id,
1016                stream,
1017                pending_sessions_tx,
1018                remote_addr,
1019                self.secret_key,
1020                self.hello.clone(),
1021                self.status,
1022                self.fork_filter.clone(),
1023                Default::default(),
1024            ));
1025
1026            let mut stream = ReceiverStream::new(pending_sessions_rx);
1027
1028            match stream.next().await.unwrap() {
1029                PendingSessionEvent::Established {
1030                    session_id,
1031                    remote_addr,
1032                    peer_id,
1033                    capabilities,
1034                    conn,
1035                    ..
1036                } => {
1037                    let (_to_session_tx, messages_rx) = mpsc::channel(10);
1038                    let (commands_to_session, commands_rx) = mpsc::channel(10);
1039                    let poll_sender = PollSender::new(self.active_session_tx.clone());
1040
1041                    self.to_sessions.push(commands_to_session);
1042
1043                    ActiveSession {
1044                        next_id: 0,
1045                        remote_peer_id: peer_id,
1046                        remote_addr,
1047                        remote_capabilities: Arc::clone(&capabilities),
1048                        session_id,
1049                        commands_rx: ReceiverStream::new(commands_rx),
1050                        to_session_manager: MeteredPollSender::new(
1051                            poll_sender,
1052                            "network_active_session",
1053                        ),
1054                        pending_message_to_session: None,
1055                        internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
1056                        inflight_requests: Default::default(),
1057                        conn,
1058                        queued_outgoing: QueuedOutgoingMessages::new(Gauge::noop()),
1059                        received_requests_from_remote: Default::default(),
1060                        internal_request_timeout_interval: tokio::time::interval(
1061                            INITIAL_REQUEST_TIMEOUT,
1062                        ),
1063                        internal_request_timeout: Arc::new(AtomicU64::new(
1064                            INITIAL_REQUEST_TIMEOUT.as_millis() as u64,
1065                        )),
1066                        protocol_breach_request_timeout: PROTOCOL_BREACH_REQUEST_TIMEOUT,
1067                        terminate_message: None,
1068                        range_info: None,
1069                        local_range_info: BlockRangeInfo::new(
1070                            0,
1071                            1000,
1072                            alloy_primitives::B256::ZERO,
1073                        ),
1074                        range_update_interval: None,
1075                        last_sent_latest_block: None,
1076                    }
1077                }
1078                ev => {
1079                    panic!("unexpected message {ev:?}")
1080                }
1081            }
1082        }
1083    }
1084
1085    impl Default for SessionBuilder {
1086        fn default() -> Self {
1087            let (active_session_tx, active_session_rx) = mpsc::channel(100);
1088
1089            let (secret_key, pk) = SECP256K1.generate_keypair(&mut rand_08::thread_rng());
1090            let local_peer_id = pk2id(&pk);
1091
1092            Self {
1093                next_id: 0,
1094                _remote_capabilities: Arc::new(Capabilities::from(vec![])),
1095                active_session_tx,
1096                active_session_rx: ReceiverStream::new(active_session_rx),
1097                to_sessions: vec![],
1098                hello: eth_hello(&secret_key),
1099                secret_key,
1100                local_peer_id,
1101                status: StatusBuilder::default().build(),
1102                fork_filter: MAINNET
1103                    .hardfork_fork_filter(EthereumHardfork::Frontier)
1104                    .expect("The Frontier fork filter should exist on mainnet"),
1105            }
1106        }
1107    }
1108
1109    #[tokio::test(flavor = "multi_thread")]
1110    async fn test_disconnect() {
1111        let mut builder = SessionBuilder::default();
1112
1113        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1114        let local_addr = listener.local_addr().unwrap();
1115
1116        let expected_disconnect = DisconnectReason::UselessPeer;
1117
1118        let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1119            let msg = client_stream.next().await.unwrap().unwrap_err();
1120            assert_eq!(msg.as_disconnected().unwrap(), expected_disconnect);
1121        });
1122
1123        tokio::task::spawn(async move {
1124            let (incoming, _) = listener.accept().await.unwrap();
1125            let mut session = builder.connect_incoming(incoming).await;
1126
1127            session.start_disconnect(expected_disconnect).unwrap();
1128            session.await
1129        });
1130
1131        fut.await;
1132    }
1133
1134    #[tokio::test(flavor = "multi_thread")]
1135    async fn handle_dropped_stream() {
1136        let mut builder = SessionBuilder::default();
1137
1138        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1139        let local_addr = listener.local_addr().unwrap();
1140
1141        let fut = builder.with_client_stream(local_addr, move |client_stream| async move {
1142            drop(client_stream);
1143            tokio::time::sleep(Duration::from_secs(1)).await
1144        });
1145
1146        let (tx, rx) = oneshot::channel();
1147
1148        tokio::task::spawn(async move {
1149            let (incoming, _) = listener.accept().await.unwrap();
1150            let session = builder.connect_incoming(incoming).await;
1151            session.await;
1152
1153            tx.send(()).unwrap();
1154        });
1155
1156        tokio::task::spawn(fut);
1157
1158        rx.await.unwrap();
1159    }
1160
1161    #[tokio::test(flavor = "multi_thread")]
1162    async fn test_send_many_messages() {
1163        reth_tracing::init_test_tracing();
1164        let mut builder = SessionBuilder::default();
1165
1166        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1167        let local_addr = listener.local_addr().unwrap();
1168
1169        let num_messages = 100;
1170
1171        let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1172            for _ in 0..num_messages {
1173                client_stream
1174                    .send(EthMessage::NewPooledTransactionHashes66(Vec::new().into()))
1175                    .await
1176                    .unwrap();
1177            }
1178        });
1179
1180        let (tx, rx) = oneshot::channel();
1181
1182        tokio::task::spawn(async move {
1183            let (incoming, _) = listener.accept().await.unwrap();
1184            let session = builder.connect_incoming(incoming).await;
1185            session.await;
1186
1187            tx.send(()).unwrap();
1188        });
1189
1190        tokio::task::spawn(fut);
1191
1192        rx.await.unwrap();
1193    }
1194
1195    #[tokio::test(flavor = "multi_thread")]
1196    async fn test_request_timeout() {
1197        reth_tracing::init_test_tracing();
1198
1199        let mut builder = SessionBuilder::default();
1200
1201        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1202        let local_addr = listener.local_addr().unwrap();
1203
1204        let request_timeout = Duration::from_millis(100);
1205        let drop_timeout = Duration::from_millis(1500);
1206
1207        let fut = builder.with_client_stream(local_addr, move |client_stream| async move {
1208            let _client_stream = client_stream;
1209            tokio::time::sleep(drop_timeout * 60).await;
1210        });
1211        tokio::task::spawn(fut);
1212
1213        let (incoming, _) = listener.accept().await.unwrap();
1214        let mut session = builder.connect_incoming(incoming).await;
1215        session
1216            .internal_request_timeout
1217            .store(request_timeout.as_millis() as u64, Ordering::Relaxed);
1218        session.protocol_breach_request_timeout = drop_timeout;
1219        session.internal_request_timeout_interval =
1220            tokio::time::interval_at(tokio::time::Instant::now(), request_timeout);
1221        let (tx, rx) = oneshot::channel();
1222        let req = PeerRequest::GetBlockBodies { request: GetBlockBodies(vec![]), response: tx };
1223        session.on_internal_peer_request(req, Instant::now());
1224        tokio::spawn(session);
1225
1226        let err = rx.await.unwrap().unwrap_err();
1227        assert_eq!(err, RequestError::Timeout);
1228
1229        // wait for protocol breach error
1230        let msg = builder.active_session_rx.next().await.unwrap();
1231        match msg {
1232            ActiveSessionMessage::ProtocolBreach { .. } => {}
1233            ev => unreachable!("{ev:?}"),
1234        }
1235    }
1236
1237    #[tokio::test(flavor = "multi_thread")]
1238    async fn test_keep_alive() {
1239        let mut builder = SessionBuilder::default();
1240
1241        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1242        let local_addr = listener.local_addr().unwrap();
1243
1244        let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1245            let _ = tokio::time::timeout(Duration::from_secs(5), client_stream.next()).await;
1246            client_stream.into_inner().disconnect(DisconnectReason::UselessPeer).await.unwrap();
1247        });
1248
1249        let (tx, rx) = oneshot::channel();
1250
1251        tokio::task::spawn(async move {
1252            let (incoming, _) = listener.accept().await.unwrap();
1253            let session = builder.connect_incoming(incoming).await;
1254            session.await;
1255
1256            tx.send(()).unwrap();
1257        });
1258
1259        tokio::task::spawn(fut);
1260
1261        rx.await.unwrap();
1262    }
1263
1264    // This tests that incoming messages are delivered when there's capacity.
1265    #[tokio::test(flavor = "multi_thread")]
1266    async fn test_send_at_capacity() {
1267        let mut builder = SessionBuilder::default();
1268
1269        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1270        let local_addr = listener.local_addr().unwrap();
1271
1272        let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1273            client_stream
1274                .send(EthMessage::NewPooledTransactionHashes68(Default::default()))
1275                .await
1276                .unwrap();
1277            let _ = tokio::time::timeout(Duration::from_secs(100), client_stream.next()).await;
1278        });
1279        tokio::task::spawn(fut);
1280
1281        let (incoming, _) = listener.accept().await.unwrap();
1282        let session = builder.connect_incoming(incoming).await;
1283
1284        // fill the entire message buffer with an unrelated message
1285        let mut num_fill_messages = 0;
1286        loop {
1287            if builder
1288                .active_session_tx
1289                .try_send(ActiveSessionMessage::ProtocolBreach { peer_id: PeerId::random() })
1290                .is_err()
1291            {
1292                break
1293            }
1294            num_fill_messages += 1;
1295        }
1296
1297        tokio::task::spawn(async move {
1298            session.await;
1299        });
1300
1301        tokio::time::sleep(Duration::from_millis(100)).await;
1302
1303        for _ in 0..num_fill_messages {
1304            let message = builder.active_session_rx.next().await.unwrap();
1305            match message {
1306                ActiveSessionMessage::ProtocolBreach { .. } => {}
1307                ev => unreachable!("{ev:?}"),
1308            }
1309        }
1310
1311        let message = builder.active_session_rx.next().await.unwrap();
1312        match message {
1313            ActiveSessionMessage::ValidMessage {
1314                message: PeerMessage::PooledTransactions(_),
1315                ..
1316            } => {}
1317            _ => unreachable!(),
1318        }
1319    }
1320
1321    #[test]
1322    fn timeout_calculation_sanity_tests() {
1323        let rtt = Duration::from_secs(5);
1324        // timeout for an RTT of `rtt`
1325        let timeout = rtt * TIMEOUT_SCALING;
1326
1327        // if rtt hasn't changed, timeout shouldn't change
1328        assert_eq!(calculate_new_timeout(timeout, rtt), timeout);
1329
1330        // if rtt changed, the new timeout should change less than it
1331        assert!(calculate_new_timeout(timeout, rtt / 2) < timeout);
1332        assert!(calculate_new_timeout(timeout, rtt / 2) > timeout / 2);
1333        assert!(calculate_new_timeout(timeout, rtt * 2) > timeout);
1334        assert!(calculate_new_timeout(timeout, rtt * 2) < timeout * 2);
1335    }
1336}