Skip to content

Commit

Permalink
command to list peers
Browse files Browse the repository at this point in the history
  • Loading branch information
b5 committed Oct 22, 2022
1 parent 1f1c47a commit 4a76890
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 6 additions & 0 deletions iroh-api/src/p2p.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use anyhow::Result;
use async_trait::async_trait;
use iroh_rpc_client::{Lookup, P2pClient};
Expand Down Expand Up @@ -27,6 +28,7 @@ pub trait P2p: Sync {
async fn lookup_local(&self) -> Result<Lookup>;
async fn lookup(&self, addr: &PeerIdOrAddr) -> Result<Lookup>;
async fn connect(&self, addr: &PeerIdOrAddr) -> Result<()>;
async fn peers(&self) -> Result<HashMap<PeerId, Vec<Multiaddr>>>;
}

#[async_trait]
Expand Down Expand Up @@ -62,6 +64,10 @@ impl P2p for ClientP2p {
}
}
}

async fn peers(&self) -> Result<HashMap<PeerId, Vec<Multiaddr>>> {
self.client.get_peers().await
}
}

fn peer_id_from_multiaddr(addr: &Multiaddr) -> Result<PeerId> {
Expand Down
19 changes: 18 additions & 1 deletion iroh/src/p2p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -29,6 +29,8 @@ pub enum P2pCommands {
/// multiaddress or peer ID
addr: Option<PeerIdOrAddrArg>,
},
#[clap(about = "List known peers")]
Peers {}
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -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(())
Expand All @@ -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<PeerId, Vec<Multiaddr>>) {
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());
}
}

0 comments on commit 4a76890

Please sign in to comment.