Skip to main content

vector_core/xdc/
wire.rs

1//! The realtime wire, byte for byte as every Vector client speaks it: base32
2//! topic ids, relay-only node addresses, and the gossip frame trailer.
3
4use iroh::{EndpointAddr, TransportAddr};
5
6/// The largest payload an app may send in one frame (the WebXDC limit).
7pub const MAX_PAYLOAD: usize = 128_000;
8
9/// What the gossip layer accepts per message: payload plus trailer, with headroom.
10pub const MAX_GOSSIP_MESSAGE: usize = 128 * 1024;
11
12pub const NODE_KEY_LEN: usize = 32;
13
14/// Every frame ends in a 4-byte little-endian sequence number and the sending
15/// node's key. Gossip dedups by content hash, so the trailer is what keeps two
16/// peers' identical payloads (two "hello"s) from collapsing into one.
17pub const TRAILER_LEN: usize = 4 + NODE_KEY_LEN;
18
19/// Append the trailer to an outbound payload.
20pub fn seal_frame(mut payload: Vec<u8>, seq: i32, node_key: &[u8; NODE_KEY_LEN]) -> Vec<u8> {
21    payload.reserve(TRAILER_LEN);
22    payload.extend_from_slice(&seq.to_le_bytes());
23    payload.extend_from_slice(node_key);
24    payload
25}
26
27/// Split an inbound frame into `(payload, sender node key)`. `None` for a frame
28/// too short to carry a trailer.
29pub fn open_frame(frame: &[u8]) -> Option<(&[u8], [u8; NODE_KEY_LEN])> {
30    let body = frame.len().checked_sub(TRAILER_LEN)?;
31    let mut key = [0u8; NODE_KEY_LEN];
32    key.copy_from_slice(&frame[body + 4..]);
33    Some((&frame[..body], key))
34}
35
36pub use crate::webxdc::{base32_nopad_decode, base32_nopad_encode};
37
38/// A topic id as it rides the `webxdc-topic` tag: 52 base32 characters.
39pub fn decode_topic(s: &str) -> Result<[u8; 32], String> {
40    let bytes = base32_nopad_decode(s.as_bytes())?;
41    bytes.try_into().map_err(|_| "a topic id is 32 bytes".to_string())
42}
43
44pub fn encode_topic(topic: &[u8; 32]) -> String {
45    base32_nopad_encode(topic)
46}
47
48/// The topic for an app whose message carries none: derived from the app's
49/// name (as its manifest gives it) and the message, so every copy agrees.
50pub fn fallback_topic(app_name: &str, chat_id: &str, message_id: &str) -> [u8; 32] {
51    let mut input = Vec::with_capacity(20 + app_name.len() + chat_id.len() + message_id.len());
52    input.extend_from_slice(b"webxdc-realtime-v1:");
53    input.extend_from_slice(app_name.as_bytes());
54    input.push(b':');
55    input.extend_from_slice(chat_id.as_bytes());
56    input.push(b':');
57    input.extend_from_slice(message_id.as_bytes());
58    crate::crypto::sha256::digest(&input)
59}
60
61pub fn encode_node_addr(addr: &EndpointAddr) -> Result<String, String> {
62    let json = serde_json::to_string(addr).map_err(|e| e.to_string())?;
63    Ok(base32_nopad_encode(json.as_bytes()))
64}
65
66/// A peer-supplied address, reduced to its relay paths: dialling a direct
67/// address someone else nominated would hand them our IP. Which relays may be
68/// dialled is the mesh's call (`is_default_relay`).
69pub fn decode_node_addr(s: &str) -> Result<EndpointAddr, String> {
70    if s.len() > 2048 {
71        return Err("node address too long".into());
72    }
73    let bytes = base32_nopad_decode(s.as_bytes())?;
74    let addr: EndpointAddr = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
75    Ok(relay_only(addr))
76}
77
78/// A peer's address as this platform may dial it: only relays every client
79/// uses (a peer-named relay would be a server of their choosing that we connect
80/// to), spelled as the platform can reach them. Empty when none is left.
81pub fn dialable(peer: EndpointAddr) -> EndpointAddr {
82    let mut addr = relay_only(peer);
83    addr.addrs.retain(|a| matches!(a, TransportAddr::Relay(url) if is_default_relay(url)));
84    #[cfg(target_arch = "wasm32")]
85    {
86        addr.addrs = addr
87            .addrs
88            .into_iter()
89            .map(|a| match a {
90                TransportAddr::Relay(url) => TransportAddr::Relay(browser_relay(&url)),
91                other => other,
92            })
93            .collect();
94    }
95    addr
96}
97
98pub fn relay_only(addr: EndpointAddr) -> EndpointAddr {
99    EndpointAddr {
100        id: addr.id,
101        addrs: addr.addrs.into_iter().filter(|a| matches!(a, TransportAddr::Relay(_))).collect(),
102    }
103}
104
105/// Whether a relay is one of iroh's defaults, the set every Vector client uses.
106/// Hosts compare without iroh's trailing dot.
107pub fn is_default_relay(url: &iroh::RelayUrl) -> bool {
108    let host = |u: &iroh::RelayUrl| u.host_str().map(|h| h.trim_end_matches('.').to_ascii_lowercase());
109    let theirs = host(url);
110    theirs.is_some()
111        && iroh::defaults::prod::default_relay_map()
112            .urls::<Vec<iroh::RelayUrl>>()
113            .iter()
114            .any(|d| host(d) == theirs)
115}
116
117/// A relay as a browser can dial it. WebKit refuses a WebSocket to a fully
118/// qualified host, and iroh spells its relays with the trailing dot; without it
119/// the URL names the same server.
120pub fn browser_relay(url: &iroh::RelayUrl) -> iroh::RelayUrl {
121    let mut u = (**url).clone();
122    if let Some(host) = u.host_str().and_then(|h| h.strip_suffix('.')).map(str::to_string) {
123        let _ = u.set_host(Some(&host));
124    }
125    iroh::RelayUrl::from(u)
126}
127
128/// The relays a node uses: iroh's defaults, as the platform can dial them.
129pub fn relay_mode() -> iroh::RelayMode {
130    #[cfg(not(target_arch = "wasm32"))]
131    {
132        iroh::RelayMode::Default
133    }
134    #[cfg(target_arch = "wasm32")]
135    {
136        iroh::RelayMode::Custom(iroh::defaults::prod::default_relay_map().urls::<Vec<iroh::RelayUrl>>().iter().map(browser_relay).collect())
137    }
138}
139
140pub fn relay_urls(addr: &EndpointAddr) -> String {
141    let urls: Vec<String> = addr
142        .addrs
143        .iter()
144        .filter_map(|a| match a {
145            TransportAddr::Relay(u) => Some(u.to_string()),
146            _ => None,
147        })
148        .collect();
149    if urls.is_empty() { "none".into() } else { urls.join(", ") }
150}
151
152#[cfg(test)]
153mod tests {
154
155    #[test]
156    fn a_browser_dials_the_relay_without_its_trailing_dot() {
157        let dotted: iroh::RelayUrl = "https://euc1-1.relay.n0.iroh.link./".parse().unwrap();
158        let plain = browser_relay(&dotted);
159        assert_eq!(plain.host_str(), Some("euc1-1.relay.n0.iroh.link"));
160        assert!(is_default_relay(&plain), "still one of the default relays");
161    }
162
163
164    #[test]
165    fn the_fallback_topic_is_the_one_every_client_derives() {
166        assert_eq!(encode_topic(&fallback_topic("Chess", "npub1chat", "msg1")), "YFLKK3KDFMLO5GJXVLY6CIMNTMMN53BKOYAJ7LXBSW4DOMFWTCXA");
167    }
168
169    use super::*;
170
171    #[test]
172    fn a_frame_round_trips_its_payload_and_sender() {
173        let key = [7u8; 32];
174        let frame = seal_frame(b"{\"t\":\"hello\"}".to_vec(), 3, &key);
175        assert_eq!(frame.len(), 13 + TRAILER_LEN);
176        // The trailer is little-endian seq then key, as the app's clients write it.
177        assert_eq!(&frame[13..17], &3i32.to_le_bytes());
178        let (payload, sender) = open_frame(&frame).unwrap();
179        assert_eq!(payload, b"{\"t\":\"hello\"}");
180        assert_eq!(sender, key);
181    }
182
183    #[test]
184    fn an_empty_payload_is_a_valid_frame_and_a_short_one_is_not() {
185        let frame = seal_frame(Vec::new(), 1, &[1u8; 32]);
186        assert_eq!(open_frame(&frame).unwrap().0, b"");
187        assert!(open_frame(&frame[1..]).is_none());
188    }
189
190    #[test]
191    fn topics_round_trip_and_reject_the_wrong_length() {
192        let t = [0xABu8; 32];
193        let s = encode_topic(&t);
194        assert_eq!(s.len(), 52);
195        assert_eq!(decode_topic(&s).unwrap(), t);
196        assert!(decode_topic("MZXW6").is_err());
197        assert!(decode_topic(&"1".repeat(52)).is_err());
198    }
199
200    #[test]
201    fn only_the_default_relays_are_dialled() {
202        for url in iroh::defaults::prod::default_relay_map().urls::<Vec<iroh::RelayUrl>>() {
203            assert!(is_default_relay(&url));
204            let undotted: iroh::RelayUrl = url.as_str().replacen(".iroh.link./", ".iroh.link/", 1).parse().unwrap();
205            assert!(is_default_relay(&undotted), "{undotted} is the same server");
206        }
207        for evil in ["https://attacker.example./", "https://euc1-1.relay.n0.iroh.link.evil.example/", "http://127.0.0.1:3340/"] {
208            assert!(!is_default_relay(&evil.parse().unwrap()), "{evil}");
209        }
210    }
211
212    #[test]
213    fn a_dialable_address_keeps_only_the_default_relays() {
214        let default = iroh::defaults::prod::default_relay_map().urls::<Vec<iroh::RelayUrl>>()[0].clone();
215        let evil: iroh::RelayUrl = "https://attacker.example./".parse().unwrap();
216        let addr = EndpointAddr {
217            id: iroh::SecretKey::from([1u8; 32]).public(),
218            addrs: [
219                TransportAddr::Relay(default.clone()),
220                TransportAddr::Relay(evil),
221                TransportAddr::Ip("203.0.113.7:4433".parse().unwrap()),
222            ]
223            .into_iter()
224            .collect(),
225        };
226        let kept: Vec<_> = dialable(addr).addrs.into_iter().collect();
227        assert_eq!(kept, vec![TransportAddr::Relay(default)]);
228    }
229
230    #[test]
231    fn a_minted_topic_decodes() {
232        let minted = crate::webxdc::mint_topic_id("hash", "sender");
233        assert!(decode_topic(&minted).is_ok());
234    }
235}