Skip to content

Commit

Permalink
feat(iroh-api): implement connect
Browse files Browse the repository at this point in the history
  • Loading branch information
ramfox committed Oct 18, 2022
1 parent 5114380 commit d06c463
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
23 changes: 22 additions & 1 deletion iroh-api/src/p2p.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use anyhow::Result;
use async_trait::async_trait;
use iroh_rpc_client::P2pClient;
use libp2p::{Multiaddr, PeerId};
use libp2p::{multiaddr::Protocol, Multiaddr, PeerId};
#[cfg(feature = "testing")]
use mockall::automock;

Expand Down Expand Up @@ -31,6 +31,7 @@ impl ClientP2p {
#[async_trait]
pub trait P2p: Sync {
async fn lookup(&self, addr: &PeerIdOrAddr) -> Result<Lookup>;
async fn connect(&self, addr: &PeerIdOrAddr) -> Result<()>;
}

#[async_trait]
Expand All @@ -45,4 +46,24 @@ impl P2p for ClientP2p {
local_addrs: self.client.external_addresses().await?,
})
}

// TODO(ramfox): once lookup is implemented, use lookup to get appropriate multiaddr if no
// address is given
async fn connect(&self, addr: &PeerIdOrAddr) -> Result<()> {
match addr {
PeerIdOrAddr::PeerId(_) => {
anyhow::bail!("Connecting two nodes based soley on PeerId is not yet implemented")
}
PeerIdOrAddr::Multiaddr(addr) => {
if let Some(Protocol::P2p(peer_id)) =
addr.iter().find(|p| matches!(*p, Protocol::P2p(_)))
{
let peer_id = PeerId::from_multihash(peer_id).map_err(|m| anyhow::anyhow!("Multiaddr contains invalid p2p multihash {:?}. Cannot derive a PeerId from this address.", m))?;
self.client.connect(peer_id, vec![addr.clone()]).await
} else {
anyhow::bail!("Mulitaddress must include the peer id")
}
}
}
}
}
9 changes: 6 additions & 3 deletions iroh/src/p2p.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,12 @@ impl FromStr for PeerIdOrAddrArg {

pub async fn run_command(p2p: &impl P2pApi, cmd: &P2p) -> Result<()> {
match &cmd.command {
P2pCommands::Connect { .. } => {
todo!("`iroh p2p connect` is not yet implemented")
}
P2pCommands::Connect { addr } => match p2p.connect(&addr.0).await {
Ok(_) => {
println!("Connected!");
}
Err(e) => return Err(e),
},
P2pCommands::Lookup { addr } => {
let lookup = p2p.lookup(&addr.0).await?;
println!("peer id: {}", lookup.peer_id);
Expand Down

0 comments on commit d06c463

Please sign in to comment.