Skip to main content

weirdnet_device_link/
net.rs

1//! Running a link over Weirdnet (`/weirdnet/link/2`, Noise-authenticated
2//! request/response): the new device listens, the existing device dials it.
3use std::sync::{Arc, OnceLock};
4use std::time::{Duration, Instant};
5
6use weirdnet_keys::Key32;
7use weirdnet_net::node::{Handler, Message, Node, NodeConfig};
8use weirdnet_net::{Keypair, PeerId, now_ms};
9
10use crate::offer::has_circuit;
11use crate::reach::{self, LinkNode};
12use crate::session::{Host, HostStatus, Sender};
13use crate::wire::{LinkReply, LinkRequest, Received, Transfer};
14use crate::{Error, LINK_PROFILE, Result, decode_link, offer_addrs};
15
16/// How long a listening device waits for its listeners before giving up.
17const LISTEN_WAIT: Duration = Duration::from_secs(5);
18/// How long it waits for a relay circuit once it has direct addresses; past
19/// that the code carries direct addresses only (same network).
20const RELAY_WAIT: Duration = Duration::from_secs(5);
21
22/// The addresses a listening link node puts in its code. With relays
23/// configured it waits up to [`RELAY_WAIT`] for a circuit through one, so a
24/// device on another network (a phone on mobile data, a guest Wi-Fi) can
25/// dial in. `None` (and the node halted) when it never listened.
26pub(crate) fn listen_addrs<Q: Message, R: Message>(node: &Node<Q, R>, want_relay: bool) -> Option<Vec<String>> {
27    let start = Instant::now();
28    let mut direct_at: Option<Instant> = None;
29    loop {
30        let addrs = offer_addrs(&node.reachable_addrs());
31        if !addrs.is_empty() {
32            let since = *direct_at.get_or_insert_with(Instant::now);
33            if !want_relay || has_circuit(&addrs) || since.elapsed() > RELAY_WAIT {
34                return Some(addrs);
35            }
36        } else if start.elapsed() > LISTEN_WAIT {
37            node.halt();
38            return None;
39        }
40        std::thread::sleep(Duration::from_millis(20));
41    }
42}
43
44struct HostHandler(Arc<OnceLock<Arc<Host>>>);
45
46impl Handler<LinkRequest, LinkReply> for HostHandler {
47    fn request(&self, from: &PeerId, req: LinkRequest) -> LinkReply {
48        match self.0.get() {
49            Some(host) => host.handle(from, req, now_ms()),
50            None => LinkReply::refused("not ready"),
51        }
52    }
53}
54
55/// The new device: a node on its own key, listening, with the offer it shows.
56/// Stops listening when dropped.
57pub struct HostNode {
58    node: LinkNode<LinkRequest, LinkReply>,
59    host: Arc<Host>,
60}
61
62impl HostNode {
63    /// Starts listening as `node_key` and makes a fresh offer naming the
64    /// addresses the node ended up on.
65    pub fn start(scheme: &str, node_key: Keypair, cfg: NodeConfig, hint: &str) -> Result<Self> {
66        let slot = Arc::new(OnceLock::new());
67        let node = reach::start(&LINK_PROFILE, node_key.clone(), cfg, Arc::new(HostHandler(slot.clone())))?;
68        let addrs =
69            listen_addrs(&node.node, !node.relays.is_empty()).ok_or_else(|| Error::Net("network: could not listen for the other device".into()))?;
70        let host = Arc::new(Host::new(scheme, &node_key, addrs, hint, now_ms())?);
71        let _ = slot.set(host.clone());
72        Ok(HostNode { node, host })
73    }
74
75    pub fn link(&self) -> &str {
76        self.host.link()
77    }
78
79    pub fn expires_ms(&self) -> i64 {
80        self.host.expires_ms()
81    }
82
83    pub fn status(&self) -> HostStatus {
84        self.host.status(now_ms())
85    }
86
87    pub fn confirm(&self) {
88        self.host.confirm();
89    }
90
91    pub fn take(&self) -> Result<Transfer> {
92        self.host.take()
93    }
94
95    /// A full or a service link, whichever arrived (see [`Host::take_any`]).
96    pub fn take_any(&self) -> Result<Received> {
97        self.host.take_any()
98    }
99
100    pub fn cancel(&self) {
101        self.host.cancel();
102    }
103
104    pub fn peer_id(&self) -> PeerId {
105        self.node.node.peer_id()
106    }
107
108    /// The node's network status (connections, relay reservations).
109    pub fn net_status(&self) -> weirdnet_net::node::Status {
110        self.node.node.status()
111    }
112}
113
114impl Drop for HostNode {
115    fn drop(&mut self) {
116        self.host.cancel();
117        self.node.node.halt();
118    }
119}
120
121/// The existing device, paired with a scanned offer, waiting for the user to
122/// compare codes. Holds a short-lived node on a throwaway key.
123pub struct Pairing {
124    node: LinkNode<LinkRequest, LinkReply>,
125    sender: Sender,
126    sent: bool,
127}
128
129struct NoRequests;
130
131impl Handler<LinkRequest, LinkReply> for NoRequests {
132    fn request(&self, _from: &PeerId, _req: LinkRequest) -> LinkReply {
133        LinkReply::refused("this device is not offering a link")
134    }
135}
136
137impl Pairing {
138    /// Reads `link`, dials the new device and pairs. On success both screens
139    /// show [`Pairing::sas`].
140    pub fn start(scheme: &str, link: &str, cfg: NodeConfig) -> Result<Self> {
141        let offer = decode_link(scheme, link)?;
142        let (sender, hello) = Sender::start(offer, now_ms())?;
143        let node = reach::start(&LINK_PROFILE, Keypair::generate_ed25519(), cfg, Arc::new(NoRequests))?;
144        let pairing = Pairing { node, sender, sent: false };
145        pairing.ask(hello)?;
146        Ok(pairing)
147    }
148
149    fn ask(&self, req: LinkRequest) -> Result<()> {
150        let offer = self.sender.offer();
151        match self.node.node.request(offer.peer(), &offer.dial_addrs(), req)? {
152            LinkReply::Ok => Ok(()),
153            LinkReply::Refused { reason } => Err(Error::Refused(reason)),
154        }
155    }
156
157    /// The code to compare with the new device's screen.
158    pub fn sas(&self) -> &str {
159        self.sender.sas()
160    }
161
162    /// What the new device calls itself.
163    pub fn device(&self) -> &str {
164        &self.sender.offer().offer.hint
165    }
166
167    pub fn peer(&self) -> PeerId {
168        self.sender.offer().peer()
169    }
170
171    /// The node's network status (connections, relay reservations).
172    pub fn net_status(&self) -> weirdnet_net::node::Status {
173        self.node.node.status()
174    }
175
176    /// The user confirmed the codes match: send the identity, once.
177    pub fn send(&mut self, seed: &Key32, profile_name: &str, settings: &str) -> Result<()> {
178        self.send_with(seed, profile_name, settings, &[]).map(|_| ())
179    }
180
181    /// [`Pairing::send`], carrying sync opt-ins, and returning the new device's cert.
182    pub fn send_with(&mut self, seed: &Key32, profile_name: &str, settings: &str, sync: &[String]) -> Result<weirdnet_net::user::NodeCert> {
183        if self.sent {
184            return Err(Error::Invalid("already sent"));
185        }
186        let t = crate::session::make_transfer_with(seed, profile_name, settings, sync, self.sender.offer(), now_ms())?;
187        let cert = t.node_cert.clone();
188        self.ask(self.sender.transfer(&t)?)?;
189        self.sent = true;
190        Ok(cert)
191    }
192
193    /// The user confirmed the codes match: link the new device as a **service** device,
194    /// once. Sends the user's public key, a certificate made here with `user` (which never
195    /// leaves this device) and `bundle` (sync material, such as
196    /// `weirdnet_sync::Identity::service_bundle`), never the seed. Returns the new device's
197    /// cert, to approve in the roster.
198    pub fn send_credential(
199        &mut self,
200        user: &Keypair,
201        profile_name: &str,
202        settings: &str,
203        sync: &[String],
204        bundle: &[u8],
205    ) -> Result<weirdnet_net::user::NodeCert> {
206        if self.sent {
207            return Err(Error::Invalid("already sent"));
208        }
209        let c = crate::session::make_credential(user, profile_name, settings, sync, bundle, self.sender.offer(), now_ms())?;
210        let cert = c.node_cert.clone();
211        self.ask(self.sender.credential(&c)?)?;
212        self.sent = true;
213        Ok(cert)
214    }
215
216    /// The codes differ (or the user gave up): tell the new device.
217    pub fn cancel(&self) -> Result<()> {
218        self.ask(self.sender.cancel())
219    }
220}
221
222impl Drop for Pairing {
223    fn drop(&mut self) {
224        self.node.node.halt();
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    const SCHEME: &str = "weirdnet-morph://";
233
234    fn memory() -> NodeConfig {
235        NodeConfig { listen: vec!["/memory/0".parse().unwrap()], memory: true, ..Default::default() }
236    }
237
238    fn dial_only() -> NodeConfig {
239        NodeConfig { memory: true, ..Default::default() }
240    }
241
242    #[test]
243    fn an_identity_moves_over_the_network_after_both_confirm() {
244        let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "Morph on desk").unwrap();
245        assert_eq!(new_device.status(), HostStatus::Waiting);
246        let mut phone = Pairing::start(SCHEME, new_device.link(), dial_only()).unwrap();
247        assert_eq!(phone.device(), "Morph on desk");
248        assert_eq!(phone.peer(), new_device.peer_id());
249        let HostStatus::Paired { sas } = new_device.status() else { panic!("not paired") };
250        assert_eq!(sas, phone.sas());
251
252        let seed = Key32::random().unwrap();
253        new_device.confirm();
254        phone.send(&seed, "Work", "{}").unwrap();
255        assert!(phone.send(&seed, "Work", "{}").is_err(), "single send");
256        let t = new_device.take().unwrap();
257        assert_eq!(t.seed, seed.0.to_vec());
258        assert_eq!(t.node_cert.peer_id, new_device.peer_id().to_string());
259        assert_eq!(new_device.status(), HostStatus::Done);
260    }
261
262    #[test]
263    fn a_service_link_moves_over_the_network_without_a_seed() {
264        let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "model node").unwrap();
265        let mut phone = Pairing::start(SCHEME, new_device.link(), dial_only()).unwrap();
266        let user = Keypair::generate_ed25519();
267        new_device.confirm();
268        // A large roster with epoch keys still fits one request.
269        let big = vec![7u8; crate::MAX_BUNDLE];
270        let cert = phone.send_credential(&user, "Work", "{}", &[], &big).unwrap();
271        assert!(phone.send_credential(&user, "Work", "{}", &[], &big).is_err(), "single send");
272        let Received::Service(c) = new_device.take_any().unwrap() else { panic!("expected a service link") };
273        assert_eq!(c.node_cert, cert);
274        assert_eq!(c.node_cert.peer_id, new_device.peer_id().to_string());
275        assert_eq!(c.bundle, big);
276    }
277
278    /// Over the internet through the WeirdBrains public relay, with no direct
279    /// address in the code at all: `cargo test -p weirdnet-device-link -- --ignored`.
280    #[test]
281    #[ignore = "needs the public relay"]
282    fn a_link_works_through_the_public_relay_alone() {
283        let relays: Vec<weirdnet_net::Multiaddr> = crate::KNOWN_RELAYS.iter().map(|a| a.parse().unwrap()).collect();
284        let cfg = NodeConfig { relays: relays.clone(), ..Default::default() };
285        let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), cfg.clone(), "Morph behind NAT").unwrap();
286        let offer = decode_link(SCHEME, new_device.link()).unwrap();
287        assert!(offer.offer.addrs.iter().all(|a| a.contains("/p2p-circuit")), "{:?}", offer.offer.addrs);
288        let mut phone = Pairing::start(SCHEME, new_device.link(), cfg).unwrap();
289        let HostStatus::Paired { sas } = new_device.status() else { panic!("not paired") };
290        assert_eq!(sas, phone.sas());
291        new_device.confirm();
292        phone.send(&Key32::random().unwrap(), "Work", "{}").unwrap();
293        assert!(new_device.take().is_ok());
294    }
295
296    #[test]
297    fn a_cancel_from_the_phone_ends_the_offer() {
298        let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "desk").unwrap();
299        let phone = Pairing::start(SCHEME, new_device.link(), dial_only()).unwrap();
300        phone.cancel().unwrap();
301        assert_eq!(new_device.status(), HostStatus::Cancelled);
302        assert!(matches!(Pairing::start(SCHEME, new_device.link(), dial_only()), Err(Error::Refused(_))));
303    }
304}