1use core::sync::atomic::Ordering;
4use std::{
5 collections::VecDeque,
6 future::Future,
7 net::SocketAddr,
8 pin::Pin,
9 sync::{atomic::AtomicU64, Arc},
10 task::{ready, Context, Poll},
11 time::{Duration, Instant},
12};
13
14use crate::{
15 message::{NewBlockMessage, PeerMessage, PeerResponse, PeerResponseResult},
16 session::{
17 conn::EthRlpxConnection,
18 handle::{ActiveSessionMessage, SessionCommand},
19 BlockRangeInfo, EthVersion, SessionId,
20 },
21};
22use alloy_eips::merge::EPOCH_SLOTS;
23use alloy_primitives::Sealable;
24use futures::{stream::Fuse, SinkExt, StreamExt};
25use metrics::Gauge;
26use reth_eth_wire::{
27 errors::{EthHandshakeError, EthStreamError},
28 message::{EthBroadcastMessage, MessageError, RequestPair},
29 Capabilities, DisconnectP2P, DisconnectReason, EthMessage, NetworkPrimitives, NewBlockPayload,
30};
31use reth_eth_wire_types::RawCapabilityMessage;
32use reth_metrics::common::mpsc::MeteredPollSender;
33use reth_network_api::PeerRequest;
34use reth_network_p2p::error::RequestError;
35use reth_network_peers::PeerId;
36use reth_network_types::session::config::INITIAL_REQUEST_TIMEOUT;
37use reth_primitives_traits::Block;
38use rustc_hash::FxHashMap;
39use tokio::{
40 sync::{mpsc::error::TrySendError, oneshot},
41 time::Interval,
42};
43use tokio_stream::wrappers::ReceiverStream;
44use tokio_util::sync::PollSender;
45use tracing::{debug, trace};
46
47pub(super) const RANGE_UPDATE_INTERVAL: Duration = Duration::from_secs(EPOCH_SLOTS * 12);
53
54const MINIMUM_TIMEOUT: Duration = Duration::from_secs(2);
58
59const MAXIMUM_TIMEOUT: Duration = INITIAL_REQUEST_TIMEOUT;
61const SAMPLE_IMPACT: f64 = 0.1;
63const TIMEOUT_SCALING: u32 = 3;
65
66const MAX_QUEUED_OUTGOING_RESPONSES: usize = 4;
78
79#[expect(dead_code)]
89pub(crate) struct ActiveSession<N: NetworkPrimitives> {
90 pub(crate) next_id: u64,
92 pub(crate) conn: EthRlpxConnection<N>,
94 pub(crate) remote_peer_id: PeerId,
96 pub(crate) remote_addr: SocketAddr,
98 pub(crate) remote_capabilities: Arc<Capabilities>,
100 pub(crate) session_id: SessionId,
102 pub(crate) commands_rx: ReceiverStream<SessionCommand<N>>,
104 pub(crate) to_session_manager: MeteredPollSender<ActiveSessionMessage<N>>,
106 pub(crate) pending_message_to_session: Option<ActiveSessionMessage<N>>,
108 pub(crate) internal_request_rx: Fuse<ReceiverStream<PeerRequest<N>>>,
110 pub(crate) inflight_requests: FxHashMap<u64, InflightRequest<PeerRequest<N>>>,
112 pub(crate) received_requests_from_remote: Vec<ReceivedRequest<N>>,
114 pub(crate) queued_outgoing: QueuedOutgoingMessages<N>,
116 pub(crate) internal_request_timeout: Arc<AtomicU64>,
118 pub(crate) internal_request_timeout_interval: Interval,
120 pub(crate) protocol_breach_request_timeout: Duration,
123 pub(crate) terminate_message:
125 Option<(PollSender<ActiveSessionMessage<N>>, ActiveSessionMessage<N>)>,
126 pub(crate) range_info: Option<BlockRangeInfo>,
128 pub(crate) local_range_info: BlockRangeInfo,
131 pub(crate) range_update_interval: Option<Interval>,
135 pub(crate) last_sent_latest_block: Option<u64>,
138}
139
140impl<N: NetworkPrimitives> ActiveSession<N> {
141 fn is_disconnecting(&self) -> bool {
143 self.conn.inner().is_disconnecting()
144 }
145
146 const fn next_id(&mut self) -> u64 {
148 let id = self.next_id;
149 self.next_id += 1;
150 id
151 }
152
153 pub fn shrink_to_fit(&mut self) {
155 self.received_requests_from_remote.shrink_to_fit();
156 self.queued_outgoing.shrink_to_fit();
157 }
158
159 fn queued_response_count(&self) -> usize {
161 self.queued_outgoing.messages.iter().filter(|m| m.is_response()).count()
162 }
163
164 fn on_incoming_message(&mut self, msg: EthMessage<N>) -> OnIncomingMessageOutcome<N> {
168 macro_rules! on_request {
172 ($req:ident, $resp_item:ident, $req_item:ident) => {{
173 let RequestPair { request_id, message: request } = $req;
174 let (tx, response) = oneshot::channel();
175 let received = ReceivedRequest {
176 request_id,
177 rx: PeerResponse::$resp_item { response },
178 received: Instant::now(),
179 };
180 self.received_requests_from_remote.push(received);
181 self.try_emit_request(PeerMessage::EthRequest(PeerRequest::$req_item {
182 request,
183 response: tx,
184 }))
185 .into()
186 }};
187 }
188
189 macro_rules! on_response {
191 ($resp:ident, $item:ident) => {{
192 let RequestPair { request_id, message } = $resp;
193 if let Some(req) = self.inflight_requests.remove(&request_id) {
194 match req.request {
195 RequestState::Waiting(PeerRequest::$item { response, .. }) => {
196 trace!(peer_id=?self.remote_peer_id, ?request_id, "received response from peer");
197 let _ = response.send(Ok(message));
198 self.update_request_timeout(req.timestamp, Instant::now());
199 }
200 RequestState::Waiting(request) => {
201 request.send_bad_response();
202 }
203 RequestState::TimedOut => {
204 self.update_request_timeout(req.timestamp, Instant::now());
206 }
207 }
208 } else {
209 trace!(peer_id=?self.remote_peer_id, ?request_id, "received response to unknown request");
210 self.on_bad_message();
212 }
213
214 OnIncomingMessageOutcome::Ok
215 }};
216 }
217
218 match msg {
219 message @ EthMessage::Status(_) => OnIncomingMessageOutcome::BadMessage {
220 error: EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake),
221 message,
222 },
223 EthMessage::NewBlockHashes(msg) => {
224 self.try_emit_broadcast(PeerMessage::NewBlockHashes(msg)).into()
225 }
226 EthMessage::NewBlock(msg) => {
227 let block = NewBlockMessage {
228 hash: msg.block().header().hash_slow(),
229 block: Arc::new(*msg),
230 };
231 self.try_emit_broadcast(PeerMessage::NewBlock(block)).into()
232 }
233 EthMessage::Transactions(msg) => {
234 self.try_emit_broadcast(PeerMessage::ReceivedTransaction(msg)).into()
235 }
236 EthMessage::NewPooledTransactionHashes66(msg) => {
237 self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
238 }
239 EthMessage::NewPooledTransactionHashes68(msg) => {
240 self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into()
241 }
242 EthMessage::GetBlockHeaders(req) => {
243 on_request!(req, BlockHeaders, GetBlockHeaders)
244 }
245 EthMessage::BlockHeaders(resp) => {
246 on_response!(resp, GetBlockHeaders)
247 }
248 EthMessage::GetBlockBodies(req) => {
249 on_request!(req, BlockBodies, GetBlockBodies)
250 }
251 EthMessage::BlockBodies(resp) => {
252 on_response!(resp, GetBlockBodies)
253 }
254 EthMessage::GetPooledTransactions(req) => {
255 on_request!(req, PooledTransactions, GetPooledTransactions)
256 }
257 EthMessage::PooledTransactions(resp) => {
258 on_response!(resp, GetPooledTransactions)
259 }
260 EthMessage::GetNodeData(req) => {
261 on_request!(req, NodeData, GetNodeData)
262 }
263 EthMessage::NodeData(resp) => {
264 on_response!(resp, GetNodeData)
265 }
266 EthMessage::GetReceipts(req) => {
267 if self.conn.version() >= EthVersion::Eth69 {
268 on_request!(req, Receipts69, GetReceipts69)
269 } else {
270 on_request!(req, Receipts, GetReceipts)
271 }
272 }
273 EthMessage::Receipts(resp) => {
274 on_response!(resp, GetReceipts)
275 }
276 EthMessage::Receipts69(resp) => {
277 on_response!(resp, GetReceipts69)
278 }
279 EthMessage::BlockRangeUpdate(msg) => {
280 if msg.earliest > msg.latest {
282 return OnIncomingMessageOutcome::BadMessage {
283 error: EthStreamError::InvalidMessage(MessageError::Other(format!(
284 "invalid block range: earliest ({}) > latest ({})",
285 msg.earliest, msg.latest
286 ))),
287 message: EthMessage::BlockRangeUpdate(msg),
288 };
289 }
290
291 if msg.latest_hash.is_zero() {
293 return OnIncomingMessageOutcome::BadMessage {
294 error: EthStreamError::InvalidMessage(MessageError::Other(
295 "invalid block range: latest_hash cannot be zero".to_string(),
296 )),
297 message: EthMessage::BlockRangeUpdate(msg),
298 };
299 }
300
301 if let Some(range_info) = self.range_info.as_ref() {
302 range_info.update(msg.earliest, msg.latest, msg.latest_hash);
303 }
304
305 OnIncomingMessageOutcome::Ok
306 }
307 EthMessage::Other(bytes) => self.try_emit_broadcast(PeerMessage::Other(bytes)).into(),
308 }
309 }
310
311 fn on_internal_peer_request(&mut self, request: PeerRequest<N>, deadline: Instant) {
313 let request_id = self.next_id();
314
315 trace!(?request, peer_id=?self.remote_peer_id, ?request_id, "sending request to peer");
316 let msg = request.create_request_message(request_id);
317 self.queued_outgoing.push_back(msg.into());
318 let req = InflightRequest {
319 request: RequestState::Waiting(request),
320 timestamp: Instant::now(),
321 deadline,
322 };
323 self.inflight_requests.insert(request_id, req);
324 }
325
326 fn on_internal_peer_message(&mut self, msg: PeerMessage<N>) {
328 match msg {
329 PeerMessage::NewBlockHashes(msg) => {
330 self.queued_outgoing.push_back(EthMessage::NewBlockHashes(msg).into());
331 }
332 PeerMessage::NewBlock(msg) => {
333 self.queued_outgoing.push_back(EthBroadcastMessage::NewBlock(msg.block).into());
334 }
335 PeerMessage::PooledTransactions(msg) => {
336 if msg.is_valid_for_version(self.conn.version()) {
337 self.queued_outgoing.push_back(EthMessage::from(msg).into());
338 } else {
339 debug!(target: "net", ?msg, version=?self.conn.version(), "Message is invalid for connection version, skipping");
340 }
341 }
342 PeerMessage::EthRequest(req) => {
343 let deadline = self.request_deadline();
344 self.on_internal_peer_request(req, deadline);
345 }
346 PeerMessage::SendTransactions(msg) => {
347 self.queued_outgoing.push_back(EthBroadcastMessage::Transactions(msg).into());
348 }
349 PeerMessage::BlockRangeUpdated(_) => {}
350 PeerMessage::ReceivedTransaction(_) => {
351 unreachable!("Not emitted by network")
352 }
353 PeerMessage::Other(other) => {
354 self.queued_outgoing.push_back(OutgoingMessage::Raw(other));
355 }
356 }
357 }
358
359 fn request_deadline(&self) -> Instant {
361 Instant::now() +
362 Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed))
363 }
364
365 fn handle_outgoing_response(&mut self, id: u64, resp: PeerResponseResult<N>) {
369 match resp.try_into_message(id) {
370 Ok(msg) => {
371 self.queued_outgoing.push_back(msg.into());
372 }
373 Err(err) => {
374 debug!(target: "net", %err, "Failed to respond to received request");
375 }
376 }
377 }
378
379 #[expect(clippy::result_large_err)]
383 fn try_emit_broadcast(&self, message: PeerMessage<N>) -> Result<(), ActiveSessionMessage<N>> {
384 let Some(sender) = self.to_session_manager.inner().get_ref() else { return Ok(()) };
385
386 match sender
387 .try_send(ActiveSessionMessage::ValidMessage { peer_id: self.remote_peer_id, message })
388 {
389 Ok(_) => Ok(()),
390 Err(err) => {
391 trace!(
392 target: "net",
393 %err,
394 "no capacity for incoming broadcast",
395 );
396 match err {
397 TrySendError::Full(msg) => Err(msg),
398 TrySendError::Closed(_) => Ok(()),
399 }
400 }
401 }
402 }
403
404 #[expect(clippy::result_large_err)]
409 fn try_emit_request(&self, message: PeerMessage<N>) -> Result<(), ActiveSessionMessage<N>> {
410 let Some(sender) = self.to_session_manager.inner().get_ref() else { return Ok(()) };
411
412 match sender
413 .try_send(ActiveSessionMessage::ValidMessage { peer_id: self.remote_peer_id, message })
414 {
415 Ok(_) => Ok(()),
416 Err(err) => {
417 trace!(
418 target: "net",
419 %err,
420 "no capacity for incoming request",
421 );
422 match err {
423 TrySendError::Full(msg) => Err(msg),
424 TrySendError::Closed(_) => {
425 Ok(())
428 }
429 }
430 }
431 }
432 }
433
434 fn on_bad_message(&self) {
436 let Some(sender) = self.to_session_manager.inner().get_ref() else { return };
437 let _ = sender.try_send(ActiveSessionMessage::BadMessage { peer_id: self.remote_peer_id });
438 }
439
440 fn emit_disconnect(&mut self, cx: &mut Context<'_>) -> Poll<()> {
442 trace!(target: "net::session", remote_peer_id=?self.remote_peer_id, "emitting disconnect");
443 let msg = ActiveSessionMessage::Disconnected {
444 peer_id: self.remote_peer_id,
445 remote_addr: self.remote_addr,
446 };
447
448 self.terminate_message = Some((self.to_session_manager.inner().clone(), msg));
449 self.poll_terminate_message(cx).expect("message is set")
450 }
451
452 fn close_on_error(&mut self, error: EthStreamError, cx: &mut Context<'_>) -> Poll<()> {
454 let msg = ActiveSessionMessage::ClosedOnConnectionError {
455 peer_id: self.remote_peer_id,
456 remote_addr: self.remote_addr,
457 error,
458 };
459 self.terminate_message = Some((self.to_session_manager.inner().clone(), msg));
460 self.poll_terminate_message(cx).expect("message is set")
461 }
462
463 fn start_disconnect(&mut self, reason: DisconnectReason) -> Result<(), EthStreamError> {
465 Ok(self.conn.inner_mut().start_disconnect(reason)?)
466 }
467
468 fn poll_disconnect(&mut self, cx: &mut Context<'_>) -> Poll<()> {
470 debug_assert!(self.is_disconnecting(), "not disconnecting");
471
472 let _ = ready!(self.conn.poll_close_unpin(cx));
474 self.emit_disconnect(cx)
475 }
476
477 fn try_disconnect(&mut self, reason: DisconnectReason, cx: &mut Context<'_>) -> Poll<()> {
479 match self.start_disconnect(reason) {
480 Ok(()) => {
481 self.poll_disconnect(cx)
483 }
484 Err(err) => {
485 debug!(target: "net::session", %err, remote_peer_id=?self.remote_peer_id, "could not send disconnect");
486 self.close_on_error(err, cx)
487 }
488 }
489 }
490
491 #[must_use]
500 fn check_timed_out_requests(&mut self, now: Instant) -> bool {
501 for (id, req) in &mut self.inflight_requests {
502 if req.is_timed_out(now) {
503 if req.is_waiting() {
504 debug!(target: "net::session", ?id, remote_peer_id=?self.remote_peer_id, "timed out outgoing request");
505 req.timeout();
506 } else if now - req.timestamp > self.protocol_breach_request_timeout {
507 return true
508 }
509 }
510 }
511
512 false
513 }
514
515 fn update_request_timeout(&mut self, sent: Instant, received: Instant) {
517 let elapsed = received.saturating_duration_since(sent);
518
519 let current = Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed));
520 let request_timeout = calculate_new_timeout(current, elapsed);
521 self.internal_request_timeout.store(request_timeout.as_millis() as u64, Ordering::Relaxed);
522 self.internal_request_timeout_interval = tokio::time::interval(request_timeout);
523 }
524
525 fn poll_terminate_message(&mut self, cx: &mut Context<'_>) -> Option<Poll<()>> {
527 let (mut tx, msg) = self.terminate_message.take()?;
528 match tx.poll_reserve(cx) {
529 Poll::Pending => {
530 self.terminate_message = Some((tx, msg));
531 return Some(Poll::Pending)
532 }
533 Poll::Ready(Ok(())) => {
534 let _ = tx.send_item(msg);
535 }
536 Poll::Ready(Err(_)) => {
537 }
539 }
540 Some(Poll::Ready(()))
542 }
543}
544
545impl<N: NetworkPrimitives> Future for ActiveSession<N> {
546 type Output = ();
547
548 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
549 let this = self.get_mut();
550
551 if let Some(terminate) = this.poll_terminate_message(cx) {
553 return terminate
554 }
555
556 if this.is_disconnecting() {
557 return this.poll_disconnect(cx)
558 }
559
560 let mut budget = 4;
566
567 'main: loop {
569 let mut progress = false;
570
571 loop {
573 match this.commands_rx.poll_next_unpin(cx) {
574 Poll::Pending => break,
575 Poll::Ready(None) => {
576 return Poll::Ready(())
579 }
580 Poll::Ready(Some(cmd)) => {
581 progress = true;
582 match cmd {
583 SessionCommand::Disconnect { reason } => {
584 debug!(
585 target: "net::session",
586 ?reason,
587 remote_peer_id=?this.remote_peer_id,
588 "Received disconnect command for session"
589 );
590 let reason =
591 reason.unwrap_or(DisconnectReason::DisconnectRequested);
592
593 return this.try_disconnect(reason, cx)
594 }
595 SessionCommand::Message(msg) => {
596 this.on_internal_peer_message(msg);
597 }
598 }
599 }
600 }
601 }
602
603 let deadline = this.request_deadline();
604
605 while let Poll::Ready(Some(req)) = this.internal_request_rx.poll_next_unpin(cx) {
606 progress = true;
607 this.on_internal_peer_request(req, deadline);
608 }
609
610 for idx in (0..this.received_requests_from_remote.len()).rev() {
613 let mut req = this.received_requests_from_remote.swap_remove(idx);
614 match req.rx.poll(cx) {
615 Poll::Pending => {
616 this.received_requests_from_remote.push(req);
618 }
619 Poll::Ready(resp) => {
620 this.handle_outgoing_response(req.request_id, resp);
621 }
622 }
623 }
624
625 while this.conn.poll_ready_unpin(cx).is_ready() {
627 if let Some(msg) = this.queued_outgoing.pop_front() {
628 progress = true;
629 let res = match msg {
630 OutgoingMessage::Eth(msg) => this.conn.start_send_unpin(msg),
631 OutgoingMessage::Broadcast(msg) => this.conn.start_send_broadcast(msg),
632 OutgoingMessage::Raw(msg) => this.conn.start_send_raw(msg),
633 };
634 if let Err(err) = res {
635 debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to send message");
636 return this.close_on_error(err, cx)
638 }
639 } else {
640 break
642 }
643 }
644
645 'receive: loop {
647 budget -= 1;
649 if budget == 0 {
650 cx.waker().wake_by_ref();
652 break 'main
653 }
654
655 if let Some(msg) = this.pending_message_to_session.take() {
659 match this.to_session_manager.poll_reserve(cx) {
660 Poll::Ready(Ok(_)) => {
661 let _ = this.to_session_manager.send_item(msg);
662 }
663 Poll::Ready(Err(_)) => return Poll::Ready(()),
664 Poll::Pending => {
665 this.pending_message_to_session = Some(msg);
666 break 'receive
667 }
668 };
669 }
670
671 if this.received_requests_from_remote.len() > MAX_QUEUED_OUTGOING_RESPONSES {
673 break 'receive
679 }
680
681 if this.queued_outgoing.messages.len() > MAX_QUEUED_OUTGOING_RESPONSES &&
683 this.queued_response_count() > MAX_QUEUED_OUTGOING_RESPONSES
684 {
685 break 'receive
692 }
693
694 match this.conn.poll_next_unpin(cx) {
695 Poll::Pending => break,
696 Poll::Ready(None) => {
697 if this.is_disconnecting() {
698 break
699 }
700 debug!(target: "net::session", remote_peer_id=?this.remote_peer_id, "eth stream completed");
701 return this.emit_disconnect(cx)
702 }
703 Poll::Ready(Some(res)) => {
704 match res {
705 Ok(msg) => {
706 trace!(target: "net::session", msg_id=?msg.message_id(), remote_peer_id=?this.remote_peer_id, "received eth message");
707 match this.on_incoming_message(msg) {
709 OnIncomingMessageOutcome::Ok => {
710 progress = true;
712 }
713 OnIncomingMessageOutcome::BadMessage { error, message } => {
714 debug!(target: "net::session", %error, msg=?message, remote_peer_id=?this.remote_peer_id, "received invalid protocol message");
715 return this.close_on_error(error, cx)
716 }
717 OnIncomingMessageOutcome::NoCapacity(msg) => {
718 this.pending_message_to_session = Some(msg);
720 }
721 }
722 }
723 Err(err) => {
724 debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to receive message");
725 return this.close_on_error(err, cx)
726 }
727 }
728 }
729 }
730 }
731
732 if !progress {
733 break 'main
734 }
735 }
736
737 if let Some(interval) = &mut this.range_update_interval {
738 while interval.poll_tick(cx).is_ready() {
740 let current_latest = this.local_range_info.latest();
741 let should_send = if let Some(last_sent) = this.last_sent_latest_block {
742 current_latest.saturating_sub(last_sent) >= EPOCH_SLOTS
744 } else {
745 true };
747
748 if should_send {
749 this.queued_outgoing.push_back(
750 EthMessage::BlockRangeUpdate(this.local_range_info.to_message()).into(),
751 );
752 this.last_sent_latest_block = Some(current_latest);
753 }
754 }
755 }
756
757 while this.internal_request_timeout_interval.poll_tick(cx).is_ready() {
758 if this.check_timed_out_requests(Instant::now()) &&
760 let Poll::Ready(Ok(_)) = this.to_session_manager.poll_reserve(cx)
761 {
762 let msg = ActiveSessionMessage::ProtocolBreach { peer_id: this.remote_peer_id };
763 this.pending_message_to_session = Some(msg);
764 }
765 }
766
767 this.shrink_to_fit();
768
769 Poll::Pending
770 }
771}
772
773pub(crate) struct ReceivedRequest<N: NetworkPrimitives> {
775 request_id: u64,
777 rx: PeerResponse<N>,
779 #[expect(dead_code)]
781 received: Instant,
782}
783
784pub(crate) struct InflightRequest<R> {
786 request: RequestState<R>,
788 timestamp: Instant,
790 deadline: Instant,
792}
793
794impl<N: NetworkPrimitives> InflightRequest<PeerRequest<N>> {
797 #[inline]
799 fn is_timed_out(&self, now: Instant) -> bool {
800 now > self.deadline
801 }
802
803 #[inline]
805 const fn is_waiting(&self) -> bool {
806 matches!(self.request, RequestState::Waiting(_))
807 }
808
809 fn timeout(&mut self) {
811 let mut req = RequestState::TimedOut;
812 std::mem::swap(&mut self.request, &mut req);
813
814 if let RequestState::Waiting(req) = req {
815 req.send_err_response(RequestError::Timeout);
816 }
817 }
818}
819
820enum OnIncomingMessageOutcome<N: NetworkPrimitives> {
822 Ok,
824 BadMessage { error: EthStreamError, message: EthMessage<N> },
826 NoCapacity(ActiveSessionMessage<N>),
828}
829
830impl<N: NetworkPrimitives> From<Result<(), ActiveSessionMessage<N>>>
831 for OnIncomingMessageOutcome<N>
832{
833 fn from(res: Result<(), ActiveSessionMessage<N>>) -> Self {
834 match res {
835 Ok(_) => Self::Ok,
836 Err(msg) => Self::NoCapacity(msg),
837 }
838 }
839}
840
841enum RequestState<R> {
842 Waiting(R),
844 TimedOut,
846}
847
848#[derive(Debug)]
850pub(crate) enum OutgoingMessage<N: NetworkPrimitives> {
851 Eth(EthMessage<N>),
853 Broadcast(EthBroadcastMessage<N>),
855 Raw(RawCapabilityMessage),
857}
858
859impl<N: NetworkPrimitives> OutgoingMessage<N> {
860 const fn is_response(&self) -> bool {
862 match self {
863 Self::Eth(msg) => msg.is_response(),
864 _ => false,
865 }
866 }
867}
868
869impl<N: NetworkPrimitives> From<EthMessage<N>> for OutgoingMessage<N> {
870 fn from(value: EthMessage<N>) -> Self {
871 Self::Eth(value)
872 }
873}
874
875impl<N: NetworkPrimitives> From<EthBroadcastMessage<N>> for OutgoingMessage<N> {
876 fn from(value: EthBroadcastMessage<N>) -> Self {
877 Self::Broadcast(value)
878 }
879}
880
881#[inline]
883fn calculate_new_timeout(current_timeout: Duration, estimated_rtt: Duration) -> Duration {
884 let new_timeout = estimated_rtt.mul_f64(SAMPLE_IMPACT) * TIMEOUT_SCALING;
885
886 let smoothened_timeout = current_timeout.mul_f64(1.0 - SAMPLE_IMPACT) + new_timeout;
888
889 smoothened_timeout.clamp(MINIMUM_TIMEOUT, MAXIMUM_TIMEOUT)
890}
891
892pub(crate) struct QueuedOutgoingMessages<N: NetworkPrimitives> {
894 messages: VecDeque<OutgoingMessage<N>>,
895 count: Gauge,
896}
897
898impl<N: NetworkPrimitives> QueuedOutgoingMessages<N> {
899 pub(crate) const fn new(metric: Gauge) -> Self {
900 Self { messages: VecDeque::new(), count: metric }
901 }
902
903 pub(crate) fn push_back(&mut self, message: OutgoingMessage<N>) {
904 self.messages.push_back(message);
905 self.count.increment(1);
906 }
907
908 pub(crate) fn pop_front(&mut self) -> Option<OutgoingMessage<N>> {
909 self.messages.pop_front().inspect(|_| self.count.decrement(1))
910 }
911
912 pub(crate) fn shrink_to_fit(&mut self) {
913 self.messages.shrink_to_fit();
914 }
915}
916
917impl<N: NetworkPrimitives> Drop for QueuedOutgoingMessages<N> {
918 fn drop(&mut self) {
919 let remaining = self.messages.len();
921 if remaining > 0 {
922 self.count.decrement(remaining as f64);
923 }
924 }
925}
926
927#[cfg(test)]
928mod tests {
929 use super::*;
930 use crate::session::{handle::PendingSessionEvent, start_pending_incoming_session};
931 use alloy_eips::eip2124::ForkFilter;
932 use reth_chainspec::MAINNET;
933 use reth_ecies::stream::ECIESStream;
934 use reth_eth_wire::{
935 handshake::EthHandshake, EthNetworkPrimitives, EthStream, GetBlockBodies,
936 HelloMessageWithProtocols, P2PStream, StatusBuilder, UnauthedEthStream, UnauthedP2PStream,
937 UnifiedStatus,
938 };
939 use reth_ethereum_forks::EthereumHardfork;
940 use reth_network_peers::pk2id;
941 use reth_network_types::session::config::PROTOCOL_BREACH_REQUEST_TIMEOUT;
942 use secp256k1::{SecretKey, SECP256K1};
943 use tokio::{
944 net::{TcpListener, TcpStream},
945 sync::mpsc,
946 };
947
948 fn eth_hello(server_key: &SecretKey) -> HelloMessageWithProtocols {
950 HelloMessageWithProtocols::builder(pk2id(&server_key.public_key(SECP256K1))).build()
951 }
952
953 struct SessionBuilder<N: NetworkPrimitives = EthNetworkPrimitives> {
954 _remote_capabilities: Arc<Capabilities>,
955 active_session_tx: mpsc::Sender<ActiveSessionMessage<N>>,
956 active_session_rx: ReceiverStream<ActiveSessionMessage<N>>,
957 to_sessions: Vec<mpsc::Sender<SessionCommand<N>>>,
958 secret_key: SecretKey,
959 local_peer_id: PeerId,
960 hello: HelloMessageWithProtocols,
961 status: UnifiedStatus,
962 fork_filter: ForkFilter,
963 next_id: usize,
964 }
965
966 impl<N: NetworkPrimitives> SessionBuilder<N> {
967 fn next_id(&mut self) -> SessionId {
968 let id = self.next_id;
969 self.next_id += 1;
970 SessionId(id)
971 }
972
973 fn with_client_stream<F, O>(
975 &self,
976 local_addr: SocketAddr,
977 f: F,
978 ) -> Pin<Box<dyn Future<Output = ()> + Send>>
979 where
980 F: FnOnce(EthStream<P2PStream<ECIESStream<TcpStream>>, N>) -> O + Send + 'static,
981 O: Future<Output = ()> + Send + Sync,
982 {
983 let mut status = self.status;
984 let fork_filter = self.fork_filter.clone();
985 let local_peer_id = self.local_peer_id;
986 let mut hello = self.hello.clone();
987 let key = SecretKey::new(&mut rand_08::thread_rng());
988 hello.id = pk2id(&key.public_key(SECP256K1));
989 Box::pin(async move {
990 let outgoing = TcpStream::connect(local_addr).await.unwrap();
991 let sink = ECIESStream::connect(outgoing, key, local_peer_id).await.unwrap();
992
993 let (p2p_stream, _) = UnauthedP2PStream::new(sink).handshake(hello).await.unwrap();
994
995 let eth_version = p2p_stream.shared_capabilities().eth_version().unwrap();
996 status.set_eth_version(eth_version);
997
998 let (client_stream, _) = UnauthedEthStream::new(p2p_stream)
999 .handshake(status, fork_filter)
1000 .await
1001 .unwrap();
1002 f(client_stream).await
1003 })
1004 }
1005
1006 async fn connect_incoming(&mut self, stream: TcpStream) -> ActiveSession<N> {
1007 let remote_addr = stream.local_addr().unwrap();
1008 let session_id = self.next_id();
1009 let (_disconnect_tx, disconnect_rx) = oneshot::channel();
1010 let (pending_sessions_tx, pending_sessions_rx) = mpsc::channel(1);
1011
1012 tokio::task::spawn(start_pending_incoming_session(
1013 Arc::new(EthHandshake::default()),
1014 disconnect_rx,
1015 session_id,
1016 stream,
1017 pending_sessions_tx,
1018 remote_addr,
1019 self.secret_key,
1020 self.hello.clone(),
1021 self.status,
1022 self.fork_filter.clone(),
1023 Default::default(),
1024 ));
1025
1026 let mut stream = ReceiverStream::new(pending_sessions_rx);
1027
1028 match stream.next().await.unwrap() {
1029 PendingSessionEvent::Established {
1030 session_id,
1031 remote_addr,
1032 peer_id,
1033 capabilities,
1034 conn,
1035 ..
1036 } => {
1037 let (_to_session_tx, messages_rx) = mpsc::channel(10);
1038 let (commands_to_session, commands_rx) = mpsc::channel(10);
1039 let poll_sender = PollSender::new(self.active_session_tx.clone());
1040
1041 self.to_sessions.push(commands_to_session);
1042
1043 ActiveSession {
1044 next_id: 0,
1045 remote_peer_id: peer_id,
1046 remote_addr,
1047 remote_capabilities: Arc::clone(&capabilities),
1048 session_id,
1049 commands_rx: ReceiverStream::new(commands_rx),
1050 to_session_manager: MeteredPollSender::new(
1051 poll_sender,
1052 "network_active_session",
1053 ),
1054 pending_message_to_session: None,
1055 internal_request_rx: ReceiverStream::new(messages_rx).fuse(),
1056 inflight_requests: Default::default(),
1057 conn,
1058 queued_outgoing: QueuedOutgoingMessages::new(Gauge::noop()),
1059 received_requests_from_remote: Default::default(),
1060 internal_request_timeout_interval: tokio::time::interval(
1061 INITIAL_REQUEST_TIMEOUT,
1062 ),
1063 internal_request_timeout: Arc::new(AtomicU64::new(
1064 INITIAL_REQUEST_TIMEOUT.as_millis() as u64,
1065 )),
1066 protocol_breach_request_timeout: PROTOCOL_BREACH_REQUEST_TIMEOUT,
1067 terminate_message: None,
1068 range_info: None,
1069 local_range_info: BlockRangeInfo::new(
1070 0,
1071 1000,
1072 alloy_primitives::B256::ZERO,
1073 ),
1074 range_update_interval: None,
1075 last_sent_latest_block: None,
1076 }
1077 }
1078 ev => {
1079 panic!("unexpected message {ev:?}")
1080 }
1081 }
1082 }
1083 }
1084
1085 impl Default for SessionBuilder {
1086 fn default() -> Self {
1087 let (active_session_tx, active_session_rx) = mpsc::channel(100);
1088
1089 let (secret_key, pk) = SECP256K1.generate_keypair(&mut rand_08::thread_rng());
1090 let local_peer_id = pk2id(&pk);
1091
1092 Self {
1093 next_id: 0,
1094 _remote_capabilities: Arc::new(Capabilities::from(vec![])),
1095 active_session_tx,
1096 active_session_rx: ReceiverStream::new(active_session_rx),
1097 to_sessions: vec![],
1098 hello: eth_hello(&secret_key),
1099 secret_key,
1100 local_peer_id,
1101 status: StatusBuilder::default().build(),
1102 fork_filter: MAINNET
1103 .hardfork_fork_filter(EthereumHardfork::Frontier)
1104 .expect("The Frontier fork filter should exist on mainnet"),
1105 }
1106 }
1107 }
1108
1109 #[tokio::test(flavor = "multi_thread")]
1110 async fn test_disconnect() {
1111 let mut builder = SessionBuilder::default();
1112
1113 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1114 let local_addr = listener.local_addr().unwrap();
1115
1116 let expected_disconnect = DisconnectReason::UselessPeer;
1117
1118 let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1119 let msg = client_stream.next().await.unwrap().unwrap_err();
1120 assert_eq!(msg.as_disconnected().unwrap(), expected_disconnect);
1121 });
1122
1123 tokio::task::spawn(async move {
1124 let (incoming, _) = listener.accept().await.unwrap();
1125 let mut session = builder.connect_incoming(incoming).await;
1126
1127 session.start_disconnect(expected_disconnect).unwrap();
1128 session.await
1129 });
1130
1131 fut.await;
1132 }
1133
1134 #[tokio::test(flavor = "multi_thread")]
1135 async fn handle_dropped_stream() {
1136 let mut builder = SessionBuilder::default();
1137
1138 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1139 let local_addr = listener.local_addr().unwrap();
1140
1141 let fut = builder.with_client_stream(local_addr, move |client_stream| async move {
1142 drop(client_stream);
1143 tokio::time::sleep(Duration::from_secs(1)).await
1144 });
1145
1146 let (tx, rx) = oneshot::channel();
1147
1148 tokio::task::spawn(async move {
1149 let (incoming, _) = listener.accept().await.unwrap();
1150 let session = builder.connect_incoming(incoming).await;
1151 session.await;
1152
1153 tx.send(()).unwrap();
1154 });
1155
1156 tokio::task::spawn(fut);
1157
1158 rx.await.unwrap();
1159 }
1160
1161 #[tokio::test(flavor = "multi_thread")]
1162 async fn test_send_many_messages() {
1163 reth_tracing::init_test_tracing();
1164 let mut builder = SessionBuilder::default();
1165
1166 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1167 let local_addr = listener.local_addr().unwrap();
1168
1169 let num_messages = 100;
1170
1171 let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1172 for _ in 0..num_messages {
1173 client_stream
1174 .send(EthMessage::NewPooledTransactionHashes66(Vec::new().into()))
1175 .await
1176 .unwrap();
1177 }
1178 });
1179
1180 let (tx, rx) = oneshot::channel();
1181
1182 tokio::task::spawn(async move {
1183 let (incoming, _) = listener.accept().await.unwrap();
1184 let session = builder.connect_incoming(incoming).await;
1185 session.await;
1186
1187 tx.send(()).unwrap();
1188 });
1189
1190 tokio::task::spawn(fut);
1191
1192 rx.await.unwrap();
1193 }
1194
1195 #[tokio::test(flavor = "multi_thread")]
1196 async fn test_request_timeout() {
1197 reth_tracing::init_test_tracing();
1198
1199 let mut builder = SessionBuilder::default();
1200
1201 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1202 let local_addr = listener.local_addr().unwrap();
1203
1204 let request_timeout = Duration::from_millis(100);
1205 let drop_timeout = Duration::from_millis(1500);
1206
1207 let fut = builder.with_client_stream(local_addr, move |client_stream| async move {
1208 let _client_stream = client_stream;
1209 tokio::time::sleep(drop_timeout * 60).await;
1210 });
1211 tokio::task::spawn(fut);
1212
1213 let (incoming, _) = listener.accept().await.unwrap();
1214 let mut session = builder.connect_incoming(incoming).await;
1215 session
1216 .internal_request_timeout
1217 .store(request_timeout.as_millis() as u64, Ordering::Relaxed);
1218 session.protocol_breach_request_timeout = drop_timeout;
1219 session.internal_request_timeout_interval =
1220 tokio::time::interval_at(tokio::time::Instant::now(), request_timeout);
1221 let (tx, rx) = oneshot::channel();
1222 let req = PeerRequest::GetBlockBodies { request: GetBlockBodies(vec![]), response: tx };
1223 session.on_internal_peer_request(req, Instant::now());
1224 tokio::spawn(session);
1225
1226 let err = rx.await.unwrap().unwrap_err();
1227 assert_eq!(err, RequestError::Timeout);
1228
1229 let msg = builder.active_session_rx.next().await.unwrap();
1231 match msg {
1232 ActiveSessionMessage::ProtocolBreach { .. } => {}
1233 ev => unreachable!("{ev:?}"),
1234 }
1235 }
1236
1237 #[tokio::test(flavor = "multi_thread")]
1238 async fn test_keep_alive() {
1239 let mut builder = SessionBuilder::default();
1240
1241 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1242 let local_addr = listener.local_addr().unwrap();
1243
1244 let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1245 let _ = tokio::time::timeout(Duration::from_secs(5), client_stream.next()).await;
1246 client_stream.into_inner().disconnect(DisconnectReason::UselessPeer).await.unwrap();
1247 });
1248
1249 let (tx, rx) = oneshot::channel();
1250
1251 tokio::task::spawn(async move {
1252 let (incoming, _) = listener.accept().await.unwrap();
1253 let session = builder.connect_incoming(incoming).await;
1254 session.await;
1255
1256 tx.send(()).unwrap();
1257 });
1258
1259 tokio::task::spawn(fut);
1260
1261 rx.await.unwrap();
1262 }
1263
1264 #[tokio::test(flavor = "multi_thread")]
1266 async fn test_send_at_capacity() {
1267 let mut builder = SessionBuilder::default();
1268
1269 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1270 let local_addr = listener.local_addr().unwrap();
1271
1272 let fut = builder.with_client_stream(local_addr, move |mut client_stream| async move {
1273 client_stream
1274 .send(EthMessage::NewPooledTransactionHashes68(Default::default()))
1275 .await
1276 .unwrap();
1277 let _ = tokio::time::timeout(Duration::from_secs(100), client_stream.next()).await;
1278 });
1279 tokio::task::spawn(fut);
1280
1281 let (incoming, _) = listener.accept().await.unwrap();
1282 let session = builder.connect_incoming(incoming).await;
1283
1284 let mut num_fill_messages = 0;
1286 loop {
1287 if builder
1288 .active_session_tx
1289 .try_send(ActiveSessionMessage::ProtocolBreach { peer_id: PeerId::random() })
1290 .is_err()
1291 {
1292 break
1293 }
1294 num_fill_messages += 1;
1295 }
1296
1297 tokio::task::spawn(async move {
1298 session.await;
1299 });
1300
1301 tokio::time::sleep(Duration::from_millis(100)).await;
1302
1303 for _ in 0..num_fill_messages {
1304 let message = builder.active_session_rx.next().await.unwrap();
1305 match message {
1306 ActiveSessionMessage::ProtocolBreach { .. } => {}
1307 ev => unreachable!("{ev:?}"),
1308 }
1309 }
1310
1311 let message = builder.active_session_rx.next().await.unwrap();
1312 match message {
1313 ActiveSessionMessage::ValidMessage {
1314 message: PeerMessage::PooledTransactions(_),
1315 ..
1316 } => {}
1317 _ => unreachable!(),
1318 }
1319 }
1320
1321 #[test]
1322 fn timeout_calculation_sanity_tests() {
1323 let rtt = Duration::from_secs(5);
1324 let timeout = rtt * TIMEOUT_SCALING;
1326
1327 assert_eq!(calculate_new_timeout(timeout, rtt), timeout);
1329
1330 assert!(calculate_new_timeout(timeout, rtt / 2) < timeout);
1332 assert!(calculate_new_timeout(timeout, rtt / 2) > timeout / 2);
1333 assert!(calculate_new_timeout(timeout, rtt * 2) > timeout);
1334 assert!(calculate_new_timeout(timeout, rtt * 2) < timeout * 2);
1335 }
1336}