Skip to main content

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::{
10        atomic::{AtomicU64, AtomicUsize},
11        Arc,
12    },
13    task::{ready, Context, Poll},
14    time::{Duration, Instant},
15};
16
17use crate::{
18    message::{NewBlockMessage, PeerMessage, PeerResponse, PeerResponseResult},
19    session::{
20        conn::EthRlpxConnection,
21        handle::{ActiveSessionMessage, SessionCommand},
22        BlockRangeInfo, EthVersion, SessionId,
23    },
24};
25use alloy_eips::merge::{EPOCH_DURATION, EPOCH_SLOTS};
26use alloy_primitives::Sealable;
27use futures::{stream::Fuse, SinkExt, StreamExt};
28use metrics::{Counter, Gauge};
29use reth_eth_wire::{
30    errors::{EthHandshakeError, EthStreamError},
31    message::{EthBroadcastMessage, MessageError},
32    Capabilities, DisconnectP2P, DisconnectReason, EthMessage, EthSnapMessage, NetworkPrimitives,
33    NewBlockPayload,
34};
35use reth_eth_wire_types::{
36    message::RequestPair, snap::SnapProtocolMessage, NewPooledTransactionHashes,
37    RawCapabilityMessage,
38};
39use reth_metrics::common::mpsc::MeteredPollSender;
40use reth_network_api::{PeerRequest, RequestMessage};
41use reth_network_p2p::{error::RequestError, snap::client::SnapResponse};
42use reth_network_peers::PeerId;
43use reth_network_types::session::config::INITIAL_REQUEST_TIMEOUT;
44use reth_primitives_traits::Block;
45use rustc_hash::FxHashMap;
46use tokio::{
47    sync::{mpsc, mpsc::error::TrySendError, oneshot},
48    time::Interval,
49};
50use tokio_stream::wrappers::ReceiverStream;
51use tokio_util::sync::PollSender;
52use tracing::{debug, error, trace};
53
54/// The recommended interval at which to check if a new range update should be sent to the remote
55/// peer.
56///
57/// Updates are only sent when the block height has advanced by at least one epoch (32 blocks)
58/// since the last update. The interval is set to one epoch duration in seconds.
59pub(super) const RANGE_UPDATE_INTERVAL: Duration = EPOCH_DURATION;
60
61// Constants for timeout updating.
62
63/// Minimum timeout value
64const MINIMUM_TIMEOUT: Duration = Duration::from_secs(2);
65
66/// Maximum timeout value
67const MAXIMUM_TIMEOUT: Duration = INITIAL_REQUEST_TIMEOUT;
68/// How much the new measurements affect the current timeout (X percent)
69const SAMPLE_IMPACT: f64 = 0.1;
70/// Amount of RTTs before timeout
71const TIMEOUT_SCALING: u32 = 3;
72
73/// Restricts the number of queued outgoing messages for larger responses:
74///  - Block Bodies
75///  - Receipts
76///  - Headers
77///  - `PooledTransactions`
78///
79/// With proper softlimits in place (2MB) this targets 10MB (4+1 * 2MB) of outgoing response data.
80///
81/// This parameter serves as backpressure for reading additional requests from the remote.
82/// Once we've queued up more responses than this, the session should prioritize message flushing
83/// before reading any more messages from the remote peer, throttling the peer.
84const MAX_QUEUED_OUTGOING_RESPONSES: usize = 4;
85
86/// Capacity above which the drained outgoing message queue is shrunk back to its steady-state
87/// size, see [`QueuedOutgoingMessages::shrink_to_fit`].
88const SHRINK_CAPACITY_THRESHOLD: usize = 64;
89
90/// Maximum number of messages read from the connection per session poll before the task yields
91/// back to the scheduler, see the receive loop in the session's `Future` impl.
92///
93/// Message decoding is CPU intensive, so the budget bounds how long a single busy session can
94/// occupy the executor thread. Small tx gossip messages dominate under load and are cheap to
95/// decode individually, so the budget is sized such that their per-poll fixed costs (draining
96/// command channels, advancing the sink, flushing the transport) amortize over a larger batch.
97const RECEIVE_MESSAGE_BUDGET: usize = 16;
98
99/// Soft limit for the total number of buffered outgoing broadcast items (e.g. transaction hashes).
100///
101/// Many small broadcast messages carrying a single tx hash each are equivalent in cost to one
102/// message carrying many hashes. This limit counts individual items (hashes, transactions, blocks)
103/// rather than messages, so that many small messages don't trigger aggressive drops unnecessarily.
104const MAX_QUEUED_BROADCAST_ITEMS: usize = 4096;
105
106/// How long a session waits for its disconnect message to be flushed before it gives up and
107/// closes anyway.
108///
109/// The flush can stay pending forever when the remote stops reading but keeps the connection open,
110/// which would otherwise keep the session (and the peer's slot) alive indefinitely.
111const DISCONNECT_TIMEOUT: Duration = Duration::from_secs(10);
112
113/// Shared counter for in-flight broadcast items (tx hashes, transactions, blocks) across the
114/// bounded command channel, unbounded overflow channel, and session outgoing queue.
115///
116/// Wrapped in a newtype so the backing storage can be changed later (e.g. to track memory) without
117/// touching every call-site.
118#[derive(Debug, Clone)]
119pub(crate) struct BroadcastItemCounter(Arc<AtomicUsize>);
120
121impl BroadcastItemCounter {
122    /// Creates a new counter starting at zero.
123    pub(crate) fn new() -> Self {
124        Self(Arc::new(AtomicUsize::new(0)))
125    }
126
127    /// Returns the current count.
128    pub(crate) fn get(&self) -> usize {
129        self.0.load(Ordering::Relaxed)
130    }
131
132    /// Attempts to add `n` items. Returns `true` if under the limit, `false` if over (no change).
133    pub(crate) fn try_add(&self, n: usize) -> bool {
134        let prev = self.0.fetch_add(n, Ordering::Relaxed);
135        if prev >= MAX_QUEUED_BROADCAST_ITEMS {
136            self.0.fetch_sub(n, Ordering::Relaxed);
137            false
138        } else {
139            true
140        }
141    }
142
143    /// Subtracts `n` items from the counter.
144    pub(crate) fn sub(&self, n: usize) {
145        self.0.fetch_sub(n, Ordering::Relaxed);
146    }
147}
148
149/// The type that advances an established session by listening for incoming messages (from local
150/// node or read from connection) and emitting events back to the
151/// [`SessionManager`](super::SessionManager).
152///
153/// It listens for
154///    - incoming commands from the [`SessionManager`](super::SessionManager)
155///    - incoming _internal_ requests/broadcasts via the request/command channel
156///    - incoming requests/broadcasts _from remote_ via the connection
157///    - responses for handled ETH requests received from the remote peer.
158#[expect(dead_code)]
159pub(crate) struct ActiveSession<N: NetworkPrimitives> {
160    /// Keeps track of request ids.
161    pub(crate) next_id: u64,
162    /// The underlying connection.
163    pub(crate) conn: EthRlpxConnection<N>,
164    /// Identifier of the node we're connected to.
165    pub(crate) remote_peer_id: PeerId,
166    /// The address we're connected to.
167    pub(crate) remote_addr: SocketAddr,
168    /// All capabilities the peer announced
169    pub(crate) remote_capabilities: Arc<Capabilities>,
170    /// Internal identifier of this session
171    pub(crate) session_id: SessionId,
172    /// Incoming commands from the manager
173    pub(crate) commands_rx: ReceiverStream<SessionCommand<N>>,
174    /// Unbounded channel for commands that couldn't fit in the bounded channel (broadcast
175    /// overflow) and for disconnect commands that must never be dropped.
176    pub(crate) unbounded_rx: mpsc::UnboundedReceiver<SessionCommand<N>>,
177    /// Counter for broadcast messages received via the unbounded overflow channel.
178    pub(crate) unbounded_broadcast_msgs: Counter,
179    /// Sink to send messages to the [`SessionManager`](super::SessionManager).
180    pub(crate) to_session_manager: MeteredPollSender<ActiveSessionMessage<N>>,
181    /// A message that needs to be delivered to the session manager
182    pub(crate) pending_message_to_session: Option<ActiveSessionMessage<N>>,
183    /// Incoming internal requests which are delegated to the remote peer.
184    pub(crate) internal_request_rx: Fuse<ReceiverStream<PeerRequest<N>>>,
185    /// All requests sent to the remote peer we're waiting on a response for, including `snap/2`
186    /// requests ([`PeerRequest::GetSnap`]).
187    pub(crate) inflight_requests: FxHashMap<u64, InflightRequest<PeerRequest<N>>>,
188    /// All requests that were sent by the remote peer and we're waiting on an internal response
189    pub(crate) received_requests_from_remote: Vec<ReceivedRequest<N>>,
190    /// Buffered messages that should be handled and sent to the peer.
191    pub(crate) queued_outgoing: QueuedOutgoingMessages<N>,
192    /// The maximum time we wait for a response from a peer.
193    pub(crate) internal_request_timeout: Arc<AtomicU64>,
194    /// Interval when to check for timed out requests.
195    pub(crate) internal_request_timeout_interval: Interval,
196    /// If an [`ActiveSession`] does not receive a response at all within this duration then it is
197    /// considered a protocol violation and the session will initiate a drop.
198    pub(crate) protocol_breach_request_timeout: Duration,
199    /// Used to reserve a slot to guarantee that the termination message is delivered
200    pub(crate) terminate_message:
201        Option<(PollSender<ActiveSessionMessage<N>>, ActiveSessionMessage<N>)>,
202    /// The eth69 range info for the remote peer.
203    /// This is `None` for peers negotiating versions below `eth/69`.
204    pub(crate) range_info: Option<BlockRangeInfo>,
205    /// The eth69 range info for the local node (this node).
206    /// This represents the range of blocks that this node can serve to other peers.
207    pub(crate) local_range_info: BlockRangeInfo,
208    /// Optional interval for sending periodic range updates to the remote peer (eth69+)
209    /// The interval is set to one epoch duration (~6.4 minutes), but updates are only sent when
210    /// the block height has advanced by at least one epoch (32 blocks) since the last update
211    pub(crate) range_update_interval: Option<Interval>,
212    /// The last latest block number we sent in a range update
213    /// Used to avoid sending unnecessary updates when block height hasn't changed significantly
214    pub(crate) last_sent_latest_block: Option<u64>,
215    /// Deadline for flushing the disconnect message, armed when the disconnect starts.
216    pub(crate) disconnect_deadline: Option<Pin<Box<tokio::time::Sleep>>>,
217}
218
219impl<N: NetworkPrimitives> ActiveSession<N> {
220    /// Returns `true` if the session is currently in the process of disconnecting
221    fn is_disconnecting(&self) -> bool {
222        self.conn.inner().is_disconnecting()
223    }
224
225    /// Returns the next request id
226    const fn next_id(&mut self) -> u64 {
227        let id = self.next_id;
228        self.next_id += 1;
229        id
230    }
231
232    /// Shrinks the capacity of the outgoing message queue once it is drained.
233    ///
234    /// The buffered incoming requests need no shrinking: the receive loop stops reading from the
235    /// wire while more than [`MAX_QUEUED_OUTGOING_RESPONSES`] of them are pending, which keeps
236    /// that buffer's capacity small.
237    pub fn shrink_to_fit(&mut self) {
238        self.queued_outgoing.shrink_to_fit();
239    }
240
241    /// Drains messages queued for sending into the connection's sink as long as the connection
242    /// can accept more, without flushing the underlying transport.
243    ///
244    /// This always advances the sink at least once, even with nothing queued, so connection
245    /// keepalive (ping) timers embedded in the sink's readiness logic are polled every session
246    /// poll.
247    ///
248    /// Returns `true` if at least one message was handed to the connection.
249    ///
250    /// A readiness error closes the session: a satellite connection reports messages it already
251    /// accepted but the wire rejected through its readiness.
252    fn poll_send_queued(&mut self, cx: &mut Context<'_>) -> Result<bool, EthStreamError> {
253        let mut progress = false;
254        while let Poll::Ready(ready) = self.conn.poll_ready_unpin(cx) {
255            ready?;
256            let Some(msg) = self.queued_outgoing.pop_front() else { break };
257            progress = true;
258            let res = match msg {
259                OutgoingMessage::Snap(msg) => self.conn.start_send_snap(msg),
260                OutgoingMessage::Eth(msg) => self.conn.start_send_unpin(msg),
261                OutgoingMessage::Broadcast(msg) => self.conn.start_send_broadcast(msg),
262                OutgoingMessage::Raw(msg) => self.conn.start_send_raw(msg),
263            };
264            res?;
265        }
266        Ok(progress)
267    }
268
269    /// Handle a message read from the connection.
270    ///
271    /// Returns an error if the message is considered to be in violation of the protocol.
272    fn on_incoming_message(&mut self, msg: EthMessage<N>) -> OnIncomingMessageOutcome<N> {
273        /// A macro that handles an incoming request
274        /// This creates a new channel and tries to send the sender half to the session while
275        /// storing the receiver half internally so the pending response can be polled.
276        macro_rules! on_request {
277            ($req:ident, $resp_item:ident, $req_item:ident) => {{
278                let RequestPair { request_id, message: request } = $req;
279                let (tx, response) = oneshot::channel();
280                let received = ReceivedRequest {
281                    request_id,
282                    rx: PeerResponse::$resp_item { response },
283                    received: Instant::now(),
284                };
285                self.received_requests_from_remote.push(received);
286                self.try_emit_request(PeerMessage::EthRequest(PeerRequest::$req_item {
287                    request,
288                    response: tx,
289                }))
290                .into()
291            }};
292        }
293
294        /// Processes a response received from the peer
295        macro_rules! on_response {
296            ($resp:ident, $item:ident) => {{
297                let RequestPair { request_id, message } = $resp;
298                if let Some(req) = self.inflight_requests.remove(&request_id) {
299                    match req.request {
300                        RequestState::Waiting(PeerRequest::$item { response, .. }) => {
301                            trace!(peer_id=?self.remote_peer_id, ?request_id, "received response from peer");
302                            let _ = response.send(Ok(message));
303                            self.update_request_timeout(req.timestamp, Instant::now());
304                        }
305                        RequestState::Waiting(request) => {
306                            // The peer replied to a request id we handed out, but with the wrong
307                            // response type. This cancels the pending request, so it must cost the
308                            // peer reputation. Without the penalty the peer can kill any request we
309                            // send it, repeatedly and for free.
310                            debug!(target: "net::session", ?request_id, remote_peer_id=?self.remote_peer_id, "received response of wrong type");
311                            self.on_bad_message();
312                            request.send_bad_response();
313                        }
314                        RequestState::TimedOut => {
315                            // request was already timed out internally
316                            self.update_request_timeout(req.timestamp, Instant::now());
317                        }
318                    }
319                } else {
320                    trace!(peer_id=?self.remote_peer_id, ?request_id, "received response to unknown request");
321                    // we received a response to a request we never sent
322                    self.on_bad_message();
323                }
324
325                OnIncomingMessageOutcome::Ok
326            }};
327        }
328
329        match msg {
330            message @ EthMessage::Status(_) => OnIncomingMessageOutcome::BadMessage {
331                error: EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake),
332                message,
333            },
334            EthMessage::NewBlockHashes(msg) => {
335                self.try_emit_broadcast(PeerMessage::NewBlockHashes(msg)).into()
336            }
337            EthMessage::NewBlock(msg) => {
338                let block = NewBlockMessage {
339                    hash: msg.block().header().hash_slow(),
340                    block: Arc::new(*msg),
341                };
342                self.try_emit_broadcast(PeerMessage::NewBlock(block)).into()
343            }
344            EthMessage::Transactions(msg) => {
345                self.try_emit_broadcast(PeerMessage::ReceivedTransaction(msg)).into()
346            }
347            EthMessage::NewPooledTransactionHashes66(msg) => {
348                self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
349            }
350            EthMessage::NewPooledTransactionHashes68(msg) => {
351                self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
352            }
353            EthMessage::NewPooledTransactionHashes72(msg) => {
354                self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
355            }
356            EthMessage::GetBlockHeaders(req) => {
357                on_request!(req, BlockHeaders, GetBlockHeaders)
358            }
359            EthMessage::BlockHeaders(resp) => {
360                on_response!(resp, GetBlockHeaders)
361            }
362            EthMessage::GetBlockBodies(req) => {
363                on_request!(req, BlockBodies, GetBlockBodies)
364            }
365            EthMessage::BlockBodies(resp) => {
366                on_response!(resp, GetBlockBodies)
367            }
368            EthMessage::GetPooledTransactions(req) => {
369                on_request!(req, PooledTransactions, GetPooledTransactions)
370            }
371            EthMessage::PooledTransactions(resp) => {
372                on_response!(resp, GetPooledTransactions)
373            }
374            EthMessage::GetNodeData(req) => {
375                on_request!(req, NodeData, GetNodeData)
376            }
377            EthMessage::NodeData(resp) => {
378                on_response!(resp, GetNodeData)
379            }
380            EthMessage::GetReceipts(req) => {
381                if self.conn.version() >= EthVersion::Eth69 {
382                    on_request!(req, Receipts69, GetReceipts69)
383                } else {
384                    on_request!(req, Receipts, GetReceipts)
385                }
386            }
387            EthMessage::GetReceipts70(req) => {
388                on_request!(req, Receipts70, GetReceipts70)
389            }
390            EthMessage::Receipts(resp) => {
391                on_response!(resp, GetReceipts)
392            }
393            EthMessage::Receipts69(resp) => {
394                on_response!(resp, GetReceipts69)
395            }
396            EthMessage::Receipts70(resp) => {
397                on_response!(resp, GetReceipts70)
398            }
399            EthMessage::GetBlockAccessLists(req) => {
400                on_request!(req, BlockAccessLists, GetBlockAccessLists)
401            }
402            EthMessage::BlockAccessLists(resp) => {
403                on_response!(resp, GetBlockAccessLists)
404            }
405            EthMessage::Cells(resp) => {
406                if let Some(req) = self.inflight_requests.get(&resp.request_id) &&
407                    let RequestState::Waiting(PeerRequest::GetCells { request, .. }) =
408                        &req.request &&
409                    let Err(err) = resp.message.validate_response(request)
410                {
411                    debug!(target: "net::session", request_id=?resp.request_id, %err, remote_peer_id=?self.remote_peer_id, "received invalid cells response");
412                    if let Some(req) = self.inflight_requests.remove(&resp.request_id) &&
413                        let RequestState::Waiting(request) = req.request
414                    {
415                        request.send_bad_response();
416                    }
417                    self.on_bad_message();
418                    return OnIncomingMessageOutcome::Ok
419                }
420                on_response!(resp, GetCells)
421            }
422            EthMessage::BlockRangeUpdate(msg) => {
423                // Validate that earliest <= latest according to the spec
424                if msg.earliest > msg.latest {
425                    return OnIncomingMessageOutcome::BadMessage {
426                        error: EthStreamError::InvalidMessage(MessageError::Other(format!(
427                            "invalid block range: earliest ({}) > latest ({})",
428                            msg.earliest, msg.latest
429                        ))),
430                        message: EthMessage::BlockRangeUpdate(msg),
431                    };
432                }
433
434                // Validate that the latest hash is not zero
435                if msg.latest_hash.is_zero() {
436                    return OnIncomingMessageOutcome::BadMessage {
437                        error: EthStreamError::InvalidMessage(MessageError::Other(
438                            "invalid block range: latest_hash cannot be zero".to_string(),
439                        )),
440                        message: EthMessage::BlockRangeUpdate(msg),
441                    };
442                }
443
444                if let Some(range_info) = self.range_info.as_ref() {
445                    range_info.update(msg.earliest, msg.latest, msg.latest_hash);
446                }
447
448                OnIncomingMessageOutcome::Ok
449            }
450            EthMessage::GetCells(resp) => {
451                on_request!(resp, Cells, GetCells)
452            }
453            EthMessage::Other(bytes) => self.try_emit_broadcast(PeerMessage::Other(bytes)).into(),
454        }
455    }
456
457    /// Handles an inbound `snap/2` message.
458    ///
459    /// Responses are correlated to the in-flight [`PeerRequest::GetSnap`] by `request_id` (shared
460    /// with eth requests in [`Self::inflight_requests`]) and type-checked against the originally
461    /// sent request kind; unsolicited or mismatched ones count as bad messages. Inbound requests
462    /// are routed upward as [`PeerRequest::GetSnap`], same as any other eth request.
463    fn on_incoming_snap_message(
464        &mut self,
465        mut msg: SnapProtocolMessage,
466    ) -> OnIncomingMessageOutcome<N> {
467        let request_id = msg.request_id();
468        if !msg.is_response() {
469            let (tx, response) = oneshot::channel();
470            self.received_requests_from_remote.push(ReceivedRequest {
471                request_id,
472                rx: PeerResponse::Snap { response },
473                received: Instant::now(),
474            });
475            return self
476                .try_emit_request(PeerMessage::EthRequest(PeerRequest::GetSnap {
477                    request: msg,
478                    response: tx,
479                }))
480                .into()
481        }
482
483        let Some(req) = self.inflight_requests.remove(&request_id) else {
484            trace!(target: "net::session", ?request_id, remote_peer_id=?self.remote_peer_id, "received snap response to unknown request");
485            self.on_bad_message();
486            return OnIncomingMessageOutcome::Ok
487        };
488
489        match req.request {
490            RequestState::Waiting(PeerRequest::GetSnap { request, response }) => {
491                if Some(msg.message_id()) != request.message_id().response() {
492                    debug!(target: "net::session", ?request_id, msg_id=?msg.message_id(), remote_peer_id=?self.remote_peer_id, "received snap response of wrong type");
493                    self.on_bad_message();
494                    let _ = response.send(Err(RequestError::BadResponse));
495                    return OnIncomingMessageOutcome::Ok
496                }
497                // Restore the caller's original request id, not the wire-assigned one.
498                msg.set_request_id(request.request_id());
499                match SnapResponse::try_from(msg) {
500                    Ok(snap_response) => {
501                        trace!(target: "net::session", ?request_id, remote_peer_id=?self.remote_peer_id, "received snap response from peer");
502                        let _ = response.send(Ok(snap_response));
503                        self.update_request_timeout(req.timestamp, Instant::now());
504                    }
505                    Err(_) => {
506                        let _ = response.send(Err(RequestError::BadResponse));
507                    }
508                }
509            }
510            RequestState::Waiting(request) => {
511                // A different PeerRequest kind was pending for this id: the peer answered an `eth`
512                // request with a `snap` message. Same as the wrong-type case above, this cancels
513                // the pending request and must be penalized.
514                debug!(target: "net::session", ?request_id, msg_id=?msg.message_id(), remote_peer_id=?self.remote_peer_id, "received snap response for non-snap request");
515                self.on_bad_message();
516                request.send_bad_response();
517            }
518            RequestState::TimedOut => {
519                self.update_request_timeout(req.timestamp, Instant::now());
520            }
521        }
522        OnIncomingMessageOutcome::Ok
523    }
524
525    /// Handle an internal peer request that will be sent to the remote.
526    fn on_internal_peer_request(&mut self, request: PeerRequest<N>, deadline: Instant) {
527        let version = self.conn.version();
528        if !Self::is_request_supported_for_version(&request, version) {
529            debug!(
530                target: "net",
531                ?request,
532                peer_id=?self.remote_peer_id,
533                ?version,
534                "Request not supported for negotiated eth version",
535            );
536            request.send_err_response(RequestError::UnsupportedCapability);
537            return;
538        }
539
540        // `GetSnap` isn't covered by the eth-version check above, and a connection that never
541        // negotiated `snap/2` can't send one without erroring the whole session.
542        if matches!(request, PeerRequest::GetSnap { .. }) && !self.conn.supports_snap() {
543            request.send_err_response(RequestError::UnsupportedCapability);
544            return;
545        }
546
547        if let PeerRequest::GetCells { request: cells, .. } = &request &&
548            let Err(err) = cells.cell_mask.validate(&cells.hashes, false)
549        {
550            error!(target: "net", peer_id=?self.remote_peer_id, %err, "Rejected invalid local cell request");
551            request.send_err_response(RequestError::InvalidRequest);
552            return
553        }
554
555        let request_id = self.next_id();
556        trace!(?request, peer_id=?self.remote_peer_id, ?request_id, "sending request to peer");
557        let msg = match request.create_request_message(request_id) {
558            RequestMessage::Eth(msg) => msg.into(),
559            RequestMessage::Snap(msg) => OutgoingMessage::Snap(msg),
560        };
561
562        self.queued_outgoing.push_back(msg);
563        let req = InflightRequest {
564            request: RequestState::Waiting(request),
565            timestamp: Instant::now(),
566            deadline,
567        };
568        self.inflight_requests.insert(request_id, req);
569    }
570
571    #[inline]
572    fn is_request_supported_for_version(request: &PeerRequest<N>, version: EthVersion) -> bool {
573        request.is_supported_by_eth_version(version)
574    }
575
576    /// Handle a message received from the internal network
577    fn on_internal_peer_message(&mut self, msg: PeerMessage<N>) {
578        match msg {
579            PeerMessage::NewBlockHashes(msg) => {
580                self.queued_outgoing.push_back(EthMessage::NewBlockHashes(msg).into());
581            }
582            PeerMessage::NewBlock(msg) => {
583                self.queued_outgoing.push_back(EthBroadcastMessage::NewBlock(msg.block).into());
584            }
585            PeerMessage::PooledTransactions(msg) => {
586                if msg.is_valid_for_version(self.conn.version()) {
587                    self.queued_outgoing.push_pooled_hashes(msg);
588                } else {
589                    self.queued_outgoing.broadcast_items.sub(msg.len());
590                    debug!(target: "net", ?msg,  version=?self.conn.version(), "Message is invalid for connection version, skipping");
591                }
592            }
593            PeerMessage::EthRequest(req) => {
594                let deadline = self.request_deadline();
595                self.on_internal_peer_request(req, deadline);
596            }
597            PeerMessage::SendTransactions(msg) => {
598                self.queued_outgoing.push_back(EthBroadcastMessage::Transactions(msg).into());
599            }
600            PeerMessage::SendBroadcastPoolTransactions(msg) => {
601                self.queued_outgoing
602                    .push_back(EthBroadcastMessage::BroadcastPoolTransactions(msg).into());
603            }
604            PeerMessage::BlockRangeUpdated(_) => {}
605            PeerMessage::ReceivedTransaction(_) => {
606                unreachable!("Not emitted by network")
607            }
608            PeerMessage::Other(other) => {
609                self.queued_outgoing.push_back(OutgoingMessage::Raw(other));
610            }
611        }
612    }
613
614    /// Returns the deadline timestamp at which the request times out
615    fn request_deadline(&self) -> Instant {
616        Instant::now() +
617            Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed))
618    }
619
620    /// Handle a Response to the peer
621    ///
622    /// This will queue the response to be sent to the peer
623    fn handle_outgoing_response(&mut self, id: u64, resp: PeerResponseResult<N>) {
624        match resp.try_into_message(id) {
625            Ok(RequestMessage::Eth(msg)) => {
626                self.queued_outgoing.push_back(msg.into());
627            }
628            Ok(RequestMessage::Snap(msg)) => {
629                self.queued_outgoing.push_back(OutgoingMessage::Snap(msg));
630            }
631            Err(err) => {
632                debug!(target: "net", %err, "Failed to respond to received request");
633            }
634        }
635    }
636
637    /// Send a message back to the [`SessionManager`](super::SessionManager).
638    ///
639    /// Returns the message if the bounded channel is currently unable to handle this message.
640    #[expect(clippy::result_large_err)]
641    fn try_emit_broadcast(&self, message: PeerMessage<N>) -> Result<(), ActiveSessionMessage<N>> {
642        let Some(sender) = self.to_session_manager.inner().get_ref() else { return Ok(()) };
643
644        match sender
645            .try_send(ActiveSessionMessage::ValidMessage { peer_id: self.remote_peer_id, message })
646        {
647            Ok(_) => Ok(()),
648            Err(err) => {
649                trace!(
650                    target: "net",
651                    %err,
652                    "no capacity for incoming broadcast",
653                );
654                match err {
655                    TrySendError::Full(msg) => Err(msg),
656                    TrySendError::Closed(_) => Ok(()),
657                }
658            }
659        }
660    }
661
662    /// Send a message back to the [`SessionManager`](super::SessionManager)
663    /// covering both broadcasts and incoming requests.
664    ///
665    /// Returns the message if the bounded channel is currently unable to handle this message.
666    #[expect(clippy::result_large_err)]
667    fn try_emit_request(&self, message: PeerMessage<N>) -> Result<(), ActiveSessionMessage<N>> {
668        let Some(sender) = self.to_session_manager.inner().get_ref() else { return Ok(()) };
669
670        match sender
671            .try_send(ActiveSessionMessage::ValidMessage { peer_id: self.remote_peer_id, message })
672        {
673            Ok(_) => Ok(()),
674            Err(err) => {
675                trace!(
676                    target: "net",
677                    %err,
678                    "no capacity for incoming request",
679                );
680                match err {
681                    TrySendError::Full(msg) => Err(msg),
682                    TrySendError::Closed(_) => {
683                        // Note: this would mean the `SessionManager` was dropped, which is already
684                        // handled by checking if the command receiver channel has been closed.
685                        Ok(())
686                    }
687                }
688            }
689        }
690    }
691
692    /// Notify the manager that the peer sent a bad message
693    fn on_bad_message(&self) {
694        let Some(sender) = self.to_session_manager.inner().get_ref() else { return };
695        let _ = sender.try_send(ActiveSessionMessage::BadMessage { peer_id: self.remote_peer_id });
696    }
697
698    /// Report back that this session has been closed.
699    fn emit_disconnect(&mut self, cx: &mut Context<'_>) -> Poll<()> {
700        trace!(target: "net::session", remote_peer_id=?self.remote_peer_id, "emitting disconnect");
701        let msg = ActiveSessionMessage::Disconnected {
702            peer_id: self.remote_peer_id,
703            remote_addr: self.remote_addr,
704        };
705
706        self.terminate_message = Some((self.to_session_manager.inner().clone(), msg));
707        self.poll_terminate_message(cx).expect("message is set")
708    }
709
710    /// Report back that this session has been closed due to an error
711    fn close_on_error(&mut self, error: EthStreamError, cx: &mut Context<'_>) -> Poll<()> {
712        let msg = ActiveSessionMessage::ClosedOnConnectionError {
713            peer_id: self.remote_peer_id,
714            remote_addr: self.remote_addr,
715            error,
716        };
717        self.terminate_message = Some((self.to_session_manager.inner().clone(), msg));
718        self.poll_terminate_message(cx).expect("message is set")
719    }
720
721    /// Starts the disconnect process
722    fn start_disconnect(&mut self, reason: DisconnectReason) -> Result<(), EthStreamError> {
723        Ok(self.conn.inner_mut().start_disconnect(reason)?)
724    }
725
726    /// Flushes the disconnect message and emits the corresponding message
727    fn poll_disconnect(&mut self, cx: &mut Context<'_>) -> Poll<()> {
728        debug_assert!(self.is_disconnecting(), "not disconnecting");
729
730        let deadline = self
731            .disconnect_deadline
732            .get_or_insert_with(|| Box::pin(tokio::time::sleep(DISCONNECT_TIMEOUT)));
733
734        // try to close the flush out the remaining Disconnect message, but don't wait forever: a
735        // peer that stops reading would otherwise pin this session.
736        if self.conn.poll_close_unpin(cx).is_pending() {
737            ready!(deadline.as_mut().poll(cx));
738            debug!(target: "net::session", remote_peer_id=?self.remote_peer_id, "timed out flushing disconnect");
739        }
740        self.emit_disconnect(cx)
741    }
742
743    /// Attempts to disconnect by sending the given disconnect reason
744    fn try_disconnect(&mut self, reason: DisconnectReason, cx: &mut Context<'_>) -> Poll<()> {
745        match self.start_disconnect(reason) {
746            Ok(()) => {
747                // we're done
748                self.poll_disconnect(cx)
749            }
750            Err(err) => {
751                debug!(target: "net::session", %err, remote_peer_id=?self.remote_peer_id, "could not send disconnect");
752                self.close_on_error(err, cx)
753            }
754        }
755    }
756
757    /// Checks for _internally_ timed out requests.
758    ///
759    /// If a requests misses its deadline, then it is timed out internally.
760    /// If a request misses the `protocol_breach_request_timeout` then this session is considered in
761    /// protocol violation and will close.
762    ///
763    /// Returns `true` if a peer missed the `protocol_breach_request_timeout`, in which case the
764    /// session should be terminated.
765    #[must_use]
766    fn check_timed_out_requests(&mut self, now: Instant) -> bool {
767        for (id, req) in &mut self.inflight_requests {
768            if req.is_timed_out(now) {
769                if req.is_waiting() {
770                    debug!(target: "net::session", ?id, remote_peer_id=?self.remote_peer_id, "timed out outgoing request");
771                    req.timeout();
772                } else if now - req.timestamp > self.protocol_breach_request_timeout {
773                    return true
774                }
775            }
776        }
777
778        false
779    }
780
781    /// Updates the request timeout with a request's timestamps
782    fn update_request_timeout(&mut self, sent: Instant, received: Instant) {
783        let elapsed = received.saturating_duration_since(sent);
784
785        let current = Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed));
786        let request_timeout = calculate_new_timeout(current, elapsed);
787        self.internal_request_timeout.store(request_timeout.as_millis() as u64, Ordering::Relaxed);
788        self.internal_request_timeout_interval = request_timeout_interval(request_timeout);
789    }
790
791    /// If a termination message is queued this will try to send it
792    fn poll_terminate_message(&mut self, cx: &mut Context<'_>) -> Option<Poll<()>> {
793        let (mut tx, msg) = self.terminate_message.take()?;
794        match tx.poll_reserve(cx) {
795            Poll::Pending => {
796                self.terminate_message = Some((tx, msg));
797                return Some(Poll::Pending)
798            }
799            Poll::Ready(Ok(())) => {
800                let _ = tx.send_item(msg);
801            }
802            Poll::Ready(Err(_)) => {
803                // channel closed
804            }
805        }
806        // terminate the task
807        Some(Poll::Ready(()))
808    }
809}
810
811impl<N: NetworkPrimitives> Future for ActiveSession<N> {
812    type Output = ();
813
814    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
815        let this = self.get_mut();
816
817        // if the session is terminate we have to send the termination message before we can close
818        if let Some(terminate) = this.poll_terminate_message(cx) {
819            return terminate
820        }
821
822        if this.is_disconnecting() {
823            return this.poll_disconnect(cx)
824        }
825
826        // The receive loop can be CPU intensive since it involves message decoding which could take
827        // up a lot of resources and increase latencies for other sessions if not yielded manually.
828        // If the budget is exhausted we manually yield back control to the (coop) scheduler. This
829        // manual yield point should prevent situations where polling appears to be frozen. See also <https://tokio.rs/blog/2020-04-preemption>
830        // And tokio's docs on cooperative scheduling <https://docs.rs/tokio/latest/tokio/task/#cooperative-scheduling>
831        let mut budget = RECEIVE_MESSAGE_BUDGET;
832
833        // The main poll loop that drives the session
834        'main: loop {
835            let mut progress = false;
836            let mut receive_pending = false;
837
838            // we prioritize incoming commands sent from the session manager
839            loop {
840                match this.commands_rx.poll_next_unpin(cx) {
841                    Poll::Pending => break,
842                    Poll::Ready(None) => {
843                        // this is only possible when the manager was dropped, in which case we also
844                        // terminate this session
845                        return Poll::Ready(())
846                    }
847                    Poll::Ready(Some(cmd)) => {
848                        progress = true;
849                        match cmd {
850                            SessionCommand::Disconnect { reason } => {
851                                debug!(
852                                    target: "net::session",
853                                    ?reason,
854                                    remote_peer_id=?this.remote_peer_id,
855                                    "Received disconnect command for session"
856                                );
857                                let reason =
858                                    reason.unwrap_or(DisconnectReason::DisconnectRequested);
859
860                                return this.try_disconnect(reason, cx)
861                            }
862                            SessionCommand::Message(msg) => {
863                                this.on_internal_peer_message(msg);
864                            }
865                        }
866                    }
867                }
868            }
869
870            // Drain the unbounded channel (broadcast overflow + disconnect commands)
871            while let Poll::Ready(Some(cmd)) = this.unbounded_rx.poll_recv(cx) {
872                progress = true;
873                match cmd {
874                    SessionCommand::Message(msg) => {
875                        this.unbounded_broadcast_msgs.increment(1);
876                        this.on_internal_peer_message(msg);
877                    }
878                    SessionCommand::Disconnect { reason } => {
879                        let reason = reason.unwrap_or(DisconnectReason::DisconnectRequested);
880                        return this.try_disconnect(reason, cx);
881                    }
882                }
883            }
884
885            let deadline = this.request_deadline();
886
887            while let Poll::Ready(Some(req)) = this.internal_request_rx.poll_next_unpin(cx) {
888                progress = true;
889                this.on_internal_peer_request(req, deadline);
890            }
891
892            // Advance all active requests.
893            // We remove each request one by one and add them back.
894            for idx in (0..this.received_requests_from_remote.len()).rev() {
895                let mut req = this.received_requests_from_remote.swap_remove(idx);
896                match req.rx.poll(cx) {
897                    Poll::Pending => {
898                        // not ready yet
899                        this.received_requests_from_remote.push(req);
900                    }
901                    Poll::Ready(resp) => {
902                        this.handle_outgoing_response(req.request_id, resp);
903                    }
904                }
905            }
906
907            // Send messages by advancing the sink and queuing in buffered messages. The sink only
908            // buffers sent messages; the explicit flush happens once per poll after the main
909            // loop, so messages queued across the loop's passes batch up (the sink still writes
910            // out on its own for control messages and when its write buffer runs full).
911            match this.poll_send_queued(cx) {
912                Ok(sent) => progress |= sent,
913                Err(err) => {
914                    debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to send message");
915                    // notify the manager
916                    return this.close_on_error(err, cx)
917                }
918            }
919
920            // read incoming messages from the wire
921            'receive: loop {
922                // ensure we still have enough budget for another iteration
923                budget -= 1;
924                if budget == 0 {
925                    // make sure we're woken up again
926                    cx.waker().wake_by_ref();
927                    break 'main
928                }
929
930                // try to resend the pending message that we could not send because the channel was
931                // full. [`PollSender`] will ensure that we're woken up again when the channel is
932                // ready to receive the message, and will only error if the channel is closed.
933                if let Some(msg) = this.pending_message_to_session.take() {
934                    match this.to_session_manager.poll_reserve(cx) {
935                        Poll::Ready(Ok(_)) => {
936                            let _ = this.to_session_manager.send_item(msg);
937                        }
938                        Poll::Ready(Err(_)) => return Poll::Ready(()),
939                        Poll::Pending => {
940                            this.pending_message_to_session = Some(msg);
941                            break 'receive
942                        }
943                    };
944                }
945
946                // check whether we should throttle incoming messages
947                if this.received_requests_from_remote.len() > MAX_QUEUED_OUTGOING_RESPONSES {
948                    // we're currently waiting for the responses to the peer's requests which aren't
949                    // queued as outgoing yet
950                    //
951                    // Note: we don't need to register the waker here because we polled the requests
952                    // above
953                    break 'receive
954                }
955
956                // we also need to check if we have multiple responses queued up
957                if this.queued_outgoing.response_count() > MAX_QUEUED_OUTGOING_RESPONSES {
958                    // if we've queued up more responses than allowed, we don't poll for new
959                    // messages and break the receive loop early
960                    //
961                    // Note: we don't need to register the waker here because we still have
962                    // queued messages and the sink impl registered the waker because we've
963                    // already advanced it to `Pending` earlier
964                    break 'receive
965                }
966
967                match this.conn.poll_next_unpin(cx) {
968                    Poll::Pending => {
969                        receive_pending = true;
970                        break
971                    }
972                    Poll::Ready(None) => {
973                        if this.is_disconnecting() {
974                            break
975                        }
976                        debug!(target: "net::session", remote_peer_id=?this.remote_peer_id, "eth stream completed");
977                        return this.emit_disconnect(cx)
978                    }
979                    Poll::Ready(Some(res)) => {
980                        match res {
981                            Ok(msg) => {
982                                let outcome = match msg {
983                                    EthSnapMessage::Eth(msg) => {
984                                        trace!(target: "net::session", msg_id=?msg.message_id(), remote_peer_id=?this.remote_peer_id, "received eth message");
985                                        // decode and handle message
986                                        this.on_incoming_message(msg)
987                                    }
988                                    EthSnapMessage::Snap(msg) => this.on_incoming_snap_message(msg),
989                                };
990                                match outcome {
991                                    OnIncomingMessageOutcome::Ok => {
992                                        // handled successfully
993                                        progress = true;
994                                    }
995                                    OnIncomingMessageOutcome::BadMessage { error, message } => {
996                                        debug!(target: "net::session", %error, msg=?message, remote_peer_id=?this.remote_peer_id, "received invalid protocol message");
997                                        this.on_bad_message();
998                                        return this
999                                            .try_disconnect(DisconnectReason::ProtocolBreach, cx)
1000                                    }
1001                                    OnIncomingMessageOutcome::NoCapacity(msg) => {
1002                                        // failed to send due to lack of capacity
1003                                        this.pending_message_to_session = Some(msg);
1004                                    }
1005                                }
1006                            }
1007                            Err(err) => {
1008                                debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to receive message");
1009                                if err.is_protocol_breach() {
1010                                    this.on_bad_message();
1011                                    return this.try_disconnect(DisconnectReason::ProtocolBreach, cx)
1012                                }
1013                                return this.close_on_error(err, cx)
1014                            }
1015                        }
1016                    }
1017                }
1018            }
1019
1020            // Avoid one extra empty outer-loop pass after the wire is pending, unless the receive
1021            // pass produced work that should be driven immediately.
1022            if receive_pending &&
1023                this.queued_outgoing.is_empty() &&
1024                this.pending_message_to_session.is_none() &&
1025                this.received_requests_from_remote.is_empty()
1026            {
1027                break 'main
1028            }
1029
1030            if !progress {
1031                break 'main
1032            }
1033        }
1034
1035        if let Some(interval) = &mut this.range_update_interval {
1036            // Check if we should send a range update based on block height changes
1037            while interval.poll_tick(cx).is_ready() {
1038                let current_latest = this.local_range_info.latest();
1039                // The first update is always sent; after that, only send if block height has
1040                // advanced by at least one epoch (32 blocks).
1041                let should_send = this.last_sent_latest_block.is_none_or(|last_sent| {
1042                    current_latest.saturating_sub(last_sent) >= EPOCH_SLOTS
1043                });
1044
1045                if should_send {
1046                    this.queued_outgoing.push_back(
1047                        EthMessage::BlockRangeUpdate(this.local_range_info.to_message()).into(),
1048                    );
1049                    this.last_sent_latest_block = Some(current_latest);
1050                }
1051            }
1052        }
1053
1054        if !this.inflight_requests.is_empty() {
1055            while this.internal_request_timeout_interval.poll_tick(cx).is_ready() {
1056                // check for timed out requests
1057                if this.check_timed_out_requests(Instant::now()) &&
1058                    let Poll::Ready(Ok(_)) = this.to_session_manager.poll_reserve(cx)
1059                {
1060                    let msg = ActiveSessionMessage::ProtocolBreach { peer_id: this.remote_peer_id };
1061                    this.pending_message_to_session = Some(msg);
1062                }
1063            }
1064        }
1065
1066        // Send anything the interval handlers above queued, then flush the transport for
1067        // everything buffered during this poll. This also resumes a flush that returned pending
1068        // on an earlier poll; a no-op if nothing is buffered.
1069        if let Err(err) = this.poll_send_queued(cx) {
1070            debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to send message");
1071            return this.close_on_error(err, cx)
1072        }
1073        match this.conn.poll_flush_unpin(cx) {
1074            Poll::Pending | Poll::Ready(Ok(())) => {}
1075            Poll::Ready(Err(err)) => {
1076                debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to flush connection");
1077                return this.close_on_error(err, cx)
1078            }
1079        }
1080
1081        // Polling sink readiness can start a keepalive disconnect. Arm its deadline before
1082        // yielding, since the expired keepalive timer cannot wake the session again.
1083        if this.is_disconnecting() {
1084            return this.poll_disconnect(cx)
1085        }
1086
1087        this.shrink_to_fit();
1088
1089        Poll::Pending
1090    }
1091}
1092
1093/// Tracks a request received from the peer
1094pub(crate) struct ReceivedRequest<N: NetworkPrimitives> {
1095    /// Protocol Identifier
1096    request_id: u64,
1097    /// Receiver half of the channel that's supposed to receive the proper response.
1098    rx: PeerResponse<N>,
1099    /// Timestamp when we read this msg from the wire.
1100    #[expect(dead_code)]
1101    received: Instant,
1102}
1103
1104/// A request that waits for a response from the peer
1105pub(crate) struct InflightRequest<R> {
1106    /// Request we sent to peer and the internal response channel
1107    request: RequestState<R>,
1108    /// Instant when the request was sent
1109    timestamp: Instant,
1110    /// Time limit for the response
1111    deadline: Instant,
1112}
1113
1114impl<N: NetworkPrimitives> InflightRequest<PeerRequest<N>> {
1115    /// Returns true if the request is timedout
1116    #[inline]
1117    fn is_timed_out(&self, now: Instant) -> bool {
1118        now > self.deadline
1119    }
1120
1121    /// Returns true if we're still waiting for a response
1122    #[inline]
1123    const fn is_waiting(&self) -> bool {
1124        matches!(self.request, RequestState::Waiting(_))
1125    }
1126
1127    /// This will timeout the request by sending an error response to the internal channel
1128    fn timeout(&mut self) {
1129        let mut req = RequestState::TimedOut;
1130        std::mem::swap(&mut self.request, &mut req);
1131
1132        if let RequestState::Waiting(req) = req {
1133            req.send_err_response(RequestError::Timeout);
1134        }
1135    }
1136}
1137
1138/// All outcome variants when handling an incoming message
1139enum OnIncomingMessageOutcome<N: NetworkPrimitives> {
1140    /// Message successfully handled.
1141    Ok,
1142    /// Message is considered to be in violation of the protocol
1143    BadMessage { error: EthStreamError, message: EthMessage<N> },
1144    /// Currently no capacity to handle the message
1145    NoCapacity(ActiveSessionMessage<N>),
1146}
1147
1148impl<N: NetworkPrimitives> From<Result<(), ActiveSessionMessage<N>>>
1149    for OnIncomingMessageOutcome<N>
1150{
1151    fn from(res: Result<(), ActiveSessionMessage<N>>) -> Self {
1152        match res {
1153            Ok(_) => Self::Ok,
1154            Err(msg) => Self::NoCapacity(msg),
1155        }
1156    }
1157}
1158
1159enum RequestState<R> {
1160    /// Waiting for the response
1161    Waiting(R),
1162    /// Request already timed out
1163    TimedOut,
1164}
1165
1166/// Outgoing messages that can be sent over the wire.
1167#[derive(Debug)]
1168pub(crate) enum OutgoingMessage<N: NetworkPrimitives> {
1169    /// A message that is owned.
1170    Eth(EthMessage<N>),
1171    /// A message that may be shared by multiple sessions.
1172    Broadcast(EthBroadcastMessage<N>),
1173    /// A raw capability message
1174    Raw(RawCapabilityMessage),
1175    /// A `snap/2` message to send over the dedicated `eth`+`snap` stream.
1176    Snap(SnapProtocolMessage),
1177}
1178
1179impl<N: NetworkPrimitives> OutgoingMessage<N> {
1180    /// Returns true if this is a response.
1181    const fn is_response(&self) -> bool {
1182        match self {
1183            Self::Eth(msg) => msg.is_response(),
1184            // Served snap responses count toward response backpressure; outbound snap requests do
1185            // not. `SnapProtocolMessage::is_response` distinguishes the two.
1186            Self::Snap(msg) => msg.is_response(),
1187            Self::Broadcast(_) | Self::Raw(_) => false,
1188        }
1189    }
1190
1191    /// Returns the number of broadcast items in this message.
1192    ///
1193    /// For transaction hash announcements this is the number of hashes, for full transaction
1194    /// broadcasts it is the number of transactions, and for blocks it is 1.
1195    /// Request/response messages return 0.
1196    fn broadcast_item_count(&self) -> usize {
1197        match self {
1198            Self::Eth(msg) => match msg {
1199                EthMessage::NewBlockHashes(h) => h.len(),
1200                EthMessage::NewPooledTransactionHashes66(h) => h.len(),
1201                EthMessage::NewPooledTransactionHashes68(h) => h.hashes.len(),
1202                EthMessage::NewPooledTransactionHashes72(h) => h.hashes.len(),
1203                _ => 0,
1204            },
1205            Self::Broadcast(msg) => match msg {
1206                EthBroadcastMessage::NewBlock(_) => 1,
1207                EthBroadcastMessage::Transactions(txs) => txs.len(),
1208                EthBroadcastMessage::BroadcastPoolTransactions(txs) => txs.len(),
1209            },
1210            Self::Raw(_) | Self::Snap(_) => 0,
1211        }
1212    }
1213
1214    /// Tries to merge pooled transaction hash announcements into this message, consuming the
1215    /// incoming hashes. Returns `Some(incoming)` back if the variants don't match.
1216    fn try_merge_hashes(
1217        &mut self,
1218        incoming: NewPooledTransactionHashes,
1219    ) -> Option<NewPooledTransactionHashes> {
1220        let Self::Eth(eth) = self else { return Some(incoming) };
1221        match (eth, incoming) {
1222            (
1223                EthMessage::NewPooledTransactionHashes66(existing),
1224                NewPooledTransactionHashes::Eth66(inc),
1225            ) => {
1226                existing.extend(inc);
1227                None
1228            }
1229            (
1230                EthMessage::NewPooledTransactionHashes68(existing),
1231                NewPooledTransactionHashes::Eth68(inc),
1232            ) => {
1233                existing.hashes.extend(inc.hashes);
1234                existing.sizes.extend(inc.sizes);
1235                existing.types.extend(inc.types);
1236                None
1237            }
1238            (
1239                EthMessage::NewPooledTransactionHashes72(existing),
1240                NewPooledTransactionHashes::Eth72(inc),
1241            ) => {
1242                // One mask describes every blob transaction in the message.
1243                if existing.cell_mask != inc.cell_mask {
1244                    return Some(inc.into())
1245                }
1246                existing.hashes.extend(inc.hashes);
1247                existing.sizes.extend(inc.sizes);
1248                existing.types.extend(inc.types);
1249                None
1250            }
1251            (_, incoming) => Some(incoming),
1252        }
1253    }
1254}
1255
1256impl<N: NetworkPrimitives> From<EthMessage<N>> for OutgoingMessage<N> {
1257    fn from(value: EthMessage<N>) -> Self {
1258        Self::Eth(value)
1259    }
1260}
1261
1262impl<N: NetworkPrimitives> From<EthBroadcastMessage<N>> for OutgoingMessage<N> {
1263    fn from(value: EthBroadcastMessage<N>) -> Self {
1264        Self::Broadcast(value)
1265    }
1266}
1267
1268/// Returns the interval used to check for timed out requests.
1269///
1270/// Uses delayed missed-tick behavior because the interval is only polled while requests are in
1271/// flight, so ticks that elapsed while the session was idle must not fire in a burst.
1272pub(super) fn request_timeout_interval(timeout: Duration) -> Interval {
1273    let mut interval = tokio::time::interval(timeout);
1274    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1275    interval
1276}
1277
1278/// Calculates a new timeout using an updated estimation of the RTT
1279#[inline]
1280fn calculate_new_timeout(current_timeout: Duration, estimated_rtt: Duration) -> Duration {
1281    let new_timeout = estimated_rtt.mul_f64(SAMPLE_IMPACT) * TIMEOUT_SCALING;
1282
1283    // this dampens sudden changes by taking a weighted mean of the old and new values
1284    let smoothened_timeout = current_timeout.mul_f64(1.0 - SAMPLE_IMPACT) + new_timeout;
1285
1286    smoothened_timeout.clamp(MINIMUM_TIMEOUT, MAXIMUM_TIMEOUT)
1287}
1288
1289/// A helper struct that wraps the queue of outgoing messages with broadcast-aware tracking.
1290///
1291/// Tracks both the total number of queued messages (via a metric gauge) and the total number of
1292/// broadcast items (tx hashes, transactions, blocks) via a shared atomic counter. The atomic
1293/// counter is shared with [`ActiveSessionHandle`](super::handle::ActiveSessionHandle) so the
1294/// [`SessionManager`](super::SessionManager) can apply size-based backpressure.
1295pub(crate) struct QueuedOutgoingMessages<N: NetworkPrimitives> {
1296    messages: VecDeque<OutgoingMessage<N>>,
1297    /// Number of queued response messages, tracked separately so the session can apply
1298    /// backpressure on incoming requests without scanning the whole queue.
1299    queued_responses: usize,
1300    count: Gauge,
1301    /// Shared counter of buffered broadcast items for size-based backpressure.
1302    broadcast_items: BroadcastItemCounter,
1303}
1304
1305impl<N: NetworkPrimitives> QueuedOutgoingMessages<N> {
1306    pub(crate) const fn new(metric: Gauge, broadcast_items: BroadcastItemCounter) -> Self {
1307        Self { messages: VecDeque::new(), queued_responses: 0, count: metric, broadcast_items }
1308    }
1309
1310    /// Returns the number of queued response messages.
1311    pub(crate) const fn response_count(&self) -> usize {
1312        self.queued_responses
1313    }
1314
1315    pub(crate) fn is_empty(&self) -> bool {
1316        self.messages.is_empty()
1317    }
1318
1319    pub(crate) fn push_back(&mut self, message: OutgoingMessage<N>) {
1320        self.queued_responses += message.is_response() as usize;
1321        self.messages.push_back(message);
1322        self.count.increment(1);
1323    }
1324
1325    pub(crate) fn pop_front(&mut self) -> Option<OutgoingMessage<N>> {
1326        self.messages.pop_front().inspect(|msg| {
1327            self.count.decrement(1);
1328            self.queued_responses -= msg.is_response() as usize;
1329            let items = msg.broadcast_item_count();
1330            if items > 0 {
1331                self.broadcast_items.sub(items);
1332            }
1333        })
1334    }
1335
1336    /// Pushes a pooled transaction hash announcement, merging into the last queued message if
1337    /// it is the same variant (eth66, eth68, or eth72) and has a compatible cell mask.
1338    pub(crate) fn push_pooled_hashes(&mut self, msg: NewPooledTransactionHashes) {
1339        let msg = if let Some(last) = self.messages.back_mut() {
1340            match last.try_merge_hashes(msg) {
1341                None => return,
1342                Some(msg) => msg,
1343            }
1344        } else {
1345            msg
1346        };
1347        self.messages.push_back(EthMessage::from(msg).into());
1348        self.count.increment(1);
1349    }
1350
1351    /// Shrinks the queue's capacity back to its steady-state size once it is drained, if it grew
1352    /// well beyond it. The threshold avoids a shrink/regrow reallocation cycle on every poll
1353    /// under regular bursty traffic.
1354    pub(crate) fn shrink_to_fit(&mut self) {
1355        if self.messages.is_empty() && self.messages.capacity() > SHRINK_CAPACITY_THRESHOLD {
1356            self.messages.shrink_to(MAX_QUEUED_OUTGOING_RESPONSES);
1357        }
1358    }
1359}
1360
1361impl<N: NetworkPrimitives> Drop for QueuedOutgoingMessages<N> {
1362    fn drop(&mut self) {
1363        // Ensure gauge is decremented for any remaining items to avoid metric leak on teardown.
1364        let remaining = self.messages.len();
1365        if remaining > 0 {
1366            self.count.decrement(remaining as f64);
1367        }
1368    }
1369}
1370
1371#[cfg(test)]
1372mod tests {
1373    use super::*;
1374    use crate::session::{
1375        conn::EthPeerConnection, handle::PendingSessionEvent, start_pending_incoming_session,
1376    };
1377    use alloy_eips::eip2124::ForkFilter;
1378    use alloy_primitives::{B128, B256};
1379    use futures::task::noop_waker;
1380    use reth_chainspec::MAINNET;
1381    use reth_ecies::stream::ECIESStream;
1382    use reth_eth_wire::{
1383        handshake::EthHandshake, protocol::Protocol, BlockBodies, BlockHeaders,
1384        EthNetworkPrimitives, EthStream, GetBlockAccessLists, GetBlockBodies,
1385        HelloMessageWithProtocols, P2PStream, StatusBuilder, UnauthedEthStream, UnauthedP2PStream,
1386        UnifiedStatus, MAX_PAYLOAD_SIZE,
1387    };
1388    use reth_eth_wire_types::{
1389        message::MAX_MESSAGE_SIZE,
1390        snap::{
1391            AccountRangeMessage, BlockAccessListsMessage, GetAccountRangeMessage,
1392            GetBlockAccessListsMessage,
1393        },
1394        BlockAccessLists, BlockHashNumber, CellMasks, Cells, EthMessageID, GetCells,
1395        NewBlockHashes, NewPooledTransactionHashes72,
1396    };
1397    use reth_ethereum_forks::EthereumHardfork;
1398    use reth_network_p2p::error::RequestResult;
1399    use reth_network_peers::pk2id;
1400    use reth_network_types::session::config::PROTOCOL_BREACH_REQUEST_TIMEOUT;
1401    use secp256k1::SecretKey;
1402    use std::future::poll_fn;
1403    use tokio::{
1404        net::{TcpListener, TcpStream},
1405        sync::mpsc,
1406    };
1407
1408    /// Returns a testing `HelloMessage` and new secretkey
1409    fn eth_hello(server_key: &SecretKey) -> HelloMessageWithProtocols {
1410        HelloMessageWithProtocols::builder(pk2id(&server_key.public_key())).build()
1411    }
1412
1413    struct SessionBuilder<N: NetworkPrimitives = EthNetworkPrimitives> {
1414        _remote_capabilities: Arc<Capabilities>,
1415        active_session_tx: mpsc::Sender<ActiveSessionMessage<N>>,
1416        active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
1417        to_sessions: Vec<mpsc::Sender<SessionCommand<N>>>,
1418        secret_key: SecretKey,
1419        local_peer_id: PeerId,
1420        hello: HelloMessageWithProtocols,
1421        status: UnifiedStatus,
1422        fork_filter: ForkFilter,
1423        next_id: usize,
1424    }
1425
1426    impl<N: NetworkPrimitives> SessionBuilder<N> {
1427        fn next_id(&mut self) -> SessionId {
1428            let id = self.next_id;
1429            self.next_id += 1;
1430            SessionId(id)
1431        }
1432
1433        /// Connects a new Eth stream and executes the given closure with that established stream
1434        fn with_client_stream<F, O>(
1435            &self,
1436            local_addr: SocketAddr,
1437            f: F,
1438        ) -> Pin<Box<dyn Future<Output = ()> + Send>>
1439        where
1440            F: FnOnce(EthStream<P2PStream<ECIESStream<TcpStream>>, N>) -> O + Send + 'static,
1441            O: Future<Output = ()> + Send + Sync,
1442        {
1443            let mut status = self.status;
1444            let fork_filter = self.fork_filter.clone();
1445            let local_peer_id = self.local_peer_id;
1446            let mut hello = self.hello.clone();
1447            let key = SecretKey::new(&mut rand::rng());
1448            hello.id = pk2id(&key.public_key());
1449            Box::pin(async move {
1450                let outgoing = TcpStream::connect(local_addr).await.unwrap();
1451                let sink = ECIESStream::connect(outgoing, key, local_peer_id).await.unwrap();
1452
1453                let (p2p_stream, _) = UnauthedP2PStream::new(sink).handshake(hello).await.unwrap();
1454
1455                let eth_version = p2p_stream.shared_capabilities().eth_version().unwrap();
1456                status.set_eth_version(eth_version);
1457
1458                let (client_stream, _) = UnauthedEthStream::new(p2p_stream)
1459                    .handshake(status, fork_filter)
1460                    .await
1461                    .unwrap();
1462                f(client_stream).await
1463            })
1464        }
1465
1466        async fn connect_incoming(&mut self, stream: TcpStream) -> ActiveSession<N> {
1467            let remote_addr = stream.local_addr().unwrap();
1468            let session_id = self.next_id();
1469            let (_disconnect_tx, disconnect_rx) = oneshot::channel();
1470            let (pending_sessions_tx, pending_sessions_rx) = mpsc::channel(1);
1471
1472            tokio::task::spawn(start_pending_incoming_session(
1473                Arc::new(EthHandshake::default()),
1474                MAX_MESSAGE_SIZE,
1475                MAX_PAYLOAD_SIZE,
1476                disconnect_rx,
1477                session_id,
1478                stream,
1479                pending_sessions_tx,
1480                remote_addr,
1481                self.secret_key,
1482                self.hello.clone(),
1483                self.status,
1484                self.fork_filter.clone(),
1485                Default::default(),
1486            ));
1487
1488            let mut stream = ReceiverStream::new(pending_sessions_rx);
1489
1490            match stream.next().await.unwrap() {
1491                PendingSessionEvent::Established {
1492                    session_id,
1493                    remote_addr,
1494                    peer_id,
1495                    capabilities,
1496                    conn,
1497                    ..
1498                } => {
1499                    let (_to_session_tx, messages_rx) = mpsc::channel(10);
1500                    let (commands_to_session, commands_rx) = mpsc::channel(10);
1501                    let (_unbounded_tx, unbounded_rx) = mpsc::unbounded_channel();
1502                    let poll_sender = PollSender::new(self.active_session_tx.clone());
1503
1504                    self.to_sessions.push(commands_to_session);
1505
1506                    ActiveSession {
1507                        next_id: 0,
1508                        remote_peer_id: peer_id,
1509                        remote_addr,
1510                        remote_capabilities: Arc::clone(&capabilities),
1511                        session_id,
1512                        commands_rx: ReceiverStream::new(commands_rx),
1513                        unbounded_rx,
1514                        unbounded_broadcast_msgs: Counter::noop(),
1515                        to_session_manager: MeteredPollSender::new(
1516                            poll_sender,
1517                            "network_active_session",
1518                        ),
1519                        pending_message_to_session: None,
1520                        internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
1521                        inflight_requests: Default::default(),
1522                        conn,
1523                        queued_outgoing: QueuedOutgoingMessages::new(
1524                            Gauge::noop(),
1525                            BroadcastItemCounter::new(),
1526                        ),
1527                        received_requests_from_remote: Default::default(),
1528                        internal_request_timeout_interval: request_timeout_interval(
1529                            INITIAL_REQUEST_TIMEOUT,
1530                        ),
1531                        internal_request_timeout: Arc::new(AtomicU64::new(
1532                            INITIAL_REQUEST_TIMEOUT.as_millis() as u64,
1533                        )),
1534                        protocol_breach_request_timeout: PROTOCOL_BREACH_REQUEST_TIMEOUT,
1535                        terminate_message: None,
1536                        range_info: None,
1537                        local_range_info: BlockRangeInfo::new(
1538                            0,
1539                            1000,
1540                            alloy_primitives::B256::ZERO,
1541                        ),
1542                        range_update_interval: None,
1543                        last_sent_latest_block: None,
1544                        disconnect_deadline: None,
1545                    }
1546                }
1547                ev => {
1548                    panic!("unexpected message {ev:?}")
1549                }
1550            }
1551        }
1552
1553        async fn connect_idle_peer(&mut self) -> (ActiveSession<N>, EthPeerConnection<N>) {
1554            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1555            let (client_tx, client_rx) = oneshot::channel();
1556            let addr = listener.local_addr().unwrap();
1557            tokio::spawn(self.with_client_stream(addr, async move |peer| {
1558                let _ = client_tx.send(peer);
1559            }));
1560            let (incoming, _) = listener.accept().await.unwrap();
1561            (self.connect_incoming(incoming).await, client_rx.await.unwrap())
1562        }
1563    }
1564
1565    impl Default for SessionBuilder {
1566        fn default() -> Self {
1567            let (active_session_tx, active_session_rx) = mpsc::channel(100);
1568
1569            let (secret_key, pk) = secp256k1::generate_keypair(&mut rand::rng());
1570            let local_peer_id = pk2id(&pk);
1571
1572            Self {
1573                next_id: 0,
1574                _remote_capabilities: Arc::new(Capabilities::from(vec![])),
1575                active_session_tx,
1576                active_session_rx: ReceiverStream::new(active_session_rx),
1577                to_sessions: vec![],
1578                hello: eth_hello(&secret_key),
1579                secret_key,
1580                local_peer_id,
1581                status: StatusBuilder::default().build(),
1582                fork_filter: MAINNET
1583                    .hardfork_fork_filter(EthereumHardfork::Frontier)
1584                    .expect("The Frontier fork filter should exist on mainnet"),
1585            }
1586        }
1587    }
1588
1589    /// Returns a [`SessionBuilder`] whose hello also advertises `snap/2`, so the negotiated
1590    /// session ends up on an [`EthSnapStream`](reth_eth_wire::EthSnapStream) connection instead
1591    /// of a plain `eth`-only one.
1592    fn snap_session_builder() -> SessionBuilder {
1593        let mut builder = SessionBuilder::default();
1594        builder.hello.try_add_protocol(Protocol::snap_2()).unwrap();
1595        builder
1596    }
1597
1598    /// Dispatches a `snap/2` request via [`ActiveSession::on_internal_peer_request`] and returns
1599    /// the session-assigned request id plus the caller's response receiver.
1600    fn dispatch_snap_request(
1601        session: &mut ActiveSession<EthNetworkPrimitives>,
1602        caller_request_id: u64,
1603    ) -> (u64, oneshot::Receiver<RequestResult<SnapResponse>>) {
1604        let (response, rx) = oneshot::channel();
1605        let request = SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
1606            request_id: caller_request_id,
1607            block_hashes: Vec::new(),
1608            response_bytes: 0,
1609        });
1610        let deadline = session.request_deadline();
1611        session.on_internal_peer_request(PeerRequest::GetSnap { request, response }, deadline);
1612        let id = *session.inflight_requests.keys().next().expect("snap request tracked");
1613        (id, rx)
1614    }
1615
1616    /// Dispatches an `eth` `GetBlockBodies` request via
1617    /// [`ActiveSession::on_internal_peer_request`] and returns the session-assigned request id plus
1618    /// the caller's response receiver.
1619    fn dispatch_block_bodies_request(
1620        session: &mut ActiveSession<EthNetworkPrimitives>,
1621    ) -> (u64, oneshot::Receiver<RequestResult<BlockBodies>>) {
1622        let (response, rx) = oneshot::channel();
1623        let deadline = session.request_deadline();
1624        session.on_internal_peer_request(
1625            PeerRequest::GetBlockBodies { request: GetBlockBodies(Vec::new()), response },
1626            deadline,
1627        );
1628        let id = *session.inflight_requests.keys().next().expect("eth request tracked");
1629        (id, rx)
1630    }
1631
1632    #[tokio::test(flavor = "multi_thread")]
1633    async fn test_disconnect() {
1634        let mut builder = SessionBuilder::default();
1635
1636        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1637        let local_addr = listener.local_addr().unwrap();
1638
1639        let expected_disconnect = DisconnectReason::UselessPeer;
1640
1641        let fut = builder.with_client_stream(local_addr, async move |mut client_stream| {
1642            let msg = client_stream.next().await.unwrap().unwrap_err();
1643            assert_eq!(msg.as_disconnected().unwrap(), expected_disconnect);
1644        });
1645
1646        tokio::task::spawn(async move {
1647            let (incoming, _) = listener.accept().await.unwrap();
1648            let mut session = builder.connect_incoming(incoming).await;
1649
1650            session.start_disconnect(expected_disconnect).unwrap();
1651            session.await
1652        });
1653
1654        fut.await;
1655    }
1656
1657    #[tokio::test(flavor = "multi_thread")]
1658    async fn test_invalid_message_disconnects_with_protocol_breach() {
1659        let mut builder = SessionBuilder::default();
1660
1661        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1662        let local_addr = listener.local_addr().unwrap();
1663
1664        let fut = builder.with_client_stream(local_addr, async move |mut client_stream| {
1665            client_stream
1666                .start_send_raw(RawCapabilityMessage::eth(
1667                    EthMessageID::PooledTransactions,
1668                    vec![0xc0].into(),
1669                ))
1670                .unwrap();
1671            client_stream.flush().await.unwrap();
1672
1673            let msg = client_stream.next().await.unwrap().unwrap_err();
1674            assert_eq!(msg.as_disconnected(), Some(DisconnectReason::ProtocolBreach));
1675        });
1676
1677        let (tx, rx) = oneshot::channel();
1678
1679        tokio::task::spawn(async move {
1680            let (incoming, _) = listener.accept().await.unwrap();
1681            let session = builder.connect_incoming(incoming).await;
1682            session.await;
1683
1684            tx.send(()).unwrap();
1685        });
1686
1687        fut.await;
1688        rx.await.unwrap();
1689    }
1690
1691    #[tokio::test(flavor = "multi_thread")]
1692    async fn test_unsolicited_response_disconnects_with_protocol_breach() {
1693        let mut builder = SessionBuilder::default();
1694
1695        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1696        let local_addr = listener.local_addr().unwrap();
1697
1698        let fut = builder.with_client_stream(local_addr, async move |mut client_stream| {
1699            assert_eq!(client_stream.version(), EthVersion::Eth71);
1700            client_stream
1701                .send(EthMessage::BlockAccessLists(RequestPair {
1702                    request_id: 7,
1703                    message: BlockAccessLists(vec![None; 1024]),
1704                }))
1705                .await
1706                .unwrap();
1707
1708            let msg = client_stream.next().await.unwrap().unwrap_err();
1709            assert_eq!(msg.as_disconnected(), Some(DisconnectReason::ProtocolBreach));
1710        });
1711
1712        let (tx, rx) = oneshot::channel();
1713
1714        tokio::task::spawn(async move {
1715            let (incoming, _) = listener.accept().await.unwrap();
1716            let session = builder.connect_incoming(incoming).await;
1717            session.await;
1718
1719            tx.send(()).unwrap();
1720        });
1721
1722        fut.await;
1723        rx.await.unwrap();
1724    }
1725
1726    #[tokio::test(flavor = "multi_thread")]
1727    async fn handle_dropped_stream() {
1728        let mut builder = SessionBuilder::default();
1729
1730        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1731        let local_addr = listener.local_addr().unwrap();
1732
1733        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1734            drop(client_stream);
1735            tokio::time::sleep(Duration::from_secs(1)).await
1736        });
1737
1738        let (tx, rx) = oneshot::channel();
1739
1740        tokio::task::spawn(async move {
1741            let (incoming, _) = listener.accept().await.unwrap();
1742            let session = builder.connect_incoming(incoming).await;
1743            session.await;
1744
1745            tx.send(()).unwrap();
1746        });
1747
1748        tokio::task::spawn(fut);
1749
1750        rx.await.unwrap();
1751    }
1752
1753    #[tokio::test(flavor = "multi_thread")]
1754    async fn test_send_many_messages() {
1755        reth_tracing::init_test_tracing();
1756        let mut builder = SessionBuilder::default();
1757
1758        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1759        let local_addr = listener.local_addr().unwrap();
1760
1761        let num_messages = 100;
1762
1763        let fut = builder.with_client_stream(local_addr, async move |mut client_stream| {
1764            for _ in 0..num_messages {
1765                client_stream
1766                    .send(EthMessage::NewPooledTransactionHashes66(Vec::new().into()))
1767                    .await
1768                    .unwrap();
1769            }
1770        });
1771
1772        let (tx, rx) = oneshot::channel();
1773
1774        tokio::task::spawn(async move {
1775            let (incoming, _) = listener.accept().await.unwrap();
1776            let session = builder.connect_incoming(incoming).await;
1777            session.await;
1778
1779            tx.send(()).unwrap();
1780        });
1781
1782        tokio::task::spawn(fut);
1783
1784        rx.await.unwrap();
1785    }
1786
1787    #[tokio::test(flavor = "multi_thread")]
1788    async fn test_request_timeout() {
1789        reth_tracing::init_test_tracing();
1790
1791        let mut builder = SessionBuilder::default();
1792
1793        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1794        let local_addr = listener.local_addr().unwrap();
1795
1796        let request_timeout = Duration::from_millis(100);
1797        let drop_timeout = Duration::from_millis(1500);
1798
1799        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1800            let _client_stream = client_stream;
1801            tokio::time::sleep(drop_timeout * 60).await;
1802        });
1803        tokio::task::spawn(fut);
1804
1805        let (incoming, _) = listener.accept().await.unwrap();
1806        let mut session = builder.connect_incoming(incoming).await;
1807        session
1808            .internal_request_timeout
1809            .store(request_timeout.as_millis() as u64, Ordering::Relaxed);
1810        session.protocol_breach_request_timeout = drop_timeout;
1811        session.internal_request_timeout_interval =
1812            tokio::time::interval_at(tokio::time::Instant::now(), request_timeout);
1813        session
1814            .internal_request_timeout_interval
1815            .set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1816        let (tx, rx) = oneshot::channel();
1817        let req = PeerRequest::GetBlockBodies { request: GetBlockBodies(vec![]), response: tx };
1818        session.on_internal_peer_request(req, Instant::now());
1819        tokio::spawn(session);
1820
1821        let err = rx.await.unwrap().unwrap_err();
1822        assert_eq!(err, RequestError::Timeout);
1823
1824        // wait for protocol breach error
1825        let msg = builder.active_session_rx.next().await.unwrap();
1826        match msg {
1827            ActiveSessionMessage::ProtocolBreach { .. } => {}
1828            ev => unreachable!("{ev:?}"),
1829        }
1830    }
1831
1832    #[tokio::test(flavor = "multi_thread")]
1833    async fn snap_request_is_assigned_unique_id_and_response_correlated() {
1834        let mut builder = snap_session_builder();
1835        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1836        let local_addr = listener.local_addr().unwrap();
1837        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1838            let _client_stream = client_stream;
1839            tokio::time::sleep(Duration::from_secs(60)).await;
1840        });
1841        tokio::task::spawn(fut);
1842        let (incoming, _) = listener.accept().await.unwrap();
1843        let mut session = builder.connect_incoming(incoming).await;
1844
1845        // The session assigns its own request id (not the caller's sentinel) and tracks it.
1846        let (id, rx) = dispatch_snap_request(&mut session, u64::MAX);
1847        assert_ne!(id, u64::MAX, "session must assign its own request id");
1848
1849        // A response carrying that id is correlated back to the caller's future.
1850        let outcome = session.on_incoming_snap_message(SnapProtocolMessage::BlockAccessLists(
1851            BlockAccessListsMessage {
1852                request_id: id,
1853                block_access_lists: BlockAccessLists(Vec::new()),
1854            },
1855        ));
1856        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
1857        assert!(!session.inflight_requests.contains_key(&id));
1858
1859        // The delivered response carries the caller's original id again, not the session's.
1860        let response = rx.await.unwrap().unwrap();
1861        assert!(matches!(
1862            response,
1863            SnapResponse::BlockAccessLists(m) if m.request_id == u64::MAX
1864        ));
1865    }
1866
1867    #[tokio::test(flavor = "multi_thread")]
1868    async fn wrong_type_snap_response_is_rejected() {
1869        let mut builder = snap_session_builder();
1870        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1871        let local_addr = listener.local_addr().unwrap();
1872        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1873            let _client_stream = client_stream;
1874            tokio::time::sleep(Duration::from_secs(60)).await;
1875        });
1876        tokio::task::spawn(fut);
1877        let (incoming, _) = listener.accept().await.unwrap();
1878        let mut session = builder.connect_incoming(incoming).await;
1879
1880        let (id, rx) = dispatch_snap_request(&mut session, 0);
1881
1882        // Answering a GetBlockAccessLists with an AccountRange under the same id is a bad message.
1883        let outcome = session.on_incoming_snap_message(SnapProtocolMessage::AccountRange(
1884            AccountRangeMessage { request_id: id, accounts: Vec::new(), proof: Vec::new() },
1885        ));
1886        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
1887        assert!(!session.inflight_requests.contains_key(&id));
1888        assert_eq!(rx.await.unwrap().unwrap_err(), RequestError::BadResponse);
1889        assert!(matches!(
1890            builder.active_session_rx.next().await,
1891            Some(ActiveSessionMessage::BadMessage { .. })
1892        ));
1893    }
1894
1895    #[tokio::test(flavor = "multi_thread")]
1896    async fn late_snap_response_is_consumed_without_penalty() {
1897        let mut builder = snap_session_builder();
1898        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1899        let local_addr = listener.local_addr().unwrap();
1900        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1901            let _client_stream = client_stream;
1902            tokio::time::sleep(Duration::from_secs(60)).await;
1903        });
1904        tokio::task::spawn(fut);
1905        let (incoming, _) = listener.accept().await.unwrap();
1906        let mut session = builder.connect_incoming(incoming).await;
1907
1908        session.internal_request_timeout.store(1, Ordering::Relaxed);
1909        let (id, rx) = dispatch_snap_request(&mut session, 0);
1910        tokio::time::sleep(Duration::from_millis(20)).await;
1911        assert!(!session.check_timed_out_requests(Instant::now()));
1912        assert_eq!(rx.await.unwrap().unwrap_err(), RequestError::Timeout);
1913
1914        // A response arriving after the timeout clears the entry without a bad-message report.
1915        let outcome = session.on_incoming_snap_message(SnapProtocolMessage::BlockAccessLists(
1916            BlockAccessListsMessage {
1917                request_id: id,
1918                block_access_lists: BlockAccessLists(Vec::new()),
1919            },
1920        ));
1921        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
1922        assert!(!session.inflight_requests.contains_key(&id));
1923        assert!(futures::FutureExt::now_or_never(builder.active_session_rx.next())
1924            .flatten()
1925            .is_none());
1926    }
1927
1928    #[tokio::test(flavor = "multi_thread")]
1929    async fn unknown_snap_response_is_penalized() {
1930        let mut builder = snap_session_builder();
1931        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1932        let local_addr = listener.local_addr().unwrap();
1933        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1934            let _client_stream = client_stream;
1935            tokio::time::sleep(Duration::from_secs(60)).await;
1936        });
1937        tokio::task::spawn(fut);
1938        let (incoming, _) = listener.accept().await.unwrap();
1939        let mut session = builder.connect_incoming(incoming).await;
1940
1941        // A response for a request we never sent is dropped and reported as a bad message.
1942        let outcome = session.on_incoming_snap_message(SnapProtocolMessage::BlockAccessLists(
1943            BlockAccessListsMessage {
1944                request_id: 999,
1945                block_access_lists: BlockAccessLists(Vec::new()),
1946            },
1947        ));
1948        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
1949        assert!(session.inflight_requests.is_empty());
1950        assert!(session.queued_outgoing.pop_front().is_none());
1951        assert!(matches!(
1952            builder.active_session_rx.next().await,
1953            Some(ActiveSessionMessage::BadMessage { .. })
1954        ));
1955    }
1956
1957    #[tokio::test(flavor = "multi_thread")]
1958    async fn wrong_type_eth_response_is_penalized() {
1959        let mut builder = SessionBuilder::default();
1960        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1961        let local_addr = listener.local_addr().unwrap();
1962        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1963            let _client_stream = client_stream;
1964            tokio::time::sleep(Duration::from_secs(60)).await;
1965        });
1966        tokio::task::spawn(fut);
1967        let (incoming, _) = listener.accept().await.unwrap();
1968        let mut session = builder.connect_incoming(incoming).await;
1969
1970        let (id, rx) = dispatch_block_bodies_request(&mut session);
1971
1972        // The peer knows this id because we sent it. Answering the GetBlockBodies with BlockHeaders
1973        // cancels our request, so it must cost the peer reputation, otherwise the peer can kill
1974        // every request we make for free.
1975        let outcome = session.on_incoming_message(EthMessage::BlockHeaders(RequestPair {
1976            request_id: id,
1977            message: BlockHeaders(Vec::new()),
1978        }));
1979        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
1980        assert!(!session.inflight_requests.contains_key(&id));
1981        assert_eq!(rx.await.unwrap().unwrap_err(), RequestError::BadResponse);
1982        assert!(matches!(
1983            futures::FutureExt::now_or_never(builder.active_session_rx.next()).flatten(),
1984            Some(ActiveSessionMessage::BadMessage { .. })
1985        ));
1986    }
1987
1988    #[tokio::test(flavor = "multi_thread")]
1989    async fn matching_eth_response_is_not_penalized() {
1990        let mut builder = SessionBuilder::default();
1991        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1992        let local_addr = listener.local_addr().unwrap();
1993        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
1994            let _client_stream = client_stream;
1995            tokio::time::sleep(Duration::from_secs(60)).await;
1996        });
1997        tokio::task::spawn(fut);
1998        let (incoming, _) = listener.accept().await.unwrap();
1999        let mut session = builder.connect_incoming(incoming).await;
2000
2001        let (id, rx) = dispatch_block_bodies_request(&mut session);
2002
2003        let outcome = session.on_incoming_message(EthMessage::BlockBodies(RequestPair {
2004            request_id: id,
2005            message: BlockBodies(Vec::new()),
2006        }));
2007        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
2008        assert!(!session.inflight_requests.contains_key(&id));
2009        assert!(rx.await.unwrap().is_ok());
2010        assert!(futures::FutureExt::now_or_never(builder.active_session_rx.next())
2011            .flatten()
2012            .is_none());
2013    }
2014
2015    #[tokio::test(flavor = "multi_thread")]
2016    async fn snap_response_to_eth_request_is_penalized() {
2017        let mut builder = snap_session_builder();
2018        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2019        let local_addr = listener.local_addr().unwrap();
2020        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
2021            let _client_stream = client_stream;
2022            tokio::time::sleep(Duration::from_secs(60)).await;
2023        });
2024        tokio::task::spawn(fut);
2025        let (incoming, _) = listener.accept().await.unwrap();
2026        let mut session = builder.connect_incoming(incoming).await;
2027
2028        // `eth` and `snap/2` requests share one id space, so a snap response can land on a pending
2029        // eth request. It cancels that request just the same and is penalized the same way.
2030        let (id, rx) = dispatch_block_bodies_request(&mut session);
2031
2032        let outcome = session.on_incoming_snap_message(SnapProtocolMessage::AccountRange(
2033            AccountRangeMessage { request_id: id, accounts: Vec::new(), proof: Vec::new() },
2034        ));
2035        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
2036        assert!(!session.inflight_requests.contains_key(&id));
2037        assert_eq!(rx.await.unwrap().unwrap_err(), RequestError::BadResponse);
2038        assert!(matches!(
2039            futures::FutureExt::now_or_never(builder.active_session_rx.next()).flatten(),
2040            Some(ActiveSessionMessage::BadMessage { .. })
2041        ));
2042    }
2043
2044    #[tokio::test(flavor = "multi_thread")]
2045    async fn invalid_local_cells_requests_do_not_affect_session() {
2046        tokio::time::timeout(Duration::from_secs(15), async {
2047            let mut builder = SessionBuilder::default();
2048            builder.hello = HelloMessageWithProtocols::builder(builder.local_peer_id)
2049                .protocols(vec![EthVersion::Eth73.into()])
2050                .build();
2051            builder.status.set_eth_version(EthVersion::Eth73);
2052            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2053            let valid = GetCells::from_masks(
2054                vec![B256::ZERO, B256::repeat_byte(1)],
2055                vec![B128::repeat_byte(1), B128::repeat_byte(2)],
2056            )
2057            .unwrap();
2058            let expected = valid.clone();
2059            let reply = Cells {
2060                cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Default::default() },
2061                ..Default::default()
2062            };
2063            let client_reply = reply.clone();
2064            let client = tokio::spawn(builder.with_client_stream(
2065                listener.local_addr().unwrap(),
2066                async move |mut stream| {
2067                    let EthMessage::GetCells(request) = stream.next().await.unwrap().unwrap()
2068                    else {
2069                        panic!("expected the valid cell request")
2070                    };
2071                    assert_eq!(request.message, expected);
2072                    stream
2073                        .send(EthMessage::Cells(RequestPair {
2074                            request_id: request.request_id,
2075                            message: client_reply,
2076                        }))
2077                        .await
2078                        .unwrap();
2079                },
2080            ));
2081            let (incoming, _) = listener.accept().await.unwrap();
2082            let mut session = builder.connect_incoming(incoming).await;
2083            assert_eq!(session.conn.version(), EthVersion::Eth73);
2084            let mut invalid = Vec::new();
2085            for ids in [vec![0], vec![0, 2], vec![1, 0], vec![0, 0]] {
2086                invalid.push(GetCells {
2087                    hashes: valid.hashes.clone(),
2088                    cell_mask: CellMasks::Indexed {
2089                        masks: vec![B128::repeat_byte(1), B128::repeat_byte(2)],
2090                        mask_ids: ids.into(),
2091                    },
2092                });
2093            }
2094            invalid
2095                .push(GetCells { hashes: vec![B256::ZERO; 2], cell_mask: valid.cell_mask.clone() });
2096            invalid.push(GetCells {
2097                hashes: valid.hashes.clone(),
2098                cell_mask: CellMasks::Indexed {
2099                    masks: vec![B128::ZERO; 2],
2100                    mask_ids: vec![0, 1].into(),
2101                },
2102            });
2103            invalid.push(GetCells {
2104                hashes: vec![],
2105                cell_mask: CellMasks::Indexed { masks: vec![], mask_ids: Default::default() },
2106            });
2107            invalid.push(GetCells {
2108                hashes: valid.hashes.clone(),
2109                cell_mask: CellMasks::Indexed {
2110                    masks: vec![B128::ZERO],
2111                    mask_ids: vec![0, 0].into(),
2112                },
2113            });
2114            for request in invalid {
2115                let (response, rx) = oneshot::channel();
2116                let deadline = session.request_deadline();
2117                session.on_internal_peer_request(
2118                    PeerRequest::GetCells { request, response },
2119                    deadline,
2120                );
2121                assert_eq!(rx.await.unwrap(), Err(RequestError::InvalidRequest));
2122                assert!(session.inflight_requests.is_empty());
2123                assert!(session.queued_outgoing.is_empty());
2124                assert_eq!(session.next_id, 0);
2125                assert!(!session.is_disconnecting());
2126            }
2127            assert!(futures::FutureExt::now_or_never(builder.active_session_rx.next()).is_none());
2128            let (response, rx) = oneshot::channel();
2129            let deadline = session.request_deadline();
2130            session.on_internal_peer_request(
2131                PeerRequest::GetCells { request: valid, response },
2132                deadline,
2133            );
2134            assert_eq!(session.next_id, 1);
2135            let session_task = tokio::spawn(session);
2136            assert_eq!(rx.await.unwrap(), Ok(reply));
2137            client.await.unwrap();
2138            session_task.await.unwrap();
2139        })
2140        .await
2141        .expect("cell request rejection and subsequent round trip timed out");
2142    }
2143
2144    #[tokio::test(flavor = "multi_thread")]
2145    async fn get_snap_request_rejected_without_negotiated_snap() {
2146        // A plain `eth`-only session: no `snap/2` was negotiated.
2147        let mut builder = SessionBuilder::default();
2148        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2149        let local_addr = listener.local_addr().unwrap();
2150        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
2151            let _client_stream = client_stream;
2152            tokio::time::sleep(Duration::from_secs(60)).await;
2153        });
2154        tokio::task::spawn(fut);
2155        let (incoming, _) = listener.accept().await.unwrap();
2156        let mut session = builder.connect_incoming(incoming).await;
2157        assert!(!session.conn.supports_snap());
2158
2159        let (response, rx) = oneshot::channel();
2160        let request = SnapProtocolMessage::GetBlockAccessLists(GetBlockAccessListsMessage {
2161            request_id: 0,
2162            block_hashes: Vec::new(),
2163            response_bytes: 0,
2164        });
2165        let deadline = session.request_deadline();
2166        session.on_internal_peer_request(PeerRequest::GetSnap { request, response }, deadline);
2167
2168        // Rejected immediately instead of being queued for a connection that can't send it.
2169        assert!(session.inflight_requests.is_empty());
2170        assert!(session.queued_outgoing.pop_front().is_none());
2171        assert_eq!(rx.await.unwrap().unwrap_err(), RequestError::UnsupportedCapability);
2172    }
2173
2174    #[tokio::test(flavor = "multi_thread")]
2175    async fn inbound_snap_request_round_trips_to_a_response() {
2176        let mut builder = snap_session_builder();
2177        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2178        let local_addr = listener.local_addr().unwrap();
2179        let fut = builder.with_client_stream(local_addr, async move |client_stream| {
2180            let _client_stream = client_stream;
2181            tokio::time::sleep(Duration::from_secs(60)).await;
2182        });
2183        tokio::task::spawn(fut);
2184        let (incoming, _) = listener.accept().await.unwrap();
2185        let mut session = builder.connect_incoming(incoming).await;
2186
2187        // The peer sends an inbound GetAccountRange request.
2188        let outcome = session.on_incoming_snap_message(SnapProtocolMessage::GetAccountRange(
2189            GetAccountRangeMessage {
2190                request_id: 7,
2191                root_hash: B256::ZERO,
2192                starting_hash: B256::ZERO,
2193                limit_hash: B256::ZERO,
2194                response_bytes: 1024,
2195            },
2196        ));
2197        assert!(matches!(outcome, OnIncomingMessageOutcome::Ok));
2198        assert_eq!(session.received_requests_from_remote.len(), 1);
2199
2200        // It's routed upward instead of being served inline.
2201        let Some(ActiveSessionMessage::ValidMessage {
2202            message: PeerMessage::EthRequest(PeerRequest::GetSnap { request, response }),
2203            ..
2204        }) = builder.active_session_rx.next().await
2205        else {
2206            panic!("expected an outbound GetSnap request")
2207        };
2208        assert!(matches!(request, SnapProtocolMessage::GetAccountRange(_)));
2209
2210        // The handler answers with an empty-but-valid range.
2211        let _ = response.send(Ok(SnapResponse::AccountRange(AccountRangeMessage {
2212            request_id: 7,
2213            accounts: Vec::new(),
2214            proof: Vec::new(),
2215        })));
2216
2217        // Drive the same conversion the session's main poll loop would.
2218        let mut req = session.received_requests_from_remote.pop().unwrap();
2219        let waker = noop_waker();
2220        let mut cx = Context::from_waker(&waker);
2221        let Poll::Ready(resp) = req.rx.poll(&mut cx) else { panic!("response should be ready") };
2222        session.handle_outgoing_response(req.request_id, resp);
2223
2224        // The reply goes out as a snap/2 message carrying the original request id, not an eth
2225        // message.
2226        let msg = session.queued_outgoing.pop_front().expect("response queued for send");
2227        assert!(matches!(
2228            msg,
2229            OutgoingMessage::Snap(SnapProtocolMessage::AccountRange(AccountRangeMessage {
2230                request_id: 7,
2231                ..
2232            }))
2233        ));
2234    }
2235
2236    #[test]
2237    fn eth72_coalescing_preserves_cell_masks() {
2238        let masks =
2239            [None, Some(B128::repeat_byte(0xff)), Some(B128::from(1u128)), Some(B128::from(2u128))];
2240        for existing_mask in masks {
2241            for incoming_mask in masks {
2242                let announcement = |mask: Option<B128>, byte| NewPooledTransactionHashes72 {
2243                    types: vec![if mask.is_some() { 3 } else { 2 }],
2244                    sizes: vec![100],
2245                    hashes: vec![B256::repeat_byte(byte)],
2246                    cell_mask: mask,
2247                };
2248                let existing = announcement(existing_mask, 1);
2249                let incoming = announcement(incoming_mask, 2);
2250                let mut message: OutgoingMessage<EthNetworkPrimitives> =
2251                    EthMessage::NewPooledTransactionHashes72(existing.clone()).into();
2252
2253                let remainder = message.try_merge_hashes(incoming.clone().into());
2254
2255                let OutgoingMessage::Eth(EthMessage::NewPooledTransactionHashes72(merged)) =
2256                    message
2257                else {
2258                    panic!("expected eth72 announcement");
2259                };
2260                if existing_mask == incoming_mask {
2261                    assert!(remainder.is_none());
2262                    assert_eq!(merged.cell_mask, existing_mask);
2263                    assert_eq!(merged.hashes, vec![B256::repeat_byte(1), B256::repeat_byte(2)]);
2264                    assert_eq!(merged.types, [existing.types, incoming.types].concat());
2265                    assert_eq!(merged.sizes, vec![100, 100]);
2266                } else {
2267                    assert_eq!(remainder, Some(incoming.into()));
2268                    assert_eq!(merged, existing);
2269                }
2270            }
2271        }
2272    }
2273
2274    #[test]
2275    fn eth72_pooled_hashes_count_broadcast_items() {
2276        let hashes =
2277            vec![alloy_primitives::B256::repeat_byte(1), alloy_primitives::B256::repeat_byte(2)];
2278        let msg: OutgoingMessage<EthNetworkPrimitives> =
2279            EthMessage::NewPooledTransactionHashes72(NewPooledTransactionHashes72 {
2280                types: vec![0; hashes.len()],
2281                sizes: vec![1; hashes.len()],
2282                hashes,
2283                cell_mask: None,
2284            })
2285            .into();
2286
2287        assert_eq!(2, msg.broadcast_item_count());
2288    }
2289
2290    #[test]
2291    fn test_reject_bal_request_for_eth70() {
2292        let (tx, _rx) = oneshot::channel();
2293        let request: PeerRequest<EthNetworkPrimitives> =
2294            PeerRequest::GetBlockAccessLists { request: GetBlockAccessLists(vec![]), response: tx };
2295
2296        assert!(!ActiveSession::<EthNetworkPrimitives>::is_request_supported_for_version(
2297            &request,
2298            EthVersion::Eth70
2299        ));
2300        assert!(ActiveSession::<EthNetworkPrimitives>::is_request_supported_for_version(
2301            &request,
2302            EthVersion::Eth71
2303        ));
2304    }
2305
2306    #[tokio::test(flavor = "multi_thread")]
2307    async fn test_keep_alive() {
2308        let mut builder = SessionBuilder::default();
2309
2310        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2311        let local_addr = listener.local_addr().unwrap();
2312
2313        let fut = builder.with_client_stream(local_addr, async move |mut client_stream| {
2314            let _ = tokio::time::timeout(Duration::from_secs(1), client_stream.next()).await;
2315            client_stream.into_inner().disconnect(DisconnectReason::UselessPeer).await.unwrap();
2316        });
2317
2318        let (tx, rx) = oneshot::channel();
2319
2320        tokio::task::spawn(async move {
2321            let (incoming, _) = listener.accept().await.unwrap();
2322            let session = builder.connect_incoming(incoming).await;
2323            session.await;
2324
2325            tx.send(()).unwrap();
2326        });
2327
2328        tokio::task::spawn(fut);
2329
2330        rx.await.unwrap();
2331    }
2332
2333    // This tests that incoming messages are delivered when there's capacity.
2334    #[tokio::test(flavor = "multi_thread")]
2335    async fn test_send_at_capacity() {
2336        let mut builder = SessionBuilder::default();
2337
2338        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2339        let local_addr = listener.local_addr().unwrap();
2340
2341        let fut = builder.with_client_stream(local_addr, async move |mut client_stream| {
2342            client_stream
2343                .send(EthMessage::NewPooledTransactionHashes68(Default::default()))
2344                .await
2345                .unwrap();
2346            let _ = tokio::time::timeout(Duration::from_secs(100), client_stream.next()).await;
2347        });
2348        tokio::task::spawn(fut);
2349
2350        let (incoming, _) = listener.accept().await.unwrap();
2351        let session = builder.connect_incoming(incoming).await;
2352
2353        // fill the entire message buffer with an unrelated message
2354        let mut num_fill_messages = 0;
2355        loop {
2356            if builder
2357                .active_session_tx
2358                .try_send(ActiveSessionMessage::ProtocolBreach { peer_id: PeerId::random() })
2359                .is_err()
2360            {
2361                break
2362            }
2363            num_fill_messages += 1;
2364        }
2365
2366        tokio::task::spawn(async move {
2367            session.await;
2368        });
2369
2370        tokio::time::sleep(Duration::from_millis(100)).await;
2371
2372        for _ in 0..num_fill_messages {
2373            let message = builder.active_session_rx.next().await.unwrap();
2374            match message {
2375                ActiveSessionMessage::ProtocolBreach { .. } => {}
2376                ev => unreachable!("{ev:?}"),
2377            }
2378        }
2379
2380        let message = builder.active_session_rx.next().await.unwrap();
2381        match message {
2382            ActiveSessionMessage::ValidMessage {
2383                message: PeerMessage::PooledTransactions(_),
2384                ..
2385            } => {}
2386            _ => unreachable!(),
2387        }
2388    }
2389
2390    #[tokio::test]
2391    async fn keepalive_timeout_drives_disconnect_in_same_poll() {
2392        let mut builder = SessionBuilder::default();
2393        let (mut session, _client_stream) = builder.connect_idle_peer().await;
2394        tokio::time::pause();
2395
2396        let drive_session = poll_fn(|cx| {
2397            let result = Pin::new(&mut session).poll(cx);
2398            if result.is_pending() && session.is_disconnecting() {
2399                assert!(session.disconnect_deadline.is_some(), "missing disconnect deadline");
2400            }
2401            result
2402        });
2403        tokio::time::timeout(Duration::from_secs(120), drive_session)
2404            .await
2405            .expect("keepalive disconnect did not complete");
2406        assert!(session.is_disconnecting());
2407    }
2408
2409    // This tests that a disconnect completes even if the remote keeps the connection open but
2410    // stops reading, so the disconnect message can never be flushed.
2411    #[tokio::test]
2412    async fn test_disconnect_completes_when_remote_stops_reading() {
2413        let mut builder = SessionBuilder::default();
2414        let (mut session, _client_stream) = builder.connect_idle_peer().await;
2415        let commands = builder.to_sessions.pop().unwrap();
2416
2417        // Queue large, incompressible broadcasts until the socket stops draining and messages
2418        // stay queued in the session.
2419        let mut stalled_rounds = 0;
2420        while stalled_rounds < 50 {
2421            let hashes = (0..4096)
2422                .map(|number| BlockHashNumber {
2423                    hash: B256::from(rand::random::<[u8; 32]>()),
2424                    number,
2425                })
2426                .collect();
2427            commands
2428                .try_send(SessionCommand::Message(PeerMessage::NewBlockHashes(NewBlockHashes(
2429                    hashes,
2430                ))))
2431                .unwrap();
2432            let _ = tokio::time::timeout(
2433                Duration::from_millis(1),
2434                poll_fn(|cx| Pin::new(&mut session).poll(cx)),
2435            )
2436            .await;
2437            if session.queued_outgoing.is_empty() {
2438                stalled_rounds = 0;
2439            } else {
2440                stalled_rounds += 1;
2441            }
2442        }
2443
2444        // Pause the clock so the disconnect deadline elapses without waiting in real time.
2445        tokio::time::pause();
2446        commands.try_send(SessionCommand::Disconnect { reason: None }).unwrap();
2447        tokio::time::timeout(DISCONNECT_TIMEOUT * 2, poll_fn(|cx| Pin::new(&mut session).poll(cx)))
2448            .await
2449            .expect("session did not terminate after a disconnect command");
2450
2451        let msg = futures::FutureExt::now_or_never(builder.active_session_rx.next()).flatten();
2452        assert!(
2453            matches!(msg, Some(ActiveSessionMessage::Disconnected { .. })),
2454            "expected a disconnected message, got {msg:?}"
2455        );
2456        assert!(futures::FutureExt::now_or_never(builder.active_session_rx.next()).is_none());
2457    }
2458
2459    #[test]
2460    fn timeout_calculation_sanity_tests() {
2461        let rtt = Duration::from_secs(5);
2462        // timeout for an RTT of `rtt`
2463        let timeout = rtt * TIMEOUT_SCALING;
2464
2465        // if rtt hasn't changed, timeout shouldn't change
2466        assert_eq!(calculate_new_timeout(timeout, rtt), timeout);
2467
2468        // if rtt changed, the new timeout should change less than it
2469        assert!(calculate_new_timeout(timeout, rtt / 2) < timeout);
2470        assert!(calculate_new_timeout(timeout, rtt / 2) > timeout / 2);
2471        assert!(calculate_new_timeout(timeout, rtt * 2) > timeout);
2472        assert!(calculate_new_timeout(timeout, rtt * 2) < timeout * 2);
2473    }
2474}