Skip to main content

reth_network/session/
mod.rs

1//! Support for handling peer sessions.
2
3mod active;
4mod conn;
5mod counter;
6mod handle;
7#[cfg(test)]
8mod tests;
9mod types;
10pub use types::BlockRangeInfo;
11
12use crate::{
13    budget::DEFAULT_BUDGET_PRIORITIZED_EVENTS,
14    message::PeerMessage,
15    metrics::SessionManagerMetrics,
16    protocol::{IntoRlpxSubProtocol, OnNotSupported, RlpxSubProtocolHandlers, RlpxSubProtocols},
17    session::active::ActiveSession,
18};
19use active::QueuedOutgoingMessages;
20use alloy_primitives::map::{FbBuildHasher, HashMap};
21use counter::SessionCounter;
22use futures::{
23    future::{self, Either},
24    io, stream, FutureExt, StreamExt,
25};
26use reth_ecies::{stream::ECIESStream, ECIESError};
27use reth_eth_wire::{
28    errors::EthStreamError, handshake::EthRlpxHandshake, multiplex::RlpxProtocolMultiplexer,
29    BlockRangeUpdate, Capabilities, DisconnectReason, EthSnapStream, EthStream, EthVersion,
30    HelloMessageWithProtocols, NetworkPrimitives, UnauthedP2PStream, UnifiedStatus,
31    HANDSHAKE_TIMEOUT,
32};
33use reth_ethereum_forks::{ForkFilter, ForkId, ForkTransition, Head};
34use reth_metrics::common::mpsc::MeteredPollSender;
35use reth_network_api::{PeerRequest, PeerRequestSender};
36use reth_network_peers::PeerId;
37use reth_network_types::SessionsConfig;
38use reth_primitives_traits::{GotExpected, GotExpectedBoxed};
39use reth_tasks::Runtime;
40use rustc_hash::FxHashMap;
41use secp256k1::SecretKey;
42use std::{
43    future::Future,
44    net::SocketAddr,
45    sync::{atomic::AtomicU64, Arc},
46    task::{Context, Poll},
47    time::{Duration, Instant},
48};
49use tokio::{
50    io::{AsyncRead, AsyncWrite},
51    net::TcpStream,
52    sync::{mpsc, oneshot, watch},
53};
54use tokio_stream::wrappers::ReceiverStream;
55use tokio_util::sync::PollSender;
56use tracing::{instrument, trace};
57
58use crate::session::active::{
59    request_timeout_interval, BroadcastItemCounter, RANGE_UPDATE_INTERVAL,
60};
61pub use conn::EthRlpxConnection;
62use handle::SessionCommandSender;
63pub use handle::{
64    ActiveSessionHandle, ActiveSessionMessage, PendingSessionEvent, PendingSessionHandle,
65    SessionCommand,
66};
67pub use reth_network_api::{Direction, PeerInfo};
68
69/// Internal identifier for active sessions.
70#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq, Hash)]
71pub struct SessionId(usize);
72
73/// Manages a set of sessions.
74#[must_use = "Session Manager must be polled to process session events."]
75#[derive(Debug)]
76pub struct SessionManager<N: NetworkPrimitives> {
77    /// Tracks the identifier for the next session.
78    next_id: usize,
79    /// Keeps track of all sessions
80    counter: SessionCounter,
81    ///  The maximum initial time an [`ActiveSession`] waits for a response from the peer before it
82    /// responds to an _internal_ request with a `TimeoutError`
83    initial_internal_request_timeout: Duration,
84    /// If an [`ActiveSession`] does not receive a response at all within this duration then it is
85    /// considered a protocol violation and the session will initiate a drop.
86    protocol_breach_request_timeout: Duration,
87    /// The timeout after which a pending session attempt is considered failed.
88    pending_session_timeout: Duration,
89    /// The secret key used for authenticating sessions.
90    secret_key: SecretKey,
91    /// The `Status` message to send to peers.
92    status: UnifiedStatus,
93    /// The `HelloMessage` message to send to peers.
94    hello_message: HelloMessageWithProtocols,
95    /// The [`ForkFilter`] used to validate the peer's `Status` message.
96    fork_filter: ForkFilter,
97    /// Size of the command buffer per session.
98    session_command_buffer: usize,
99    /// The executor for spawned tasks.
100    executor: Runtime,
101    /// All pending session that are currently handshaking, exchanging `Hello`s.
102    ///
103    /// Events produced during the authentication phase are reported to this manager. Once the
104    /// session is authenticated, it can be moved to the `active_session` set.
105    pending_sessions: FxHashMap<SessionId, PendingSessionHandle>,
106    /// All active sessions that are ready to exchange messages.
107    active_sessions: HashMap<PeerId, ActiveSessionHandle<N>, FbBuildHasher<64>>,
108    /// The original Sender half of the [`PendingSessionEvent`] channel.
109    ///
110    /// When a new (pending) session is created, the corresponding [`PendingSessionHandle`] will
111    /// get a clone of this sender half.
112    pending_sessions_tx: mpsc::Sender<PendingSessionEvent<N>>,
113    /// Receiver half that listens for [`PendingSessionEvent`] produced by pending sessions.
114    pending_session_rx: ReceiverStream<PendingSessionEvent<N>>,
115    /// The original Sender half of the [`ActiveSessionMessage`] channel.
116    ///
117    /// When active session state is reached, the corresponding [`ActiveSessionHandle`] will get a
118    /// clone of this sender half.
119    active_session_tx: MeteredPollSender<ActiveSessionMessage<N>>,
120    /// Receiver half that listens for [`ActiveSessionMessage`] produced by pending sessions.
121    active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
122    /// Number of active session events returned since pending sessions were last polled.
123    active_events_in_row: u32,
124    /// Additional `RLPx` sub-protocols to be used by the session manager.
125    extra_protocols: RlpxSubProtocols,
126    /// Tracks the ongoing graceful disconnections attempts for incoming connections.
127    disconnections_counter: DisconnectionsCounter,
128    /// Metrics for the session manager.
129    metrics: SessionManagerMetrics,
130    /// The [`EthRlpxHandshake`] is used to perform the initial handshake with the peer.
131    handshake: Arc<dyn EthRlpxHandshake>,
132    /// Maximum allowed ETH message size for post-handshake ETH/Snap streams.
133    eth_max_message_size: usize,
134    /// Maximum uncompressed size of a message payload on the `p2p` stream.
135    p2p_max_payload_size: usize,
136    /// Shared local range information that gets propagated to active sessions.
137    /// This represents the range of blocks that this node can serve to other peers.
138    local_range_info: BlockRangeInfo,
139    /// When true, block announcement messages (`NewBlock`, `NewBlockHashes`) are rejected before
140    /// RLP decoding on new sessions to avoid memory amplification.
141    reject_block_announcements: bool,
142}
143
144// === impl SessionManager ===
145
146impl<N: NetworkPrimitives> SessionManager<N> {
147    /// Creates a new empty [`SessionManager`].
148    #[expect(clippy::too_many_arguments)]
149    pub fn new(
150        secret_key: SecretKey,
151        config: SessionsConfig,
152        executor: Runtime,
153        status: UnifiedStatus,
154        hello_message: HelloMessageWithProtocols,
155        fork_filter: ForkFilter,
156        extra_protocols: RlpxSubProtocols,
157        handshake: Arc<dyn EthRlpxHandshake>,
158        eth_max_message_size: usize,
159        p2p_max_payload_size: usize,
160        reject_block_announcements: bool,
161    ) -> Self {
162        let (pending_sessions_tx, pending_sessions_rx) = mpsc::channel(config.session_event_buffer);
163        let (active_session_tx, active_session_rx) = mpsc::channel(config.session_event_buffer);
164        let active_session_tx = PollSender::new(active_session_tx);
165
166        // Initialize local range info from the status
167        let local_range_info = BlockRangeInfo::new(
168            status.earliest_block.unwrap_or_default(),
169            status.latest_block.unwrap_or_default(),
170            status.blockhash,
171        );
172
173        Self {
174            next_id: 0,
175            counter: SessionCounter::new(config.limits),
176            initial_internal_request_timeout: config.initial_internal_request_timeout,
177            protocol_breach_request_timeout: config.protocol_breach_request_timeout,
178            pending_session_timeout: config.pending_session_timeout,
179            secret_key,
180            status,
181            hello_message,
182            fork_filter,
183            session_command_buffer: config.session_command_buffer,
184            executor,
185            pending_sessions: Default::default(),
186            active_sessions: Default::default(),
187            pending_sessions_tx,
188            pending_session_rx: ReceiverStream::new(pending_sessions_rx),
189            active_session_tx: MeteredPollSender::new(active_session_tx, "network_active_session"),
190            active_session_rx: ReceiverStream::new(active_session_rx),
191            active_events_in_row: 0,
192            extra_protocols,
193            disconnections_counter: Default::default(),
194            metrics: Default::default(),
195            handshake,
196            eth_max_message_size,
197            p2p_max_payload_size,
198            local_range_info,
199            reject_block_announcements,
200        }
201    }
202
203    /// Returns the currently tracked [`ForkId`].
204    pub(crate) const fn fork_id(&self) -> ForkId {
205        self.fork_filter.current()
206    }
207
208    /// Check whether the provided [`ForkId`] is compatible based on the validation rules in
209    /// `EIP-2124`.
210    pub fn is_valid_fork_id(&self, fork_id: ForkId) -> bool {
211        self.fork_filter.validate(fork_id).is_ok()
212    }
213
214    /// Returns the next unique [`SessionId`].
215    const fn next_id(&mut self) -> SessionId {
216        let id = self.next_id;
217        self.next_id += 1;
218        SessionId(id)
219    }
220
221    /// Returns the current status of the session.
222    pub const fn status(&self) -> UnifiedStatus {
223        self.status
224    }
225
226    /// Returns the secret key used for authenticating sessions.
227    pub const fn secret_key(&self) -> SecretKey {
228        self.secret_key
229    }
230
231    /// Returns a borrowed reference to the active sessions.
232    pub const fn active_sessions(
233        &self,
234    ) -> &HashMap<PeerId, ActiveSessionHandle<N>, FbBuildHasher<64>> {
235        &self.active_sessions
236    }
237
238    /// Returns the session hello message.
239    pub fn hello_message(&self) -> HelloMessageWithProtocols {
240        self.hello_message.clone()
241    }
242
243    /// Adds an additional protocol handler to the `RLPx` sub-protocol list.
244    pub(crate) fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {
245        self.extra_protocols.push(protocol)
246    }
247
248    /// Returns the number of currently pending connections.
249    #[inline]
250    pub(crate) fn num_pending_connections(&self) -> usize {
251        self.pending_sessions.len()
252    }
253
254    /// Spawns the given future onto a new task that is tracked in the `spawned_tasks`
255    /// [`JoinSet`](tokio::task::JoinSet).
256    fn spawn<F>(&self, f: F)
257    where
258        F: Future<Output = ()> + Send + 'static,
259    {
260        self.executor.spawn_task(f);
261    }
262
263    /// Invoked on a received status update.
264    ///
265    /// If the updated activated another fork, this will return a [`ForkTransition`] and updates the
266    /// active [`ForkId`]. See also [`ForkFilter::set_head`].
267    pub(crate) fn on_status_update(&mut self, head: Head) -> Option<ForkTransition> {
268        self.status.blockhash = head.hash;
269        self.status.total_difficulty = Some(head.total_difficulty);
270        let transition = self.fork_filter.set_head(head);
271        self.status.forkid = self.fork_filter.current();
272        self.status.latest_block = Some(head.number);
273
274        transition
275    }
276
277    /// Replaces the active [`ForkFilter`] with a newly derived one and returns the resulting
278    /// [`ForkId`].
279    ///
280    /// This is used to adopt a fork schedule that changed at runtime (e.g. an L1-signalled
281    /// upgrade) without restarting the node. The caller is expected to build `fork_filter` from
282    /// the updated chain spec already advanced to the node's current head, so that
283    /// [`ForkFilter::current`] reflects the correct [`ForkId`] immediately.
284    ///
285    /// Every subsequent handshake clones this filter and advertises the returned [`ForkId`], so
286    /// the node's advertised fork identity stays aligned with the rules it now enforces. Existing
287    /// active sessions are not revalidated here; see [`SessionManager::active_sessions`].
288    pub(crate) fn set_fork_filter(&mut self, fork_filter: ForkFilter) -> ForkId {
289        self.fork_filter = fork_filter;
290        self.status.forkid = self.fork_filter.current();
291        self.status.forkid
292    }
293
294    /// An incoming TCP connection was received. This starts the authentication process to turn this
295    /// stream into an active peer session.
296    ///
297    /// Returns an error if the configured limit has been reached.
298    pub(crate) fn on_incoming(
299        &mut self,
300        stream: TcpStream,
301        remote_addr: SocketAddr,
302    ) -> Result<SessionId, ExceedsSessionLimit> {
303        self.counter.ensure_pending_inbound()?;
304
305        let session_id = self.next_id();
306
307        trace!(
308            target: "net::session",
309            ?remote_addr,
310            ?session_id,
311            "new pending incoming session"
312        );
313
314        let (disconnect_tx, disconnect_rx) = oneshot::channel();
315        let pending_events = self.pending_sessions_tx.clone();
316        let secret_key = self.secret_key;
317        let hello_message = self.hello_message.clone();
318        let status = self.status;
319        let fork_filter = self.fork_filter.clone();
320        let extra_handlers = self.extra_protocols.on_incoming(remote_addr);
321        self.spawn(pending_session_with_timeout(
322            self.pending_session_timeout,
323            session_id,
324            remote_addr,
325            Direction::Incoming,
326            pending_events.clone(),
327            start_pending_incoming_session(
328                self.handshake.clone(),
329                self.eth_max_message_size,
330                self.p2p_max_payload_size,
331                disconnect_rx,
332                session_id,
333                stream,
334                pending_events,
335                remote_addr,
336                secret_key,
337                hello_message,
338                status,
339                fork_filter,
340                extra_handlers,
341            ),
342        ));
343
344        let handle = PendingSessionHandle {
345            disconnect_tx: Some(disconnect_tx),
346            direction: Direction::Incoming,
347        };
348        self.pending_sessions.insert(session_id, handle);
349        self.counter.inc_pending_inbound();
350        Ok(session_id)
351    }
352
353    /// Starts a new pending session from the local node to the given remote node.
354    /// Skips the dial if the pending outbound session limit is reached.
355    pub fn dial_outbound(&mut self, remote_addr: SocketAddr, remote_peer_id: PeerId) {
356        if let Err(err) = self.try_dial_outbound(remote_addr, remote_peer_id) {
357            trace!(target: "net", %err, "Outgoing connection rejected, capacity already reached.");
358        }
359    }
360
361    /// Starts an outbound session or reports that no dial was made due to the session limit.
362    pub(crate) fn try_dial_outbound(
363        &mut self,
364        remote_addr: SocketAddr,
365        remote_peer_id: PeerId,
366    ) -> Result<(), ExceedsSessionLimit> {
367        self.counter.ensure_pending_outbound()?;
368        let session_id = self.next_id();
369        let (disconnect_tx, disconnect_rx) = oneshot::channel();
370        let pending_events = self.pending_sessions_tx.clone();
371        let secret_key = self.secret_key;
372        let hello_message = self.hello_message.clone();
373        let fork_filter = self.fork_filter.clone();
374        let status = self.status;
375        let extra_handlers = self.extra_protocols.on_outgoing(remote_addr, remote_peer_id);
376        self.spawn(pending_session_with_timeout(
377            self.pending_session_timeout,
378            session_id,
379            remote_addr,
380            Direction::Outgoing(remote_peer_id),
381            pending_events.clone(),
382            start_pending_outbound_session(
383                self.handshake.clone(),
384                self.eth_max_message_size,
385                self.p2p_max_payload_size,
386                disconnect_rx,
387                pending_events,
388                session_id,
389                remote_addr,
390                remote_peer_id,
391                secret_key,
392                hello_message,
393                status,
394                fork_filter,
395                extra_handlers,
396            ),
397        ));
398
399        let handle = PendingSessionHandle {
400            disconnect_tx: Some(disconnect_tx),
401            direction: Direction::Outgoing(remote_peer_id),
402        };
403        self.pending_sessions.insert(session_id, handle);
404        self.counter.inc_pending_outbound();
405        Ok(())
406    }
407
408    /// Initiates a shutdown of the channel.
409    ///
410    /// This will trigger the disconnect on the session task to gracefully terminate. The result
411    /// will be picked up by the receiver.
412    pub fn disconnect(&self, node: PeerId, reason: Option<DisconnectReason>) {
413        if let Some(session) = self.active_sessions.get(&node) {
414            session.disconnect(reason);
415        }
416    }
417
418    /// Initiates a shutdown of all sessions.
419    ///
420    /// It will trigger the disconnect on all the session tasks to gracefully terminate. The result
421    /// will be picked by the receiver.
422    pub fn disconnect_all(&self, reason: Option<DisconnectReason>) {
423        for session in self.active_sessions.values() {
424            session.disconnect(reason);
425        }
426    }
427
428    /// Disconnects all pending sessions.
429    pub fn disconnect_all_pending(&mut self) {
430        for session in self.pending_sessions.values_mut() {
431            session.disconnect();
432        }
433    }
434
435    /// Sends a message to the peer's session.
436    ///
437    /// Broadcast messages use size-based backpressure: the total number of in-flight broadcast
438    /// items (across the command channel, overflow channel, and session outgoing queue) is tracked
439    /// by a shared atomic counter. If the bounded command channel is full but the broadcast limit
440    /// hasn't been reached, the message overflows to a dedicated unbounded channel.
441    pub fn send_message(&self, peer_id: &PeerId, msg: PeerMessage<N>) {
442        if let Some(session) = self.active_sessions.get(peer_id) &&
443            !session.commands.send_message(msg)
444        {
445            self.metrics.total_outgoing_peer_messages_dropped.increment(1);
446        }
447    }
448
449    /// Removes the [`PendingSessionHandle`] if it exists.
450    fn remove_pending_session(&mut self, id: &SessionId) -> Option<PendingSessionHandle> {
451        let session = self.pending_sessions.remove(id)?;
452        self.counter.dec_pending(&session.direction);
453        Some(session)
454    }
455
456    /// Cancels outgoing attempts superseded by an incoming session for this peer.
457    fn cancel_pending_outbound(&mut self, peer_id: PeerId) {
458        self.pending_sessions.retain(|_, session| {
459            if session.direction == Direction::Outgoing(peer_id) {
460                session.disconnect();
461                self.counter.dec_pending(&session.direction);
462                return false
463            }
464            true
465        });
466    }
467
468    /// Closes a completed handshake that will not become an active session.
469    fn disconnect_pending_connection(&self, conn: EthRlpxConnection<N>, reason: DisconnectReason) {
470        self.spawn(async move {
471            let _ =
472                tokio::time::timeout(HANDSHAKE_TIMEOUT, conn.into_inner().disconnect(reason)).await;
473        });
474    }
475
476    /// Removes the [`PendingSessionHandle`] if it exists.
477    fn remove_active_session(&mut self, id: &PeerId) -> Option<ActiveSessionHandle<N>> {
478        let session = self.active_sessions.remove(id)?;
479        self.counter.dec_active(&session.direction);
480        Some(session)
481    }
482
483    /// Try to gracefully disconnect an incoming connection by initiating a ECIES connection and
484    /// sending a disconnect. If [`SessionManager`] is at capacity for ongoing disconnections, will
485    /// simply drop the incoming connection.
486    pub(crate) fn try_disconnect_incoming_connection(
487        &self,
488        stream: TcpStream,
489        reason: DisconnectReason,
490    ) {
491        if !self.disconnections_counter.has_capacity() {
492            // drop the connection if we don't have capacity for gracefully disconnecting
493            return
494        }
495
496        let guard = self.disconnections_counter.clone();
497        let secret_key = self.secret_key;
498
499        self.spawn(async move {
500            trace!(
501                target: "net::session",
502                "gracefully disconnecting incoming connection"
503            );
504            let _ = tokio::time::timeout(HANDSHAKE_TIMEOUT, async move {
505                if let Ok(stream) = get_ecies_stream(stream, secret_key, Direction::Incoming).await
506                {
507                    let mut unauth = UnauthedP2PStream::new(stream);
508                    let _ = unauth.send_disconnect(reason).await;
509                }
510            })
511            .await;
512            // Holds the slot until the handshake and disconnect finish or time out.
513            drop(guard);
514        });
515    }
516
517    /// This polls all the session handles and returns [`SessionEvent`].
518    ///
519    /// Active sessions are prioritized, but after [`DEFAULT_BUDGET_PRIORITIZED_EVENTS`] active
520    /// session events in a row pending sessions are polled first once, so a steady stream of active
521    /// session messages can't hold back new sessions. Established incoming sessions are
522    /// disconnected with the reason returned by `inbound_session_rejection` instead of being
523    /// activated.
524    pub(crate) fn poll(
525        &mut self,
526        cx: &mut Context<'_>,
527        inbound_session_rejection: impl Fn(PeerId) -> Option<DisconnectReason>,
528    ) -> Poll<SessionEvent<N>> {
529        if self.active_events_in_row >= DEFAULT_BUDGET_PRIORITIZED_EVENTS {
530            self.active_events_in_row = 0;
531            if let Poll::Ready(event) =
532                self.poll_pending_session_event(cx, &inbound_session_rejection)
533            {
534                return Poll::Ready(event)
535            }
536        }
537
538        if let Poll::Ready(event) = self.poll_active_session_event(cx) {
539            self.active_events_in_row += 1;
540            return Poll::Ready(event)
541        }
542
543        self.active_events_in_row = 0;
544        self.poll_pending_session_event(cx, inbound_session_rejection)
545    }
546
547    /// Polls the next event from the active sessions.
548    fn poll_active_session_event(&mut self, cx: &mut Context<'_>) -> Poll<SessionEvent<N>> {
549        match self.active_session_rx.poll_next_unpin(cx) {
550            Poll::Pending => {}
551            Poll::Ready(None) => {
552                unreachable!("Manager holds both channel halves.")
553            }
554            Poll::Ready(Some(event)) => {
555                return match event {
556                    ActiveSessionMessage::Disconnected { peer_id, remote_addr } => {
557                        trace!(
558                            target: "net::session",
559                            ?peer_id,
560                            "gracefully disconnected active session."
561                        );
562                        self.remove_active_session(&peer_id);
563                        Poll::Ready(SessionEvent::Disconnected { peer_id, remote_addr })
564                    }
565                    ActiveSessionMessage::ClosedOnConnectionError {
566                        peer_id,
567                        remote_addr,
568                        error,
569                    } => {
570                        trace!(target: "net::session", ?peer_id, %error,"closed session.");
571                        self.remove_active_session(&peer_id);
572                        Poll::Ready(SessionEvent::SessionClosedOnConnectionError {
573                            remote_addr,
574                            peer_id,
575                            error,
576                        })
577                    }
578                    ActiveSessionMessage::ValidMessage { peer_id, message } => {
579                        Poll::Ready(SessionEvent::ValidMessage { peer_id, message })
580                    }
581                    ActiveSessionMessage::BadMessage { peer_id } => {
582                        Poll::Ready(SessionEvent::BadMessage { peer_id })
583                    }
584                    ActiveSessionMessage::ProtocolBreach { peer_id } => {
585                        Poll::Ready(SessionEvent::ProtocolBreach { peer_id })
586                    }
587                }
588            }
589        }
590        Poll::Pending
591    }
592
593    /// Polls the next event from the pending sessions.
594    fn poll_pending_session_event(
595        &mut self,
596        cx: &mut Context<'_>,
597        inbound_session_rejection: impl Fn(PeerId) -> Option<DisconnectReason>,
598    ) -> Poll<SessionEvent<N>> {
599        let event = loop {
600            let event = match self.pending_session_rx.poll_next_unpin(cx) {
601                Poll::Pending => return Poll::Pending,
602                Poll::Ready(None) => unreachable!("Manager holds both channel halves."),
603                Poll::Ready(Some(event)) => event,
604            };
605            let session_id = match &event {
606                PendingSessionEvent::Established { session_id, .. } |
607                PendingSessionEvent::Disconnected { session_id, .. } |
608                PendingSessionEvent::OutgoingConnectionError { session_id, .. } |
609                PendingSessionEvent::EciesAuthError { session_id, .. } => session_id,
610            };
611            // Canceled attempts must not affect a replacement session for the same peer.
612            if self.remove_pending_session(session_id).is_some() {
613                break event
614            }
615            if let PendingSessionEvent::Established { conn, .. } = event {
616                self.disconnect_pending_connection(conn, DisconnectReason::AlreadyConnected);
617            }
618        };
619        match event {
620            PendingSessionEvent::Established {
621                session_id,
622                remote_addr,
623                local_addr,
624                peer_id,
625                capabilities,
626                mut conn,
627                status,
628                direction,
629                client_id,
630                peer_listen_port,
631            } => {
632                // If there's already a session to the peer then we disconnect right away
633                if self.active_sessions.contains_key(&peer_id) {
634                    trace!(
635                        target: "net::session",
636                        ?session_id,
637                        ?remote_addr,
638                        ?peer_id,
639                        ?direction,
640                        "already connected"
641                    );
642
643                    self.disconnect_pending_connection(conn, DisconnectReason::AlreadyConnected);
644
645                    return Poll::Ready(SessionEvent::AlreadyConnected {
646                        peer_id,
647                        remote_addr,
648                        direction,
649                    })
650                }
651
652                if direction.is_incoming() {
653                    if let Some(reason) = inbound_session_rejection(peer_id) {
654                        self.disconnect_pending_connection(conn, reason);
655                        return Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
656                            remote_addr,
657                            error: None,
658                        })
659                    }
660                    self.cancel_pending_outbound(peer_id);
661                }
662
663                let (commands_tx, commands_rx) = mpsc::channel(self.session_command_buffer);
664                let (unbounded_tx, unbounded_rx) = mpsc::unbounded_channel();
665
666                let (to_session_tx, messages_rx) = mpsc::channel(self.session_command_buffer);
667
668                let messages = PeerRequestSender::new(peer_id, to_session_tx);
669
670                let timeout = Arc::new(AtomicU64::new(
671                    self.initial_internal_request_timeout.as_millis() as u64,
672                ));
673
674                // negotiated version
675                let version = conn.version();
676
677                // Configure the interval at which the range information is updated, starting with
678                // ETH69. We use interval_at to delay the first tick, avoiding sending
679                // BlockRangeUpdate immediately after connection (which can cause issues with
680                // peers that don't properly handle the message).
681                let range_update_interval = (conn.version() >= EthVersion::Eth69).then(|| {
682                    let start = tokio::time::Instant::now() + RANGE_UPDATE_INTERVAL;
683                    let mut interval = tokio::time::interval_at(start, RANGE_UPDATE_INTERVAL);
684                    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
685                    interval
686                });
687
688                // Shared counter of in-flight broadcast items. The session task must decrement
689                // this when it pops messages from the outgoing queue, and the
690                // `SessionCommandSender` increments it before enqueuing. This invariant ensures
691                // the `SessionManager` always has an accurate view of total buffered broadcast
692                // pressure for a peer.
693                let broadcast_items = BroadcastItemCounter::new();
694                let remote_range_info = status.block_range_update().map(|update| {
695                    BlockRangeInfo::new(update.earliest, update.latest, update.latest_hash)
696                });
697
698                if self.reject_block_announcements {
699                    conn.set_reject_block_announcements(true);
700                }
701
702                let session = ActiveSession {
703                    next_id: 0,
704                    remote_peer_id: peer_id,
705                    remote_addr,
706                    remote_capabilities: Arc::clone(&capabilities),
707                    session_id,
708                    commands_rx: ReceiverStream::new(commands_rx),
709                    unbounded_rx,
710                    unbounded_broadcast_msgs: self.metrics.total_unbounded_broadcast_msgs.clone(),
711                    to_session_manager: self.active_session_tx.clone(),
712                    pending_message_to_session: None,
713                    internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
714                    inflight_requests: Default::default(),
715                    conn,
716                    queued_outgoing: QueuedOutgoingMessages::new(
717                        self.metrics.queued_outgoing_messages.clone(),
718                        broadcast_items.clone(),
719                    ),
720                    received_requests_from_remote: Default::default(),
721                    internal_request_timeout_interval: request_timeout_interval(
722                        self.initial_internal_request_timeout,
723                    ),
724                    internal_request_timeout: Arc::clone(&timeout),
725                    protocol_breach_request_timeout: self.protocol_breach_request_timeout,
726                    terminate_message: None,
727                    range_info: remote_range_info.clone(),
728                    local_range_info: self.local_range_info.clone(),
729                    range_update_interval,
730                    last_sent_latest_block: None,
731                    disconnect_deadline: None,
732                };
733
734                let supports_snap = session.conn.supports_snap();
735                self.spawn(session);
736
737                let client_version = client_id.into();
738                let handle = ActiveSessionHandle {
739                    status: status.clone(),
740                    direction,
741                    session_id,
742                    remote_id: peer_id,
743                    version,
744                    established: Instant::now(),
745                    capabilities: Arc::clone(&capabilities),
746                    commands: SessionCommandSender::new(commands_tx, unbounded_tx, broadcast_items),
747                    client_version: Arc::clone(&client_version),
748                    remote_addr,
749                    local_addr,
750                    peer_listen_port,
751                };
752
753                self.active_sessions.insert(peer_id, handle);
754                self.counter.inc_active(&direction);
755
756                if direction.is_outgoing() {
757                    self.metrics.total_dial_successes.increment(1);
758                }
759
760                Poll::Ready(SessionEvent::SessionEstablished {
761                    peer_id,
762                    remote_addr,
763                    client_version,
764                    version,
765                    capabilities,
766                    status,
767                    messages,
768                    direction,
769                    timeout,
770                    range_info: remote_range_info,
771                    supports_snap,
772                })
773            }
774            PendingSessionEvent::Disconnected { remote_addr, session_id, direction, error } => {
775                trace!(
776                    target: "net::session",
777                    ?session_id,
778                    ?remote_addr,
779                    ?error,
780                    "disconnected pending session"
781                );
782                match direction {
783                    Direction::Incoming => {
784                        Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
785                            remote_addr,
786                            error,
787                        })
788                    }
789                    Direction::Outgoing(peer_id) => {
790                        Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
791                            remote_addr,
792                            peer_id,
793                            error,
794                        })
795                    }
796                }
797            }
798            PendingSessionEvent::OutgoingConnectionError {
799                remote_addr,
800                session_id,
801                peer_id,
802                error,
803            } => {
804                trace!(
805                    target: "net::session",
806                    %error,
807                    ?session_id,
808                    ?remote_addr,
809                    ?peer_id,
810                    "connection refused"
811                );
812                Poll::Ready(SessionEvent::OutgoingConnectionError { remote_addr, peer_id, error })
813            }
814            PendingSessionEvent::EciesAuthError { remote_addr, session_id, error, direction } => {
815                trace!(
816                    target: "net::session",
817                    %error,
818                    ?session_id,
819                    ?remote_addr,
820                    "ecies auth failed"
821                );
822                match direction {
823                    Direction::Incoming => {
824                        Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
825                            remote_addr,
826                            error: Some(PendingSessionHandshakeError::Ecies(error)),
827                        })
828                    }
829                    Direction::Outgoing(peer_id) => {
830                        Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
831                            remote_addr,
832                            peer_id,
833                            error: Some(PendingSessionHandshakeError::Ecies(error)),
834                        })
835                    }
836                }
837            }
838        }
839    }
840
841    /// Updates the advertised block range that this node can serve to other peers starting with
842    /// Eth69.
843    ///
844    /// This method updates both the local status message that gets sent to peers during handshake
845    /// and the shared local range information that gets propagated to active sessions (Eth69).
846    /// The range information is used in ETH69 protocol where peers announce the range of blocks
847    /// they can serve to optimize data synchronization.
848    pub(crate) fn update_advertised_block_range(&mut self, block_range_update: BlockRangeUpdate) {
849        self.status.earliest_block = Some(block_range_update.earliest);
850        self.status.latest_block = Some(block_range_update.latest);
851        self.status.blockhash = block_range_update.latest_hash;
852
853        // Update the shared local range info that gets propagated to active sessions
854        self.local_range_info.update(
855            block_range_update.earliest,
856            block_range_update.latest,
857            block_range_update.latest_hash,
858        );
859    }
860}
861
862/// A counter for ongoing graceful disconnections attempts.
863#[derive(Default, Debug, Clone)]
864struct DisconnectionsCounter(Arc<()>);
865
866impl DisconnectionsCounter {
867    const MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS: usize = 15;
868
869    /// Returns true if the [`DisconnectionsCounter`] still has capacity
870    /// for an additional graceful disconnection.
871    fn has_capacity(&self) -> bool {
872        Arc::strong_count(&self.0) <= Self::MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS
873    }
874}
875
876/// Events produced by the [`SessionManager`]
877#[derive(Debug)]
878pub enum SessionEvent<N: NetworkPrimitives> {
879    /// A new session was successfully authenticated.
880    ///
881    /// This session is now able to exchange data.
882    SessionEstablished {
883        /// The remote node's public key
884        peer_id: PeerId,
885        /// The remote node's socket address
886        remote_addr: SocketAddr,
887        /// The user agent of the remote node, usually containing the client name and version
888        client_version: Arc<str>,
889        /// The capabilities the remote node has announced
890        capabilities: Arc<Capabilities>,
891        /// negotiated eth version
892        version: EthVersion,
893        /// The Status message the peer sent during the `eth` handshake
894        status: Arc<UnifiedStatus>,
895        /// The channel for sending messages to the peer with the session
896        messages: PeerRequestSender<PeerRequest<N>>,
897        /// The direction of the session, either `Inbound` or `Outgoing`
898        direction: Direction,
899        /// The maximum time that the session waits for a response from the peer before timing out
900        /// the connection
901        timeout: Arc<AtomicU64>,
902        /// The range info for the peer.
903        range_info: Option<BlockRangeInfo>,
904        /// Whether the connection negotiated `snap/2` and can serve [`PeerRequest::GetSnap`].
905        supports_snap: bool,
906    },
907    /// The peer was already connected with another session.
908    AlreadyConnected {
909        /// The remote node's public key
910        peer_id: PeerId,
911        /// The remote node's socket address
912        remote_addr: SocketAddr,
913        /// The direction of the session, either `Inbound` or `Outgoing`
914        direction: Direction,
915    },
916    /// A session received a valid message via `RLPx`.
917    ValidMessage {
918        /// The remote node's public key
919        peer_id: PeerId,
920        /// Message received from the peer.
921        message: PeerMessage<N>,
922    },
923    /// Received a bad message from the peer.
924    BadMessage {
925        /// Identifier of the remote peer.
926        peer_id: PeerId,
927    },
928    /// Remote peer is considered in protocol violation
929    ProtocolBreach {
930        /// Identifier of the remote peer.
931        peer_id: PeerId,
932    },
933    /// Closed an incoming pending session during handshaking.
934    IncomingPendingSessionClosed {
935        /// The remote node's socket address
936        remote_addr: SocketAddr,
937        /// The pending handshake session error that caused the session to close
938        error: Option<PendingSessionHandshakeError>,
939    },
940    /// Closed an outgoing pending session during handshaking.
941    OutgoingPendingSessionClosed {
942        /// The remote node's socket address
943        remote_addr: SocketAddr,
944        /// The remote node's public key
945        peer_id: PeerId,
946        /// The pending handshake session error that caused the session to close
947        error: Option<PendingSessionHandshakeError>,
948    },
949    /// Failed to establish a tcp stream
950    OutgoingConnectionError {
951        /// The remote node's socket address
952        remote_addr: SocketAddr,
953        /// The remote node's public key
954        peer_id: PeerId,
955        /// The error that caused the outgoing connection to fail
956        error: io::Error,
957    },
958    /// Session was closed due to an error
959    SessionClosedOnConnectionError {
960        /// The id of the remote peer.
961        peer_id: PeerId,
962        /// The socket we were connected to.
963        remote_addr: SocketAddr,
964        /// The error that caused the session to close
965        error: EthStreamError,
966    },
967    /// Active session was gracefully disconnected.
968    Disconnected {
969        /// The remote node's public key
970        peer_id: PeerId,
971        /// The remote node's socket address that we were connected to
972        remote_addr: SocketAddr,
973    },
974}
975
976/// Errors that can occur during handshaking/authenticating the underlying streams.
977#[derive(Debug, thiserror::Error)]
978pub enum PendingSessionHandshakeError {
979    /// The pending session failed due to an error while establishing the `eth` stream
980    #[error(transparent)]
981    Eth(EthStreamError),
982    /// The pending session failed due to an error while establishing the ECIES stream
983    #[error(transparent)]
984    Ecies(ECIESError),
985    /// Thrown when the authentication timed out
986    #[error("authentication timed out")]
987    Timeout,
988    /// Thrown when the remote lacks the required capability
989    #[error("Mandatory extra capability unsupported")]
990    UnsupportedExtraCapability,
991    /// Thrown when the node id in the remote's `Hello` message differs from the identity that the
992    /// ECIES handshake authenticated.
993    #[error("unexpected identity in hello message: {0}")]
994    UnexpectedHandshakeIdentity(GotExpectedBoxed<PeerId>),
995}
996
997impl PendingSessionHandshakeError {
998    /// Returns the [`DisconnectReason`] the session was disconnected with, either because the
999    /// remote sent one or because we sent one before failing the handshake.
1000    pub const fn as_disconnected(&self) -> Option<DisconnectReason> {
1001        match self {
1002            Self::Eth(eth_err) => eth_err.as_disconnected(),
1003            Self::UnexpectedHandshakeIdentity(_) => {
1004                Some(DisconnectReason::UnexpectedHandshakeIdentity)
1005            }
1006            _ => None,
1007        }
1008    }
1009}
1010
1011/// The error thrown when the max configured limit has been reached and no more connections are
1012/// accepted.
1013#[derive(Debug, Clone, thiserror::Error)]
1014#[error("session limit reached {0}")]
1015pub struct ExceedsSessionLimit(pub(crate) u32);
1016
1017/// Starts a pending session authentication with a timeout.
1018pub(crate) async fn pending_session_with_timeout<F, N: NetworkPrimitives>(
1019    timeout: Duration,
1020    session_id: SessionId,
1021    remote_addr: SocketAddr,
1022    direction: Direction,
1023    events: mpsc::Sender<PendingSessionEvent<N>>,
1024    f: F,
1025) where
1026    F: Future<Output = ()>,
1027{
1028    if tokio::time::timeout(timeout, f).await.is_err() {
1029        trace!(target: "net::session", ?remote_addr, ?direction, "pending session timed out");
1030        let event = PendingSessionEvent::Disconnected {
1031            remote_addr,
1032            session_id,
1033            direction,
1034            error: Some(PendingSessionHandshakeError::Timeout),
1035        };
1036        let _ = events.send(event).await;
1037    }
1038}
1039
1040/// Starts the authentication process for a connection initiated by a remote peer.
1041///
1042/// This will wait for the _incoming_ handshake request and answer it.
1043#[expect(clippy::too_many_arguments)]
1044pub(crate) async fn start_pending_incoming_session<N: NetworkPrimitives>(
1045    handshake: Arc<dyn EthRlpxHandshake>,
1046    eth_max_message_size: usize,
1047    p2p_max_payload_size: usize,
1048    disconnect_rx: oneshot::Receiver<()>,
1049    session_id: SessionId,
1050    stream: TcpStream,
1051    events: mpsc::Sender<PendingSessionEvent<N>>,
1052    remote_addr: SocketAddr,
1053    secret_key: SecretKey,
1054    hello: HelloMessageWithProtocols,
1055    status: UnifiedStatus,
1056    fork_filter: ForkFilter,
1057    extra_handlers: RlpxSubProtocolHandlers,
1058) {
1059    authenticate(
1060        handshake,
1061        eth_max_message_size,
1062        p2p_max_payload_size,
1063        disconnect_rx,
1064        events,
1065        stream,
1066        session_id,
1067        remote_addr,
1068        secret_key,
1069        Direction::Incoming,
1070        hello,
1071        status,
1072        fork_filter,
1073        extra_handlers,
1074    )
1075    .await
1076}
1077
1078/// Starts the authentication process for a connection initiated by a remote peer.
1079#[instrument(level = "trace", target = "net::network", skip_all, fields(%remote_addr, peer_id = ?remote_peer_id))]
1080#[expect(clippy::too_many_arguments)]
1081async fn start_pending_outbound_session<N: NetworkPrimitives>(
1082    handshake: Arc<dyn EthRlpxHandshake>,
1083    eth_max_message_size: usize,
1084    p2p_max_payload_size: usize,
1085    mut disconnect_rx: oneshot::Receiver<()>,
1086    events: mpsc::Sender<PendingSessionEvent<N>>,
1087    session_id: SessionId,
1088    remote_addr: SocketAddr,
1089    remote_peer_id: PeerId,
1090    secret_key: SecretKey,
1091    hello: HelloMessageWithProtocols,
1092    status: UnifiedStatus,
1093    fork_filter: ForkFilter,
1094    extra_handlers: RlpxSubProtocolHandlers,
1095) {
1096    let connection = tokio::select! {
1097        _ = &mut disconnect_rx => {
1098            let _ = events.send(PendingSessionEvent::Disconnected {
1099                remote_addr,
1100                session_id,
1101                direction: Direction::Outgoing(remote_peer_id),
1102                error: None,
1103            }).await;
1104            return
1105        },
1106        connection = TcpStream::connect(remote_addr) => connection,
1107    };
1108    let stream = match connection {
1109        Ok(stream) => {
1110            if let Err(err) = stream.set_nodelay(true) {
1111                tracing::warn!(target: "net::session", "set nodelay failed: {:?}", err);
1112            }
1113            stream
1114        }
1115        Err(error) => {
1116            let _ = events
1117                .send(PendingSessionEvent::OutgoingConnectionError {
1118                    remote_addr,
1119                    session_id,
1120                    peer_id: remote_peer_id,
1121                    error,
1122                })
1123                .await;
1124            return
1125        }
1126    };
1127    authenticate(
1128        handshake,
1129        eth_max_message_size,
1130        p2p_max_payload_size,
1131        disconnect_rx,
1132        events,
1133        stream,
1134        session_id,
1135        remote_addr,
1136        secret_key,
1137        Direction::Outgoing(remote_peer_id),
1138        hello,
1139        status,
1140        fork_filter,
1141        extra_handlers,
1142    )
1143    .await
1144}
1145
1146/// Authenticates a session
1147#[expect(clippy::too_many_arguments)]
1148async fn authenticate<N: NetworkPrimitives>(
1149    handshake: Arc<dyn EthRlpxHandshake>,
1150    eth_max_message_size: usize,
1151    p2p_max_payload_size: usize,
1152    disconnect_rx: oneshot::Receiver<()>,
1153    events: mpsc::Sender<PendingSessionEvent<N>>,
1154    stream: TcpStream,
1155    session_id: SessionId,
1156    remote_addr: SocketAddr,
1157    secret_key: SecretKey,
1158    direction: Direction,
1159    hello: HelloMessageWithProtocols,
1160    status: UnifiedStatus,
1161    fork_filter: ForkFilter,
1162    extra_handlers: RlpxSubProtocolHandlers,
1163) {
1164    let local_addr = stream.local_addr().ok();
1165    let auth = async move {
1166        let stream = match get_ecies_stream(stream, secret_key, direction).await {
1167            Ok(stream) => stream,
1168            Err(error) => {
1169                return PendingSessionEvent::EciesAuthError {
1170                    remote_addr,
1171                    session_id,
1172                    error,
1173                    direction,
1174                }
1175            }
1176        };
1177
1178        let unauthed = UnauthedP2PStream::new(stream).with_max_payload_size(p2p_max_payload_size);
1179
1180        authenticate_stream(
1181            handshake,
1182            eth_max_message_size,
1183            unauthed,
1184            session_id,
1185            remote_addr,
1186            local_addr,
1187            direction,
1188            hello,
1189            status,
1190            fork_filter,
1191            extra_handlers,
1192        )
1193        .await
1194    }
1195    .boxed();
1196
1197    match futures::future::select(disconnect_rx, auth).await {
1198        Either::Left((_, _)) => {
1199            let _ = events
1200                .send(PendingSessionEvent::Disconnected {
1201                    remote_addr,
1202                    session_id,
1203                    direction,
1204                    error: None,
1205                })
1206                .await;
1207        }
1208        Either::Right((res, _)) => {
1209            let _ = events.send(res).await;
1210        }
1211    }
1212}
1213
1214/// Returns an [`ECIESStream`] if it can be built. If not, send a
1215/// [`PendingSessionEvent::EciesAuthError`] and returns `None`
1216async fn get_ecies_stream<Io: AsyncRead + AsyncWrite + Unpin>(
1217    stream: Io,
1218    secret_key: SecretKey,
1219    direction: Direction,
1220) -> Result<ECIESStream<Io>, ECIESError> {
1221    match direction {
1222        Direction::Incoming => ECIESStream::incoming(stream, secret_key).await,
1223        Direction::Outgoing(remote_peer_id) => {
1224            ECIESStream::connect(stream, secret_key, remote_peer_id).await
1225        }
1226    }
1227}
1228
1229/// Authenticate the stream via handshake
1230///
1231/// On Success return the authenticated stream as [`PendingSessionEvent`].
1232///
1233/// If additional [`RlpxSubProtocolHandlers`] are provided, the hello message will be updated to
1234/// also negotiate the additional protocols.
1235#[expect(clippy::too_many_arguments)]
1236async fn authenticate_stream<N: NetworkPrimitives>(
1237    handshake: Arc<dyn EthRlpxHandshake>,
1238    eth_max_message_size: usize,
1239    stream: UnauthedP2PStream<ECIESStream<TcpStream>>,
1240    session_id: SessionId,
1241    remote_addr: SocketAddr,
1242    local_addr: Option<SocketAddr>,
1243    direction: Direction,
1244    mut hello: HelloMessageWithProtocols,
1245    mut status: UnifiedStatus,
1246    fork_filter: ForkFilter,
1247    mut extra_handlers: RlpxSubProtocolHandlers,
1248) -> PendingSessionEvent<N> {
1249    // Add extra protocols to the hello message
1250    extra_handlers.retain(|handler| hello.try_add_protocol(handler.protocol()).is_ok());
1251
1252    let authenticated_peer_id = stream.inner().remote_id();
1253
1254    // conduct the p2p rlpx handshake and return the rlpx authenticated stream
1255    let (mut p2p_stream, their_hello) = match stream.handshake(hello).await {
1256        Ok(stream_res) => stream_res,
1257        Err(err) => {
1258            return PendingSessionEvent::Disconnected {
1259                remote_addr,
1260                session_id,
1261                direction,
1262                error: Some(PendingSessionHandshakeError::Eth(err.into())),
1263            }
1264        }
1265    };
1266
1267    // The ECIES handshake proved possession of this key, so it is the only trustworthy identity of
1268    // the connection. Everything the peer states in `Hello` is unauthenticated.
1269    //
1270    // Bind the session to the authenticated identity before anything else observes the peer. A
1271    // peer that announces a different node id could otherwise act on behalf of that node, for
1272    // example by making an extra protocol report reputation changes against it.
1273    if their_hello.id != authenticated_peer_id {
1274        let _ = p2p_stream.disconnect(DisconnectReason::UnexpectedHandshakeIdentity).await;
1275
1276        return PendingSessionEvent::Disconnected {
1277            remote_addr,
1278            session_id,
1279            direction,
1280            error: Some(PendingSessionHandshakeError::UnexpectedHandshakeIdentity(
1281                GotExpected { got: their_hello.id, expected: authenticated_peer_id }.into(),
1282            )),
1283        }
1284    }
1285
1286    // if we have extra handlers, check if it must be supported by the remote
1287    if !extra_handlers.is_empty() {
1288        // ensure that no extra handlers that aren't supported are not mandatory
1289        while let Some(pos) = extra_handlers.iter().position(|handler| {
1290            p2p_stream
1291                .shared_capabilities()
1292                .ensure_matching_capability(&handler.protocol().cap)
1293                .is_err()
1294        }) {
1295            let handler = extra_handlers.remove(pos);
1296            if handler.on_unsupported_by_peer(
1297                p2p_stream.shared_capabilities(),
1298                direction,
1299                authenticated_peer_id,
1300            ) == OnNotSupported::Disconnect
1301            {
1302                return PendingSessionEvent::Disconnected {
1303                    remote_addr,
1304                    session_id,
1305                    direction,
1306                    error: Some(PendingSessionHandshakeError::UnsupportedExtraCapability),
1307                };
1308            }
1309        }
1310    }
1311
1312    // Ensure we negotiated mandatory eth protocol
1313    let eth_version = match p2p_stream.shared_capabilities().eth_version() {
1314        Ok(version) => version,
1315        Err(err) => {
1316            return PendingSessionEvent::Disconnected {
1317                remote_addr,
1318                session_id,
1319                direction,
1320                error: Some(PendingSessionHandshakeError::Eth(err.into())),
1321            }
1322        }
1323    };
1324
1325    // Before trying status handshake, set up the version to negotiated shared version
1326    status.set_eth_version(eth_version);
1327
1328    let (conn, their_status) = if p2p_stream.shared_capabilities().len() == 1 {
1329        // if the shared caps are 1, we know both support the eth version
1330        // if the hello handshake was successful we can try status handshake
1331
1332        // perform the eth protocol handshake
1333        match handshake
1334            .handshake(&mut p2p_stream, status, fork_filter.clone(), HANDSHAKE_TIMEOUT)
1335            .await
1336        {
1337            Ok(their_status) => {
1338                let eth_stream =
1339                    EthStream::with_max_message_size(eth_version, p2p_stream, eth_max_message_size);
1340                (eth_stream.into(), their_status)
1341            }
1342            Err(err) => {
1343                return PendingSessionEvent::Disconnected {
1344                    remote_addr,
1345                    session_id,
1346                    direction,
1347                    error: Some(PendingSessionHandshakeError::Eth(err)),
1348                }
1349            }
1350        }
1351    } else if p2p_stream.shared_capabilities().is_exact_eth_snap_v2() {
1352        // Exactly `eth` + `snap/2` (no other extras): use the dedicated stream instead of the
1353        // general-purpose satellite multiplexer. If `snap/2` is negotiated alongside other extra
1354        // capabilities, fall through to the satellite path — the dedicated stream only composes
1355        // `eth` and `snap/2`.
1356        match EthSnapStream::handshake(
1357            p2p_stream,
1358            status,
1359            fork_filter,
1360            handshake,
1361            eth_max_message_size,
1362        )
1363        .await
1364        {
1365            Ok((stream, their_status)) => (stream.into(), their_status),
1366            Err(err) => {
1367                return PendingSessionEvent::Disconnected {
1368                    remote_addr,
1369                    session_id,
1370                    direction,
1371                    error: Some(PendingSessionHandshakeError::Eth(err)),
1372                }
1373            }
1374        }
1375    } else {
1376        let mut multiplex_stream = RlpxProtocolMultiplexer::new(p2p_stream);
1377        let (protocol_start, protocol_ready) = watch::channel(false);
1378
1379        // Register bounded inbound queues and frame limits before reading early satellite frames.
1380        // The application callbacks stay dormant until the eth Status handshake succeeds.
1381        for handler in extra_handlers.into_iter() {
1382            let protocol = handler.protocol();
1383            let limits = handler.inbound_limits();
1384            let remote_peer_id = authenticated_peer_id;
1385            let mut protocol_ready = protocol_ready.clone();
1386            // The unsupported-handler pass guarantees a matching negotiated capability. The
1387            // multiplexer retains that immutable capability set, so installation cannot fail.
1388            multiplex_stream
1389                .install_protocol_with_limits(&protocol.cap, limits, move |conn| {
1390                    stream::once(async move {
1391                        // A closed gate means authentication failed and the connection is dropped.
1392                        protocol_ready
1393                            .wait_for(|started| *started)
1394                            .await
1395                            .is_ok()
1396                            .then(|| handler.into_connection(direction, remote_peer_id, conn))
1397                    })
1398                    .filter_map(future::ready)
1399                    .flatten()
1400                })
1401                .expect("remaining handler capability was negotiated");
1402        }
1403
1404        let (multiplex_stream, their_status) = match multiplex_stream
1405            .into_eth_satellite_stream(status, fork_filter, handshake, eth_max_message_size)
1406            .await
1407        {
1408            Ok((multiplex_stream, their_status)) => (multiplex_stream, their_status),
1409            Err(err) => {
1410                return PendingSessionEvent::Disconnected {
1411                    remote_addr,
1412                    session_id,
1413                    direction,
1414                    error: Some(PendingSessionHandshakeError::Eth(err)),
1415                }
1416            }
1417        };
1418        protocol_start.send_replace(true);
1419
1420        (multiplex_stream.into(), their_status)
1421    };
1422
1423    // `port` field is effectively deprecated, so we treat 0 value as a missing port.
1424    let peer_listen_port = (their_hello.port != 0).then_some(their_hello.port);
1425
1426    PendingSessionEvent::Established {
1427        session_id,
1428        remote_addr,
1429        local_addr,
1430        peer_id: authenticated_peer_id,
1431        capabilities: Arc::new(Capabilities::from(their_hello.capabilities)),
1432        status: Arc::new(their_status),
1433        conn,
1434        direction,
1435        client_id: their_hello.client_version,
1436        peer_listen_port,
1437    }
1438}