logicaffeine_system/addr.rs
1//! Address normalization — libp2p multiaddr → WebSocket URL.
2//!
3//! The compiled path dials peers with libp2p multiaddrs
4//! (`/ip4/127.0.0.1/tcp/9944`); the interpreter rides the thin WS relay, which
5//! speaks `ws://`. To keep one surface across both runtimes a program can write
6//! `Connect to "/ip4/127.0.0.1/tcp/9944"` and have the interpreter accept it —
7//! this maps the multiaddr to the relay's `ws://host:port`. Raw `ws://`/`wss://`
8//! URLs pass through unchanged, so either form works.
9//!
10//! Pure string logic, no libp2p, no target gating — it compiles into the native
11//! binary and the wasm bundle alike, so the interpreter normalizes addresses the
12//! same way on both.
13
14/// Normalize a peer address to a WebSocket URL the relay can dial.
15///
16/// Accepts:
17/// - a libp2p multiaddr: `/ip4/H/tcp/P`, `/ip6/H/tcp/P`, `/dns4/H/tcp/P`
18/// (also `/dns`, `/dns6`, `/dnsaddr`), with an optional `/ws` or `/wss`
19/// transport suffix (default `ws`) and an optional trailing `/p2p/<id>`
20/// (ignored — the relay addresses by host:port, not peer id);
21/// - a raw `ws://…` or `wss://…` URL, returned unchanged.
22///
23/// IPv6 literals are bracketed (`/ip6/::1/tcp/9944` → `ws://[::1]:9944`).
24///
25/// Returns `Err` with a human message on anything it cannot map.
26pub fn multiaddr_to_ws_url(addr: &str) -> Result<String, String> {
27 let trimmed = addr.trim();
28 if trimmed.is_empty() {
29 return Err("address is empty".to_string());
30 }
31
32 let lower = trimmed.to_ascii_lowercase();
33 if lower.starts_with("ws://") || lower.starts_with("wss://") {
34 return Ok(trimmed.to_string());
35 }
36
37 if !trimmed.starts_with('/') {
38 return Err(format!("not a ws:// URL or multiaddr: {trimmed}"));
39 }
40
41 let segs: Vec<&str> = trimmed.split('/').skip(1).collect();
42 let mut host: Option<(String, bool)> = None; // (host, is_ipv6_literal)
43 let mut port: Option<String> = None;
44 let mut scheme = "ws";
45
46 let mut i = 0;
47 while i < segs.len() {
48 match segs[i] {
49 "ip4" | "dns" | "dns4" | "dns6" | "dnsaddr" => {
50 let v = segs.get(i + 1).filter(|s| !s.is_empty());
51 let v = v.ok_or_else(|| {
52 format!("multiaddr '{trimmed}' has no host after /{}/", segs[i])
53 })?;
54 host = Some((v.to_string(), false));
55 i += 2;
56 }
57 "ip6" => {
58 let v = segs
59 .get(i + 1)
60 .filter(|s| !s.is_empty())
61 .ok_or_else(|| format!("multiaddr '{trimmed}' has no host after /ip6/"))?;
62 host = Some((v.to_string(), true));
63 i += 2;
64 }
65 "tcp" => {
66 let v = segs
67 .get(i + 1)
68 .filter(|s| !s.is_empty())
69 .ok_or_else(|| format!("multiaddr '{trimmed}' has no port after /tcp/"))?;
70 if v.parse::<u16>().is_err() {
71 return Err(format!(
72 "multiaddr '{trimmed}' has a non-numeric port '{v}'"
73 ));
74 }
75 port = Some(v.to_string());
76 i += 2;
77 }
78 "ws" => {
79 scheme = "ws";
80 i += 1;
81 }
82 "wss" | "tls" => {
83 scheme = "wss";
84 i += 1;
85 }
86 "p2p" | "p2p-circuit" => {
87 // The peer-id (and circuit-relay marker) carry no host:port; the
88 // relay does not use them. Skip the marker and any value.
89 i += if segs[i] == "p2p" { 2 } else { 1 };
90 }
91 other => {
92 return Err(format!(
93 "multiaddr '{trimmed}' has unsupported protocol '/{other}'"
94 ));
95 }
96 }
97 }
98
99 let (host, is_v6) =
100 host.ok_or_else(|| format!("multiaddr '{trimmed}' has no host component"))?;
101 let port = port.ok_or_else(|| format!("multiaddr '{trimmed}' has no /tcp/<port>"))?;
102 let host = if is_v6 { format!("[{host}]") } else { host };
103 Ok(format!("{scheme}://{host}:{port}"))
104}
105
106/// The canonical relay topic for a peer address — its stable identity on the
107/// relay, computed identically by both endpoints.
108///
109/// A multiaddr or `ws://` URL normalizes to its `ws://` form (so
110/// `/ip4/127.0.0.1/tcp/8000` and `ws://127.0.0.1:8000` name the same peer); any
111/// other string (a bare name like `"alice"`) is used verbatim (trimmed). This is
112/// what `Send … to <peer>` publishes on and what `Listen at "<me>"` subscribes
113/// to, so a sender and a receiver that write the same address agree on the topic.
114pub fn canonical_topic(addr: &str) -> String {
115 multiaddr_to_ws_url(addr).unwrap_or_else(|_| addr.trim().to_string())
116}
117
118#[cfg(test)]
119#[path = "../../logicaffeine_tests/unit/logicaffeine_system/addr/tests.rs"]
120mod tests;