Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce connected_peers() API #4400

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions prdoc/pr_4400.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
title: Introduce connected_peers() API to sc-network

doc:
- audience: Node Dev
description: |
The new change exposes a list of the currently connected peers to use in other parts of the system. A list of PeerId will be used by request-response protocol operations.

crates:
- name: sc-network
bump: patch
30 changes: 30 additions & 0 deletions substrate/client/network/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,21 @@ impl<B: BlockT + 'static, H: ExHashT> NetworkService<B, H> {
}
}

/// 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 @@ -1312,6 +1327,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 @@ -1454,9 +1472,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