From 4a768901d6925ef4629f88692d329e5cdeaed69d Mon Sep 17 00:00:00 2001 From: b5 Date: Fri, 21 Oct 2022 23:51:41 -0400 Subject: [PATCH] command to list peers --- iroh-api/src/p2p.rs | 6 ++++++ iroh/src/p2p.rs | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/iroh-api/src/p2p.rs b/iroh-api/src/p2p.rs index 1c3cbff5e80..b53708da35e 100644 --- a/iroh-api/src/p2p.rs +++ b/iroh-api/src/p2p.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use anyhow::Result; use async_trait::async_trait; use iroh_rpc_client::{Lookup, P2pClient}; @@ -27,6 +28,7 @@ pub trait P2p: Sync { async fn lookup_local(&self) -> Result; async fn lookup(&self, addr: &PeerIdOrAddr) -> Result; async fn connect(&self, addr: &PeerIdOrAddr) -> Result<()>; + async fn peers(&self) -> Result>>; } #[async_trait] @@ -62,6 +64,10 @@ impl P2p for ClientP2p { } } } + + async fn peers(&self) -> Result>> { + self.client.get_peers().await + } } fn peer_id_from_multiaddr(addr: &Multiaddr) -> Result { diff --git a/iroh/src/p2p.rs b/iroh/src/p2p.rs index d76c1465476..b0dacce4363 100644 --- a/iroh/src/p2p.rs +++ b/iroh/src/p2p.rs @@ -2,7 +2,7 @@ use crate::doc; use anyhow::{Error, Result}; use clap::{Args, Subcommand}; use iroh_api::{Lookup, Multiaddr, P2pApi, PeerId, PeerIdOrAddr}; -use std::{fmt::Display, str::FromStr}; +use std::{fmt::Display, str::FromStr, collections::HashMap}; #[derive(Args, Debug, Clone)] #[clap(about = "Peer-2-peer commands")] @@ -29,6 +29,8 @@ pub enum P2pCommands { /// multiaddress or peer ID addr: Option, }, + #[clap(about = "List known peers")] + Peers {} } #[derive(Debug, Clone)] @@ -71,6 +73,10 @@ pub async fn run_command(p2p: &impl P2pApi, cmd: &P2p) -> Result<()> { None => p2p.lookup_local().await?, }; display_lookup(&lookup); + }, + P2pCommands::Peers { } => { + let peers = p2p.peers().await?; + display_peers(peers); } }; Ok(()) @@ -88,3 +94,14 @@ observed addresses: {:?} l.peer_id, l.listen_addrs, l.protocols, l.protocol_version, l.observed_addrs ); } + +fn display_peers(peers: HashMap>) { + let mut pid_str:String; + for (peer_id, addrs) in peers { + pid_str = peer_id.to_string(); + if pid_str.len() < 52 { + pid_str.push_str(&" ".repeat(52 - pid_str.len())); + } + println!("{}\t{} addresses", pid_str, addrs.len()); + } +} \ No newline at end of file