diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 47e23337633b..0ac8ca1ecd27 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -743,6 +743,21 @@ impl NetworkService { rx.await.map_err(|_| ()) } + /// Returns a collection of currently connected (open) peers. + pub async fn connected_peers(&self) -> Result, ()> { + 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 @@ -1173,6 +1188,9 @@ enum ServiceToWorkerMsg { NetworkState { pending_response: oneshot::Sender>, }, + ConnectedPeers { + pending_response: oneshot::Sender>, + }, DisconnectPeer(PeerId, ProtocolName), } @@ -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 { + self.network_service + .behaviour() + .user_protocol() + .open_peers() + .cloned() + .collect::>() + } + /// Process the next event coming from `Swarm`. fn handle_swarm_event(&mut self, event: SwarmEvent>>) { match event {