1mod 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#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq, Hash)]
61pub struct SessionId(usize);
62
63#[must_use = "Session Manager must be polled to process session events."]
65#[derive(Debug)]
66pub struct SessionManager<N: NetworkPrimitives> {
67 next_id: usize,
69 counter: SessionCounter,
71 initial_internal_request_timeout: Duration,
74 protocol_breach_request_timeout: Duration,
77 pending_session_timeout: Duration,
79 secret_key: SecretKey,
81 status: UnifiedStatus,
83 hello_message: HelloMessageWithProtocols,
85 fork_filter: ForkFilter,
87 session_command_buffer: usize,
89 executor: Box<dyn TaskSpawner>,
91 pending_sessions: FxHashMap<SessionId, PendingSessionHandle>,
96 active_sessions: HashMap<PeerId, ActiveSessionHandle<N>>,
98 pending_sessions_tx: mpsc::Sender<PendingSessionEvent<N>>,
103 pending_session_rx: ReceiverStream<PendingSessionEvent<N>>,
105 active_session_tx: MeteredPollSender<ActiveSessionMessage<N>>,
110 active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
112 extra_protocols: RlpxSubProtocols,
114 disconnections_counter: DisconnectionsCounter,
116 metrics: SessionManagerMetrics,
118 handshake: Arc<dyn EthRlpxHandshake>,
120 local_range_info: BlockRangeInfo,
123}
124
125impl<N: NetworkPrimitives> SessionManager<N> {
128 #[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 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 pub(crate) const fn fork_id(&self) -> ForkId {
179 self.fork_filter.current()
180 }
181
182 pub fn is_valid_fork_id(&self, fork_id: ForkId) -> bool {
185 self.fork_filter.validate(fork_id).is_ok()
186 }
187
188 const fn next_id(&mut self) -> SessionId {
190 let id = self.next_id;
191 self.next_id += 1;
192 SessionId(id)
193 }
194
195 pub const fn status(&self) -> UnifiedStatus {
197 self.status
198 }
199
200 pub const fn secret_key(&self) -> SecretKey {
202 self.secret_key
203 }
204
205 pub const fn active_sessions(&self) -> &HashMap<PeerId, ActiveSessionHandle<N>> {
207 &self.active_sessions
208 }
209
210 pub fn hello_message(&self) -> HelloMessageWithProtocols {
212 self.hello_message.clone()
213 }
214
215 pub(crate) fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {
217 self.extra_protocols.push(protocol)
218 }
219
220 #[inline]
222 pub(crate) fn num_pending_connections(&self) -> usize {
223 self.pending_sessions.len()
224 }
225
226 fn spawn<F>(&self, f: F)
229 where
230 F: Future<Output = ()> + Send + 'static,
231 {
232 self.executor.spawn(f.boxed());
233 }
234
235 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 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 pub fn dial_outbound(&mut self, remote_addr: SocketAddr, remote_peer_id: PeerId) {
308 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 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 pub fn disconnect_all(&self, reason: Option<DisconnectReason>) {
363 for session in self.active_sessions.values() {
364 session.disconnect(reason);
365 }
366 }
367
368 pub fn disconnect_all_pending(&mut self) {
370 for session in self.pending_sessions.values_mut() {
371 session.disconnect();
372 }
373 }
374
375 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 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 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 pub(crate) fn try_disconnect_incoming_connection(
411 &self,
412 stream: TcpStream,
413 reason: DisconnectReason,
414 ) {
415 if !self.disconnections_counter.has_capacity() {
416 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 pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<SessionEvent<N>> {
440 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 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 self.remove_pending_session(&session_id);
503
504 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 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 let version = conn.version();
540
541 let range_update_interval = (conn.version() >= EthVersion::Eth69).then(|| {
544 let mut interval = tokio::time::interval(RANGE_UPDATE_INTERVAL);
545 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
546 interval
547 });
548
549 let session = ActiveSession {
550 next_id: 0,
551 remote_peer_id: peer_id,
552 remote_addr,
553 remote_capabilities: Arc::clone(&capabilities),
554 session_id,
555 commands_rx: ReceiverStream::new(commands_rx),
556 to_session_manager: self.active_session_tx.clone(),
557 pending_message_to_session: None,
558 internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
559 inflight_requests: Default::default(),
560 conn,
561 queued_outgoing: QueuedOutgoingMessages::new(
562 self.metrics.queued_outgoing_messages.clone(),
563 ),
564 received_requests_from_remote: Default::default(),
565 internal_request_timeout_interval: tokio::time::interval(
566 self.initial_internal_request_timeout,
567 ),
568 internal_request_timeout: Arc::clone(&timeout),
569 protocol_breach_request_timeout: self.protocol_breach_request_timeout,
570 terminate_message: None,
571 range_info: None,
572 local_range_info: self.local_range_info.clone(),
573 range_update_interval,
574 last_sent_latest_block: None,
575 };
576
577 self.spawn(session);
578
579 let client_version = client_id.into();
580 let handle = ActiveSessionHandle {
581 status: status.clone(),
582 direction,
583 session_id,
584 remote_id: peer_id,
585 version,
586 established: Instant::now(),
587 capabilities: Arc::clone(&capabilities),
588 commands_to_session,
589 client_version: Arc::clone(&client_version),
590 remote_addr,
591 local_addr,
592 };
593
594 self.active_sessions.insert(peer_id, handle);
595 self.counter.inc_active(&direction);
596
597 if direction.is_outgoing() {
598 self.metrics.total_dial_successes.increment(1);
599 }
600
601 Poll::Ready(SessionEvent::SessionEstablished {
602 peer_id,
603 remote_addr,
604 client_version,
605 version,
606 capabilities,
607 status,
608 messages,
609 direction,
610 timeout,
611 range_info: None,
612 })
613 }
614 PendingSessionEvent::Disconnected { remote_addr, session_id, direction, error } => {
615 trace!(
616 target: "net::session",
617 ?session_id,
618 ?remote_addr,
619 ?error,
620 "disconnected pending session"
621 );
622 self.remove_pending_session(&session_id);
623 match direction {
624 Direction::Incoming => {
625 Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
626 remote_addr,
627 error,
628 })
629 }
630 Direction::Outgoing(peer_id) => {
631 Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
632 remote_addr,
633 peer_id,
634 error,
635 })
636 }
637 }
638 }
639 PendingSessionEvent::OutgoingConnectionError {
640 remote_addr,
641 session_id,
642 peer_id,
643 error,
644 } => {
645 trace!(
646 target: "net::session",
647 %error,
648 ?session_id,
649 ?remote_addr,
650 ?peer_id,
651 "connection refused"
652 );
653 self.remove_pending_session(&session_id);
654 Poll::Ready(SessionEvent::OutgoingConnectionError { remote_addr, peer_id, error })
655 }
656 PendingSessionEvent::EciesAuthError { remote_addr, session_id, error, direction } => {
657 trace!(
658 target: "net::session",
659 %error,
660 ?session_id,
661 ?remote_addr,
662 "ecies auth failed"
663 );
664 self.remove_pending_session(&session_id);
665 match direction {
666 Direction::Incoming => {
667 Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
668 remote_addr,
669 error: Some(PendingSessionHandshakeError::Ecies(error)),
670 })
671 }
672 Direction::Outgoing(peer_id) => {
673 Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
674 remote_addr,
675 peer_id,
676 error: Some(PendingSessionHandshakeError::Ecies(error)),
677 })
678 }
679 }
680 }
681 }
682 }
683
684 pub(crate) fn update_advertised_block_range(&mut self, block_range_update: BlockRangeUpdate) {
692 self.status.earliest_block = Some(block_range_update.earliest);
693 self.status.latest_block = Some(block_range_update.latest);
694 self.status.blockhash = block_range_update.latest_hash;
695
696 self.local_range_info.update(
698 block_range_update.earliest,
699 block_range_update.latest,
700 block_range_update.latest_hash,
701 );
702 }
703}
704
705#[derive(Default, Debug, Clone)]
707struct DisconnectionsCounter(Arc<()>);
708
709impl DisconnectionsCounter {
710 const MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS: usize = 15;
711
712 fn has_capacity(&self) -> bool {
715 Arc::strong_count(&self.0) <= Self::MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS
716 }
717}
718
719#[derive(Debug)]
721pub enum SessionEvent<N: NetworkPrimitives> {
722 SessionEstablished {
726 peer_id: PeerId,
728 remote_addr: SocketAddr,
730 client_version: Arc<str>,
732 capabilities: Arc<Capabilities>,
734 version: EthVersion,
736 status: Arc<UnifiedStatus>,
738 messages: PeerRequestSender<PeerRequest<N>>,
740 direction: Direction,
742 timeout: Arc<AtomicU64>,
745 range_info: Option<BlockRangeInfo>,
747 },
748 AlreadyConnected {
750 peer_id: PeerId,
752 remote_addr: SocketAddr,
754 direction: Direction,
756 },
757 ValidMessage {
759 peer_id: PeerId,
761 message: PeerMessage<N>,
763 },
764 BadMessage {
766 peer_id: PeerId,
768 },
769 ProtocolBreach {
771 peer_id: PeerId,
773 },
774 IncomingPendingSessionClosed {
776 remote_addr: SocketAddr,
778 error: Option<PendingSessionHandshakeError>,
780 },
781 OutgoingPendingSessionClosed {
783 remote_addr: SocketAddr,
785 peer_id: PeerId,
787 error: Option<PendingSessionHandshakeError>,
789 },
790 OutgoingConnectionError {
792 remote_addr: SocketAddr,
794 peer_id: PeerId,
796 error: io::Error,
798 },
799 SessionClosedOnConnectionError {
801 peer_id: PeerId,
803 remote_addr: SocketAddr,
805 error: EthStreamError,
807 },
808 Disconnected {
810 peer_id: PeerId,
812 remote_addr: SocketAddr,
814 },
815}
816
817#[derive(Debug, thiserror::Error)]
819pub enum PendingSessionHandshakeError {
820 #[error(transparent)]
822 Eth(EthStreamError),
823 #[error(transparent)]
825 Ecies(ECIESError),
826 #[error("authentication timed out")]
828 Timeout,
829 #[error("Mandatory extra capability unsupported")]
831 UnsupportedExtraCapability,
832}
833
834impl PendingSessionHandshakeError {
835 pub const fn as_disconnected(&self) -> Option<DisconnectReason> {
837 match self {
838 Self::Eth(eth_err) => eth_err.as_disconnected(),
839 _ => None,
840 }
841 }
842}
843
844#[derive(Debug, Clone, thiserror::Error)]
847#[error("session limit reached {0}")]
848pub struct ExceedsSessionLimit(pub(crate) u32);
849
850pub(crate) async fn pending_session_with_timeout<F, N: NetworkPrimitives>(
852 timeout: Duration,
853 session_id: SessionId,
854 remote_addr: SocketAddr,
855 direction: Direction,
856 events: mpsc::Sender<PendingSessionEvent<N>>,
857 f: F,
858) where
859 F: Future<Output = ()>,
860{
861 if tokio::time::timeout(timeout, f).await.is_err() {
862 trace!(target: "net::session", ?remote_addr, ?direction, "pending session timed out");
863 let event = PendingSessionEvent::Disconnected {
864 remote_addr,
865 session_id,
866 direction,
867 error: Some(PendingSessionHandshakeError::Timeout),
868 };
869 let _ = events.send(event).await;
870 }
871}
872
873#[expect(clippy::too_many_arguments)]
877pub(crate) async fn start_pending_incoming_session<N: NetworkPrimitives>(
878 handshake: Arc<dyn EthRlpxHandshake>,
879 disconnect_rx: oneshot::Receiver<()>,
880 session_id: SessionId,
881 stream: TcpStream,
882 events: mpsc::Sender<PendingSessionEvent<N>>,
883 remote_addr: SocketAddr,
884 secret_key: SecretKey,
885 hello: HelloMessageWithProtocols,
886 status: UnifiedStatus,
887 fork_filter: ForkFilter,
888 extra_handlers: RlpxSubProtocolHandlers,
889) {
890 authenticate(
891 handshake,
892 disconnect_rx,
893 events,
894 stream,
895 session_id,
896 remote_addr,
897 secret_key,
898 Direction::Incoming,
899 hello,
900 status,
901 fork_filter,
902 extra_handlers,
903 )
904 .await
905}
906
907#[instrument(skip_all, fields(%remote_addr, peer_id), target = "net")]
909#[expect(clippy::too_many_arguments)]
910async fn start_pending_outbound_session<N: NetworkPrimitives>(
911 handshake: Arc<dyn EthRlpxHandshake>,
912 disconnect_rx: oneshot::Receiver<()>,
913 events: mpsc::Sender<PendingSessionEvent<N>>,
914 session_id: SessionId,
915 remote_addr: SocketAddr,
916 remote_peer_id: PeerId,
917 secret_key: SecretKey,
918 hello: HelloMessageWithProtocols,
919 status: UnifiedStatus,
920 fork_filter: ForkFilter,
921 extra_handlers: RlpxSubProtocolHandlers,
922) {
923 let stream = match TcpStream::connect(remote_addr).await {
924 Ok(stream) => {
925 if let Err(err) = stream.set_nodelay(true) {
926 tracing::warn!(target: "net::session", "set nodelay failed: {:?}", err);
927 }
928 stream
929 }
930 Err(error) => {
931 let _ = events
932 .send(PendingSessionEvent::OutgoingConnectionError {
933 remote_addr,
934 session_id,
935 peer_id: remote_peer_id,
936 error,
937 })
938 .await;
939 return
940 }
941 };
942 authenticate(
943 handshake,
944 disconnect_rx,
945 events,
946 stream,
947 session_id,
948 remote_addr,
949 secret_key,
950 Direction::Outgoing(remote_peer_id),
951 hello,
952 status,
953 fork_filter,
954 extra_handlers,
955 )
956 .await
957}
958
959#[expect(clippy::too_many_arguments)]
961async fn authenticate<N: NetworkPrimitives>(
962 handshake: Arc<dyn EthRlpxHandshake>,
963 disconnect_rx: oneshot::Receiver<()>,
964 events: mpsc::Sender<PendingSessionEvent<N>>,
965 stream: TcpStream,
966 session_id: SessionId,
967 remote_addr: SocketAddr,
968 secret_key: SecretKey,
969 direction: Direction,
970 hello: HelloMessageWithProtocols,
971 status: UnifiedStatus,
972 fork_filter: ForkFilter,
973 extra_handlers: RlpxSubProtocolHandlers,
974) {
975 let local_addr = stream.local_addr().ok();
976 let stream = match get_ecies_stream(stream, secret_key, direction).await {
977 Ok(stream) => stream,
978 Err(error) => {
979 let _ = events
980 .send(PendingSessionEvent::EciesAuthError {
981 remote_addr,
982 session_id,
983 error,
984 direction,
985 })
986 .await;
987 return
988 }
989 };
990
991 let unauthed = UnauthedP2PStream::new(stream);
992
993 let auth = authenticate_stream(
994 handshake,
995 unauthed,
996 session_id,
997 remote_addr,
998 local_addr,
999 direction,
1000 hello,
1001 status,
1002 fork_filter,
1003 extra_handlers,
1004 )
1005 .boxed();
1006
1007 match futures::future::select(disconnect_rx, auth).await {
1008 Either::Left((_, _)) => {
1009 let _ = events
1010 .send(PendingSessionEvent::Disconnected {
1011 remote_addr,
1012 session_id,
1013 direction,
1014 error: None,
1015 })
1016 .await;
1017 }
1018 Either::Right((res, _)) => {
1019 let _ = events.send(res).await;
1020 }
1021 }
1022}
1023
1024async fn get_ecies_stream<Io: AsyncRead + AsyncWrite + Unpin>(
1027 stream: Io,
1028 secret_key: SecretKey,
1029 direction: Direction,
1030) -> Result<ECIESStream<Io>, ECIESError> {
1031 match direction {
1032 Direction::Incoming => ECIESStream::incoming(stream, secret_key).await,
1033 Direction::Outgoing(remote_peer_id) => {
1034 ECIESStream::connect(stream, secret_key, remote_peer_id).await
1035 }
1036 }
1037}
1038
1039#[expect(clippy::too_many_arguments)]
1046async fn authenticate_stream<N: NetworkPrimitives>(
1047 handshake: Arc<dyn EthRlpxHandshake>,
1048 stream: UnauthedP2PStream<ECIESStream<TcpStream>>,
1049 session_id: SessionId,
1050 remote_addr: SocketAddr,
1051 local_addr: Option<SocketAddr>,
1052 direction: Direction,
1053 mut hello: HelloMessageWithProtocols,
1054 mut status: UnifiedStatus,
1055 fork_filter: ForkFilter,
1056 mut extra_handlers: RlpxSubProtocolHandlers,
1057) -> PendingSessionEvent<N> {
1058 extra_handlers.retain(|handler| hello.try_add_protocol(handler.protocol()).is_ok());
1060
1061 let (mut p2p_stream, their_hello) = match stream.handshake(hello).await {
1063 Ok(stream_res) => stream_res,
1064 Err(err) => {
1065 return PendingSessionEvent::Disconnected {
1066 remote_addr,
1067 session_id,
1068 direction,
1069 error: Some(PendingSessionHandshakeError::Eth(err.into())),
1070 }
1071 }
1072 };
1073
1074 if !extra_handlers.is_empty() {
1076 while let Some(pos) = extra_handlers.iter().position(|handler| {
1078 p2p_stream
1079 .shared_capabilities()
1080 .ensure_matching_capability(&handler.protocol().cap)
1081 .is_err()
1082 }) {
1083 let handler = extra_handlers.remove(pos);
1084 if handler.on_unsupported_by_peer(
1085 p2p_stream.shared_capabilities(),
1086 direction,
1087 their_hello.id,
1088 ) == OnNotSupported::Disconnect
1089 {
1090 return PendingSessionEvent::Disconnected {
1091 remote_addr,
1092 session_id,
1093 direction,
1094 error: Some(PendingSessionHandshakeError::UnsupportedExtraCapability),
1095 };
1096 }
1097 }
1098 }
1099
1100 let eth_version = match p2p_stream.shared_capabilities().eth_version() {
1102 Ok(version) => version,
1103 Err(err) => {
1104 return PendingSessionEvent::Disconnected {
1105 remote_addr,
1106 session_id,
1107 direction,
1108 error: Some(PendingSessionHandshakeError::Eth(err.into())),
1109 }
1110 }
1111 };
1112
1113 status.set_eth_version(eth_version);
1115
1116 let (conn, their_status) = if p2p_stream.shared_capabilities().len() == 1 {
1117 match handshake
1122 .handshake(&mut p2p_stream, status, fork_filter.clone(), HANDSHAKE_TIMEOUT)
1123 .await
1124 {
1125 Ok(their_status) => {
1126 let eth_stream = EthStream::new(eth_version, p2p_stream);
1127 (eth_stream.into(), their_status)
1128 }
1129 Err(err) => {
1130 return PendingSessionEvent::Disconnected {
1131 remote_addr,
1132 session_id,
1133 direction,
1134 error: Some(PendingSessionHandshakeError::Eth(err)),
1135 }
1136 }
1137 }
1138 } else {
1139 let mut multiplex_stream = RlpxProtocolMultiplexer::new(p2p_stream);
1141
1142 for handler in extra_handlers.into_iter() {
1144 let cap = handler.protocol().cap;
1145 let remote_peer_id = their_hello.id;
1146
1147 multiplex_stream
1148 .install_protocol(&cap, move |conn| {
1149 handler.into_connection(direction, remote_peer_id, conn)
1150 })
1151 .ok();
1152 }
1153
1154 let (multiplex_stream, their_status) = match multiplex_stream
1155 .into_eth_satellite_stream(status, fork_filter, handshake)
1156 .await
1157 {
1158 Ok((multiplex_stream, their_status)) => (multiplex_stream, their_status),
1159 Err(err) => {
1160 return PendingSessionEvent::Disconnected {
1161 remote_addr,
1162 session_id,
1163 direction,
1164 error: Some(PendingSessionHandshakeError::Eth(err)),
1165 }
1166 }
1167 };
1168
1169 (multiplex_stream.into(), their_status)
1170 };
1171
1172 PendingSessionEvent::Established {
1173 session_id,
1174 remote_addr,
1175 local_addr,
1176 peer_id: their_hello.id,
1177 capabilities: Arc::new(Capabilities::from(their_hello.capabilities)),
1178 status: Arc::new(their_status),
1179 conn,
1180 direction,
1181 client_id: their_hello.client_version,
1182 }
1183}