Skip to main content

vector_core/transfer/
service.rs

1//! The network side, and the one transfer a process runs at a time.
2//!
3//! A temporary client on the trusted relays carries the session, signing every event and every
4//! relay AUTH as a throwaway key, never the account. Progress reaches the page as `transfer_state`.
5//! The sender's page never sees the number: the user carries it from the new device's screen.
6
7use std::collections::HashSet;
8use crate::event_ext::FinalizeOnClock;
9use std::sync::{Arc, Mutex};
10use std::time::Duration;
11
12use futures_util::StreamExt;
13use nostr_sdk::prelude::*;
14use serde::Serialize;
15use tokio::sync::{mpsc, oneshot};
16
17use super::code::Code;
18use super::session::{ApproveError, Bundle, Failure, Out, Presentation, Role, Session};
19use super::wire::Msg;
20use crate::rt::time::{sleep_until, Instant};
21
22/// Ephemeral: relays pass it on without keeping it for long.
23pub const KIND: u16 = 24681;
24/// How long a shown code waits for the other device.
25const CODE_WINDOW: Duration = Duration::from_secs(5 * 60);
26/// How long a matched pair waits for the user to approve. PIN entry and Tor can be slow.
27const APPROVAL_WINDOW: Duration = Duration::from_secs(10 * 60);
28/// How long a receiver stays to answer a repeated bundle after it has the identity.
29const LINGER: Duration = Duration::from_secs(20);
30/// Gaps between repeats of a message the peer hasn't answered.
31const BACKOFF_SECS: [u64; 4] = [3, 6, 12, 15];
32/// Events older than the session by more than this are someone else's.
33const STALE_SECS: u64 = 120;
34
35enum Command {
36    CheckNumber(String, oneshot::Sender<Result<(), ApproveError>>),
37    Approve(Bundle, oneshot::Sender<Result<(), ApproveError>>),
38    Deny,
39    Cancel,
40}
41
42struct Active {
43    id: u64,
44    role: Role,
45    cmd: mpsc::UnboundedSender<Command>,
46    /// A sender's account. Approval refuses once it's no longer the one on screen.
47    owner: Option<Arc<crate::db::Session>>,
48}
49
50// Process-wide rather than on the session: a receiver has no account yet, and a sender's run
51// carries its own account in `owner`.
52static ACTIVE: Mutex<Option<Active>> = Mutex::new(None);
53/// The identity a receiver holds until it has signed in with it, and when it arrived.
54static RECEIVED: Mutex<Option<(u64, Bundle, Instant)>> = Mutex::new(None);
55/// How long an identity waits for its sign-in before it's wiped.
56const RECEIVED_TTL: Duration = Duration::from_secs(10 * 60);
57/// How often dropped relays get another try.
58const RECONNECT_EVERY: Duration = Duration::from_secs(10);
59/// Moved by every start and cancel, so a start that a newer one overtook installs nothing.
60static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
61
62fn next_id() -> u64 {
63    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
64    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
65}
66
67/// What the page is told, as `transfer_state`.
68#[derive(Serialize, Default)]
69struct UiState {
70    /// The transfer this belongs to, so the page ignores a session it has moved on from.
71    id: u64,
72    stage: &'static str,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    sas: Option<String>,
75    #[serde(skip_serializing_if = "Option::is_none")]
76    sender: Option<String>,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    name: Option<String>,
79    /// The sender's avatar, re-encoded here as a PNG data URL.
80    #[serde(skip_serializing_if = "Option::is_none")]
81    avatar: Option<String>,
82    #[serde(skip_serializing_if = "Option::is_none")]
83    error: Option<String>,
84    #[serde(skip_serializing_if = "std::ops::Not::not")]
85    unconfirmed: bool,
86}
87
88/// What `start` hands back: the transfer's id, and the code to display when this device shows it.
89pub struct Started {
90    pub id: u64,
91    pub code: Option<String>,
92    pub qr: Option<String>,
93}
94
95/// Begin a transfer. With `typed`, this device joins that code; without, it shows a new one once
96/// the relays are listening. A sender passes the identity it will hand over.
97pub async fn start(role: Role, typed: Option<&str>, identity: Option<PublicKey>) -> Result<Started, String> {
98    let code = match typed {
99        Some(t) => Code::parse(t)?,
100        None => Code::generate(),
101    };
102    let presentation = if typed.is_some() { Presentation::Joiner } else { Presentation::Shower };
103    if role == Role::Sender && identity.is_none() {
104        return Err("This account has no key on this device to move".to_string());
105    }
106    let generation = GENERATION.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
107    stop_active();
108    let id = next_id();
109    let (cmd, cmds) = mpsc::unbounded_channel();
110    let (ready_tx, ready_rx) = oneshot::channel();
111    let owner = (role == Role::Sender).then(crate::db::current_session);
112    let face = match identity {
113        Some(pk) if role == Role::Sender => own_face(pk).await,
114        _ => (None, None),
115    };
116    {
117        let mut active = ACTIVE.lock().unwrap();
118        if GENERATION.load(std::sync::atomic::Ordering::SeqCst) != generation {
119            return Err("A newer transfer replaced this one".to_string());
120        }
121        if let Some(previous) = active.replace(Active { id, role, cmd, owner: owner.clone() }) {
122            let _ = previous.cmd.send(Command::Cancel);
123        }
124    }
125    // spawn-detached: a receiver has no account yet; a sender's run checks `owner` before acting.
126    crate::rt::spawn(run(id, role, presentation, code.clone(), identity, face, cmds, ready_tx, owner));
127    match ready_rx.await {
128        Ok(Ok(())) => Ok(match presentation {
129            Presentation::Shower => Started { id, code: Some(code.canonical().to_string()), qr: Some(code.qr().to_string()) },
130            Presentation::Joiner => Started { id, code: None, qr: None },
131        }),
132        Ok(Err(e)) => Err(e),
133        Err(_) => Err("The transfer stopped before it began".to_string()),
134    }
135}
136
137/// This device's name and a thumbnail of its cached avatar, for the new device's screen.
138async fn own_face(pk: PublicKey) -> (Option<String>, Option<Vec<u8>>) {
139    let Ok(npub) = pk.to_bech32();
140    let (name, cached) = {
141        let state = crate::STATE.lock().await;
142        match state.get_profile(&npub) {
143            Some(p) => {
144                let name = if p.display_name().trim().is_empty() { p.name().trim() } else { p.display_name().trim() };
145                ((!name.is_empty()).then(|| name.to_string()), p.avatar_cached().into_owned())
146            }
147            None => (None, String::new()),
148        }
149    };
150    // An avatar file this large isn't one Vector cached; skip it rather than decode it.
151    const MAX_SOURCE: usize = 8 * 1024 * 1024;
152    let source = match cached.is_empty() {
153        true => None,
154        false => crate::files::read(std::path::Path::new(&cached)).await.ok().filter(|b| b.len() <= MAX_SOURCE),
155    };
156    let avatar = match source {
157        Some(bytes) => crate::rt::spawn_blocking(move || super::avatar::thumbnail(&bytes)).await.ok().flatten(),
158        None => None,
159    };
160    (name, avatar)
161}
162
163fn command(make: impl FnOnce() -> Command) -> Result<(), String> {
164    let guard = ACTIVE.lock().unwrap();
165    let active = guard.as_ref().ok_or("No transfer is running")?;
166    active.cmd.send(make()).map_err(|_| "The transfer has ended".to_string())
167}
168
169fn active_role() -> Option<Role> {
170    ACTIVE.lock().unwrap().as_ref().map(|a| a.role)
171}
172
173/// Sender: is this the number on the new device's screen?
174pub async fn check_number(typed: &str) -> Result<(), ApproveError> {
175    if active_role() != Some(Role::Sender) {
176        return Err(ApproveError::NotReady);
177    }
178    let (tx, rx) = oneshot::channel();
179    let typed = typed.to_string();
180    command(|| Command::CheckNumber(typed, tx)).map_err(|_| ApproveError::NotReady)?;
181    rx.await.unwrap_or(Err(ApproveError::NotReady))
182}
183
184/// Whether a sender's transfer may still hand over: its account is the one on screen.
185pub fn sender_is_current() -> bool {
186    matches!(ACTIVE.lock().unwrap().as_ref(), Some(Active { role: Role::Sender, owner: Some(owner), .. }) if owner.is_live())
187}
188
189/// Sender: hand the identity over. The host has already proven the user and opened the key.
190pub async fn approve(bundle: Bundle) -> Result<(), ApproveError> {
191    if !sender_is_current() {
192        return Err(ApproveError::NotReady);
193    }
194    let (tx, rx) = oneshot::channel();
195    command(|| Command::Approve(bundle, tx)).map_err(|_| ApproveError::NotReady)?;
196    rx.await.unwrap_or(Err(ApproveError::NotReady))
197}
198
199pub fn deny() {
200    let _ = command(|| Command::Deny);
201}
202
203/// Stop whatever transfer is running and forget anything it received.
204pub fn cancel() {
205    GENERATION.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
206    stop_active();
207}
208
209fn stop_active() {
210    // Under the ACTIVE lock, so an identity arriving for the run being stopped can't land after this.
211    let mut active = ACTIVE.lock().unwrap();
212    if let Some(previous) = active.take() {
213        let _ = previous.cmd.send(Command::Cancel);
214    }
215    RECEIVED.lock().unwrap().take();
216}
217
218/// Receiver: the identity that arrived. It stays held until [`forget_received`], so a sign-in
219/// that fails can be tried again.
220pub fn received() -> Option<Bundle> {
221    let mut held = RECEIVED.lock().unwrap();
222    if held.as_ref().is_some_and(|(_, _, at)| at.elapsed() > RECEIVED_TTL) {
223        held.take();
224    }
225    held.as_ref().map(|(_, bundle, _)| bundle.clone())
226}
227
228/// Receiver: signed in with it; let it go.
229pub fn forget_received() {
230    RECEIVED.lock().unwrap().take();
231}
232
233#[cfg(test)]
234static TAP: Mutex<Vec<(u64, &'static str, serde_json::Value)>> = Mutex::new(Vec::new());
235
236fn emit(id: u64, mut state: UiState) {
237    state.id = id;
238    #[cfg(test)]
239    TAP.lock().unwrap().push((id, state.stage, serde_json::to_value(&state).unwrap()));
240    let current = ACTIVE.lock().unwrap().as_ref().map(|a| (a.id, a.owner.clone()));
241    match current {
242        Some((active, owner)) if active == id && owner.as_ref().is_none_or(|o| o.is_live()) => {
243            crate::traits::emit_event("transfer_state", &state);
244        }
245        _ => {}
246    }
247}
248
249fn finish(id: u64) {
250    let mut guard = ACTIVE.lock().unwrap();
251    if guard.as_ref().is_some_and(|a| a.id == id) {
252        guard.take();
253    }
254}
255
256fn explain(failure: &Failure) -> String {
257    match failure {
258        Failure::WrongCode => "The codes didn't match. Check the code and try again.".into(),
259        Failure::Contention => "Another device tried to use this code, so the transfer stopped. Start again with a new code.".into(),
260        Failure::RoleClash(Role::Sender) => "Both devices are signed in. On the new device, choose Sign in with another device on the sign in screen.".into(),
261        Failure::RoleClash(Role::Receiver) => "Neither device is signed in. On your signed-in device, open Settings and choose Sign in on another device.".into(),
262        Failure::Version => "The other device is running a different version of Vector. Update both and try again.".into(),
263        Failure::Denied => "The transfer was declined on your other device.".into(),
264        Failure::BadBundle => "The account didn't arrive intact, so nothing was saved. Try again.".into(),
265        Failure::WrongNumber => "The number was entered wrong too many times. Start again.".into(),
266        Failure::Protocol(_) => "Something went wrong between the devices. Try again.".into(),
267        Failure::PeerAborted(why) => match why.as_str() {
268            "code" => "The codes didn't match. Check the code and try again.".into(),
269            "contention" => "Another device tried to use this code, so the transfer stopped. Start again with a new code.".into(),
270            "role" => "Both devices are on the same side of the transfer. One must be signed in and the other new.".into(),
271            "number" => "The number was entered wrong too many times on your other device. Start again.".into(),
272            "timeout" => "Your other device stopped waiting. Start again.".into(),
273            _ => "The transfer was cancelled on your other device.".into(),
274        },
275    }
276}
277
278/// Signs relay AUTH as the throwaway key, never the account's.
279#[derive(Debug)]
280struct ThrowawayAuth(Keys);
281
282impl nostr_sdk::prelude::Authenticator for ThrowawayAuth {
283    fn make_auth_event<'a>(
284        &'a self,
285        relay_url: &'a RelayUrl,
286        challenge: &'a str,
287    ) -> crate::signer::BoxedFuture<'a, std::result::Result<Event, nostr_sdk::prelude::Error>> {
288        Box::pin(async move {
289            Ok(ClientAuthentication::new(challenge, relay_url.clone()).finalize_async(&self.0).await?)
290        })
291    }
292}
293
294struct Wire {
295    client: Client,
296    keys: Keys,
297    room: PublicKey,
298    /// Since when no publish has reached a relay. Reconnects get their full budget before this counts.
299    failing_since: Option<Instant>,
300}
301
302impl Wire {
303    /// Publish `msg`, signed fresh each time: relays refuse a repeat of an old event.
304    async fn publish(&mut self, msg: &Msg) {
305        let Ok(event) = EventBuilder::new(Kind::Custom(KIND), msg.encode()).tag(Tag::public_key(self.room)).finalize_on_clock(&self.keys) else {
306            return;
307        };
308        match crate::transport_aware(self.client.send_event(&event)).await {
309            Ok(out) if !out.success.is_empty() => self.failing_since = None,
310            _ => {
311                self.failing_since.get_or_insert_with(Instant::now);
312            }
313        }
314    }
315}
316
317struct Driver {
318    id: u64,
319    role: Role,
320    session: Session,
321    wire: Wire,
322    deadline: Instant,
323    backoff: usize,
324    retry_at: Option<Instant>,
325    ended: bool,
326    announced: Option<PublicKey>,
327}
328
329impl Driver {
330    fn emit(&self, state: UiState) {
331        emit(self.id, state);
332    }
333
334    fn fail(&mut self, error: impl Into<String>) {
335        self.emit(UiState { stage: "error", error: Some(error.into()), ..Default::default() });
336        self.ended = true;
337    }
338
339    async fn dispatch(&mut self, outs: Vec<Out>) {
340        let mut linger = false;
341        for out in outs {
342            match out {
343                Out::Send(msg) => {
344                    self.wire.publish(&msg).await;
345                    self.backoff = 0;
346                    self.retry_at = None;
347                }
348                Out::Resend => {
349                    if let Some(msg) = self.session.last_sent().cloned() {
350                        self.wire.publish(&msg).await;
351                    }
352                }
353                Out::Matched { sas, sender } => {
354                    self.deadline = Instant::now() + APPROVAL_WINDOW;
355                    self.announced = sender;
356                    match self.role {
357                        Role::Receiver => {
358                            let mut state = self.who();
359                            state.stage = "match";
360                            state.sas = Some(sas);
361                            self.emit(state);
362                        }
363                        Role::Sender => self.emit(UiState { stage: "approve", ..Default::default() }),
364                    }
365                }
366                Out::Received(bundle) => {
367                    let kept = {
368                        let active = ACTIVE.lock().unwrap();
369                        let ours = active.as_ref().is_some_and(|a| a.id == self.id);
370                        if ours {
371                            *RECEIVED.lock().unwrap() = Some((self.id, bundle, Instant::now()));
372                        }
373                        ours
374                    };
375                    if !kept {
376                        // Cancelled while it arrived: no ack, so the sender doesn't report success.
377                        let outs = self.session.abort("cancel");
378                        Box::pin(self.dispatch(outs)).await;
379                        self.ended = true;
380                        return;
381                    }
382                    let id = self.id;
383                    // spawn-detached: wipes a process-wide slot after its TTL, no account state.
384                    crate::rt::spawn(async move {
385                        crate::rt::time::sleep(RECEIVED_TTL).await;
386                        let mut held = RECEIVED.lock().unwrap();
387                        if held.as_ref().is_some_and(|(r, _, _)| *r == id) {
388                            held.take();
389                        }
390                    });
391                    let mut state = self.who();
392                    state.stage = "received";
393                    self.emit(state);
394                    linger = true;
395                }
396                Out::Acked => {
397                    self.emit(UiState { stage: "sent", ..Default::default() });
398                    self.ended = true;
399                }
400                Out::Failed(failure) => self.fail(explain(&failure)),
401            }
402        }
403        // Counted from after the ack's publish, which can take a while on Tor.
404        if linger {
405            self.deadline = Instant::now() + crate::relay_request_timeout(LINGER);
406        }
407    }
408
409    /// The sender as it announced itself: npub, name and re-encoded avatar.
410    fn who(&self) -> UiState {
411        let (name, avatar) = self.session.sender_face();
412        UiState {
413            sender: self.announced.and_then(|pk| pk.to_bech32().ok()),
414            name: name.map(str::to_string),
415            avatar: avatar.and_then(super::avatar::sanitize),
416            ..Default::default()
417        }
418    }
419
420    async fn command(&mut self, cmd: Option<Command>, owner: &Option<Arc<crate::db::Session>>) {
421        match cmd {
422            Some(Command::CheckNumber(typed, reply)) => {
423                let result = self.session.check_number(&typed);
424                let over = self.session.is_over();
425                let _ = reply.send(result);
426                if over {
427                    self.wire.publish(&Msg::Abort("number".to_string())).await;
428                    self.fail(explain(&Failure::WrongNumber));
429                }
430            }
431            Some(Command::Approve(bundle, reply)) => {
432                if owner.as_ref().is_some_and(|o| !o.is_live()) {
433                    let _ = reply.send(Err(ApproveError::NotReady));
434                    let outs = self.session.abort("cancel");
435                    self.dispatch(outs).await;
436                    self.ended = true;
437                    return;
438                }
439                match self.session.approve(bundle) {
440                    Ok(outs) => {
441                        let _ = reply.send(Ok(()));
442                        self.emit(UiState { stage: "sending", ..Default::default() });
443                        self.dispatch(outs).await;
444                        // Counted from after the publish, which on Tor can take most of a minute itself.
445                        self.deadline = Instant::now() + crate::relay_request_timeout(Duration::from_secs(30));
446                    }
447                    Err(e) => {
448                        let _ = reply.send(Err(e));
449                    }
450                }
451            }
452            Some(Command::Deny) => {
453                let outs = self.session.deny();
454                self.dispatch(outs).await;
455                // Nothing answers a denial, so it goes out twice rather than leave the receiver waiting.
456                if let Some(msg) = self.session.last_sent().cloned() {
457                    crate::rt::time::sleep(Duration::from_millis(1500)).await;
458                    self.wire.publish(&msg).await;
459                }
460                self.ended = true;
461            }
462            Some(Command::Cancel) | None => {
463                let outs = self.session.abort("cancel");
464                self.dispatch(outs).await;
465                self.ended = true;
466            }
467        }
468    }
469
470    async fn tick(&mut self) {
471        let now = Instant::now();
472        if self.retry_at.is_some_and(|r| r <= now) {
473            self.retry_at = None;
474            if self.session.awaiting_reply() {
475                if let Some(msg) = self.session.last_sent().cloned() {
476                    self.wire.publish(&msg).await;
477                }
478                self.backoff += 1;
479            }
480        }
481        let given_up = crate::relay_connect_timeout(Duration::from_secs(10)) + RECONNECT_EVERY * 2;
482        if self.wire.failing_since.is_some_and(|since| since.elapsed() > given_up) {
483            return self.fail("Lost the connection to the relays. Check your connection and that the device's clock is right.");
484        }
485        if now < self.deadline {
486            return;
487        }
488        let lingering = RECEIVED.lock().unwrap().as_ref().is_some_and(|(r, _, _)| *r == self.id) || self.session.is_over();
489        match self.role {
490            // The identity is held (or already used); the linger for a repeated bundle is over.
491            Role::Receiver if lingering => {}
492            // Sent, but no ack came back. It most likely arrived anyway.
493            Role::Sender if self.session.is_sent() => {
494                self.emit(UiState { stage: "sent", unconfirmed: true, ..Default::default() });
495            }
496            _ => {
497                let matched = self.session.is_matched();
498                let outs = self.session.abort("timeout");
499                self.dispatch(outs).await;
500                return self.fail(if matched {
501                    "Nothing happened for a while, so the transfer stopped. Start again when you're ready."
502                } else {
503                    "The code expired. Start again for a new one."
504                });
505            }
506        }
507        self.ended = true;
508    }
509}
510
511#[allow(clippy::too_many_arguments)]
512async fn run(
513    id: u64,
514    role: Role,
515    presentation: Presentation,
516    code: Code,
517    identity: Option<PublicKey>,
518    face: (Option<String>, Option<Vec<u8>>),
519    mut cmds: mpsc::UnboundedReceiver<Command>,
520    ready: oneshot::Sender<Result<(), String>>,
521    owner: Option<Arc<crate::db::Session>>,
522) {
523    let keys = Keys::generate();
524    let client = crate::apply_transport(
525        ClientBuilder::new().authenticator(ThrowawayAuth(keys.clone())),
526        crate::transport::Lane::Shared,
527    )
528    .build();
529    crate::transport::cycle::track(&client);
530    for url in crate::state::TRUSTED_RELAYS {
531        let _ = crate::ClientRelayExt::add_managed_relay(&client, *url).await;
532    }
533    client.connect().and_wait(crate::relay_connect_timeout(Duration::from_secs(10))).await;
534
535    let (mut session, first) = Session::new(role, presentation, &code, keys.public_key(), identity);
536    session.set_face(face.0, face.1);
537    drop(code);
538    let room = session.room();
539    let began = crate::clock::timestamp();
540    let mut notes = client.notifications();
541    let sub = client
542        .subscribe(Filter::new().kind(Kind::Custom(KIND)).pubkey(room).since(began - STALE_SECS))
543        .await
544        .ok()
545        .map(|o| o.value);
546
547    // Only a relay that has finished replaying what it kept is trusted to be live: those stored
548    // events are other, older sessions.
549    let mut live: HashSet<RelayUrl> = HashSet::new();
550    if let Some(sub) = &sub {
551        let deadline = Instant::now() + crate::relay_request_timeout(Duration::from_secs(8));
552        while live.is_empty() {
553            let next = tokio::select! {
554                n = notes.next() => n,
555                _ = sleep_until(deadline) => None,
556            };
557            let Some(note) = next else { break };
558            if let ClientNotification::Message { relay_url, message } = note {
559                if matches!(&*message, RelayMessage::EndOfStoredEvents(s) if **s == *sub) {
560                    live.insert(relay_url);
561                }
562            }
563        }
564    }
565    if live.is_empty() {
566        let _ = ready.send(Err("Couldn't reach the relays. Check your connection and try again.".to_string()));
567        finish(id);
568        client.shutdown().await;
569        return;
570    }
571    let _ = ready.send(Ok(()));
572
573    let mut d = Driver {
574        id,
575        role,
576        session,
577        wire: Wire { client: client.clone(), keys, room, failing_since: None },
578        deadline: Instant::now() + CODE_WINDOW,
579        backoff: 0,
580        retry_at: None,
581        ended: false,
582        announced: None,
583    };
584    d.dispatch(first).await;
585    let mut seen: HashSet<EventId> = HashSet::new();
586    let mut reconnect_at = Instant::now() + RECONNECT_EVERY;
587
588    while !d.ended {
589        if d.session.awaiting_reply() && d.retry_at.is_none() {
590            d.retry_at = Some(Instant::now() + Duration::from_secs(BACKOFF_SECS[d.backoff.min(BACKOFF_SECS.len() - 1)]));
591        }
592        let wake = d.retry_at.map_or(d.deadline, |r| r.min(d.deadline));
593        tokio::select! {
594            // A message already waiting beats a deadline that expired while it was in flight.
595            biased;
596            note = notes.next() => {
597                let Some(note) = note else { break };
598                match note {
599                    ClientNotification::Message { relay_url, message } => {
600                        if let (RelayMessage::EndOfStoredEvents(s), Some(sub)) = (&*message, &sub) {
601                            if **s == *sub {
602                                live.insert(relay_url);
603                            }
604                        }
605                    }
606                    ClientNotification::Event { relay_url, event, .. } => {
607                        let fresh = event.created_at.as_secs() + STALE_SECS >= began.as_secs();
608                        let ours = event.kind == Kind::Custom(KIND) && event.tags.public_keys().any(|p| p == room);
609                        // A relay replaying what it kept after a reconnect still counts for events
610                        // from this session's own lifetime; older ones belong to someone else.
611                        let replay_ok = event.created_at >= began;
612                        if (live.contains(&relay_url) || replay_ok) && fresh && ours && seen.insert(event.id) {
613                            let outs = d.session.on_message(event.pubkey, Msg::decode(&event.content));
614                            d.dispatch(outs).await;
615                        }
616                    }
617                    _ => {}
618                }
619            }
620            cmd = cmds.recv() => d.command(cmd, &owner).await,
621            _ = sleep_until(reconnect_at) => {
622                reconnect_at = Instant::now() + RECONNECT_EVERY;
623                for (url, relay) in client.relays().await {
624                    if matches!(relay.status(), RelayStatus::Disconnected | RelayStatus::Terminated) {
625                        // Live again only once it has replayed what it kept and sent a fresh EOSE.
626                        live.remove(&url);
627                        let client = client.clone();
628                        // spawn-detached: redials a relay of this transfer's own temporary client.
629                        crate::rt::spawn(async move {
630                            if relay.try_connect().timeout(crate::relay_connect_timeout(Duration::from_secs(10))).await.is_ok() {
631                                crate::resubscribe_relay_after_reconnect(&client, &url).await;
632                            }
633                        });
634                    }
635                }
636            }
637            _ = sleep_until(wake) => d.tick().await,
638        }
639    }
640
641    finish(id);
642    client.shutdown().await;
643}
644
645#[cfg(test)]
646mod tests {
647    use super::*;
648
649    async fn wait_for(id: u64, stage: &str) -> Option<serde_json::Value> {
650        for _ in 0..600 {
651            if let Some((_, _, state)) = TAP.lock().unwrap().iter().find(|(i, s, _)| *i == id && *s == stage) {
652                return Some(state.clone());
653            }
654            if let Some((_, _, state)) = TAP.lock().unwrap().iter().find(|(i, s, _)| *i == id && *s == "error") {
655                panic!("{id} failed: {state}");
656            }
657            crate::rt::time::sleep(Duration::from_millis(100)).await;
658        }
659        None
660    }
661
662    /// Both sides over the real trusted relays, one process. `cargo test -p vector-core
663    /// transfer::service -- --ignored --nocapture`
664    #[tokio::test(flavor = "multi_thread")]
665    #[ignore]
666    async fn an_identity_crosses_the_live_relays() {
667        let identity = Keys::generate();
668        let code = Code::generate();
669        let (a, b) = (next_id(), next_id());
670        let (cmd_a, cmds_a) = mpsc::unbounded_channel();
671        let (_cmd_b, cmds_b) = mpsc::unbounded_channel();
672        let (ready_a, ready_rx_a) = oneshot::channel();
673        let (ready_b, ready_rx_b) = oneshot::channel();
674        let face = image::RgbaImage::from_fn(400, 300, |x, y| image::Rgba([x as u8, y as u8, 90, 255]));
675        let mut png = Vec::new();
676        image::DynamicImage::ImageRgba8(face).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
677        let thumb = super::super::avatar::thumbnail(&png).unwrap();
678        tokio::spawn(run(a, Role::Sender, Presentation::Shower, code.clone(), Some(identity.public_key()), (Some("Tester".into()), Some(thumb)), cmds_a, ready_a, None));
679        ready_rx_a.await.unwrap().unwrap();
680        // The receiver is the active transfer, as `start` makes it: an identity only lands for that one.
681        *ACTIVE.lock().unwrap() = Some(Active { id: b, role: Role::Receiver, cmd: _cmd_b.clone(), owner: None });
682        tokio::spawn(run(b, Role::Receiver, Presentation::Joiner, code, None, (None, None), cmds_b, ready_b, None));
683        ready_rx_b.await.unwrap().unwrap();
684
685        let matched = wait_for(b, "match").await.expect("receiver matched");
686        assert_eq!(matched["name"], "Tester");
687        assert!(matched["avatar"].as_str().is_some_and(|a| a.starts_with("data:image/png;base64,")), "avatar re-encoded as png");
688        let sas = matched["sas"].as_str().unwrap().to_string();
689        wait_for(a, "approve").await.expect("sender asked to approve");
690        let (tx, rx) = oneshot::channel();
691        cmd_a.send(Command::CheckNumber(sas, tx)).unwrap();
692        rx.await.unwrap().unwrap();
693        let (tx, rx) = oneshot::channel();
694        let nsec = identity.secret_key().to_bech32().unwrap();
695        cmd_a.send(Command::Approve(Bundle { nsec: nsec.clone(), seed: None }, tx)).unwrap();
696        rx.await.unwrap().unwrap();
697
698        wait_for(b, "received").await.expect("receiver got it");
699        wait_for(a, "sent").await.expect("sender heard the ack");
700        assert_eq!(RECEIVED.lock().unwrap().as_ref().map(|(i, bundle, _)| (*i, bundle.nsec.clone())), Some((b, nsec.clone())));
701        assert_eq!(received().map(|b| b.nsec.clone()).as_deref(), Some(nsec.as_str()), "held until signed in");
702        assert!(received().is_some(), "reading it doesn't use it up");
703        forget_received();
704        assert!(received().is_none());
705    }
706}