Skip to content

Commit

Permalink
Introduce connected_peers() API
Browse files Browse the repository at this point in the history
  • Loading branch information
shamil-gadelshin committed May 7, 2024
1 parent 480a5c3 commit 88831de
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions substrate/client/network/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,21 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
rx.await.map_err(|_| ())
}

/// Returns a collection of currently connected (open) peers.
pub async fn connected_peers(&self) -> Result<Vec<PeerId>, ()> {
let (tx, rx) = oneshot::channel();

let _ = self
.to_worker
.unbounded_send(ServiceToWorkerMsg::ConnectedPeers { pending_response: tx });

match rx.await {
Ok(v) => Ok(v),
// The channel can only be closed if the network worker no longer exists.
Err(_) => Err(()),
}
}

/// Utility function to extract `PeerId` from each `Multiaddr` for peer set updates.
///
/// Returns an `Err` if one of the given addresses is invalid or contains an
Expand Down Expand Up @@ -1173,6 +1188,9 @@ enum ServiceToWorkerMsg {
NetworkState {
pending_response: oneshot::Sender<Result<NetworkState, RequestFailure>>,
},
ConnectedPeers {
pending_response: oneshot::Sender<Vec<PeerId>>,
},
DisconnectPeer(PeerId, ProtocolName),
}

Expand Down Expand Up @@ -1315,9 +1333,21 @@ where
.behaviour_mut()
.user_protocol_mut()
.disconnect_peer(&who, protocol_name),
ServiceToWorkerMsg::ConnectedPeers { pending_response } => {
let _ = pending_response.send(self.connected_peers());
},
}
}

fn connected_peers(&self) -> Vec<PeerId> {
self.network_service
.behaviour()
.user_protocol()
.open_peers()
.cloned()
.collect::<Vec<_>>()
}

/// Process the next event coming from `Swarm`.
fn handle_swarm_event(&mut self, event: SwarmEvent<BehaviourOut, THandlerErr<Behaviour<B>>>) {
match event {
Expand Down

0 comments on commit 88831de

Please sign in to comment.