Skip to main content

reth_network/session/
mod.rs

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