1mod active;
4mod conn;
5mod counter;
6mod handle;
7#[cfg(test)]
8mod tests;
9mod types;
10pub use types::BlockRangeInfo;
11
12use crate::{
13 budget::DEFAULT_BUDGET_PRIORITIZED_EVENTS,
14 message::PeerMessage,
15 metrics::SessionManagerMetrics,
16 protocol::{IntoRlpxSubProtocol, OnNotSupported, RlpxSubProtocolHandlers, RlpxSubProtocols},
17 session::active::ActiveSession,
18};
19use active::QueuedOutgoingMessages;
20use alloy_primitives::map::{FbBuildHasher, HashMap};
21use counter::SessionCounter;
22use futures::{
23 future::{self, Either},
24 io, stream, FutureExt, StreamExt,
25};
26use reth_ecies::{stream::ECIESStream, ECIESError};
27use reth_eth_wire::{
28 errors::EthStreamError, handshake::EthRlpxHandshake, multiplex::RlpxProtocolMultiplexer,
29 BlockRangeUpdate, Capabilities, DisconnectReason, EthSnapStream, EthStream, EthVersion,
30 HelloMessageWithProtocols, NetworkPrimitives, UnauthedP2PStream, UnifiedStatus,
31 HANDSHAKE_TIMEOUT,
32};
33use reth_ethereum_forks::{ForkFilter, ForkId, ForkTransition, Head};
34use reth_metrics::common::mpsc::MeteredPollSender;
35use reth_network_api::{PeerRequest, PeerRequestSender};
36use reth_network_peers::PeerId;
37use reth_network_types::SessionsConfig;
38use reth_primitives_traits::{GotExpected, GotExpectedBoxed};
39use reth_tasks::Runtime;
40use rustc_hash::FxHashMap;
41use secp256k1::SecretKey;
42use std::{
43 future::Future,
44 net::SocketAddr,
45 sync::{atomic::AtomicU64, Arc},
46 task::{Context, Poll},
47 time::{Duration, Instant},
48};
49use tokio::{
50 io::{AsyncRead, AsyncWrite},
51 net::TcpStream,
52 sync::{mpsc, oneshot, watch},
53};
54use tokio_stream::wrappers::ReceiverStream;
55use tokio_util::sync::PollSender;
56use tracing::{instrument, trace};
57
58use crate::session::active::{
59 request_timeout_interval, BroadcastItemCounter, RANGE_UPDATE_INTERVAL,
60};
61pub use conn::EthRlpxConnection;
62use handle::SessionCommandSender;
63pub use handle::{
64 ActiveSessionHandle, ActiveSessionMessage, PendingSessionEvent, PendingSessionHandle,
65 SessionCommand,
66};
67pub use reth_network_api::{Direction, PeerInfo};
68
69#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq, Hash)]
71pub struct SessionId(usize);
72
73#[must_use = "Session Manager must be polled to process session events."]
75#[derive(Debug)]
76pub struct SessionManager<N: NetworkPrimitives> {
77 next_id: usize,
79 counter: SessionCounter,
81 initial_internal_request_timeout: Duration,
84 protocol_breach_request_timeout: Duration,
87 pending_session_timeout: Duration,
89 secret_key: SecretKey,
91 status: UnifiedStatus,
93 hello_message: HelloMessageWithProtocols,
95 fork_filter: ForkFilter,
97 session_command_buffer: usize,
99 executor: Runtime,
101 pending_sessions: FxHashMap<SessionId, PendingSessionHandle>,
106 active_sessions: HashMap<PeerId, ActiveSessionHandle<N>, FbBuildHasher<64>>,
108 pending_sessions_tx: mpsc::Sender<PendingSessionEvent<N>>,
113 pending_session_rx: ReceiverStream<PendingSessionEvent<N>>,
115 active_session_tx: MeteredPollSender<ActiveSessionMessage<N>>,
120 active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
122 active_events_in_row: u32,
124 extra_protocols: RlpxSubProtocols,
126 disconnections_counter: DisconnectionsCounter,
128 metrics: SessionManagerMetrics,
130 handshake: Arc<dyn EthRlpxHandshake>,
132 eth_max_message_size: usize,
134 p2p_max_payload_size: usize,
136 local_range_info: BlockRangeInfo,
139 reject_block_announcements: bool,
142}
143
144impl<N: NetworkPrimitives> SessionManager<N> {
147 #[expect(clippy::too_many_arguments)]
149 pub fn new(
150 secret_key: SecretKey,
151 config: SessionsConfig,
152 executor: Runtime,
153 status: UnifiedStatus,
154 hello_message: HelloMessageWithProtocols,
155 fork_filter: ForkFilter,
156 extra_protocols: RlpxSubProtocols,
157 handshake: Arc<dyn EthRlpxHandshake>,
158 eth_max_message_size: usize,
159 p2p_max_payload_size: usize,
160 reject_block_announcements: bool,
161 ) -> Self {
162 let (pending_sessions_tx, pending_sessions_rx) = mpsc::channel(config.session_event_buffer);
163 let (active_session_tx, active_session_rx) = mpsc::channel(config.session_event_buffer);
164 let active_session_tx = PollSender::new(active_session_tx);
165
166 let local_range_info = BlockRangeInfo::new(
168 status.earliest_block.unwrap_or_default(),
169 status.latest_block.unwrap_or_default(),
170 status.blockhash,
171 );
172
173 Self {
174 next_id: 0,
175 counter: SessionCounter::new(config.limits),
176 initial_internal_request_timeout: config.initial_internal_request_timeout,
177 protocol_breach_request_timeout: config.protocol_breach_request_timeout,
178 pending_session_timeout: config.pending_session_timeout,
179 secret_key,
180 status,
181 hello_message,
182 fork_filter,
183 session_command_buffer: config.session_command_buffer,
184 executor,
185 pending_sessions: Default::default(),
186 active_sessions: Default::default(),
187 pending_sessions_tx,
188 pending_session_rx: ReceiverStream::new(pending_sessions_rx),
189 active_session_tx: MeteredPollSender::new(active_session_tx, "network_active_session"),
190 active_session_rx: ReceiverStream::new(active_session_rx),
191 active_events_in_row: 0,
192 extra_protocols,
193 disconnections_counter: Default::default(),
194 metrics: Default::default(),
195 handshake,
196 eth_max_message_size,
197 p2p_max_payload_size,
198 local_range_info,
199 reject_block_announcements,
200 }
201 }
202
203 pub(crate) const fn fork_id(&self) -> ForkId {
205 self.fork_filter.current()
206 }
207
208 pub fn is_valid_fork_id(&self, fork_id: ForkId) -> bool {
211 self.fork_filter.validate(fork_id).is_ok()
212 }
213
214 const fn next_id(&mut self) -> SessionId {
216 let id = self.next_id;
217 self.next_id += 1;
218 SessionId(id)
219 }
220
221 pub const fn status(&self) -> UnifiedStatus {
223 self.status
224 }
225
226 pub const fn secret_key(&self) -> SecretKey {
228 self.secret_key
229 }
230
231 pub const fn active_sessions(
233 &self,
234 ) -> &HashMap<PeerId, ActiveSessionHandle<N>, FbBuildHasher<64>> {
235 &self.active_sessions
236 }
237
238 pub fn hello_message(&self) -> HelloMessageWithProtocols {
240 self.hello_message.clone()
241 }
242
243 pub(crate) fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {
245 self.extra_protocols.push(protocol)
246 }
247
248 #[inline]
250 pub(crate) fn num_pending_connections(&self) -> usize {
251 self.pending_sessions.len()
252 }
253
254 fn spawn<F>(&self, f: F)
257 where
258 F: Future<Output = ()> + Send + 'static,
259 {
260 self.executor.spawn_task(f);
261 }
262
263 pub(crate) fn on_status_update(&mut self, head: Head) -> Option<ForkTransition> {
268 self.status.blockhash = head.hash;
269 self.status.total_difficulty = Some(head.total_difficulty);
270 let transition = self.fork_filter.set_head(head);
271 self.status.forkid = self.fork_filter.current();
272 self.status.latest_block = Some(head.number);
273
274 transition
275 }
276
277 pub(crate) fn set_fork_filter(&mut self, fork_filter: ForkFilter) -> ForkId {
289 self.fork_filter = fork_filter;
290 self.status.forkid = self.fork_filter.current();
291 self.status.forkid
292 }
293
294 pub(crate) fn on_incoming(
299 &mut self,
300 stream: TcpStream,
301 remote_addr: SocketAddr,
302 ) -> Result<SessionId, ExceedsSessionLimit> {
303 self.counter.ensure_pending_inbound()?;
304
305 let session_id = self.next_id();
306
307 trace!(
308 target: "net::session",
309 ?remote_addr,
310 ?session_id,
311 "new pending incoming session"
312 );
313
314 let (disconnect_tx, disconnect_rx) = oneshot::channel();
315 let pending_events = self.pending_sessions_tx.clone();
316 let secret_key = self.secret_key;
317 let hello_message = self.hello_message.clone();
318 let status = self.status;
319 let fork_filter = self.fork_filter.clone();
320 let extra_handlers = self.extra_protocols.on_incoming(remote_addr);
321 self.spawn(pending_session_with_timeout(
322 self.pending_session_timeout,
323 session_id,
324 remote_addr,
325 Direction::Incoming,
326 pending_events.clone(),
327 start_pending_incoming_session(
328 self.handshake.clone(),
329 self.eth_max_message_size,
330 self.p2p_max_payload_size,
331 disconnect_rx,
332 session_id,
333 stream,
334 pending_events,
335 remote_addr,
336 secret_key,
337 hello_message,
338 status,
339 fork_filter,
340 extra_handlers,
341 ),
342 ));
343
344 let handle = PendingSessionHandle {
345 disconnect_tx: Some(disconnect_tx),
346 direction: Direction::Incoming,
347 };
348 self.pending_sessions.insert(session_id, handle);
349 self.counter.inc_pending_inbound();
350 Ok(session_id)
351 }
352
353 pub fn dial_outbound(&mut self, remote_addr: SocketAddr, remote_peer_id: PeerId) {
356 if let Err(err) = self.try_dial_outbound(remote_addr, remote_peer_id) {
357 trace!(target: "net", %err, "Outgoing connection rejected, capacity already reached.");
358 }
359 }
360
361 pub(crate) fn try_dial_outbound(
363 &mut self,
364 remote_addr: SocketAddr,
365 remote_peer_id: PeerId,
366 ) -> Result<(), ExceedsSessionLimit> {
367 self.counter.ensure_pending_outbound()?;
368 let session_id = self.next_id();
369 let (disconnect_tx, disconnect_rx) = oneshot::channel();
370 let pending_events = self.pending_sessions_tx.clone();
371 let secret_key = self.secret_key;
372 let hello_message = self.hello_message.clone();
373 let fork_filter = self.fork_filter.clone();
374 let status = self.status;
375 let extra_handlers = self.extra_protocols.on_outgoing(remote_addr, remote_peer_id);
376 self.spawn(pending_session_with_timeout(
377 self.pending_session_timeout,
378 session_id,
379 remote_addr,
380 Direction::Outgoing(remote_peer_id),
381 pending_events.clone(),
382 start_pending_outbound_session(
383 self.handshake.clone(),
384 self.eth_max_message_size,
385 self.p2p_max_payload_size,
386 disconnect_rx,
387 pending_events,
388 session_id,
389 remote_addr,
390 remote_peer_id,
391 secret_key,
392 hello_message,
393 status,
394 fork_filter,
395 extra_handlers,
396 ),
397 ));
398
399 let handle = PendingSessionHandle {
400 disconnect_tx: Some(disconnect_tx),
401 direction: Direction::Outgoing(remote_peer_id),
402 };
403 self.pending_sessions.insert(session_id, handle);
404 self.counter.inc_pending_outbound();
405 Ok(())
406 }
407
408 pub fn disconnect(&self, node: PeerId, reason: Option<DisconnectReason>) {
413 if let Some(session) = self.active_sessions.get(&node) {
414 session.disconnect(reason);
415 }
416 }
417
418 pub fn disconnect_all(&self, reason: Option<DisconnectReason>) {
423 for session in self.active_sessions.values() {
424 session.disconnect(reason);
425 }
426 }
427
428 pub fn disconnect_all_pending(&mut self) {
430 for session in self.pending_sessions.values_mut() {
431 session.disconnect();
432 }
433 }
434
435 pub fn send_message(&self, peer_id: &PeerId, msg: PeerMessage<N>) {
442 if let Some(session) = self.active_sessions.get(peer_id) &&
443 !session.commands.send_message(msg)
444 {
445 self.metrics.total_outgoing_peer_messages_dropped.increment(1);
446 }
447 }
448
449 fn remove_pending_session(&mut self, id: &SessionId) -> Option<PendingSessionHandle> {
451 let session = self.pending_sessions.remove(id)?;
452 self.counter.dec_pending(&session.direction);
453 Some(session)
454 }
455
456 fn cancel_pending_outbound(&mut self, peer_id: PeerId) {
458 self.pending_sessions.retain(|_, session| {
459 if session.direction == Direction::Outgoing(peer_id) {
460 session.disconnect();
461 self.counter.dec_pending(&session.direction);
462 return false
463 }
464 true
465 });
466 }
467
468 fn disconnect_pending_connection(&self, conn: EthRlpxConnection<N>, reason: DisconnectReason) {
470 self.spawn(async move {
471 let _ =
472 tokio::time::timeout(HANDSHAKE_TIMEOUT, conn.into_inner().disconnect(reason)).await;
473 });
474 }
475
476 fn remove_active_session(&mut self, id: &PeerId) -> Option<ActiveSessionHandle<N>> {
478 let session = self.active_sessions.remove(id)?;
479 self.counter.dec_active(&session.direction);
480 Some(session)
481 }
482
483 pub(crate) fn try_disconnect_incoming_connection(
487 &self,
488 stream: TcpStream,
489 reason: DisconnectReason,
490 ) {
491 if !self.disconnections_counter.has_capacity() {
492 return
494 }
495
496 let guard = self.disconnections_counter.clone();
497 let secret_key = self.secret_key;
498
499 self.spawn(async move {
500 trace!(
501 target: "net::session",
502 "gracefully disconnecting incoming connection"
503 );
504 let _ = tokio::time::timeout(HANDSHAKE_TIMEOUT, async move {
505 if let Ok(stream) = get_ecies_stream(stream, secret_key, Direction::Incoming).await
506 {
507 let mut unauth = UnauthedP2PStream::new(stream);
508 let _ = unauth.send_disconnect(reason).await;
509 }
510 })
511 .await;
512 drop(guard);
514 });
515 }
516
517 pub(crate) fn poll(
525 &mut self,
526 cx: &mut Context<'_>,
527 inbound_session_rejection: impl Fn(PeerId) -> Option<DisconnectReason>,
528 ) -> Poll<SessionEvent<N>> {
529 if self.active_events_in_row >= DEFAULT_BUDGET_PRIORITIZED_EVENTS {
530 self.active_events_in_row = 0;
531 if let Poll::Ready(event) =
532 self.poll_pending_session_event(cx, &inbound_session_rejection)
533 {
534 return Poll::Ready(event)
535 }
536 }
537
538 if let Poll::Ready(event) = self.poll_active_session_event(cx) {
539 self.active_events_in_row += 1;
540 return Poll::Ready(event)
541 }
542
543 self.active_events_in_row = 0;
544 self.poll_pending_session_event(cx, inbound_session_rejection)
545 }
546
547 fn poll_active_session_event(&mut self, cx: &mut Context<'_>) -> Poll<SessionEvent<N>> {
549 match self.active_session_rx.poll_next_unpin(cx) {
550 Poll::Pending => {}
551 Poll::Ready(None) => {
552 unreachable!("Manager holds both channel halves.")
553 }
554 Poll::Ready(Some(event)) => {
555 return match event {
556 ActiveSessionMessage::Disconnected { peer_id, remote_addr } => {
557 trace!(
558 target: "net::session",
559 ?peer_id,
560 "gracefully disconnected active session."
561 );
562 self.remove_active_session(&peer_id);
563 Poll::Ready(SessionEvent::Disconnected { peer_id, remote_addr })
564 }
565 ActiveSessionMessage::ClosedOnConnectionError {
566 peer_id,
567 remote_addr,
568 error,
569 } => {
570 trace!(target: "net::session", ?peer_id, %error,"closed session.");
571 self.remove_active_session(&peer_id);
572 Poll::Ready(SessionEvent::SessionClosedOnConnectionError {
573 remote_addr,
574 peer_id,
575 error,
576 })
577 }
578 ActiveSessionMessage::ValidMessage { peer_id, message } => {
579 Poll::Ready(SessionEvent::ValidMessage { peer_id, message })
580 }
581 ActiveSessionMessage::BadMessage { peer_id } => {
582 Poll::Ready(SessionEvent::BadMessage { peer_id })
583 }
584 ActiveSessionMessage::ProtocolBreach { peer_id } => {
585 Poll::Ready(SessionEvent::ProtocolBreach { peer_id })
586 }
587 }
588 }
589 }
590 Poll::Pending
591 }
592
593 fn poll_pending_session_event(
595 &mut self,
596 cx: &mut Context<'_>,
597 inbound_session_rejection: impl Fn(PeerId) -> Option<DisconnectReason>,
598 ) -> Poll<SessionEvent<N>> {
599 let event = loop {
600 let event = match self.pending_session_rx.poll_next_unpin(cx) {
601 Poll::Pending => return Poll::Pending,
602 Poll::Ready(None) => unreachable!("Manager holds both channel halves."),
603 Poll::Ready(Some(event)) => event,
604 };
605 let session_id = match &event {
606 PendingSessionEvent::Established { session_id, .. } |
607 PendingSessionEvent::Disconnected { session_id, .. } |
608 PendingSessionEvent::OutgoingConnectionError { session_id, .. } |
609 PendingSessionEvent::EciesAuthError { session_id, .. } => session_id,
610 };
611 if self.remove_pending_session(session_id).is_some() {
613 break event
614 }
615 if let PendingSessionEvent::Established { conn, .. } = event {
616 self.disconnect_pending_connection(conn, DisconnectReason::AlreadyConnected);
617 }
618 };
619 match event {
620 PendingSessionEvent::Established {
621 session_id,
622 remote_addr,
623 local_addr,
624 peer_id,
625 capabilities,
626 mut conn,
627 status,
628 direction,
629 client_id,
630 peer_listen_port,
631 } => {
632 if self.active_sessions.contains_key(&peer_id) {
634 trace!(
635 target: "net::session",
636 ?session_id,
637 ?remote_addr,
638 ?peer_id,
639 ?direction,
640 "already connected"
641 );
642
643 self.disconnect_pending_connection(conn, DisconnectReason::AlreadyConnected);
644
645 return Poll::Ready(SessionEvent::AlreadyConnected {
646 peer_id,
647 remote_addr,
648 direction,
649 })
650 }
651
652 if direction.is_incoming() {
653 if let Some(reason) = inbound_session_rejection(peer_id) {
654 self.disconnect_pending_connection(conn, reason);
655 return Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
656 remote_addr,
657 error: None,
658 })
659 }
660 self.cancel_pending_outbound(peer_id);
661 }
662
663 let (commands_tx, commands_rx) = mpsc::channel(self.session_command_buffer);
664 let (unbounded_tx, unbounded_rx) = mpsc::unbounded_channel();
665
666 let (to_session_tx, messages_rx) = mpsc::channel(self.session_command_buffer);
667
668 let messages = PeerRequestSender::new(peer_id, to_session_tx);
669
670 let timeout = Arc::new(AtomicU64::new(
671 self.initial_internal_request_timeout.as_millis() as u64,
672 ));
673
674 let version = conn.version();
676
677 let range_update_interval = (conn.version() >= EthVersion::Eth69).then(|| {
682 let start = tokio::time::Instant::now() + RANGE_UPDATE_INTERVAL;
683 let mut interval = tokio::time::interval_at(start, RANGE_UPDATE_INTERVAL);
684 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
685 interval
686 });
687
688 let broadcast_items = BroadcastItemCounter::new();
694 let remote_range_info = status.block_range_update().map(|update| {
695 BlockRangeInfo::new(update.earliest, update.latest, update.latest_hash)
696 });
697
698 if self.reject_block_announcements {
699 conn.set_reject_block_announcements(true);
700 }
701
702 let session = ActiveSession {
703 next_id: 0,
704 remote_peer_id: peer_id,
705 remote_addr,
706 remote_capabilities: Arc::clone(&capabilities),
707 session_id,
708 commands_rx: ReceiverStream::new(commands_rx),
709 unbounded_rx,
710 unbounded_broadcast_msgs: self.metrics.total_unbounded_broadcast_msgs.clone(),
711 to_session_manager: self.active_session_tx.clone(),
712 pending_message_to_session: None,
713 internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
714 inflight_requests: Default::default(),
715 conn,
716 queued_outgoing: QueuedOutgoingMessages::new(
717 self.metrics.queued_outgoing_messages.clone(),
718 broadcast_items.clone(),
719 ),
720 received_requests_from_remote: Default::default(),
721 internal_request_timeout_interval: request_timeout_interval(
722 self.initial_internal_request_timeout,
723 ),
724 internal_request_timeout: Arc::clone(&timeout),
725 protocol_breach_request_timeout: self.protocol_breach_request_timeout,
726 terminate_message: None,
727 range_info: remote_range_info.clone(),
728 local_range_info: self.local_range_info.clone(),
729 range_update_interval,
730 last_sent_latest_block: None,
731 disconnect_deadline: None,
732 };
733
734 let supports_snap = session.conn.supports_snap();
735 self.spawn(session);
736
737 let client_version = client_id.into();
738 let handle = ActiveSessionHandle {
739 status: status.clone(),
740 direction,
741 session_id,
742 remote_id: peer_id,
743 version,
744 established: Instant::now(),
745 capabilities: Arc::clone(&capabilities),
746 commands: SessionCommandSender::new(commands_tx, unbounded_tx, broadcast_items),
747 client_version: Arc::clone(&client_version),
748 remote_addr,
749 local_addr,
750 peer_listen_port,
751 };
752
753 self.active_sessions.insert(peer_id, handle);
754 self.counter.inc_active(&direction);
755
756 if direction.is_outgoing() {
757 self.metrics.total_dial_successes.increment(1);
758 }
759
760 Poll::Ready(SessionEvent::SessionEstablished {
761 peer_id,
762 remote_addr,
763 client_version,
764 version,
765 capabilities,
766 status,
767 messages,
768 direction,
769 timeout,
770 range_info: remote_range_info,
771 supports_snap,
772 })
773 }
774 PendingSessionEvent::Disconnected { remote_addr, session_id, direction, error } => {
775 trace!(
776 target: "net::session",
777 ?session_id,
778 ?remote_addr,
779 ?error,
780 "disconnected pending session"
781 );
782 match direction {
783 Direction::Incoming => {
784 Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
785 remote_addr,
786 error,
787 })
788 }
789 Direction::Outgoing(peer_id) => {
790 Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
791 remote_addr,
792 peer_id,
793 error,
794 })
795 }
796 }
797 }
798 PendingSessionEvent::OutgoingConnectionError {
799 remote_addr,
800 session_id,
801 peer_id,
802 error,
803 } => {
804 trace!(
805 target: "net::session",
806 %error,
807 ?session_id,
808 ?remote_addr,
809 ?peer_id,
810 "connection refused"
811 );
812 Poll::Ready(SessionEvent::OutgoingConnectionError { remote_addr, peer_id, error })
813 }
814 PendingSessionEvent::EciesAuthError { remote_addr, session_id, error, direction } => {
815 trace!(
816 target: "net::session",
817 %error,
818 ?session_id,
819 ?remote_addr,
820 "ecies auth failed"
821 );
822 match direction {
823 Direction::Incoming => {
824 Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
825 remote_addr,
826 error: Some(PendingSessionHandshakeError::Ecies(error)),
827 })
828 }
829 Direction::Outgoing(peer_id) => {
830 Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
831 remote_addr,
832 peer_id,
833 error: Some(PendingSessionHandshakeError::Ecies(error)),
834 })
835 }
836 }
837 }
838 }
839 }
840
841 pub(crate) fn update_advertised_block_range(&mut self, block_range_update: BlockRangeUpdate) {
849 self.status.earliest_block = Some(block_range_update.earliest);
850 self.status.latest_block = Some(block_range_update.latest);
851 self.status.blockhash = block_range_update.latest_hash;
852
853 self.local_range_info.update(
855 block_range_update.earliest,
856 block_range_update.latest,
857 block_range_update.latest_hash,
858 );
859 }
860}
861
862#[derive(Default, Debug, Clone)]
864struct DisconnectionsCounter(Arc<()>);
865
866impl DisconnectionsCounter {
867 const MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS: usize = 15;
868
869 fn has_capacity(&self) -> bool {
872 Arc::strong_count(&self.0) <= Self::MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS
873 }
874}
875
876#[derive(Debug)]
878pub enum SessionEvent<N: NetworkPrimitives> {
879 SessionEstablished {
883 peer_id: PeerId,
885 remote_addr: SocketAddr,
887 client_version: Arc<str>,
889 capabilities: Arc<Capabilities>,
891 version: EthVersion,
893 status: Arc<UnifiedStatus>,
895 messages: PeerRequestSender<PeerRequest<N>>,
897 direction: Direction,
899 timeout: Arc<AtomicU64>,
902 range_info: Option<BlockRangeInfo>,
904 supports_snap: bool,
906 },
907 AlreadyConnected {
909 peer_id: PeerId,
911 remote_addr: SocketAddr,
913 direction: Direction,
915 },
916 ValidMessage {
918 peer_id: PeerId,
920 message: PeerMessage<N>,
922 },
923 BadMessage {
925 peer_id: PeerId,
927 },
928 ProtocolBreach {
930 peer_id: PeerId,
932 },
933 IncomingPendingSessionClosed {
935 remote_addr: SocketAddr,
937 error: Option<PendingSessionHandshakeError>,
939 },
940 OutgoingPendingSessionClosed {
942 remote_addr: SocketAddr,
944 peer_id: PeerId,
946 error: Option<PendingSessionHandshakeError>,
948 },
949 OutgoingConnectionError {
951 remote_addr: SocketAddr,
953 peer_id: PeerId,
955 error: io::Error,
957 },
958 SessionClosedOnConnectionError {
960 peer_id: PeerId,
962 remote_addr: SocketAddr,
964 error: EthStreamError,
966 },
967 Disconnected {
969 peer_id: PeerId,
971 remote_addr: SocketAddr,
973 },
974}
975
976#[derive(Debug, thiserror::Error)]
978pub enum PendingSessionHandshakeError {
979 #[error(transparent)]
981 Eth(EthStreamError),
982 #[error(transparent)]
984 Ecies(ECIESError),
985 #[error("authentication timed out")]
987 Timeout,
988 #[error("Mandatory extra capability unsupported")]
990 UnsupportedExtraCapability,
991 #[error("unexpected identity in hello message: {0}")]
994 UnexpectedHandshakeIdentity(GotExpectedBoxed<PeerId>),
995}
996
997impl PendingSessionHandshakeError {
998 pub const fn as_disconnected(&self) -> Option<DisconnectReason> {
1001 match self {
1002 Self::Eth(eth_err) => eth_err.as_disconnected(),
1003 Self::UnexpectedHandshakeIdentity(_) => {
1004 Some(DisconnectReason::UnexpectedHandshakeIdentity)
1005 }
1006 _ => None,
1007 }
1008 }
1009}
1010
1011#[derive(Debug, Clone, thiserror::Error)]
1014#[error("session limit reached {0}")]
1015pub struct ExceedsSessionLimit(pub(crate) u32);
1016
1017pub(crate) async fn pending_session_with_timeout<F, N: NetworkPrimitives>(
1019 timeout: Duration,
1020 session_id: SessionId,
1021 remote_addr: SocketAddr,
1022 direction: Direction,
1023 events: mpsc::Sender<PendingSessionEvent<N>>,
1024 f: F,
1025) where
1026 F: Future<Output = ()>,
1027{
1028 if tokio::time::timeout(timeout, f).await.is_err() {
1029 trace!(target: "net::session", ?remote_addr, ?direction, "pending session timed out");
1030 let event = PendingSessionEvent::Disconnected {
1031 remote_addr,
1032 session_id,
1033 direction,
1034 error: Some(PendingSessionHandshakeError::Timeout),
1035 };
1036 let _ = events.send(event).await;
1037 }
1038}
1039
1040#[expect(clippy::too_many_arguments)]
1044pub(crate) async fn start_pending_incoming_session<N: NetworkPrimitives>(
1045 handshake: Arc<dyn EthRlpxHandshake>,
1046 eth_max_message_size: usize,
1047 p2p_max_payload_size: usize,
1048 disconnect_rx: oneshot::Receiver<()>,
1049 session_id: SessionId,
1050 stream: TcpStream,
1051 events: mpsc::Sender<PendingSessionEvent<N>>,
1052 remote_addr: SocketAddr,
1053 secret_key: SecretKey,
1054 hello: HelloMessageWithProtocols,
1055 status: UnifiedStatus,
1056 fork_filter: ForkFilter,
1057 extra_handlers: RlpxSubProtocolHandlers,
1058) {
1059 authenticate(
1060 handshake,
1061 eth_max_message_size,
1062 p2p_max_payload_size,
1063 disconnect_rx,
1064 events,
1065 stream,
1066 session_id,
1067 remote_addr,
1068 secret_key,
1069 Direction::Incoming,
1070 hello,
1071 status,
1072 fork_filter,
1073 extra_handlers,
1074 )
1075 .await
1076}
1077
1078#[instrument(level = "trace", target = "net::network", skip_all, fields(%remote_addr, peer_id = ?remote_peer_id))]
1080#[expect(clippy::too_many_arguments)]
1081async fn start_pending_outbound_session<N: NetworkPrimitives>(
1082 handshake: Arc<dyn EthRlpxHandshake>,
1083 eth_max_message_size: usize,
1084 p2p_max_payload_size: usize,
1085 mut disconnect_rx: oneshot::Receiver<()>,
1086 events: mpsc::Sender<PendingSessionEvent<N>>,
1087 session_id: SessionId,
1088 remote_addr: SocketAddr,
1089 remote_peer_id: PeerId,
1090 secret_key: SecretKey,
1091 hello: HelloMessageWithProtocols,
1092 status: UnifiedStatus,
1093 fork_filter: ForkFilter,
1094 extra_handlers: RlpxSubProtocolHandlers,
1095) {
1096 let connection = tokio::select! {
1097 _ = &mut disconnect_rx => {
1098 let _ = events.send(PendingSessionEvent::Disconnected {
1099 remote_addr,
1100 session_id,
1101 direction: Direction::Outgoing(remote_peer_id),
1102 error: None,
1103 }).await;
1104 return
1105 },
1106 connection = TcpStream::connect(remote_addr) => connection,
1107 };
1108 let stream = match connection {
1109 Ok(stream) => {
1110 if let Err(err) = stream.set_nodelay(true) {
1111 tracing::warn!(target: "net::session", "set nodelay failed: {:?}", err);
1112 }
1113 stream
1114 }
1115 Err(error) => {
1116 let _ = events
1117 .send(PendingSessionEvent::OutgoingConnectionError {
1118 remote_addr,
1119 session_id,
1120 peer_id: remote_peer_id,
1121 error,
1122 })
1123 .await;
1124 return
1125 }
1126 };
1127 authenticate(
1128 handshake,
1129 eth_max_message_size,
1130 p2p_max_payload_size,
1131 disconnect_rx,
1132 events,
1133 stream,
1134 session_id,
1135 remote_addr,
1136 secret_key,
1137 Direction::Outgoing(remote_peer_id),
1138 hello,
1139 status,
1140 fork_filter,
1141 extra_handlers,
1142 )
1143 .await
1144}
1145
1146#[expect(clippy::too_many_arguments)]
1148async fn authenticate<N: NetworkPrimitives>(
1149 handshake: Arc<dyn EthRlpxHandshake>,
1150 eth_max_message_size: usize,
1151 p2p_max_payload_size: usize,
1152 disconnect_rx: oneshot::Receiver<()>,
1153 events: mpsc::Sender<PendingSessionEvent<N>>,
1154 stream: TcpStream,
1155 session_id: SessionId,
1156 remote_addr: SocketAddr,
1157 secret_key: SecretKey,
1158 direction: Direction,
1159 hello: HelloMessageWithProtocols,
1160 status: UnifiedStatus,
1161 fork_filter: ForkFilter,
1162 extra_handlers: RlpxSubProtocolHandlers,
1163) {
1164 let local_addr = stream.local_addr().ok();
1165 let auth = async move {
1166 let stream = match get_ecies_stream(stream, secret_key, direction).await {
1167 Ok(stream) => stream,
1168 Err(error) => {
1169 return PendingSessionEvent::EciesAuthError {
1170 remote_addr,
1171 session_id,
1172 error,
1173 direction,
1174 }
1175 }
1176 };
1177
1178 let unauthed = UnauthedP2PStream::new(stream).with_max_payload_size(p2p_max_payload_size);
1179
1180 authenticate_stream(
1181 handshake,
1182 eth_max_message_size,
1183 unauthed,
1184 session_id,
1185 remote_addr,
1186 local_addr,
1187 direction,
1188 hello,
1189 status,
1190 fork_filter,
1191 extra_handlers,
1192 )
1193 .await
1194 }
1195 .boxed();
1196
1197 match futures::future::select(disconnect_rx, auth).await {
1198 Either::Left((_, _)) => {
1199 let _ = events
1200 .send(PendingSessionEvent::Disconnected {
1201 remote_addr,
1202 session_id,
1203 direction,
1204 error: None,
1205 })
1206 .await;
1207 }
1208 Either::Right((res, _)) => {
1209 let _ = events.send(res).await;
1210 }
1211 }
1212}
1213
1214async fn get_ecies_stream<Io: AsyncRead + AsyncWrite + Unpin>(
1217 stream: Io,
1218 secret_key: SecretKey,
1219 direction: Direction,
1220) -> Result<ECIESStream<Io>, ECIESError> {
1221 match direction {
1222 Direction::Incoming => ECIESStream::incoming(stream, secret_key).await,
1223 Direction::Outgoing(remote_peer_id) => {
1224 ECIESStream::connect(stream, secret_key, remote_peer_id).await
1225 }
1226 }
1227}
1228
1229#[expect(clippy::too_many_arguments)]
1236async fn authenticate_stream<N: NetworkPrimitives>(
1237 handshake: Arc<dyn EthRlpxHandshake>,
1238 eth_max_message_size: usize,
1239 stream: UnauthedP2PStream<ECIESStream<TcpStream>>,
1240 session_id: SessionId,
1241 remote_addr: SocketAddr,
1242 local_addr: Option<SocketAddr>,
1243 direction: Direction,
1244 mut hello: HelloMessageWithProtocols,
1245 mut status: UnifiedStatus,
1246 fork_filter: ForkFilter,
1247 mut extra_handlers: RlpxSubProtocolHandlers,
1248) -> PendingSessionEvent<N> {
1249 extra_handlers.retain(|handler| hello.try_add_protocol(handler.protocol()).is_ok());
1251
1252 let authenticated_peer_id = stream.inner().remote_id();
1253
1254 let (mut p2p_stream, their_hello) = match stream.handshake(hello).await {
1256 Ok(stream_res) => stream_res,
1257 Err(err) => {
1258 return PendingSessionEvent::Disconnected {
1259 remote_addr,
1260 session_id,
1261 direction,
1262 error: Some(PendingSessionHandshakeError::Eth(err.into())),
1263 }
1264 }
1265 };
1266
1267 if their_hello.id != authenticated_peer_id {
1274 let _ = p2p_stream.disconnect(DisconnectReason::UnexpectedHandshakeIdentity).await;
1275
1276 return PendingSessionEvent::Disconnected {
1277 remote_addr,
1278 session_id,
1279 direction,
1280 error: Some(PendingSessionHandshakeError::UnexpectedHandshakeIdentity(
1281 GotExpected { got: their_hello.id, expected: authenticated_peer_id }.into(),
1282 )),
1283 }
1284 }
1285
1286 if !extra_handlers.is_empty() {
1288 while let Some(pos) = extra_handlers.iter().position(|handler| {
1290 p2p_stream
1291 .shared_capabilities()
1292 .ensure_matching_capability(&handler.protocol().cap)
1293 .is_err()
1294 }) {
1295 let handler = extra_handlers.remove(pos);
1296 if handler.on_unsupported_by_peer(
1297 p2p_stream.shared_capabilities(),
1298 direction,
1299 authenticated_peer_id,
1300 ) == OnNotSupported::Disconnect
1301 {
1302 return PendingSessionEvent::Disconnected {
1303 remote_addr,
1304 session_id,
1305 direction,
1306 error: Some(PendingSessionHandshakeError::UnsupportedExtraCapability),
1307 };
1308 }
1309 }
1310 }
1311
1312 let eth_version = match p2p_stream.shared_capabilities().eth_version() {
1314 Ok(version) => version,
1315 Err(err) => {
1316 return PendingSessionEvent::Disconnected {
1317 remote_addr,
1318 session_id,
1319 direction,
1320 error: Some(PendingSessionHandshakeError::Eth(err.into())),
1321 }
1322 }
1323 };
1324
1325 status.set_eth_version(eth_version);
1327
1328 let (conn, their_status) = if p2p_stream.shared_capabilities().len() == 1 {
1329 match handshake
1334 .handshake(&mut p2p_stream, status, fork_filter.clone(), HANDSHAKE_TIMEOUT)
1335 .await
1336 {
1337 Ok(their_status) => {
1338 let eth_stream =
1339 EthStream::with_max_message_size(eth_version, p2p_stream, eth_max_message_size);
1340 (eth_stream.into(), their_status)
1341 }
1342 Err(err) => {
1343 return PendingSessionEvent::Disconnected {
1344 remote_addr,
1345 session_id,
1346 direction,
1347 error: Some(PendingSessionHandshakeError::Eth(err)),
1348 }
1349 }
1350 }
1351 } else if p2p_stream.shared_capabilities().is_exact_eth_snap_v2() {
1352 match EthSnapStream::handshake(
1357 p2p_stream,
1358 status,
1359 fork_filter,
1360 handshake,
1361 eth_max_message_size,
1362 )
1363 .await
1364 {
1365 Ok((stream, their_status)) => (stream.into(), their_status),
1366 Err(err) => {
1367 return PendingSessionEvent::Disconnected {
1368 remote_addr,
1369 session_id,
1370 direction,
1371 error: Some(PendingSessionHandshakeError::Eth(err)),
1372 }
1373 }
1374 }
1375 } else {
1376 let mut multiplex_stream = RlpxProtocolMultiplexer::new(p2p_stream);
1377 let (protocol_start, protocol_ready) = watch::channel(false);
1378
1379 for handler in extra_handlers.into_iter() {
1382 let protocol = handler.protocol();
1383 let limits = handler.inbound_limits();
1384 let remote_peer_id = authenticated_peer_id;
1385 let mut protocol_ready = protocol_ready.clone();
1386 multiplex_stream
1389 .install_protocol_with_limits(&protocol.cap, limits, move |conn| {
1390 stream::once(async move {
1391 protocol_ready
1393 .wait_for(|started| *started)
1394 .await
1395 .is_ok()
1396 .then(|| handler.into_connection(direction, remote_peer_id, conn))
1397 })
1398 .filter_map(future::ready)
1399 .flatten()
1400 })
1401 .expect("remaining handler capability was negotiated");
1402 }
1403
1404 let (multiplex_stream, their_status) = match multiplex_stream
1405 .into_eth_satellite_stream(status, fork_filter, handshake, eth_max_message_size)
1406 .await
1407 {
1408 Ok((multiplex_stream, their_status)) => (multiplex_stream, their_status),
1409 Err(err) => {
1410 return PendingSessionEvent::Disconnected {
1411 remote_addr,
1412 session_id,
1413 direction,
1414 error: Some(PendingSessionHandshakeError::Eth(err)),
1415 }
1416 }
1417 };
1418 protocol_start.send_replace(true);
1419
1420 (multiplex_stream.into(), their_status)
1421 };
1422
1423 let peer_listen_port = (their_hello.port != 0).then_some(their_hello.port);
1425
1426 PendingSessionEvent::Established {
1427 session_id,
1428 remote_addr,
1429 local_addr,
1430 peer_id: authenticated_peer_id,
1431 capabilities: Arc::new(Capabilities::from(their_hello.capabilities)),
1432 status: Arc::new(their_status),
1433 conn,
1434 direction,
1435 client_id: their_hello.client_version,
1436 peer_listen_port,
1437 }
1438}