1use reth_eth_wire_types::{
4 message::RequestPair, snap::SnapProtocolMessage, BlockAccessLists, BlockBodies, BlockHeaders,
5 Capabilities, Cells, DisconnectReason, EthMessage, EthNetworkPrimitives, EthVersion,
6 GetBlockAccessLists, GetBlockBodies, GetBlockHeaders, GetCells, GetNodeData,
7 GetPooledTransactions, GetReceipts, GetReceipts70, NetworkPrimitives, NodeData,
8 PooledTransactions, Receipts, Receipts69, Receipts70, UnifiedStatus,
9};
10use reth_ethereum_forks::ForkId;
11use reth_network_p2p::{
12 error::{RequestError, RequestResult},
13 snap::client::SnapResponse,
14};
15use reth_network_peers::{NodeRecord, PeerId};
16use reth_network_types::{PeerAddr, PeerKind};
17use reth_tokio_util::EventStream;
18use std::{
19 fmt,
20 net::SocketAddr,
21 pin::Pin,
22 sync::Arc,
23 task::{Context, Poll},
24};
25use tokio::sync::{mpsc, oneshot};
26use tokio_stream::{wrappers::UnboundedReceiverStream, Stream, StreamExt};
27
28pub struct PeerEventStream(Pin<Box<dyn Stream<Item = PeerEvent> + Send + Sync>>);
30
31impl fmt::Debug for PeerEventStream {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.debug_struct("PeerEventStream").finish_non_exhaustive()
34 }
35}
36
37impl PeerEventStream {
38 pub fn new<S, T>(stream: S) -> Self
41 where
42 S: Stream<Item = T> + Send + Sync + 'static,
43 T: Into<PeerEvent> + 'static,
44 {
45 let mapped_stream = stream.map(Into::into);
46 Self(Box::pin(mapped_stream))
47 }
48}
49
50impl Stream for PeerEventStream {
51 type Item = PeerEvent;
52
53 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
54 self.0.as_mut().poll_next(cx)
55 }
56}
57
58#[derive(Debug, Clone)]
60pub struct SessionInfo {
61 pub peer_id: PeerId,
63 pub remote_addr: SocketAddr,
65 pub client_version: Arc<str>,
67 pub capabilities: Arc<Capabilities>,
69 pub status: Arc<UnifiedStatus>,
71 pub version: EthVersion,
73 pub peer_kind: PeerKind,
75}
76
77#[derive(Debug, Clone)]
83pub enum PeerEvent {
84 SessionClosed {
86 peer_id: PeerId,
88 reason: Option<DisconnectReason>,
90 },
91 SessionEstablished(SessionInfo),
93 PeerAdded(PeerId),
95 PeerRemoved(PeerId),
97}
98
99#[derive(Debug)]
101pub enum NetworkEvent<R = PeerRequest> {
102 Peer(PeerEvent),
104 ActivePeerSession {
106 info: SessionInfo,
108 messages: PeerRequestSender<R>,
110 },
111}
112
113impl<R> Clone for NetworkEvent<R> {
114 fn clone(&self) -> Self {
115 match self {
116 Self::Peer(event) => Self::Peer(event.clone()),
117 Self::ActivePeerSession { info, messages } => {
118 Self::ActivePeerSession { info: info.clone(), messages: messages.clone() }
119 }
120 }
121 }
122}
123
124impl<R> From<NetworkEvent<R>> for PeerEvent {
125 fn from(event: NetworkEvent<R>) -> Self {
126 match event {
127 NetworkEvent::Peer(peer_event) => peer_event,
128 NetworkEvent::ActivePeerSession { info, .. } => Self::SessionEstablished(info),
129 }
130 }
131}
132
133#[auto_impl::auto_impl(&, Arc)]
135pub trait NetworkPeersEvents: Send + Sync {
136 fn peer_events(&self) -> PeerEventStream;
138}
139
140#[auto_impl::auto_impl(&, Arc)]
142pub trait NetworkEventListenerProvider: NetworkPeersEvents {
143 type Primitives: NetworkPrimitives;
145
146 fn event_listener(&self) -> EventStream<NetworkEvent<PeerRequest<Self::Primitives>>>;
148 fn discovery_listener(&self) -> UnboundedReceiverStream<DiscoveryEvent>;
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum DiscoveryEvent {
157 NewNode(DiscoveredEvent),
159 EnrForkId(NodeRecord, ForkId),
166}
167
168#[derive(Debug, Clone, PartialEq, Eq)]
170pub enum DiscoveredEvent {
171 EventQueued {
183 peer_id: PeerId,
185 addr: PeerAddr,
187 fork_id: Option<ForkId>,
190 },
191}
192
193#[derive(Debug)]
195pub enum PeerRequest<N: NetworkPrimitives = EthNetworkPrimitives> {
196 GetBlockHeaders {
200 request: GetBlockHeaders,
202 response: oneshot::Sender<RequestResult<BlockHeaders<N::BlockHeader>>>,
204 },
205 GetBlockBodies {
209 request: GetBlockBodies,
211 response: oneshot::Sender<RequestResult<BlockBodies<N::BlockBody>>>,
213 },
214 GetPooledTransactions {
218 request: GetPooledTransactions,
220 response: oneshot::Sender<RequestResult<PooledTransactions<N::PooledTransaction>>>,
222 },
223 GetNodeData {
227 request: GetNodeData,
229 response: oneshot::Sender<RequestResult<NodeData>>,
231 },
232 GetReceipts {
238 request: GetReceipts,
240 response: oneshot::Sender<RequestResult<Receipts<N::Receipt>>>,
242 },
243 GetReceipts69 {
249 request: GetReceipts,
251 response: oneshot::Sender<RequestResult<Receipts69<N::Receipt>>>,
253 },
254 GetReceipts70 {
260 request: GetReceipts70,
262 response: oneshot::Sender<RequestResult<Receipts70<N::Receipt>>>,
264 },
265 GetBlockAccessLists {
269 request: GetBlockAccessLists,
271 response: oneshot::Sender<RequestResult<BlockAccessLists>>,
273 },
274 GetCells {
278 request: GetCells,
280 response: oneshot::Sender<RequestResult<Cells>>,
282 },
283 GetSnap {
287 request: SnapProtocolMessage,
289 response: oneshot::Sender<RequestResult<SnapResponse>>,
291 },
292}
293
294#[derive(Debug)]
297pub enum RequestMessage<N: NetworkPrimitives = EthNetworkPrimitives> {
298 Eth(EthMessage<N>),
300 Snap(SnapProtocolMessage),
302}
303
304impl<N: NetworkPrimitives> PeerRequest<N> {
307 pub fn send_bad_response(self) {
309 self.send_err_response(RequestError::BadResponse)
310 }
311
312 pub fn send_err_response(self, err: RequestError) {
314 let _ = match self {
315 Self::GetBlockHeaders { response, .. } => response.send(Err(err)).ok(),
316 Self::GetBlockBodies { response, .. } => response.send(Err(err)).ok(),
317 Self::GetPooledTransactions { response, .. } => response.send(Err(err)).ok(),
318 Self::GetNodeData { response, .. } => response.send(Err(err)).ok(),
319 Self::GetReceipts { response, .. } => response.send(Err(err)).ok(),
320 Self::GetReceipts69 { response, .. } => response.send(Err(err)).ok(),
321 Self::GetReceipts70 { response, .. } => response.send(Err(err)).ok(),
322 Self::GetBlockAccessLists { response, .. } => response.send(Err(err)).ok(),
323 Self::GetCells { response, .. } => response.send(Err(err)).ok(),
324 Self::GetSnap { response, .. } => response.send(Err(err)).ok(),
325 };
326 }
327
328 #[inline]
330 pub fn is_supported_by_eth_version(&self, version: EthVersion) -> bool {
331 match self {
332 Self::GetReceipts { .. } => version < EthVersion::Eth69,
335 Self::GetReceipts69 { .. } => version == EthVersion::Eth69,
336 Self::GetReceipts70 { .. } => version >= EthVersion::Eth70,
337 Self::GetBlockAccessLists { .. } => version >= EthVersion::Eth71,
338 Self::GetCells { request, .. } => {
339 version >=
340 if request.cell_mask.is_indexed() {
341 EthVersion::Eth73
342 } else {
343 EthVersion::Eth72
344 }
345 }
346 _ => true,
347 }
348 }
349
350 pub fn create_request_message(&self, request_id: u64) -> RequestMessage<N> {
352 match self {
353 Self::GetBlockHeaders { request, .. } => {
354 RequestMessage::Eth(EthMessage::GetBlockHeaders(RequestPair {
355 request_id,
356 message: *request,
357 }))
358 }
359 Self::GetBlockBodies { request, .. } => {
360 RequestMessage::Eth(EthMessage::GetBlockBodies(RequestPair {
361 request_id,
362 message: request.clone(),
363 }))
364 }
365 Self::GetPooledTransactions { request, .. } => {
366 RequestMessage::Eth(EthMessage::GetPooledTransactions(RequestPair {
367 request_id,
368 message: request.clone(),
369 }))
370 }
371 Self::GetNodeData { request, .. } => {
372 RequestMessage::Eth(EthMessage::GetNodeData(RequestPair {
373 request_id,
374 message: request.clone(),
375 }))
376 }
377 Self::GetReceipts { request, .. } | Self::GetReceipts69 { request, .. } => {
378 RequestMessage::Eth(EthMessage::GetReceipts(RequestPair {
379 request_id,
380 message: request.clone(),
381 }))
382 }
383 Self::GetReceipts70 { request, .. } => {
384 RequestMessage::Eth(EthMessage::GetReceipts70(RequestPair {
385 request_id,
386 message: request.clone(),
387 }))
388 }
389 Self::GetBlockAccessLists { request, .. } => {
390 RequestMessage::Eth(EthMessage::GetBlockAccessLists(RequestPair {
391 request_id,
392 message: request.clone(),
393 }))
394 }
395 Self::GetCells { request, .. } => {
396 RequestMessage::Eth(EthMessage::GetCells(RequestPair {
397 request_id,
398 message: request.clone(),
399 }))
400 }
401 Self::GetSnap { request, .. } => {
402 let mut message = request.clone();
403 message.set_request_id(request_id);
404 RequestMessage::Snap(message)
405 }
406 }
407 }
408
409 pub fn into_get_pooled_transactions(self) -> Option<GetPooledTransactions> {
411 match self {
412 Self::GetPooledTransactions { request, .. } => Some(request),
413 _ => None,
414 }
415 }
416}
417
418pub struct PeerRequestSender<R = PeerRequest> {
420 pub peer_id: PeerId,
422 pub to_session_tx: mpsc::Sender<R>,
424}
425
426impl<R> Clone for PeerRequestSender<R> {
427 fn clone(&self) -> Self {
428 Self { peer_id: self.peer_id, to_session_tx: self.to_session_tx.clone() }
429 }
430}
431
432impl<R> PeerRequestSender<R> {
435 pub const fn new(peer_id: PeerId, to_session_tx: mpsc::Sender<R>) -> Self {
437 Self { peer_id, to_session_tx }
438 }
439
440 pub fn try_send(&self, req: R) -> Result<(), mpsc::error::TrySendError<R>> {
442 self.to_session_tx.try_send(req)
443 }
444
445 pub const fn peer_id(&self) -> &PeerId {
447 &self.peer_id
448 }
449}
450
451impl<R> fmt::Debug for PeerRequestSender<R> {
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 f.debug_struct("PeerRequestSender").field("peer_id", &self.peer_id).finish_non_exhaustive()
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460 use alloy_primitives::{B128, B256};
461
462 #[test]
463 fn test_get_block_access_lists_version_support() {
464 let (tx, _rx) = oneshot::channel();
465 let req: PeerRequest<EthNetworkPrimitives> =
466 PeerRequest::GetBlockAccessLists { request: GetBlockAccessLists(vec![]), response: tx };
467
468 assert!(!req.is_supported_by_eth_version(EthVersion::Eth70));
469 assert!(req.is_supported_by_eth_version(EthVersion::Eth71));
470 }
471
472 #[test]
473 fn test_get_cells_version_support() {
474 let (tx, _rx) = oneshot::channel();
475 let req: PeerRequest<EthNetworkPrimitives> =
476 PeerRequest::GetCells { request: GetCells::default(), response: tx };
477
478 assert!(!req.is_supported_by_eth_version(EthVersion::Eth71));
479 assert!(req.is_supported_by_eth_version(EthVersion::Eth72));
480 assert!(req.is_supported_by_eth_version(EthVersion::Eth73));
481 let (tx, _rx) = oneshot::channel();
482 let req = PeerRequest::<EthNetworkPrimitives>::GetCells {
483 request: GetCells::from_masks(
484 vec![B256::ZERO, B256::repeat_byte(1)],
485 vec![B128::ZERO, B128::repeat_byte(1)],
486 )
487 .unwrap(),
488 response: tx,
489 };
490 assert!(!req.is_supported_by_eth_version(EthVersion::Eth72));
491 assert!(req.is_supported_by_eth_version(EthVersion::Eth73));
492 }
493
494 #[test]
495 fn test_get_receipts_version_support() {
496 let (tx, _rx) = oneshot::channel();
497 let req = PeerRequest::<EthNetworkPrimitives>::GetReceipts {
498 request: GetReceipts(vec![]),
499 response: tx,
500 };
501
502 assert!(req.is_supported_by_eth_version(EthVersion::Eth68));
503 assert!(!req.is_supported_by_eth_version(EthVersion::Eth69));
504
505 let (tx, _rx) = oneshot::channel();
506 let req = PeerRequest::<EthNetworkPrimitives>::GetReceipts69 {
507 request: GetReceipts(vec![]),
508 response: tx,
509 };
510
511 assert!(!req.is_supported_by_eth_version(EthVersion::Eth68));
512 assert!(req.is_supported_by_eth_version(EthVersion::Eth69));
513 assert!(!req.is_supported_by_eth_version(EthVersion::Eth70));
514
515 let (tx, _rx) = oneshot::channel();
516 let req = PeerRequest::<EthNetworkPrimitives>::GetReceipts70 {
517 request: GetReceipts70 { first_block_receipt_index: 0, block_hashes: vec![] },
518 response: tx,
519 };
520
521 assert!(!req.is_supported_by_eth_version(EthVersion::Eth69));
522 assert!(req.is_supported_by_eth_version(EthVersion::Eth70));
523 assert!(req.is_supported_by_eth_version(EthVersion::Eth71));
524 }
525}