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