1//! Interaction with `reth_network::PeersManager`, for integration testing. Otherwise
2//! `reth_network::NetworkManager` manages `reth_network::PeersManager`.
34use std::net::SocketAddr;
56use derive_more::Constructor;
7use reth_network_peers::{NodeRecord, PeerId};
8use reth_network_types::{Peer, ReputationChangeKind};
9use tokio::sync::{mpsc, oneshot};
1011/// Provides an API for managing the peers of the network.
12#[auto_impl::auto_impl(&, Arc)]
13pub trait PeersHandleProvider {
14/// Returns the [`PeersHandle`] that can be cloned and shared.
15 ///
16 /// The [`PeersHandle`] can be used to interact with the network's peer set.
17fn peers_handle(&self) -> &PeersHandle;
18}
1920/// A communication channel to the `PeersManager` to apply manual changes to the peer set.
21#[derive(Clone, Debug, Constructor)]
22pub struct PeersHandle {
23/// Sender half of command channel back to the `PeersManager`
24manager_tx: mpsc::UnboundedSender<PeerCommand>,
25}
2627// === impl PeersHandle ===
2829impl PeersHandle {
30fn send(&self, cmd: PeerCommand) {
31let _ = self.manager_tx.send(cmd);
32 }
3334/// Adds a peer to the set.
35pub fn add_peer(&self, peer_id: PeerId, addr: SocketAddr) {
36self.send(PeerCommand::Add(peer_id, addr));
37 }
3839/// Removes a peer from the set.
40pub fn remove_peer(&self, peer_id: PeerId) {
41self.send(PeerCommand::Remove(peer_id));
42 }
4344/// Send a reputation change for the given peer.
45pub fn reputation_change(&self, peer_id: PeerId, kind: ReputationChangeKind) {
46self.send(PeerCommand::ReputationChange(peer_id, kind));
47 }
4849/// Returns a peer by its [`PeerId`], or `None` if the peer is not in the peer set.
50pub async fn peer_by_id(&self, peer_id: PeerId) -> Option<Peer> {
51let (tx, rx) = oneshot::channel();
52self.send(PeerCommand::GetPeer(peer_id, tx));
5354 rx.await.unwrap_or(None)
55 }
5657/// Returns all peers in the peerset.
58pub async fn all_peers(&self) -> Vec<NodeRecord> {
59let (tx, rx) = oneshot::channel();
60self.send(PeerCommand::GetPeers(tx));
6162 rx.await.unwrap_or_default()
63 }
64}
6566/// Commands the `PeersManager` listens for.
67#[derive(Debug)]
68pub enum PeerCommand {
69/// Command for manually add
70Add(PeerId, SocketAddr),
71/// Remove a peer from the set
72 ///
73 /// If currently connected this will disconnect the session
74Remove(PeerId),
75/// Apply a reputation change to the given peer.
76ReputationChange(PeerId, ReputationChangeKind),
77/// Get information about a peer
78GetPeer(PeerId, oneshot::Sender<Option<Peer>>),
79/// Get node information on all peers
80GetPeers(oneshot::Sender<Vec<NodeRecord>>),
81}