From c2ca46e6a80b02a08629cd5343c0d6b8a9188d00 Mon Sep 17 00:00:00 2001 From: Giacomo Pasini Date: Tue, 1 Aug 2023 17:04:18 +0200 Subject: [PATCH] Add command to retrieve libp2p network info (#281) * Add command to retrieve libp2p network info * fix field name * fix --- nomos-services/network/src/backends/libp2p.rs | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/nomos-services/network/src/backends/libp2p.rs b/nomos-services/network/src/backends/libp2p.rs index 6eb938c3..790fddb7 100644 --- a/nomos-services/network/src/backends/libp2p.rs +++ b/nomos-services/network/src/backends/libp2p.rs @@ -1,3 +1,4 @@ +use super::NetworkBackend; use nomos_libp2p::{ libp2p::{ gossipsub::{self, Message}, @@ -6,10 +7,9 @@ use nomos_libp2p::{ BehaviourEvent, Swarm, SwarmConfig, SwarmEvent, }; use overwatch_rs::{overwatch::handle::OverwatchHandle, services::state::NoState}; +use serde::{Deserialize, Serialize}; use tokio::sync::{broadcast, mpsc}; -use super::NetworkBackend; - macro_rules! log_error { ($e:expr) => { if let Err(e) = $e { @@ -23,6 +23,14 @@ pub struct Libp2p { commands_tx: mpsc::Sender, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Libp2pInfo { + pub listen_addresses: Vec, + pub n_peers: usize, + pub n_connections: u32, + pub n_pending_connections: u32, +} + #[derive(Debug)] pub enum EventKind { Message, @@ -38,6 +46,7 @@ pub enum Command { Broadcast { topic: Topic, message: Vec }, Subscribe(Topic), Unsubscribe(Topic), + Info { reply: oneshot::Sender }, } pub type Topic = String; @@ -129,6 +138,18 @@ impl NetworkBackend for Libp2p { tracing::debug!("unsubscribing to topic: {topic}"); log_error!(swarm.unsubscribe(&topic)); } + Command::Info { reply } => { + let swarm = swarm.swarm(); + let network_info = swarm.network_info(); + let counters = network_info.connection_counters(); + let info = Libp2pInfo { + listen_addresses: swarm.listeners().cloned().collect(), + n_peers: network_info.num_peers(), + n_connections: counters.num_connections(), + n_pending_connections: counters.num_pending(), + }; + log_error!(reply.send(info)); + } }; } }