diff --git a/iroh-net/src/magic_endpoint.rs b/iroh-net/src/magic_endpoint.rs index 6301fd695d..318ce5da92 100644 --- a/iroh-net/src/magic_endpoint.rs +++ b/iroh-net/src/magic_endpoint.rs @@ -405,6 +405,14 @@ impl MagicEndpoint { /// If addresses or relay servers are neither provided nor can be discovered, the connection /// attempt will fail with an error. pub async fn connect(&self, node_addr: NodeAddr, alpn: &[u8]) -> Result { + // Connecting to ourselves is not supported. + if node_addr.node_id == self.node_id() { + bail!( + "Connecting to ourself is not supported ({} is the node id of this node)", + node_addr.node_id.fmt_short() + ); + } + if !node_addr.info.is_empty() { self.add_node_addr(node_addr.clone())?; } @@ -501,6 +509,13 @@ impl MagicEndpoint { /// If no UDP addresses are added, and the given `relay_url` cannot be dialed, it will error. // TODO: This is infallible, stop returning a result. pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<()> { + // Connecting to ourselves is not supported. + if node_addr.node_id == self.node_id() { + bail!( + "Adding our own address is not supported ({} is the node id of this node)", + node_addr.node_id.fmt_short() + ); + } self.msock.add_node_addr(node_addr); Ok(()) } @@ -620,6 +635,26 @@ mod tests { ); } + #[tokio::test] + async fn test_connect_self() { + let _guard = iroh_test::logging::setup(); + let ep = MagicEndpoint::builder() + .alpns(vec![TEST_ALPN.to_vec()]) + .bind(0) + .await + .unwrap(); + let my_addr = ep.my_addr().await.unwrap(); + let res = ep.connect(my_addr.clone(), TEST_ALPN).await; + assert!(res.is_err()); + let err = res.err().unwrap(); + assert!(err.to_string().starts_with("Connecting to ourself")); + + let res = ep.add_node_addr(my_addr); + assert!(res.is_err()); + let err = res.err().unwrap(); + assert!(err.to_string().starts_with("Adding our own address")); + } + #[tokio::test] async fn magic_endpoint_connect_close() { let _guard = iroh_test::logging::setup();