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::Runtime;
32use rustc_hash::FxHashMap;
33use secp256k1::SecretKey;
34use std::{
35 collections::HashMap,
36 future::Future,
37 net::SocketAddr,
38 sync::{atomic::AtomicU64, Arc},
39 task::{Context, Poll},
40 time::{Duration, Instant},
41};
42use tokio::{
43 io::{AsyncRead, AsyncWrite},
44 net::TcpStream,
45 sync::{mpsc, oneshot},
46};
47use tokio_stream::wrappers::ReceiverStream;
48use tokio_util::sync::PollSender;
49use tracing::{instrument, trace};
50
51use crate::session::active::{BroadcastItemCounter, RANGE_UPDATE_INTERVAL};
52pub use conn::EthRlpxConnection;
53use handle::SessionCommandSender;
54pub use handle::{
55 ActiveSessionHandle, ActiveSessionMessage, PendingSessionEvent, PendingSessionHandle,
56 SessionCommand,
57};
58pub use reth_network_api::{Direction, PeerInfo};
59
60#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq, Hash)]
62pub struct SessionId(usize);
63
64#[must_use = "Session Manager must be polled to process session events."]
66#[derive(Debug)]
67pub struct SessionManager<N: NetworkPrimitives> {
68 next_id: usize,
70 counter: SessionCounter,
72 initial_internal_request_timeout: Duration,
75 protocol_breach_request_timeout: Duration,
78 pending_session_timeout: Duration,
80 secret_key: SecretKey,
82 status: UnifiedStatus,
84 hello_message: HelloMessageWithProtocols,
86 fork_filter: ForkFilter,
88 session_command_buffer: usize,
90 executor: Runtime,
92 pending_sessions: FxHashMap<SessionId, PendingSessionHandle>,
97 active_sessions: HashMap<PeerId, ActiveSessionHandle<N>>,
99 pending_sessions_tx: mpsc::Sender<PendingSessionEvent<N>>,
104 pending_session_rx: ReceiverStream<PendingSessionEvent<N>>,
106 active_session_tx: MeteredPollSender<ActiveSessionMessage<N>>,
111 active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
113 extra_protocols: RlpxSubProtocols,
115 disconnections_counter: DisconnectionsCounter,
117 metrics: SessionManagerMetrics,
119 handshake: Arc<dyn EthRlpxHandshake>,
121 eth_max_message_size: usize,
123 local_range_info: BlockRangeInfo,
126 reject_block_announcements: bool,
129}
130
131impl<N: NetworkPrimitives> SessionManager<N> {
134 #[expect(clippy::too_many_arguments)]
136 pub fn new(
137 secret_key: SecretKey,
138 config: SessionsConfig,
139 executor: Runtime,
140 status: UnifiedStatus,
141 hello_message: HelloMessageWithProtocols,
142 fork_filter: ForkFilter,
143 extra_protocols: RlpxSubProtocols,
144 handshake: Arc<dyn EthRlpxHandshake>,
145 eth_max_message_size: usize,
146 reject_block_announcements: bool,
147 ) -> Self {
148 let (pending_sessions_tx, pending_sessions_rx) = mpsc::channel(config.session_event_buffer);
149 let (active_session_tx, active_session_rx) = mpsc::channel(config.session_event_buffer);
150 let active_session_tx = PollSender::new(active_session_tx);
151
152 let local_range_info = BlockRangeInfo::new(
154 status.earliest_block.unwrap_or_default(),
155 status.latest_block.unwrap_or_default(),
156 status.blockhash,
157 );
158
159 Self {
160 next_id: 0,
161 counter: SessionCounter::new(config.limits),
162 initial_internal_request_timeout: config.initial_internal_request_timeout,
163 protocol_breach_request_timeout: config.protocol_breach_request_timeout,
164 pending_session_timeout: config.pending_session_timeout,
165 secret_key,
166 status,
167 hello_message,
168 fork_filter,
169 session_command_buffer: config.session_command_buffer,
170 executor,
171 pending_sessions: Default::default(),
172 active_sessions: Default::default(),
173 pending_sessions_tx,
174 pending_session_rx: ReceiverStream::new(pending_sessions_rx),
175 active_session_tx: MeteredPollSender::new(active_session_tx, "network_active_session"),
176 active_session_rx: ReceiverStream::new(active_session_rx),
177 extra_protocols,
178 disconnections_counter: Default::default(),
179 metrics: Default::default(),
180 handshake,
181 eth_max_message_size,
182 local_range_info,
183 reject_block_announcements,
184 }
185 }
186
187 pub(crate) const fn fork_id(&self) -> ForkId {
189 self.fork_filter.current()
190 }
191
192 pub fn is_valid_fork_id(&self, fork_id: ForkId) -> bool {
195 self.fork_filter.validate(fork_id).is_ok()
196 }
197
198 const fn next_id(&mut self) -> SessionId {
200 let id = self.next_id;
201 self.next_id += 1;
202 SessionId(id)
203 }
204
205 pub const fn status(&self) -> UnifiedStatus {
207 self.status
208 }
209
210 pub const fn secret_key(&self) -> SecretKey {
212 self.secret_key
213 }
214
215 pub const fn active_sessions(&self) -> &HashMap<PeerId, ActiveSessionHandle<N>> {
217 &self.active_sessions
218 }
219
220 pub fn hello_message(&self) -> HelloMessageWithProtocols {
222 self.hello_message.clone()
223 }
224
225 pub(crate) fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) {
227 self.extra_protocols.push(protocol)
228 }
229
230 #[inline]
232 pub(crate) fn num_pending_connections(&self) -> usize {
233 self.pending_sessions.len()
234 }
235
236 fn spawn<F>(&self, f: F)
239 where
240 F: Future<Output = ()> + Send + 'static,
241 {
242 self.executor.spawn_task(f);
243 }
244
245 pub(crate) fn on_status_update(&mut self, head: Head) -> Option<ForkTransition> {
250 self.status.blockhash = head.hash;
251 self.status.total_difficulty = Some(head.total_difficulty);
252 let transition = self.fork_filter.set_head(head);
253 self.status.forkid = self.fork_filter.current();
254 self.status.latest_block = Some(head.number);
255
256 transition
257 }
258
259 pub(crate) fn on_incoming(
264 &mut self,
265 stream: TcpStream,
266 remote_addr: SocketAddr,
267 ) -> Result<SessionId, ExceedsSessionLimit> {
268 self.counter.ensure_pending_inbound()?;
269
270 let session_id = self.next_id();
271
272 trace!(
273 target: "net::session",
274 ?remote_addr,
275 ?session_id,
276 "new pending incoming session"
277 );
278
279 let (disconnect_tx, disconnect_rx) = oneshot::channel();
280 let pending_events = self.pending_sessions_tx.clone();
281 let secret_key = self.secret_key;
282 let hello_message = self.hello_message.clone();
283 let status = self.status;
284 let fork_filter = self.fork_filter.clone();
285 let extra_handlers = self.extra_protocols.on_incoming(remote_addr);
286 self.spawn(pending_session_with_timeout(
287 self.pending_session_timeout,
288 session_id,
289 remote_addr,
290 Direction::Incoming,
291 pending_events.clone(),
292 start_pending_incoming_session(
293 self.handshake.clone(),
294 self.eth_max_message_size,
295 disconnect_rx,
296 session_id,
297 stream,
298 pending_events,
299 remote_addr,
300 secret_key,
301 hello_message,
302 status,
303 fork_filter,
304 extra_handlers,
305 ),
306 ));
307
308 let handle = PendingSessionHandle {
309 disconnect_tx: Some(disconnect_tx),
310 direction: Direction::Incoming,
311 };
312 self.pending_sessions.insert(session_id, handle);
313 self.counter.inc_pending_inbound();
314 Ok(session_id)
315 }
316
317 pub fn dial_outbound(&mut self, remote_addr: SocketAddr, remote_peer_id: PeerId) {
319 if self.counter.ensure_pending_outbound().is_ok() {
321 let session_id = self.next_id();
322 let (disconnect_tx, disconnect_rx) = oneshot::channel();
323 let pending_events = self.pending_sessions_tx.clone();
324 let secret_key = self.secret_key;
325 let hello_message = self.hello_message.clone();
326 let fork_filter = self.fork_filter.clone();
327 let status = self.status;
328 let extra_handlers = self.extra_protocols.on_outgoing(remote_addr, remote_peer_id);
329 self.spawn(pending_session_with_timeout(
330 self.pending_session_timeout,
331 session_id,
332 remote_addr,
333 Direction::Outgoing(remote_peer_id),
334 pending_events.clone(),
335 start_pending_outbound_session(
336 self.handshake.clone(),
337 self.eth_max_message_size,
338 disconnect_rx,
339 pending_events,
340 session_id,
341 remote_addr,
342 remote_peer_id,
343 secret_key,
344 hello_message,
345 status,
346 fork_filter,
347 extra_handlers,
348 ),
349 ));
350
351 let handle = PendingSessionHandle {
352 disconnect_tx: Some(disconnect_tx),
353 direction: Direction::Outgoing(remote_peer_id),
354 };
355 self.pending_sessions.insert(session_id, handle);
356 self.counter.inc_pending_outbound();
357 }
358 }
359
360 pub fn disconnect(&self, node: PeerId, reason: Option<DisconnectReason>) {
365 if let Some(session) = self.active_sessions.get(&node) {
366 session.disconnect(reason);
367 }
368 }
369
370 pub fn disconnect_all(&self, reason: Option<DisconnectReason>) {
375 for session in self.active_sessions.values() {
376 session.disconnect(reason);
377 }
378 }
379
380 pub fn disconnect_all_pending(&mut self) {
382 for session in self.pending_sessions.values_mut() {
383 session.disconnect();
384 }
385 }
386
387 pub fn send_message(&self, peer_id: &PeerId, msg: PeerMessage<N>) {
394 if let Some(session) = self.active_sessions.get(peer_id) &&
395 !session.commands.send_message(msg)
396 {
397 self.metrics.total_outgoing_peer_messages_dropped.increment(1);
398 }
399 }
400
401 fn remove_pending_session(&mut self, id: &SessionId) -> Option<PendingSessionHandle> {
403 let session = self.pending_sessions.remove(id)?;
404 self.counter.dec_pending(&session.direction);
405 Some(session)
406 }
407
408 fn remove_active_session(&mut self, id: &PeerId) -> Option<ActiveSessionHandle<N>> {
410 let session = self.active_sessions.remove(id)?;
411 self.counter.dec_active(&session.direction);
412 Some(session)
413 }
414
415 pub(crate) fn try_disconnect_incoming_connection(
419 &self,
420 stream: TcpStream,
421 reason: DisconnectReason,
422 ) {
423 if !self.disconnections_counter.has_capacity() {
424 return
426 }
427
428 let guard = self.disconnections_counter.clone();
429 let secret_key = self.secret_key;
430
431 self.spawn(async move {
432 trace!(
433 target: "net::session",
434 "gracefully disconnecting incoming connection"
435 );
436 if let Ok(stream) = get_ecies_stream(stream, secret_key, Direction::Incoming).await {
437 let mut unauth = UnauthedP2PStream::new(stream);
438 let _ = unauth.send_disconnect(reason).await;
439 drop(guard);
440 }
441 });
442 }
443
444 pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll<SessionEvent<N>> {
448 match self.active_session_rx.poll_next_unpin(cx) {
450 Poll::Pending => {}
451 Poll::Ready(None) => {
452 unreachable!("Manager holds both channel halves.")
453 }
454 Poll::Ready(Some(event)) => {
455 return match event {
456 ActiveSessionMessage::Disconnected { peer_id, remote_addr } => {
457 trace!(
458 target: "net::session",
459 ?peer_id,
460 "gracefully disconnected active session."
461 );
462 self.remove_active_session(&peer_id);
463 Poll::Ready(SessionEvent::Disconnected { peer_id, remote_addr })
464 }
465 ActiveSessionMessage::ClosedOnConnectionError {
466 peer_id,
467 remote_addr,
468 error,
469 } => {
470 trace!(target: "net::session", ?peer_id, %error,"closed session.");
471 self.remove_active_session(&peer_id);
472 Poll::Ready(SessionEvent::SessionClosedOnConnectionError {
473 remote_addr,
474 peer_id,
475 error,
476 })
477 }
478 ActiveSessionMessage::ValidMessage { peer_id, message } => {
479 Poll::Ready(SessionEvent::ValidMessage { peer_id, message })
480 }
481 ActiveSessionMessage::BadMessage { peer_id } => {
482 Poll::Ready(SessionEvent::BadMessage { peer_id })
483 }
484 ActiveSessionMessage::ProtocolBreach { peer_id } => {
485 Poll::Ready(SessionEvent::ProtocolBreach { peer_id })
486 }
487 }
488 }
489 }
490
491 let event = match self.pending_session_rx.poll_next_unpin(cx) {
493 Poll::Pending => return Poll::Pending,
494 Poll::Ready(None) => unreachable!("Manager holds both channel halves."),
495 Poll::Ready(Some(event)) => event,
496 };
497 match event {
498 PendingSessionEvent::Established {
499 session_id,
500 remote_addr,
501 local_addr,
502 peer_id,
503 capabilities,
504 mut conn,
505 status,
506 direction,
507 client_id,
508 } => {
509 self.remove_pending_session(&session_id);
511
512 if self.active_sessions.contains_key(&peer_id) {
514 trace!(
515 target: "net::session",
516 ?session_id,
517 ?remote_addr,
518 ?peer_id,
519 ?direction,
520 "already connected"
521 );
522
523 self.spawn(async move {
524 let _ =
526 conn.into_inner().disconnect(DisconnectReason::AlreadyConnected).await;
527 });
528
529 return Poll::Ready(SessionEvent::AlreadyConnected {
530 peer_id,
531 remote_addr,
532 direction,
533 })
534 }
535
536 let (commands_tx, commands_rx) = mpsc::channel(self.session_command_buffer);
537 let (unbounded_tx, unbounded_rx) = mpsc::unbounded_channel();
538
539 let (to_session_tx, messages_rx) = mpsc::channel(self.session_command_buffer);
540
541 let messages = PeerRequestSender::new(peer_id, to_session_tx);
542
543 let timeout = Arc::new(AtomicU64::new(
544 self.initial_internal_request_timeout.as_millis() as u64,
545 ));
546
547 let version = conn.version();
549
550 let range_update_interval = (conn.version() >= EthVersion::Eth69).then(|| {
555 let start = tokio::time::Instant::now() + RANGE_UPDATE_INTERVAL;
556 let mut interval = tokio::time::interval_at(start, RANGE_UPDATE_INTERVAL);
557 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
558 interval
559 });
560
561 let broadcast_items = BroadcastItemCounter::new();
567 let remote_range_info = status.block_range_update().map(|update| {
568 BlockRangeInfo::new(update.earliest, update.latest, update.latest_hash)
569 });
570
571 if self.reject_block_announcements {
572 conn.set_reject_block_announcements(true);
573 }
574
575 let session = ActiveSession {
576 next_id: 0,
577 remote_peer_id: peer_id,
578 remote_addr,
579 remote_capabilities: Arc::clone(&capabilities),
580 session_id,
581 commands_rx: ReceiverStream::new(commands_rx),
582 unbounded_rx,
583 unbounded_broadcast_msgs: self.metrics.total_unbounded_broadcast_msgs.clone(),
584 to_session_manager: self.active_session_tx.clone(),
585 pending_message_to_session: None,
586 internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
587 inflight_requests: Default::default(),
588 conn,
589 queued_outgoing: QueuedOutgoingMessages::new(
590 self.metrics.queued_outgoing_messages.clone(),
591 broadcast_items.clone(),
592 ),
593 received_requests_from_remote: Default::default(),
594 internal_request_timeout_interval: tokio::time::interval(
595 self.initial_internal_request_timeout,
596 ),
597 internal_request_timeout: Arc::clone(&timeout),
598 protocol_breach_request_timeout: self.protocol_breach_request_timeout,
599 terminate_message: None,
600 range_info: remote_range_info.clone(),
601 local_range_info: self.local_range_info.clone(),
602 range_update_interval,
603 last_sent_latest_block: None,
604 };
605
606 self.spawn(session);
607
608 let client_version = client_id.into();
609 let handle = ActiveSessionHandle {
610 status: status.clone(),
611 direction,
612 session_id,
613 remote_id: peer_id,
614 version,
615 established: Instant::now(),
616 capabilities: Arc::clone(&capabilities),
617 commands: SessionCommandSender::new(commands_tx, unbounded_tx, broadcast_items),
618 client_version: Arc::clone(&client_version),
619 remote_addr,
620 local_addr,
621 };
622
623 self.active_sessions.insert(peer_id, handle);
624 self.counter.inc_active(&direction);
625
626 if direction.is_outgoing() {
627 self.metrics.total_dial_successes.increment(1);
628 }
629
630 Poll::Ready(SessionEvent::SessionEstablished {
631 peer_id,
632 remote_addr,
633 client_version,
634 version,
635 capabilities,
636 status,
637 messages,
638 direction,
639 timeout,
640 range_info: remote_range_info,
641 })
642 }
643 PendingSessionEvent::Disconnected { remote_addr, session_id, direction, error } => {
644 trace!(
645 target: "net::session",
646 ?session_id,
647 ?remote_addr,
648 ?error,
649 "disconnected pending session"
650 );
651 self.remove_pending_session(&session_id);
652 match direction {
653 Direction::Incoming => {
654 Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
655 remote_addr,
656 error,
657 })
658 }
659 Direction::Outgoing(peer_id) => {
660 Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
661 remote_addr,
662 peer_id,
663 error,
664 })
665 }
666 }
667 }
668 PendingSessionEvent::OutgoingConnectionError {
669 remote_addr,
670 session_id,
671 peer_id,
672 error,
673 } => {
674 trace!(
675 target: "net::session",
676 %error,
677 ?session_id,
678 ?remote_addr,
679 ?peer_id,
680 "connection refused"
681 );
682 self.remove_pending_session(&session_id);
683 Poll::Ready(SessionEvent::OutgoingConnectionError { remote_addr, peer_id, error })
684 }
685 PendingSessionEvent::EciesAuthError { remote_addr, session_id, error, direction } => {
686 trace!(
687 target: "net::session",
688 %error,
689 ?session_id,
690 ?remote_addr,
691 "ecies auth failed"
692 );
693 self.remove_pending_session(&session_id);
694 match direction {
695 Direction::Incoming => {
696 Poll::Ready(SessionEvent::IncomingPendingSessionClosed {
697 remote_addr,
698 error: Some(PendingSessionHandshakeError::Ecies(error)),
699 })
700 }
701 Direction::Outgoing(peer_id) => {
702 Poll::Ready(SessionEvent::OutgoingPendingSessionClosed {
703 remote_addr,
704 peer_id,
705 error: Some(PendingSessionHandshakeError::Ecies(error)),
706 })
707 }
708 }
709 }
710 }
711 }
712
713 pub(crate) fn update_advertised_block_range(&mut self, block_range_update: BlockRangeUpdate) {
721 self.status.earliest_block = Some(block_range_update.earliest);
722 self.status.latest_block = Some(block_range_update.latest);
723 self.status.blockhash = block_range_update.latest_hash;
724
725 self.local_range_info.update(
727 block_range_update.earliest,
728 block_range_update.latest,
729 block_range_update.latest_hash,
730 );
731 }
732}
733
734#[derive(Default, Debug, Clone)]
736struct DisconnectionsCounter(Arc<()>);
737
738impl DisconnectionsCounter {
739 const MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS: usize = 15;
740
741 fn has_capacity(&self) -> bool {
744 Arc::strong_count(&self.0) <= Self::MAX_CONCURRENT_GRACEFUL_DISCONNECTIONS
745 }
746}
747
748#[derive(Debug)]
750pub enum SessionEvent<N: NetworkPrimitives> {
751 SessionEstablished {
755 peer_id: PeerId,
757 remote_addr: SocketAddr,
759 client_version: Arc<str>,
761 capabilities: Arc<Capabilities>,
763 version: EthVersion,
765 status: Arc<UnifiedStatus>,
767 messages: PeerRequestSender<PeerRequest<N>>,
769 direction: Direction,
771 timeout: Arc<AtomicU64>,
774 range_info: Option<BlockRangeInfo>,
776 },
777 AlreadyConnected {
779 peer_id: PeerId,
781 remote_addr: SocketAddr,
783 direction: Direction,
785 },
786 ValidMessage {
788 peer_id: PeerId,
790 message: PeerMessage<N>,
792 },
793 BadMessage {
795 peer_id: PeerId,
797 },
798 ProtocolBreach {
800 peer_id: PeerId,
802 },
803 IncomingPendingSessionClosed {
805 remote_addr: SocketAddr,
807 error: Option<PendingSessionHandshakeError>,
809 },
810 OutgoingPendingSessionClosed {
812 remote_addr: SocketAddr,
814 peer_id: PeerId,
816 error: Option<PendingSessionHandshakeError>,
818 },
819 OutgoingConnectionError {
821 remote_addr: SocketAddr,
823 peer_id: PeerId,
825 error: io::Error,
827 },
828 SessionClosedOnConnectionError {
830 peer_id: PeerId,
832 remote_addr: SocketAddr,
834 error: EthStreamError,
836 },
837 Disconnected {
839 peer_id: PeerId,
841 remote_addr: SocketAddr,
843 },
844}
845
846#[derive(Debug, thiserror::Error)]
848pub enum PendingSessionHandshakeError {
849 #[error(transparent)]
851 Eth(EthStreamError),
852 #[error(transparent)]
854 Ecies(ECIESError),
855 #[error("authentication timed out")]
857 Timeout,
858 #[error("Mandatory extra capability unsupported")]
860 UnsupportedExtraCapability,
861}
862
863impl PendingSessionHandshakeError {
864 pub const fn as_disconnected(&self) -> Option<DisconnectReason> {
866 match self {
867 Self::Eth(eth_err) => eth_err.as_disconnected(),
868 _ => None,
869 }
870 }
871}
872
873#[derive(Debug, Clone, thiserror::Error)]
876#[error("session limit reached {0}")]
877pub struct ExceedsSessionLimit(pub(crate) u32);
878
879pub(crate) async fn pending_session_with_timeout<F, N: NetworkPrimitives>(
881 timeout: Duration,
882 session_id: SessionId,
883 remote_addr: SocketAddr,
884 direction: Direction,
885 events: mpsc::Sender<PendingSessionEvent<N>>,
886 f: F,
887) where
888 F: Future<Output = ()>,
889{
890 if tokio::time::timeout(timeout, f).await.is_err() {
891 trace!(target: "net::session", ?remote_addr, ?direction, "pending session timed out");
892 let event = PendingSessionEvent::Disconnected {
893 remote_addr,
894 session_id,
895 direction,
896 error: Some(PendingSessionHandshakeError::Timeout),
897 };
898 let _ = events.send(event).await;
899 }
900}
901
902#[expect(clippy::too_many_arguments)]
906pub(crate) async fn start_pending_incoming_session<N: NetworkPrimitives>(
907 handshake: Arc<dyn EthRlpxHandshake>,
908 eth_max_message_size: usize,
909 disconnect_rx: oneshot::Receiver<()>,
910 session_id: SessionId,
911 stream: TcpStream,
912 events: mpsc::Sender<PendingSessionEvent<N>>,
913 remote_addr: SocketAddr,
914 secret_key: SecretKey,
915 hello: HelloMessageWithProtocols,
916 status: UnifiedStatus,
917 fork_filter: ForkFilter,
918 extra_handlers: RlpxSubProtocolHandlers,
919) {
920 authenticate(
921 handshake,
922 eth_max_message_size,
923 disconnect_rx,
924 events,
925 stream,
926 session_id,
927 remote_addr,
928 secret_key,
929 Direction::Incoming,
930 hello,
931 status,
932 fork_filter,
933 extra_handlers,
934 )
935 .await
936}
937
938#[instrument(level = "trace", target = "net::network", skip_all, fields(%remote_addr, peer_id = ?remote_peer_id))]
940#[expect(clippy::too_many_arguments)]
941async fn start_pending_outbound_session<N: NetworkPrimitives>(
942 handshake: Arc<dyn EthRlpxHandshake>,
943 eth_max_message_size: usize,
944 disconnect_rx: oneshot::Receiver<()>,
945 events: mpsc::Sender<PendingSessionEvent<N>>,
946 session_id: SessionId,
947 remote_addr: SocketAddr,
948 remote_peer_id: PeerId,
949 secret_key: SecretKey,
950 hello: HelloMessageWithProtocols,
951 status: UnifiedStatus,
952 fork_filter: ForkFilter,
953 extra_handlers: RlpxSubProtocolHandlers,
954) {
955 let stream = match TcpStream::connect(remote_addr).await {
956 Ok(stream) => {
957 if let Err(err) = stream.set_nodelay(true) {
958 tracing::warn!(target: "net::session", "set nodelay failed: {:?}", err);
959 }
960 stream
961 }
962 Err(error) => {
963 let _ = events
964 .send(PendingSessionEvent::OutgoingConnectionError {
965 remote_addr,
966 session_id,
967 peer_id: remote_peer_id,
968 error,
969 })
970 .await;
971 return
972 }
973 };
974 authenticate(
975 handshake,
976 eth_max_message_size,
977 disconnect_rx,
978 events,
979 stream,
980 session_id,
981 remote_addr,
982 secret_key,
983 Direction::Outgoing(remote_peer_id),
984 hello,
985 status,
986 fork_filter,
987 extra_handlers,
988 )
989 .await
990}
991
992#[expect(clippy::too_many_arguments)]
994async fn authenticate<N: NetworkPrimitives>(
995 handshake: Arc<dyn EthRlpxHandshake>,
996 eth_max_message_size: usize,
997 disconnect_rx: oneshot::Receiver<()>,
998 events: mpsc::Sender<PendingSessionEvent<N>>,
999 stream: TcpStream,
1000 session_id: SessionId,
1001 remote_addr: SocketAddr,
1002 secret_key: SecretKey,
1003 direction: Direction,
1004 hello: HelloMessageWithProtocols,
1005 status: UnifiedStatus,
1006 fork_filter: ForkFilter,
1007 extra_handlers: RlpxSubProtocolHandlers,
1008) {
1009 let local_addr = stream.local_addr().ok();
1010 let stream = match get_ecies_stream(stream, secret_key, direction).await {
1011 Ok(stream) => stream,
1012 Err(error) => {
1013 let _ = events
1014 .send(PendingSessionEvent::EciesAuthError {
1015 remote_addr,
1016 session_id,
1017 error,
1018 direction,
1019 })
1020 .await;
1021 return
1022 }
1023 };
1024
1025 let unauthed = UnauthedP2PStream::new(stream);
1026
1027 let auth = authenticate_stream(
1028 handshake,
1029 eth_max_message_size,
1030 unauthed,
1031 session_id,
1032 remote_addr,
1033 local_addr,
1034 direction,
1035 hello,
1036 status,
1037 fork_filter,
1038 extra_handlers,
1039 )
1040 .boxed();
1041
1042 match futures::future::select(disconnect_rx, auth).await {
1043 Either::Left((_, _)) => {
1044 let _ = events
1045 .send(PendingSessionEvent::Disconnected {
1046 remote_addr,
1047 session_id,
1048 direction,
1049 error: None,
1050 })
1051 .await;
1052 }
1053 Either::Right((res, _)) => {
1054 let _ = events.send(res).await;
1055 }
1056 }
1057}
1058
1059async fn get_ecies_stream<Io: AsyncRead + AsyncWrite + Unpin>(
1062 stream: Io,
1063 secret_key: SecretKey,
1064 direction: Direction,
1065) -> Result<ECIESStream<Io>, ECIESError> {
1066 match direction {
1067 Direction::Incoming => ECIESStream::incoming(stream, secret_key).await,
1068 Direction::Outgoing(remote_peer_id) => {
1069 ECIESStream::connect(stream, secret_key, remote_peer_id).await
1070 }
1071 }
1072}
1073
1074#[expect(clippy::too_many_arguments)]
1081async fn authenticate_stream<N: NetworkPrimitives>(
1082 handshake: Arc<dyn EthRlpxHandshake>,
1083 eth_max_message_size: usize,
1084 stream: UnauthedP2PStream<ECIESStream<TcpStream>>,
1085 session_id: SessionId,
1086 remote_addr: SocketAddr,
1087 local_addr: Option<SocketAddr>,
1088 direction: Direction,
1089 mut hello: HelloMessageWithProtocols,
1090 mut status: UnifiedStatus,
1091 fork_filter: ForkFilter,
1092 mut extra_handlers: RlpxSubProtocolHandlers,
1093) -> PendingSessionEvent<N> {
1094 extra_handlers.retain(|handler| hello.try_add_protocol(handler.protocol()).is_ok());
1096
1097 let (mut p2p_stream, their_hello) = match stream.handshake(hello).await {
1099 Ok(stream_res) => stream_res,
1100 Err(err) => {
1101 return PendingSessionEvent::Disconnected {
1102 remote_addr,
1103 session_id,
1104 direction,
1105 error: Some(PendingSessionHandshakeError::Eth(err.into())),
1106 }
1107 }
1108 };
1109
1110 if !extra_handlers.is_empty() {
1112 while let Some(pos) = extra_handlers.iter().position(|handler| {
1114 p2p_stream
1115 .shared_capabilities()
1116 .ensure_matching_capability(&handler.protocol().cap)
1117 .is_err()
1118 }) {
1119 let handler = extra_handlers.remove(pos);
1120 if handler.on_unsupported_by_peer(
1121 p2p_stream.shared_capabilities(),
1122 direction,
1123 their_hello.id,
1124 ) == OnNotSupported::Disconnect
1125 {
1126 return PendingSessionEvent::Disconnected {
1127 remote_addr,
1128 session_id,
1129 direction,
1130 error: Some(PendingSessionHandshakeError::UnsupportedExtraCapability),
1131 };
1132 }
1133 }
1134 }
1135
1136 let eth_version = match p2p_stream.shared_capabilities().eth_version() {
1138 Ok(version) => version,
1139 Err(err) => {
1140 return PendingSessionEvent::Disconnected {
1141 remote_addr,
1142 session_id,
1143 direction,
1144 error: Some(PendingSessionHandshakeError::Eth(err.into())),
1145 }
1146 }
1147 };
1148
1149 status.set_eth_version(eth_version);
1151
1152 let (conn, their_status) = if p2p_stream.shared_capabilities().len() == 1 {
1153 match handshake
1158 .handshake(&mut p2p_stream, status, fork_filter.clone(), HANDSHAKE_TIMEOUT)
1159 .await
1160 {
1161 Ok(their_status) => {
1162 let eth_stream =
1163 EthStream::with_max_message_size(eth_version, p2p_stream, eth_max_message_size);
1164 (eth_stream.into(), their_status)
1165 }
1166 Err(err) => {
1167 return PendingSessionEvent::Disconnected {
1168 remote_addr,
1169 session_id,
1170 direction,
1171 error: Some(PendingSessionHandshakeError::Eth(err)),
1172 }
1173 }
1174 }
1175 } else {
1176 let mut multiplex_stream = RlpxProtocolMultiplexer::new(p2p_stream);
1178
1179 for handler in extra_handlers.into_iter() {
1181 let cap = handler.protocol().cap;
1182 let remote_peer_id = their_hello.id;
1183
1184 multiplex_stream
1185 .install_protocol(&cap, move |conn| {
1186 handler.into_connection(direction, remote_peer_id, conn)
1187 })
1188 .ok();
1189 }
1190
1191 let (multiplex_stream, their_status) = match multiplex_stream
1192 .into_eth_satellite_stream(status, fork_filter, handshake, eth_max_message_size)
1193 .await
1194 {
1195 Ok((multiplex_stream, their_status)) => (multiplex_stream, their_status),
1196 Err(err) => {
1197 return PendingSessionEvent::Disconnected {
1198 remote_addr,
1199 session_id,
1200 direction,
1201 error: Some(PendingSessionHandshakeError::Eth(err)),
1202 }
1203 }
1204 };
1205
1206 (multiplex_stream.into(), their_status)
1207 };
1208
1209 PendingSessionEvent::Established {
1210 session_id,
1211 remote_addr,
1212 local_addr,
1213 peer_id: their_hello.id,
1214 capabilities: Arc::new(Capabilities::from(their_hello.capabilities)),
1215 status: Arc::new(their_status),
1216 conn,
1217 direction,
1218 client_id: their_hello.client_version,
1219 }
1220}