From 35b8caa716df6f705e12e378dc37ef2dee5ec235 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 00:54:16 -0400 Subject: [PATCH 1/7] feat(tui): ASCII chrome, invite wrap, alert truncate, remaining copy ONIONWIRE_ASCII (and NO_COLOR) switches truncation to ... and ASCII borders. Share/paste wrap at : so a mouse-copy cannot lose a mid-hex line. Alerts truncate to the frame; empty threads and paste errors keep the next-step hint. Skip the optional 40-row wordmark. --- docs/TUI.md | 60 ++++++++++++++++ src/tui.rs | 122 +++++++++++++++++++++++++++----- tests/tui_spec.rs | 173 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 337 insertions(+), 18 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 925d351..40e82e5 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -510,3 +510,63 @@ add it on this card. Preferred: depend on `unicode-width` explicitly and assert `tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three examples without adding a crate. + +## After frames (spacing / ASCII / wrap / copy) + +Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer, +1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged +here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line +header without buying hierarchy). + +### 80x24 — `draw_share` after (field-boundary wrap) + +Invite lines break on `:`. `sig=` hex that does not fit continues as an +all-hex line. Joining those lines (no extra spaces) is the original payload. + +``` +┌(o) invite────────────────────────────────────────────────────────────────────┐ +│give this string to a friend; they F3 paste it │ +│ │ +│fp ea4a6c63… │ +│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ +│ │ +│onionwire:v1: │ +│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │ +│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │ +│spk=0101010101010101010101010101010101010101010101010101010101010101: │ +│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│ +│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`) + +No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`. + +``` ++(o) invite--------------------------------------------------------------------+ +|give this string to a friend; they F3 paste it | +| | +|fp ea4a6c63... | +|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion | +| | +|onionwire:v1: | +|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: | +|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: | +|spk=0101010101010101010101010101010101010101010101010101010101010101: | +|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0| +|5401b0af934cefea617f71466f406af4bef956847200a8e915190b | ++------------------------------------------------------------------------------+ +``` + +### 80x24 / 120x40 — main chrome after + +Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump: + +``` +cargo test --locked --test tui_spec -- --nocapture dump_spec_frames +``` + +Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is +`no messages` / `type below, Enter sends`; paste error is `{err}` then +`Enter resubmits Esc back`; alerts truncate to the frame width. diff --git a/src/tui.rs b/src/tui.rs index 2ce2eab..20eb4b6 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -5,6 +5,7 @@ use std::time::Duration; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Modifier, Style}; +use ratatui::symbols::border; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; @@ -38,8 +39,90 @@ fn color_mode() -> ColorMode { } } +/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate. +pub fn ascii_chrome() -> bool { + std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some() +} + +const ASCII_BORDERS: border::Set = border::Set { + top_left: "+", + top_right: "+", + bottom_left: "+", + bottom_right: "+", + vertical_left: "|", + vertical_right: "|", + horizontal_top: "-", + horizontal_bottom: "-", +}; + fn ellipsis() -> &'static str { - "…" + if ascii_chrome() { "..." } else { "…" } +} + +/// Truncate or keep an alert so it cannot spill into the roster row. +pub fn alert_line(msg: &str, width: u16) -> String { + let mut text = msg.to_string(); + if color_mode() == ColorMode::None && !text.starts_with("! ") { + text = format!("! {text}"); + } + truncate_chars(&text, width as usize) +} + +/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation. +/// Joining the lines (no extra spaces) reconstructs `payload`. +pub fn wrap_invite(payload: &str, width: usize) -> String { + if width == 0 { + return String::new(); + } + let mut lines: Vec = Vec::new(); + let mut cur = String::new(); + let parts: Vec<&str> = payload.split(':').collect(); + for (i, part) in parts.iter().enumerate() { + let piece = if i + 1 < parts.len() { + format!("{part}:") + } else { + (*part).to_string() + }; + for chunk in char_chunks(&piece, width) { + if cur.is_empty() { + cur = chunk; + } else if char_len(&cur) + char_len(&chunk) <= width { + cur.push_str(&chunk); + } else { + lines.push(std::mem::take(&mut cur)); + cur = chunk; + } + } + } + if !cur.is_empty() { + lines.push(cur); + } + lines.join("\n") +} + +fn char_chunks(s: &str, width: usize) -> Vec { + if width == 0 { + return Vec::new(); + } + if char_len(s) <= width { + return vec![s.to_string()]; + } + let chars: Vec = s.chars().collect(); + chars.chunks(width).map(|c| c.iter().collect()).collect() +} + +/// Friend selected, no messages yet. +pub fn empty_friend_chat_text() -> &'static str { + "no messages\ntype below, Enter sends" +} + +/// Paste overlay copy. Error keeps the resubmit hint. +pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { + let hint = match err { + Some(e) => format!("{e}\nEnter resubmits Esc back"), + None => "paste onionwire:v1 payload, Enter to submit".to_string(), + }; + format!("{hint}\n\n{buf}") } fn char_len(s: &str) -> usize { @@ -1429,11 +1512,7 @@ impl App { f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); if let Some(msg) = &self.alert { - let text = if color_mode() == ColorMode::None && !msg.starts_with("! ") { - format!("! {msg}") - } else { - msg.clone() - }; + let text = alert_line(msg, area.width); f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); } @@ -1559,7 +1638,10 @@ impl App { ]; }; match self.node.list_messages(&friend.pubkey) { - Ok(msgs) if msgs.is_empty() => vec!["no messages".into()], + Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() + .lines() + .map(str::to_string) + .collect(), Ok(msgs) => msgs .iter() .map(|m| { @@ -1583,8 +1665,7 @@ impl App { } else { style_dim() }; - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(border) .title(title) .title_style(title_style) @@ -1699,9 +1780,17 @@ fn footer_hints(screen: &Screen) -> &'static str { } } +fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { + let block = block.borders(Borders::ALL); + if ascii_chrome() { + block.border_set(ASCII_BORDERS) + } else { + block + } +} + fn themed_block(title: &str) -> Block<'_> { - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(style_accent()) .title(title) .title_style(style_accent().add_modifier(Modifier::BOLD)) @@ -1712,8 +1801,10 @@ pub fn draw_share(f: &mut Frame, payload: &str) { Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion), Err(_) => ("?".into(), "?".into()), }; + let inner = f.area().width.saturating_sub(2) as usize; + let invite = wrap_invite(payload, inner.max(1)); let body = format!( - "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{payload}" + "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}" ); f.render_widget( Paragraph::new(body) @@ -1725,10 +1816,9 @@ pub fn draw_share(f: &mut Frame, payload: &str) { } fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) { - let hint = err - .unwrap_or("paste onionwire:v1 payload, Enter to submit") - .to_string(); - let body = format!("{hint}\n\n{buf}"); + let inner = f.area().width.saturating_sub(2) as usize; + let shown = wrap_invite(buf, inner.max(1)); + let body = paste_screen_text(&shown, err); let style = if err.is_some() { style_alert() } else { diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index b29270f..2310487 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,17 +1,21 @@ //! Spec implementation tests for docs/TUI.md (this card). //! Does not own `tests/tui_frames.rs` (PR #23). +use onionwire::qr; use onionwire::tui::{ - draw_text_overlay, help_overlay_text, main_footer_hints, main_header_line, roster_col_width, - status_footer, + alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text, + help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width, + status_footer, wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; use ratatui::backend::TestBackend; use ratatui::layout::{Constraint, Layout}; use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap}; +use std::sync::Mutex; const FP: &str = "abcdef0123456789deadbeefcafebabe"; +static ASCII_ENV: Mutex<()> = Mutex::new(()); const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String { @@ -179,6 +183,8 @@ fn reconstructed_main_keeps_send_failed_on_footer() { #[test] fn dump_spec_frames() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; for (w, h) in [(80u16, 24u16), (120, 40)] { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -205,5 +211,168 @@ fn dump_spec_frames() { .expect("draw"); println!("===== AFTER help {w}x{h} ====="); print!("{}", screen_from(terminal.backend().buffer(), w, h)); + + let invite = sample_invite(); + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + println!("===== AFTER share {w}x{h} ====="); + print!("{}", screen_from(terminal.backend().buffer(), w, h)); } } + +fn sample_invite() -> String { + let sk = [7u8; 32]; + qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") +} + +fn invite_line_ok(line: &str) -> bool { + let t = line.trim(); + t.is_empty() + || t.starts_with("onionwire:") + || t.starts_with("k=") + || t.starts_with("o=") + || t.starts_with("spk=") + || t.starts_with("sig=") + || t.chars().all(|c| c.is_ascii_hexdigit()) +} + +#[test] +fn alert_line_truncates_to_frame_width() { + let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped"; + let line = alert_line(long, 80); + assert!( + line.chars().count() <= 80, + "alert wider than 80: {} {line:?}", + line.chars().count() + ); + assert!( + line.contains('…') || line.contains("..."), + "long alert was not truncated: {line:?}" + ); + assert!( + !line.contains("roster on the next row"), + "alert still has overflow tail: {line:?}" + ); +} + +#[test] +fn wrap_invite_breaks_on_field_boundaries() { + let invite = sample_invite(); + assert!(invite.len() > 78, "fixture too short to wrap: {invite}"); + let wrapped = wrap_invite(&invite, 78); + for line in wrapped.lines() { + assert!( + line.chars().count() <= 78, + "invite line wider than 78: {} {line:?}", + line.chars().count() + ); + assert!( + invite_line_ok(line), + "invite wrapped mid-token: {line:?}\n{wrapped}" + ); + } + assert!( + wrapped.contains("onionwire:v1:"), + "lost invite prefix:\n{wrapped}" + ); + assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}"); + assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}"); + let joined: String = wrapped.lines().map(str::trim).collect(); + assert_eq!( + joined, invite, + "wrap must be newline-joinable back to payload" + ); +} + +#[test] +fn draw_share_invite_does_not_wrap_mid_token() { + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + assert!( + screen.contains("onionwire:v1:"), + "missing prefix:\n{screen}" + ); + for raw in screen.lines() { + let inner = raw.trim_start_matches(['│', '|', ' ']); + let inner = inner.trim_end_matches(['│', '|', ' ']); + if inner.starts_with("onionwire:") + || inner.starts_with("k=") + || inner.starts_with("o=") + || inner.starts_with("spk=") + || inner.starts_with("sig=") + || inner.chars().all(|c| c.is_ascii_hexdigit()) + { + assert!( + invite_line_ok(inner), + "share pane mid-token wrap: {inner:?}\n{screen}" + ); + } + if inner.starts_with('c') && inner.contains(":o=") { + panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}"); + } + } +} + +#[test] +fn empty_friend_chat_has_send_hint() { + let text = empty_friend_chat_text(); + assert!(text.contains("no messages"), "{text:?}"); + assert!(text.contains("type below, Enter sends"), "{text:?}"); +} + +#[test] +fn paste_error_keeps_resubmit_hint() { + let body = paste_screen_text("", Some("bad invite")); + assert!(body.contains("bad invite"), "{body:?}"); + assert!(body.contains("Enter resubmits"), "{body:?}"); + assert!(body.contains("Esc back"), "{body:?}"); + let ok = paste_screen_text("onionwire:v1:k=x", None); + assert!( + ok.contains("paste onionwire:v1 payload"), + "happy-path hint lost: {ok:?}" + ); +} + +#[test] +fn ascii_switch_80x24_frame_is_pure_ascii() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") }; + assert!( + ascii_chrome(), + "ONIONWIRE_ASCII set but ascii_chrome() is false" + ); + let footer = status_footer(80, FP, ONION, None, main_footer_hints()); + assert!( + footer.contains("..."), + "ASCII truncation marker missing: {footer:?}" + ); + assert!( + !footer.contains('…'), + "unicode ellipsis still in footer: {footer:?}" + ); + + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + let non_ascii: Vec = screen.chars().filter(|c| !c.is_ascii()).collect(); + assert!( + non_ascii.is_empty(), + "ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}" + ); + assert!( + screen.contains("..."), + "truncation marker missing from ASCII frame:\n{screen}" + ); + assert!( + screen.contains('+') && screen.contains('|') && screen.contains('-'), + "ASCII borders missing:\n{screen}" + ); + println!("===== AFTER ascii share 80x24 =====\n{screen}"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; +} From ad59a171b3353ce965b5defe1257884ecfeba501 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 13:35:10 -0400 Subject: [PATCH 2/7] feat(outbox): local retry queue for chat sends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Queue a chat send locally when the peer's v3 onion is unreachable and retry it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then terminal Failed). Still peer-to-peer: no server, no store-and-forward relay, no new frame prefix — every attempt is a fresh Noise IK handshake. - src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(), is_permanent_send_error(), background worker (15s scan). - store: `outbox` table (no body column — the body is read from the joined messages row, under that row's existing AEAD + AAD), append_message_id(), queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe. - Node::send() returns Result (Sent/Queued) instead of Err on transport failure; protocol errors still fail immediately and are never queued. - Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer was just seen" (handshake or connect_onion -> spawn_flush_friend). - File transfer and payment/rcp frames stay fail-closed. - docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements; add the seizure/cadence delta to the threat model. src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is child card t_d9a5b065. --- docs/PROTOCOL.md | 16 ++- docs/THREAT_MODEL.md | 17 ++- src/lib.rs | 1 + src/node.rs | 130 +++++++++++------- src/outbox.rs | 308 ++++++++++++++++++++++++++++++++++++++++++ src/session.rs | 10 ++ src/store.rs | 297 +++++++++++++++++++++++++++++++++++++++- src/tui.rs | 4 +- tests/outbox.rs | 312 +++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 1042 insertions(+), 53 deletions(-) create mode 100644 src/outbox.rs create mode 100644 tests/outbox.rs diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 6cda19e..e93943f 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -19,7 +19,7 @@ SOCKS proxy.” | Discovery | DHT + bootstrap nodes | Out-of-band invite only | | After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion | | Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator | -| Offline send | Expected (relays / retry) | Fail closed — no outbox | +| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) | | Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers | There is no directory, no name server, no introduction point of our own, and no @@ -51,8 +51,18 @@ not on the wire. 4. File transfer is N independent sessions (one handshake per chunk). There is no multiplexed long-lived stream in v1. -If the onion is down, send fails. No retry queue except the locator-push path, -which retries for 180 seconds and then gives up. +If the onion is down, a **chat** send is persisted to the local outbox and +retried by a background worker with exponential backoff (30s, doubling, capped +at 30 min; 8 attempts, then terminal `Failed`). There is no server and no +store-and-forward relay: each attempt is a fresh handshake straight to +`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on +unlock/foreground, and whenever that peer is heard from (successful handshake or +`connect_onion()`). A protocol failure — signature mismatch, unknown frame, +oversize — is not a transport failure and is never queued. + +File transfer and payment frames stay fail-closed: they are one-shot and are +**not** queued. The locator-push path still retries for 180 seconds and then +gives up. Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10. Excess is dropped before handshake. That is availability, not anonymity. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9773e46..96252eb 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -24,7 +24,16 @@ Identity secret key, friend public keys, and locators remain plaintext in the sa ## Fail closed -Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor. +Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor. + +## Local outbox (chat retry queue) is local, and it re-dials on a schedule + +A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted: + +- **Device seizure.** A pending (never-delivered) message sits in the same db as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure with the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase. +- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure. + +The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever. ## Profile is friend-visible, not a directory @@ -65,5 +74,7 @@ the peer already knows the plaintext they sent. ## Out of v1 -Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, -sqlcipher, A/V. +Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward +relay, multi-device, DHT / name server, sqlcipher, A/V. The local retry queue of +the previous section is not an outbox in the XMPP sense: it never leaves the +device. diff --git a/src/lib.rs b/src/lib.rs index ea6dba2..9d9eb7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod frame; pub mod hs; pub mod loc; pub mod node; +pub mod outbox; pub mod pay; pub mod profile; pub mod qr; diff --git a/src/node.rs b/src/node.rs index 97745a2..9c3e931 100644 --- a/src/node.rs +++ b/src/node.rs @@ -14,6 +14,7 @@ use crate::file; use crate::frame; use crate::hs::{self, Client, HS_PORT}; use crate::loc; +use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; use crate::profile; use crate::qr; @@ -39,9 +40,18 @@ impl Drop for HsHandle { } } +/// Abort the outbox worker when the node goes away. +struct WorkerHandle(tokio::task::JoinHandle<()>); + +impl Drop for WorkerHandle { + fn drop(&mut self) { + self.0.abort(); + } +} + pub struct Node { home: PathBuf, - store: Mutex, + store: Arc>, client: Client, hs: Mutex>, onion: Mutex, @@ -49,6 +59,8 @@ pub struct Node { wallet: Wallet, incoming_limit: Mutex, inbox: Mutex, + outbox: Arc, + _outbox_worker: WorkerHandle, } impl Node { @@ -79,9 +91,17 @@ impl Node { let (svc, rend) = launched; let onion = hs::onion_string(&svc)?; let inbox = file::Inbox::new(home.join("inbox")); + let store = Arc::new(Mutex::new(store)); + let outbox = Arc::new(Outbox::new( + Arc::clone(&store), + Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())), + )); + if let Err(e) = outbox.reset_stale() { + eprintln!("outbox: {e}"); + } let node = Arc::new(Self { home, - store: Mutex::new(store), + store, client, hs: Mutex::new(None), onion: Mutex::new(onion.clone()), @@ -89,7 +109,12 @@ impl Node { wallet: Wallet::from_env(), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), + outbox: Arc::clone(&outbox), + _outbox_worker: WorkerHandle(outbox.spawn_worker()), }); + // Unlock trigger: flush anything queued by a previous run now, in the + // background, rather than waiting out its backoff. + spawn_flush_all(Arc::clone(&node.outbox)); // Accept rens before waiting so a reachability probe can succeed // while combined status is still Bootstrapping. let rend = spawn_rend(Arc::clone(&node), rend); @@ -416,6 +441,8 @@ impl Node { self.try_send(&onion, friend_pk, &prekey, plaintext).await } + /// Dial a peer's onion. Success is evidence the peer is up, which is one of + /// the outbox retry triggers. pub async fn connect_onion(&self, onion: &str) -> Result<(), String> { tokio::time::timeout( Duration::from_secs(20), @@ -424,6 +451,14 @@ impl Node { .await .map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))? .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; + if let Ok(Some(friend)) = self + .store + .lock() + .map_err(|e| e.to_string()) + .and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string())) + { + spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey); + } Ok(()) } @@ -506,36 +541,30 @@ impl Node { Ok(name) } - pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { - let (onion, prekey) = { - let store = self.store.lock().map_err(|e| e.to_string())?; - let f = store - .get_friend(friend_pk) - .map_err(|e| e.to_string())? - .ok_or_else(|| "unknown friend".to_string())?; - if f.prekey.len() != 32 { - return Err("friend missing prekey".into()); - } - (f.onion, f.prekey) - }; - let deadline = Instant::now() + Duration::from_secs(180); - let mut last = None::; - while Instant::now() < deadline { - match self.try_send(&onion, friend_pk, &prekey, plaintext).await { - Ok(()) => { - self.store - .lock() - .map_err(|e| e.to_string())? - .append_message(friend_pk, "out", plaintext) - .map_err(|e| e.to_string())?; - return Ok(()); - } - Err(e) if e.contains("fingerprint mismatch") => return Err(e), - Err(e) => last = Some(e), - } - tokio::time::sleep(Duration::from_secs(3)).await; - } - Err(last.unwrap_or_else(|| "send timed out".into())) + /// Send one chat message. Returns `Sent` when it went out now and `Queued` + /// when the peer's onion is unreachable — the outbox worker then retries with + /// backoff. A real protocol error (signature mismatch, unknown/short/oversize + /// frame) still fails immediately and is never retried. + pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.outbox.send(friend_pk, plaintext).await + } + + /// Pending and failed outbox rows for a friend, for UI surfacing. + /// Delivered rows are dropped, so a message absent here was sent. + pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result, String> { + self.outbox.pending(friend_pk) + } + + pub fn outbox_status_of_message( + &self, + message_id: i64, + ) -> Result, String> { + self.outbox.status_of_message(message_id) + } + + /// Foreground/unlock trigger: try every outstanding queued send now. + pub fn flush_outbox(&self) { + spawn_flush_all(Arc::clone(&self.outbox)); } async fn push_loc( @@ -568,20 +597,10 @@ impl Node { remote_prekey: &[u8], plaintext: &[u8], ) -> Result<(), String> { - let mut stream = self - .client - .connect((onion, HS_PORT)) + self.outbox + .deliverer() + .deliver(onion, pinned_id, remote_prekey, plaintext) .await - .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; - let keys = self.keys()?; - let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey) - .await - .map_err(session_err)?; - let ct = sess.encrypt(plaintext).map_err(session_err)?; - frame::write_frame(&mut stream, &ct) - .await - .map_err(|e| e.to_string())?; - Ok(()) } async fn handle_incoming(&self, stream: &mut S) -> Result<(), String> @@ -598,6 +617,9 @@ impl Node { }) .await .map_err(session_err)?; + // Trigger (c): the peer just proved they are online. Try their queued + // sends now instead of waiting out the backoff, off this stream's path. + spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone()); let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?; let pt = sess.decrypt(&ct).map_err(session_err)?; match dispatch::classify(&pt) { @@ -814,6 +836,24 @@ fn spawn_rend( }) } +/// Foreground/unlock flush: every outstanding queued send gets one attempt now. +fn spawn_flush_all(outbox: Arc) { + tokio::spawn(async move { + if let Err(e) = outbox.flush_all(unix_now()).await { + eprintln!("outbox: {e}"); + } + }); +} + +/// We just saw this peer (handshake or successful dial): try their queue now. +fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { + tokio::spawn(async move { + if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await { + eprintln!("outbox: {e}"); + } + }); +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") diff --git a/src/outbox.rs b/src/outbox.rs new file mode 100644 index 0000000..495e63e --- /dev/null +++ b/src/outbox.rs @@ -0,0 +1,308 @@ +//! Local-only outbox. +//! +//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and +//! retried by a background worker with exponential backoff. There is no server +//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake +//! straight to the friend's onion, so a queued message is never handed to a +//! third party. File transfer and payment frames stay fail-closed — only chat +//! goes through here. + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use tokio::sync::Notify; + +use crate::frame; +use crate::hs::{Client, HS_PORT}; +use crate::session::{self, Keys}; +use crate::store::Store; + +pub use crate::store::{OutboxEntry, OutboxStatus}; + +/// First retry waits this long. +pub const BACKOFF_START_SECS: i64 = 30; +/// Backoff never sleeps longer than this. +pub const BACKOFF_CAP_SECS: i64 = 1_800; +/// Attempts after which a queued message is terminally `Failed`. +pub const DEFAULT_MAX_ATTEMPTS: u32 = 8; +/// Worker scan period. The shortest backoff is 30s, so a slower scan still +/// lands each retry close to its schedule without busy-waiting. +pub const WORKER_TICK: Duration = Duration::from_secs(15); +/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the +/// worker. +const MAX_PER_PASS: i64 = 32; + +pub type BoxFut<'a, T> = Pin + Send + 'a>>; + +/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s… +/// capped at 30 min. `attempt` is the number of retries already made. +pub fn backoff_secs(attempt: u32) -> i64 { + // 30 << 16 is the largest shift we ever need to reach the cap, so this + // cannot overflow even for a silly attempt count. + (BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS) +} + +/// Protocol failures: another attempt cannot fix a bad signature, a bad frame +/// header, or an oversize payload, so they must fail loudly and never queue. +const PERMANENT_ERRORS: &[&str] = &[ + "fingerprint mismatch", + "bad identity proof", + "unexpected handshake payload", + "frame too large", + "bad version", + "length mismatch", + "short frame", +]; + +pub fn is_permanent_send_error(err: &str) -> bool { + PERMANENT_ERRORS.iter().any(|p| err.contains(p)) +} + +/// One delivery attempt. Implemented by Arti for real sends and by tests for a +/// fake or flaky peer. +pub trait Deliverer: Send + Sync { + fn deliver<'a>( + &'a self, + onion: &'a str, + pinned_id: &'a [u8], + prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>>; +} + +/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's +/// identity key, send exactly one application frame, drop the circuit. +pub struct ArtiDeliverer { + client: Client, + keys: Keys, +} + +impl ArtiDeliverer { + pub fn new(client: Client, keys: Keys) -> Self { + Self { client, keys } + } +} + +impl Deliverer for ArtiDeliverer { + fn deliver<'a>( + &'a self, + onion: &'a str, + pinned_id: &'a [u8], + prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + Box::pin(async move { + let mut stream = self + .client + .connect((onion, HS_PORT)) + .await + .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; + let mut sess = + session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey) + .await + .map_err(|e| e.into_message())?; + let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?; + frame::write_frame(&mut stream, &ct) + .await + .map_err(|e| e.to_string())?; + Ok(()) + }) + } +} + +pub struct Outbox { + store: Arc>, + deliverer: Arc, + max_attempts: u32, + wake: Notify, +} + +impl Outbox { + pub fn new(store: Arc>, deliverer: Arc) -> Self { + Self { + store, + deliverer, + max_attempts: DEFAULT_MAX_ATTEMPTS, + wake: Notify::new(), + } + } + + pub fn with_max_attempts(mut self, max: u32) -> Self { + self.max_attempts = max.max(1); + self + } + + /// The transport, for callers (locator/profile pushes) that stay fail-closed + /// and must not queue. + pub fn deliverer(&self) -> &dyn Deliverer { + self.deliverer.as_ref() + } + + /// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is + /// unreachable, the message is persisted and will be retried. `Err` — a + /// protocol error or a bad local state, never retried. + pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + let (onion, prekey) = self.target(friend_pk)?; + match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await { + Ok(()) => { + self.store()?.append_message(friend_pk, "out", plaintext)?; + Ok(OutboxStatus::Sent) + } + Err(e) if is_permanent_send_error(&e) => Err(e), + Err(e) => { + let now = unix_now(); + let store = self.store()?; + let message_id = store.append_message_id(friend_pk, "out", plaintext)?; + store.enqueue_outbox( + friend_pk, + message_id, + 1, + now + backoff_secs(0), + &e, + now, + )?; + Ok(OutboxStatus::Queued) + } + } + } + + /// Timer trigger: every row whose backoff has elapsed gets one attempt. + pub async fn tick(&self, now: i64) -> Result, String> { + let due = self.store()?.due_outbox(now, MAX_PER_PASS)?; + self.attempt(due, now).await + } + + /// Unlock / foreground trigger: every outstanding row gets one attempt now, + /// regardless of where it sits in the backoff. + pub async fn flush_all(&self, now: i64) -> Result, String> { + let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?; + self.attempt(rows, now).await + } + + /// Trigger (c): we just heard from this peer, so try their rows immediately. + pub async fn flush_friend( + &self, + friend_pk: &[u8], + now: i64, + ) -> Result, String> { + let rows = self.store()?.outbox_for_friend(friend_pk)?; + self.attempt(rows, now).await + } + + /// Pending and failed rows for one friend. Delivered rows are deleted, so a + /// message that is not here was either sent first try or flushed since. + pub fn pending(&self, friend_pk: &[u8]) -> Result, String> { + self.store()?.pending_outbox(friend_pk).map_err(store_err) + } + + pub fn status_of_message(&self, message_id: i64) -> Result, String> { + self.store()? + .outbox_status_of_message(message_id) + .map_err(store_err) + } + + /// A process that died mid-attempt leaves `sending` rows behind; requeue + /// them on unlock so they are retried instead of stranded. + pub fn reset_stale(&self) -> Result { + self.store()?.reset_sending_outbox().map_err(store_err) + } + + /// Wake the worker (e.g. after `flush_all` was queued from a UI thread). + pub fn kick(&self) { + self.wake.notify_one(); + } + + /// Background retry worker. Aborted by dropping the returned handle. + pub fn spawn_worker(self: &Arc) -> tokio::task::JoinHandle<()> { + let me = Arc::clone(self); + tokio::spawn(async move { + loop { + if let Err(e) = me.tick(unix_now()).await { + eprintln!("outbox: {e}"); + } + tokio::select! { + _ = tokio::time::sleep(WORKER_TICK) => {} + _ = me.wake.notified() => {} + } + } + }) + } + + async fn attempt( + &self, + rows: Vec, + now: i64, + ) -> Result, String> { + let mut out = Vec::with_capacity(rows.len()); + for entry in rows { + self.store()?.mark_outbox_sending(entry.id, now)?; + let (onion, prekey) = match self.target(&entry.friend_pk) { + Ok(t) => t, + Err(e) => { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + out.push((entry.id, OutboxStatus::Failed(e))); + continue; + } + }; + let result = self + .deliverer + .deliver(&onion, &entry.friend_pk, &prekey, &entry.body) + .await; + let status = match result { + Ok(()) => { + self.store()?.mark_outbox_sent(entry.id)?; + OutboxStatus::Sent + } + Err(e) if is_permanent_send_error(&e) => { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + OutboxStatus::Failed(e) + } + Err(e) => { + let attempts = entry.attempts.saturating_add(1); + if attempts >= self.max_attempts { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + OutboxStatus::Failed(e) + } else { + let next = now + backoff_secs(attempts - 1); + self.store()? + .mark_outbox_retry(entry.id, attempts, next, now, &e)?; + OutboxStatus::Queued + } + } + }; + out.push((entry.id, status)); + } + Ok(out) + } + + /// Friend's current locator + Noise static. Missing prekey means the invite + /// was never completed — retrying cannot fix that, so it is fatal. + fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec), String> { + let store = self.store()?; + let f = store + .get_friend(friend_pk) + .map_err(store_err)? + .ok_or_else(|| "unknown friend".to_string())?; + if f.prekey.len() != 32 { + return Err("friend missing prekey".into()); + } + Ok((f.onion, f.prekey)) + } + + fn store(&self) -> Result, String> { + self.store.lock().map_err(|e| e.to_string()) + } +} + +fn store_err(e: crate::store::Error) -> String { + e.to_string() +} + +fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} diff --git a/src/session.rs b/src/session.rs index e5e21b6..611e8c1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -35,6 +35,16 @@ impl Error { pub fn is_fingerprint_mismatch(&self) -> bool { self.mismatch } + + /// String for the UI: a pinned-identity mismatch gets the documented banner, + /// everything else is the underlying snow/framing message. + pub fn into_message(self) -> String { + if self.mismatch { + crate::tui::fingerprint_mismatch_banner().to_string() + } else { + self.msg + } + } } impl std::fmt::Display for Error { diff --git a/src/store.rs b/src/store.rs index 1be94f3..c8a8e9b 100644 --- a/src/store.rs +++ b/src/store.rs @@ -40,6 +40,15 @@ impl From for Error { } } +/// The store error is a message and nothing else, and the rest of the crate +/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the +/// outbox boundary — no per-call `map_err`. +impl From for String { + fn from(e: Error) -> Self { + e.0 + } +} + pub struct Store { conn: Connection, msg_key: [u8; 32], @@ -88,6 +97,64 @@ pub struct Payment { pub created_at: i64, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OutboxStatus { + Queued, + Sending, + Sent, + /// Terminal: transport or protocol failure that will not be retried. + Failed(String), +} + +impl OutboxStatus { + pub fn is_terminal(&self) -> bool { + matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_)) + } + + /// Column encoding for the `outbox.status` CHECK constraint. + pub fn as_db_str(&self) -> &'static str { + match self { + OutboxStatus::Queued => "queued", + OutboxStatus::Sending => "sending", + OutboxStatus::Sent => "sent", + OutboxStatus::Failed(_) => "failed", + } + } + + pub fn from_db(status: &str, last_error: Option<&str>) -> Self { + match status { + "sending" => OutboxStatus::Sending, + "sent" => OutboxStatus::Sent, + "failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()), + _ => OutboxStatus::Queued, + } + } +} + +impl std::fmt::Display for OutboxStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + OutboxStatus::Failed(why) => write!(f, "failed: {why}"), + other => f.write_str(other.as_db_str()), + } + } +} + +/// One queued chat send. The body is not copied: it lives in the `messages` +/// row the outbox row points at, under that row's own AEAD. +#[derive(Debug, Clone)] +pub struct OutboxEntry { + pub id: i64, + pub friend_pk: Vec, + pub message_id: i64, + pub body: Vec, + pub attempts: u32, + pub next_attempt_at: i64, + pub created_at: i64, + pub status: OutboxStatus, + pub last_error: Option, +} + pub struct PaymentWrite<'a> { pub dir: &'a str, pub kind: &'a str, @@ -189,6 +256,18 @@ impl Store { verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); + CREATE TABLE IF NOT EXISTS outbox ( + id INTEGER PRIMARY KEY, + friend_id INTEGER NOT NULL REFERENCES friends(id), + message_id INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + next_attempt_at INTEGER NOT NULL, + status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')), + last_error TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at); INSERT OR IGNORE INTO self_profile (id) VALUES (1); ", )?; @@ -475,6 +554,20 @@ impl Store { .map_err(Into::into) } + /// Locator → friend. Onions are not unique in the schema (a stale row can + /// hold a rotated address), so the first match wins; the outbox uses this + /// only to pick which queue to flush early. + pub fn friend_by_onion(&self, onion: &str) -> Result> { + self.conn + .query_row( + "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1", + params![onion], + friend_from_row, + ) + .optional() + .map_err(Into::into) + } + pub fn list_friends(&self) -> Result> { let mut stmt = self.conn.prepare( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends @@ -699,6 +792,17 @@ impl Store { } pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> { + self.append_message_id(friend_pk, dir, plaintext).map(|_| ()) + } + + /// Same as `append_message`, returning the row id so an outbox row can + /// point at the body instead of storing a second copy. + pub fn append_message_id( + &self, + friend_pk: &[u8], + dir: &str, + plaintext: &[u8], + ) -> Result { if dir != "in" && dir != "out" { return Err(Error("dir must be in or out".into())); } @@ -723,7 +827,7 @@ impl Store { params![blob, row_id], )?; tx.commit()?; - Ok(()) + Ok(row_id) } pub fn list_messages(&self, friend_pk: &[u8]) -> Result> { @@ -752,9 +856,194 @@ impl Store { Ok(out) } + /// Queue one already-stored chat message for retry. `next_attempt_at` is an + /// absolute unix second; `now` is used for created_at/updated_at so the + /// caller and the row agree on the clock. + pub fn enqueue_outbox( + &self, + friend_pk: &[u8], + message_id: i64, + attempts: u32, + next_attempt_at: i64, + last_error: &str, + now: i64, + ) -> Result { + let friend_id: i64 = self + .conn + .query_row( + "SELECT id FROM friends WHERE pubkey = ?1", + params![friend_pk], + |row| row.get(0), + ) + .map_err(|_| Error("friend not found".into()))?; + self.conn.execute( + "INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)", + params![friend_id, message_id, attempts, next_attempt_at, last_error, now], + )?; + Ok(self.conn.last_insert_rowid()) + } + + /// Rows whose backoff has elapsed: the timer trigger for the worker. + pub fn due_outbox(&self, now: i64, limit: i64) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1 + ORDER BY o.next_attempt_at, o.id LIMIT ?2" + ), + params![now, limit], + ) + } + + /// Unscheduleable rows for one friend (queued or mid-attempt): the + /// "we just heard from this peer" trigger, which ignores the backoff. + pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending') + ORDER BY o.id" + ), + params![friend_pk], + ) + } + + /// Every row the worker may still try: the unlock/foreground trigger. + pub fn all_pending_outbox(&self, limit: i64) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE o.status IN ('queued','sending') + ORDER BY o.next_attempt_at, o.id LIMIT ?1" + ), + params![limit], + ) + } + + /// Pending and failed rows for one friend — what a UI shows as not-yet-sent. + /// Delivered rows are deleted, so absence means "sent". + pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed') + ORDER BY o.id" + ), + params![friend_pk], + ) + } + + pub fn outbox_status_of_message(&self, message_id: i64) -> Result> { + let row: Option<(String, Option)> = self + .conn + .query_row( + "SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1", + params![message_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref()))) + } + + pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2", + params![now, id], + )?; + Ok(()) + } + + /// Delivered. The row is dropped — the chat history is the record, and a + /// per-message status table would grow without bound. + pub fn mark_outbox_sent(&self, id: i64) -> Result<()> { + self.conn + .execute("DELETE FROM outbox WHERE id = ?1", params![id])?; + Ok(()) + } + + pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3", + params![why, now, id], + )?; + Ok(()) + } + + pub fn mark_outbox_retry( + &self, + id: i64, + attempts: u32, + next_attempt_at: i64, + now: i64, + why: &str, + ) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5", + params![attempts, next_attempt_at, why, now, id], + )?; + Ok(()) + } + + /// A row left in 'sending' means we died mid-attempt. Requeue on unlock. + pub fn reset_sending_outbox(&self) -> Result { + let n = self.conn.execute( + "UPDATE outbox SET status = 'queued' WHERE status = 'sending'", + [], + )?; + Ok(n) + } + + fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { + let mut stmt = self.conn.prepare(sql)?; + let rows = stmt.query_map(args, |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, Vec>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, i64>(3)?, + row.get::<_, i64>(4)?, + row.get::<_, String>(5)?, + row.get::<_, Option>(6)?, + row.get::<_, i64>(7)?, + row.get::<_, i64>(8)?, + row.get::<_, String>(9)?, + row.get::<_, Vec>(10)?, + )) + })?; + let mut out = Vec::new(); + for row in rows { + let ( + id, + friend_pk, + message_id, + attempts, + next_attempt_at, + status, + last_error, + created_at, + m_friend_id, + dir, + blob, + ) = row?; + let aad = message_aad(m_friend_id, &dir, message_id); + let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) + .map_err(|_| Error("outbox body decrypt failed".into()))?; + out.push(OutboxEntry { + id, + friend_pk, + message_id, + body, + attempts: attempts as u32, + next_attempt_at, + created_at, + status: OutboxStatus::from_db(&status, last_error.as_deref()), + last_error, + }); + } + Ok(out) + } + /// Drop chat + payments history. Identity + friends stay. /// Not a forensic erase: SSD wear-leveling can keep copies. pub fn wipe_messages(&self) -> Result<()> { + self.conn.execute("DELETE FROM outbox", [])?; self.conn.execute( "UPDATE messages SET plaintext = zeroblob(length(plaintext))", [], @@ -859,6 +1148,12 @@ fn mkdir_700(path: &Path) -> Result<()> { Ok(()) } +/// Base projection for outbox rows: the body comes from the `messages` row the +/// outbox row points at, so it stays under that row's AEAD + AAD. +const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \ + o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \ + FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id"; + /// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64 fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec { let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8); diff --git a/src/tui.rs b/src/tui.rs index 2ce2eab..5a8ffae 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1366,8 +1366,10 @@ impl App { let (tx, rx) = mpsc::channel(); self.status_note = Some("sending".into()); std::mem::drop(self.rt.spawn(async move { + // send() now reports `Sent`/`Queued`; surfacing `queued` in the + // footer is a follow-up card, so this arm keeps today's wording. let note = match node.send(&pk, &body).await { - Ok(()) => "sent".to_string(), + Ok(_) => "sent".to_string(), Err(e) => format!("send failed: {e}"), }; let _ = tx.send(note); diff --git a/tests/outbox.rs b/tests/outbox.rs new file mode 100644 index 0000000..3b7cc13 --- /dev/null +++ b/tests/outbox.rs @@ -0,0 +1,312 @@ +//! Local outbox: queue a chat send when the peer's onion is unreachable, retry +//! with exponential backoff, expose a terminal status. All offline — the +//! transport is a fake deliverer, so these run without Tor. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use onionwire::outbox::{ + BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs, + is_permanent_send_error, +}; +use onionwire::Store; + +const PASS: &str = "outbox-pass"; + +fn pk(tag: u8) -> [u8; 32] { + let mut k = [0u8; 32]; + k[0] = tag; + k +} + +/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext. +struct Flaky { + fail_times: AtomicUsize, + err: String, + calls: AtomicUsize, + delivered: Mutex>>, +} + +impl Flaky { + fn new(fail_times: usize, err: &str) -> Arc { + Arc::new(Self { + fail_times: AtomicUsize::new(fail_times), + err: err.into(), + calls: AtomicUsize::new(0), + delivered: Mutex::new(Vec::new()), + }) + } + + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } + + fn delivered(&self) -> Vec> { + self.delivered.lock().unwrap().clone() + } +} + +impl Deliverer for Flaky { + fn deliver<'a>( + &'a self, + _onion: &'a str, + _pinned_id: &'a [u8], + _prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + self.calls.fetch_add(1, Ordering::SeqCst); + let left = self.fail_times.load(Ordering::SeqCst); + if left > 0 { + self.fail_times.fetch_sub(1, Ordering::SeqCst); + let err = self.err.clone(); + return Box::pin(async move { Err(err) }); + } + self.delivered.lock().unwrap().push(plaintext.to_vec()); + Box::pin(async move { Ok(()) }) + } +} + +fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc> { + let store = Store::open_at_with_passphrase(dir, PASS).expect("open store"); + store.upsert_friend(&pk(1), onion, None).unwrap(); + store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap(); + Arc::new(Mutex::new(store)) +} + +fn outbox(store: Arc>, deliverer: Arc, max_attempts: u32) -> Outbox { + Outbox::new(store, deliverer).with_max_attempts(max_attempts) +} + +#[test] +fn backoff_schedule_doubles_from_30s_and_caps_at_30m() { + assert_eq!(BACKOFF_START_SECS, 30); + assert_eq!(BACKOFF_CAP_SECS, 1800); + let got: Vec = (0..9).map(backoff_secs).collect(); + assert_eq!( + got, + vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800], + "exponential backoff, capped" + ); + assert_eq!( + backoff_secs(u32::MAX), + BACKOFF_CAP_SECS, + "no overflow at silly attempt counts" + ); +} + +#[test] +fn transport_errors_are_retryable_protocol_errors_are_not() { + assert!(!is_permanent_send_error( + "connect abc.onion:80: timed out" + )); + assert!(!is_permanent_send_error("connect abc.onion:80: refused")); + assert!(is_permanent_send_error("fingerprint mismatch")); + assert!(is_permanent_send_error("frame too large")); + assert!(is_permanent_send_error("bad version")); + assert!(is_permanent_send_error("bad identity proof")); +} + +#[tokio::test] +async fn send_to_dead_onion_is_queued_and_row_persists() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "dead.onion"); + let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + + let status = ob.send(&pk(1), b"hello dead peer").await.unwrap(); + assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err"); + assert!(!status.is_terminal()); + + let pending = ob.pending(&pk(1)).unwrap(); + assert_eq!(pending.len(), 1, "one outbox row"); + assert_eq!(pending[0].status, OutboxStatus::Queued); + assert_eq!(pending[0].attempts, 1, "the immediate attempt counted"); + assert!( + ob.status_of_message(pending[0].message_id).unwrap().is_some(), + "status is addressable by chat row id" + ); + + // The chat line is already in local history while it waits. + let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap(); + assert_eq!(msgs.len(), 1); + assert_eq!(msgs[0].dir, "out"); + assert_eq!(msgs[0].plaintext, b"hello dead peer"); +} + +#[tokio::test] +async fn flaky_peer_is_flushed_by_the_worker_on_schedule() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "flaky.onion"); + // First dial fails (the immediate one), the rest succeed: "peer came up". + let flaky = Flaky::new(1, "connect flaky.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), flaky.clone(), 8); + + let status = ob.send(&pk(1), b"late hello").await.unwrap(); + assert_eq!(status, OutboxStatus::Queued); + let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at; + assert_eq!( + next - ob.pending(&pk(1)).unwrap()[0].created_at, + BACKOFF_START_SECS, + "first retry waits the start of the schedule" + ); + + // Too early: the worker must not dial out of schedule. + let t0 = next - BACKOFF_START_SECS; + let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap(); + assert!(fired.is_empty(), "not due yet"); + + let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].1, OutboxStatus::Sent); + assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]); + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "delivered rows leave the pending set" + ); +} + +#[tokio::test] +async fn max_attempts_reaches_failed_and_stops_retrying() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "gone.onion"); + let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead.clone(), 3); + + assert_eq!( + ob.send(&pk(1), b"never lands").await.unwrap(), + OutboxStatus::Queued + ); + assert_eq!(dead.calls(), 1, "immediate attempt"); + + // Walk the schedule forward; each tick is one more attempt. + let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at; + let mut last = OutboxStatus::Queued; + for _ in 0..6 { + let fired = ob.tick(now).await.unwrap(); + if let Some((_, st)) = fired.first() { + last = st.clone(); + } + if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) { + break; + } + now += BACKOFF_CAP_SECS; + } + assert_eq!( + last, + OutboxStatus::Failed("connect gone.onion:80: timed out".into()), + "gives up after max_attempts" + ); + assert_eq!(dead.calls(), 3, "attempts stop at the cap"); + + let calls_at_cap = dead.calls(); + for _ in 0..3 { + now += BACKOFF_CAP_SECS; + assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries"); + } + assert_eq!(dead.calls(), calls_at_cap); + + let pending = ob.pending(&pk(1)).unwrap(); + assert_eq!(pending.len(), 1); + assert!(matches!(pending[0].status, OutboxStatus::Failed(_))); + assert!(pending[0].status.is_terminal()); +} + +#[tokio::test] +async fn queued_message_survives_reopen_and_flushes_after_unlock() { + let dir = tempfile::tempdir().unwrap(); + let pk1 = pk(1); + let next_attempt_at = { + let store = store_and_friend(dir.path(), "later.onion"); + let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + assert_eq!( + ob.send(&pk1, b"survives restart").await.unwrap(), + OutboxStatus::Queued + ); + ob.pending(&pk1).unwrap()[0].next_attempt_at + }; + + // Process exit: everything above is dropped and the store is reopened. + let store = Arc::new(Mutex::new( + Store::open_at_with_passphrase(dir.path(), PASS).unwrap(), + )); + let up = Flaky::new(0, ""); + let ob = outbox(Arc::clone(&store), up.clone(), 8); + let fired = ob.flush_all(next_attempt_at).await.unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].1, OutboxStatus::Sent); + assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]); + assert!(ob.pending(&pk1).unwrap().is_empty()); +} + +#[tokio::test] +async fn protocol_error_fails_immediately_and_is_not_queued() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "liar.onion"); + let liar = Flaky::new(usize::MAX, "fingerprint mismatch"); + let ob = outbox(Arc::clone(&store), liar, 8); + + let err = ob.send(&pk(1), b"hello liar").await.unwrap_err(); + assert!(err.contains("fingerprint mismatch"), "got {err}"); + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "protocol errors are never queued" + ); + assert!( + store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(), + "a failed protocol send is not written to history" + ); +} + +#[tokio::test] +async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "seen.onion"); + let flaky = Flaky::new(1, "connect seen.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), flaky.clone(), 8); + + assert_eq!( + ob.send(&pk(1), b"you are back").await.unwrap(), + OutboxStatus::Queued + ); + let now = ob.pending(&pk(1)).unwrap()[0].created_at; + let fired = ob.flush_friend(&pk(1), now).await.unwrap(); + assert_eq!(fired.len(), 1, "a live handshake flushes without waiting"); + assert_eq!(fired[0].1, OutboxStatus::Sent); +} + +#[tokio::test] +async fn wipe_clears_outbox_rows() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "dead.onion"); + let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + assert_eq!( + ob.send(&pk(1), b"wipe me").await.unwrap(), + OutboxStatus::Queued + ); + assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1); + + store.lock().unwrap().wipe_messages().unwrap(); + + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "wipe must drop queued sends, not only chat" + ); +} + +#[tokio::test] +async fn missing_prekey_is_fatal_not_queued() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(Mutex::new( + Store::open_at_with_passphrase(dir.path(), PASS).unwrap(), + )); + { + let s = store.lock().unwrap(); + s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap(); + } + let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8); + let err = ob.send(&pk(2), b"hi").await.unwrap_err(); + assert!(err.contains("prekey"), "got {err}"); + assert!(ob.pending(&pk(2)).unwrap().is_empty()); +} From 068b655c197ba55c9e87fe09bb998091289e32cb Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 13:35:10 -0400 Subject: [PATCH 3/7] feat(outbox): local retry queue for chat sends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Queue a chat send locally when the peer's v3 onion is unreachable and retry it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then terminal Failed). Still peer-to-peer: no server, no store-and-forward relay, no new frame prefix — every attempt is a fresh Noise IK handshake. - src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(), is_permanent_send_error(), background worker (15s scan). - store: `outbox` table (no body column — the body is read from the joined messages row, under that row's existing AEAD + AAD), append_message_id(), queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe. - Node::send() returns Result (Sent/Queued) instead of Err on transport failure; protocol errors still fail immediately and are never queued. - Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer was just seen" (handshake or connect_onion -> spawn_flush_friend). - File transfer and payment/rcp frames stay fail-closed. - docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements; add the seizure/cadence delta to the threat model. src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is child card t_d9a5b065. --- docs/PROTOCOL.md | 16 ++- docs/THREAT_MODEL.md | 17 ++- src/lib.rs | 1 + src/node.rs | 130 +++++++++++------- src/outbox.rs | 308 ++++++++++++++++++++++++++++++++++++++++++ src/session.rs | 10 ++ src/store.rs | 297 +++++++++++++++++++++++++++++++++++++++- src/tui.rs | 4 +- tests/outbox.rs | 312 +++++++++++++++++++++++++++++++++++++++++++ 9 files changed, 1042 insertions(+), 53 deletions(-) create mode 100644 src/outbox.rs create mode 100644 tests/outbox.rs diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 6cda19e..e93943f 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -19,7 +19,7 @@ SOCKS proxy.” | Discovery | DHT + bootstrap nodes | Out-of-band invite only | | After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion | | Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator | -| Offline send | Expected (relays / retry) | Fail closed — no outbox | +| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) | | Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers | There is no directory, no name server, no introduction point of our own, and no @@ -51,8 +51,18 @@ not on the wire. 4. File transfer is N independent sessions (one handshake per chunk). There is no multiplexed long-lived stream in v1. -If the onion is down, send fails. No retry queue except the locator-push path, -which retries for 180 seconds and then gives up. +If the onion is down, a **chat** send is persisted to the local outbox and +retried by a background worker with exponential backoff (30s, doubling, capped +at 30 min; 8 attempts, then terminal `Failed`). There is no server and no +store-and-forward relay: each attempt is a fresh handshake straight to +`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on +unlock/foreground, and whenever that peer is heard from (successful handshake or +`connect_onion()`). A protocol failure — signature mismatch, unknown frame, +oversize — is not a transport failure and is never queued. + +File transfer and payment frames stay fail-closed: they are one-shot and are +**not** queued. The locator-push path still retries for 180 seconds and then +gives up. Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10. Excess is dropped before handshake. That is availability, not anonymity. diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9773e46..96252eb 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -24,7 +24,16 @@ Identity secret key, friend public keys, and locators remain plaintext in the sa ## Fail closed -Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor. +Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor. + +## Local outbox (chat retry queue) is local, and it re-dials on a schedule + +A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted: + +- **Device seizure.** A pending (never-delivered) message sits in the same db as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure with the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase. +- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure. + +The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever. ## Profile is friend-visible, not a directory @@ -65,5 +74,7 @@ the peer already knows the plaintext they sent. ## Out of v1 -Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, -sqlcipher, A/V. +Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward +relay, multi-device, DHT / name server, sqlcipher, A/V. The local retry queue of +the previous section is not an outbox in the XMPP sense: it never leaves the +device. diff --git a/src/lib.rs b/src/lib.rs index ea6dba2..9d9eb7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod frame; pub mod hs; pub mod loc; pub mod node; +pub mod outbox; pub mod pay; pub mod profile; pub mod qr; diff --git a/src/node.rs b/src/node.rs index 97745a2..9c3e931 100644 --- a/src/node.rs +++ b/src/node.rs @@ -14,6 +14,7 @@ use crate::file; use crate::frame; use crate::hs::{self, Client, HS_PORT}; use crate::loc; +use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; use crate::profile; use crate::qr; @@ -39,9 +40,18 @@ impl Drop for HsHandle { } } +/// Abort the outbox worker when the node goes away. +struct WorkerHandle(tokio::task::JoinHandle<()>); + +impl Drop for WorkerHandle { + fn drop(&mut self) { + self.0.abort(); + } +} + pub struct Node { home: PathBuf, - store: Mutex, + store: Arc>, client: Client, hs: Mutex>, onion: Mutex, @@ -49,6 +59,8 @@ pub struct Node { wallet: Wallet, incoming_limit: Mutex, inbox: Mutex, + outbox: Arc, + _outbox_worker: WorkerHandle, } impl Node { @@ -79,9 +91,17 @@ impl Node { let (svc, rend) = launched; let onion = hs::onion_string(&svc)?; let inbox = file::Inbox::new(home.join("inbox")); + let store = Arc::new(Mutex::new(store)); + let outbox = Arc::new(Outbox::new( + Arc::clone(&store), + Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())), + )); + if let Err(e) = outbox.reset_stale() { + eprintln!("outbox: {e}"); + } let node = Arc::new(Self { home, - store: Mutex::new(store), + store, client, hs: Mutex::new(None), onion: Mutex::new(onion.clone()), @@ -89,7 +109,12 @@ impl Node { wallet: Wallet::from_env(), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), + outbox: Arc::clone(&outbox), + _outbox_worker: WorkerHandle(outbox.spawn_worker()), }); + // Unlock trigger: flush anything queued by a previous run now, in the + // background, rather than waiting out its backoff. + spawn_flush_all(Arc::clone(&node.outbox)); // Accept rens before waiting so a reachability probe can succeed // while combined status is still Bootstrapping. let rend = spawn_rend(Arc::clone(&node), rend); @@ -416,6 +441,8 @@ impl Node { self.try_send(&onion, friend_pk, &prekey, plaintext).await } + /// Dial a peer's onion. Success is evidence the peer is up, which is one of + /// the outbox retry triggers. pub async fn connect_onion(&self, onion: &str) -> Result<(), String> { tokio::time::timeout( Duration::from_secs(20), @@ -424,6 +451,14 @@ impl Node { .await .map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))? .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; + if let Ok(Some(friend)) = self + .store + .lock() + .map_err(|e| e.to_string()) + .and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string())) + { + spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey); + } Ok(()) } @@ -506,36 +541,30 @@ impl Node { Ok(name) } - pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { - let (onion, prekey) = { - let store = self.store.lock().map_err(|e| e.to_string())?; - let f = store - .get_friend(friend_pk) - .map_err(|e| e.to_string())? - .ok_or_else(|| "unknown friend".to_string())?; - if f.prekey.len() != 32 { - return Err("friend missing prekey".into()); - } - (f.onion, f.prekey) - }; - let deadline = Instant::now() + Duration::from_secs(180); - let mut last = None::; - while Instant::now() < deadline { - match self.try_send(&onion, friend_pk, &prekey, plaintext).await { - Ok(()) => { - self.store - .lock() - .map_err(|e| e.to_string())? - .append_message(friend_pk, "out", plaintext) - .map_err(|e| e.to_string())?; - return Ok(()); - } - Err(e) if e.contains("fingerprint mismatch") => return Err(e), - Err(e) => last = Some(e), - } - tokio::time::sleep(Duration::from_secs(3)).await; - } - Err(last.unwrap_or_else(|| "send timed out".into())) + /// Send one chat message. Returns `Sent` when it went out now and `Queued` + /// when the peer's onion is unreachable — the outbox worker then retries with + /// backoff. A real protocol error (signature mismatch, unknown/short/oversize + /// frame) still fails immediately and is never retried. + pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.outbox.send(friend_pk, plaintext).await + } + + /// Pending and failed outbox rows for a friend, for UI surfacing. + /// Delivered rows are dropped, so a message absent here was sent. + pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result, String> { + self.outbox.pending(friend_pk) + } + + pub fn outbox_status_of_message( + &self, + message_id: i64, + ) -> Result, String> { + self.outbox.status_of_message(message_id) + } + + /// Foreground/unlock trigger: try every outstanding queued send now. + pub fn flush_outbox(&self) { + spawn_flush_all(Arc::clone(&self.outbox)); } async fn push_loc( @@ -568,20 +597,10 @@ impl Node { remote_prekey: &[u8], plaintext: &[u8], ) -> Result<(), String> { - let mut stream = self - .client - .connect((onion, HS_PORT)) + self.outbox + .deliverer() + .deliver(onion, pinned_id, remote_prekey, plaintext) .await - .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; - let keys = self.keys()?; - let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey) - .await - .map_err(session_err)?; - let ct = sess.encrypt(plaintext).map_err(session_err)?; - frame::write_frame(&mut stream, &ct) - .await - .map_err(|e| e.to_string())?; - Ok(()) } async fn handle_incoming(&self, stream: &mut S) -> Result<(), String> @@ -598,6 +617,9 @@ impl Node { }) .await .map_err(session_err)?; + // Trigger (c): the peer just proved they are online. Try their queued + // sends now instead of waiting out the backoff, off this stream's path. + spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone()); let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?; let pt = sess.decrypt(&ct).map_err(session_err)?; match dispatch::classify(&pt) { @@ -814,6 +836,24 @@ fn spawn_rend( }) } +/// Foreground/unlock flush: every outstanding queued send gets one attempt now. +fn spawn_flush_all(outbox: Arc) { + tokio::spawn(async move { + if let Err(e) = outbox.flush_all(unix_now()).await { + eprintln!("outbox: {e}"); + } + }); +} + +/// We just saw this peer (handshake or successful dial): try their queue now. +fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { + tokio::spawn(async move { + if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await { + eprintln!("outbox: {e}"); + } + }); +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") diff --git a/src/outbox.rs b/src/outbox.rs new file mode 100644 index 0000000..495e63e --- /dev/null +++ b/src/outbox.rs @@ -0,0 +1,308 @@ +//! Local-only outbox. +//! +//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and +//! retried by a background worker with exponential backoff. There is no server +//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake +//! straight to the friend's onion, so a queued message is never handed to a +//! third party. File transfer and payment frames stay fail-closed — only chat +//! goes through here. + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use tokio::sync::Notify; + +use crate::frame; +use crate::hs::{Client, HS_PORT}; +use crate::session::{self, Keys}; +use crate::store::Store; + +pub use crate::store::{OutboxEntry, OutboxStatus}; + +/// First retry waits this long. +pub const BACKOFF_START_SECS: i64 = 30; +/// Backoff never sleeps longer than this. +pub const BACKOFF_CAP_SECS: i64 = 1_800; +/// Attempts after which a queued message is terminally `Failed`. +pub const DEFAULT_MAX_ATTEMPTS: u32 = 8; +/// Worker scan period. The shortest backoff is 30s, so a slower scan still +/// lands each retry close to its schedule without busy-waiting. +pub const WORKER_TICK: Duration = Duration::from_secs(15); +/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the +/// worker. +const MAX_PER_PASS: i64 = 32; + +pub type BoxFut<'a, T> = Pin + Send + 'a>>; + +/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s… +/// capped at 30 min. `attempt` is the number of retries already made. +pub fn backoff_secs(attempt: u32) -> i64 { + // 30 << 16 is the largest shift we ever need to reach the cap, so this + // cannot overflow even for a silly attempt count. + (BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS) +} + +/// Protocol failures: another attempt cannot fix a bad signature, a bad frame +/// header, or an oversize payload, so they must fail loudly and never queue. +const PERMANENT_ERRORS: &[&str] = &[ + "fingerprint mismatch", + "bad identity proof", + "unexpected handshake payload", + "frame too large", + "bad version", + "length mismatch", + "short frame", +]; + +pub fn is_permanent_send_error(err: &str) -> bool { + PERMANENT_ERRORS.iter().any(|p| err.contains(p)) +} + +/// One delivery attempt. Implemented by Arti for real sends and by tests for a +/// fake or flaky peer. +pub trait Deliverer: Send + Sync { + fn deliver<'a>( + &'a self, + onion: &'a str, + pinned_id: &'a [u8], + prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>>; +} + +/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's +/// identity key, send exactly one application frame, drop the circuit. +pub struct ArtiDeliverer { + client: Client, + keys: Keys, +} + +impl ArtiDeliverer { + pub fn new(client: Client, keys: Keys) -> Self { + Self { client, keys } + } +} + +impl Deliverer for ArtiDeliverer { + fn deliver<'a>( + &'a self, + onion: &'a str, + pinned_id: &'a [u8], + prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + Box::pin(async move { + let mut stream = self + .client + .connect((onion, HS_PORT)) + .await + .map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?; + let mut sess = + session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey) + .await + .map_err(|e| e.into_message())?; + let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?; + frame::write_frame(&mut stream, &ct) + .await + .map_err(|e| e.to_string())?; + Ok(()) + }) + } +} + +pub struct Outbox { + store: Arc>, + deliverer: Arc, + max_attempts: u32, + wake: Notify, +} + +impl Outbox { + pub fn new(store: Arc>, deliverer: Arc) -> Self { + Self { + store, + deliverer, + max_attempts: DEFAULT_MAX_ATTEMPTS, + wake: Notify::new(), + } + } + + pub fn with_max_attempts(mut self, max: u32) -> Self { + self.max_attempts = max.max(1); + self + } + + /// The transport, for callers (locator/profile pushes) that stay fail-closed + /// and must not queue. + pub fn deliverer(&self) -> &dyn Deliverer { + self.deliverer.as_ref() + } + + /// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is + /// unreachable, the message is persisted and will be retried. `Err` — a + /// protocol error or a bad local state, never retried. + pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + let (onion, prekey) = self.target(friend_pk)?; + match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await { + Ok(()) => { + self.store()?.append_message(friend_pk, "out", plaintext)?; + Ok(OutboxStatus::Sent) + } + Err(e) if is_permanent_send_error(&e) => Err(e), + Err(e) => { + let now = unix_now(); + let store = self.store()?; + let message_id = store.append_message_id(friend_pk, "out", plaintext)?; + store.enqueue_outbox( + friend_pk, + message_id, + 1, + now + backoff_secs(0), + &e, + now, + )?; + Ok(OutboxStatus::Queued) + } + } + } + + /// Timer trigger: every row whose backoff has elapsed gets one attempt. + pub async fn tick(&self, now: i64) -> Result, String> { + let due = self.store()?.due_outbox(now, MAX_PER_PASS)?; + self.attempt(due, now).await + } + + /// Unlock / foreground trigger: every outstanding row gets one attempt now, + /// regardless of where it sits in the backoff. + pub async fn flush_all(&self, now: i64) -> Result, String> { + let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?; + self.attempt(rows, now).await + } + + /// Trigger (c): we just heard from this peer, so try their rows immediately. + pub async fn flush_friend( + &self, + friend_pk: &[u8], + now: i64, + ) -> Result, String> { + let rows = self.store()?.outbox_for_friend(friend_pk)?; + self.attempt(rows, now).await + } + + /// Pending and failed rows for one friend. Delivered rows are deleted, so a + /// message that is not here was either sent first try or flushed since. + pub fn pending(&self, friend_pk: &[u8]) -> Result, String> { + self.store()?.pending_outbox(friend_pk).map_err(store_err) + } + + pub fn status_of_message(&self, message_id: i64) -> Result, String> { + self.store()? + .outbox_status_of_message(message_id) + .map_err(store_err) + } + + /// A process that died mid-attempt leaves `sending` rows behind; requeue + /// them on unlock so they are retried instead of stranded. + pub fn reset_stale(&self) -> Result { + self.store()?.reset_sending_outbox().map_err(store_err) + } + + /// Wake the worker (e.g. after `flush_all` was queued from a UI thread). + pub fn kick(&self) { + self.wake.notify_one(); + } + + /// Background retry worker. Aborted by dropping the returned handle. + pub fn spawn_worker(self: &Arc) -> tokio::task::JoinHandle<()> { + let me = Arc::clone(self); + tokio::spawn(async move { + loop { + if let Err(e) = me.tick(unix_now()).await { + eprintln!("outbox: {e}"); + } + tokio::select! { + _ = tokio::time::sleep(WORKER_TICK) => {} + _ = me.wake.notified() => {} + } + } + }) + } + + async fn attempt( + &self, + rows: Vec, + now: i64, + ) -> Result, String> { + let mut out = Vec::with_capacity(rows.len()); + for entry in rows { + self.store()?.mark_outbox_sending(entry.id, now)?; + let (onion, prekey) = match self.target(&entry.friend_pk) { + Ok(t) => t, + Err(e) => { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + out.push((entry.id, OutboxStatus::Failed(e))); + continue; + } + }; + let result = self + .deliverer + .deliver(&onion, &entry.friend_pk, &prekey, &entry.body) + .await; + let status = match result { + Ok(()) => { + self.store()?.mark_outbox_sent(entry.id)?; + OutboxStatus::Sent + } + Err(e) if is_permanent_send_error(&e) => { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + OutboxStatus::Failed(e) + } + Err(e) => { + let attempts = entry.attempts.saturating_add(1); + if attempts >= self.max_attempts { + self.store()?.mark_outbox_failed(entry.id, now, &e)?; + OutboxStatus::Failed(e) + } else { + let next = now + backoff_secs(attempts - 1); + self.store()? + .mark_outbox_retry(entry.id, attempts, next, now, &e)?; + OutboxStatus::Queued + } + } + }; + out.push((entry.id, status)); + } + Ok(out) + } + + /// Friend's current locator + Noise static. Missing prekey means the invite + /// was never completed — retrying cannot fix that, so it is fatal. + fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec), String> { + let store = self.store()?; + let f = store + .get_friend(friend_pk) + .map_err(store_err)? + .ok_or_else(|| "unknown friend".to_string())?; + if f.prekey.len() != 32 { + return Err("friend missing prekey".into()); + } + Ok((f.onion, f.prekey)) + } + + fn store(&self) -> Result, String> { + self.store.lock().map_err(|e| e.to_string()) + } +} + +fn store_err(e: crate::store::Error) -> String { + e.to_string() +} + +fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} diff --git a/src/session.rs b/src/session.rs index e5e21b6..611e8c1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -35,6 +35,16 @@ impl Error { pub fn is_fingerprint_mismatch(&self) -> bool { self.mismatch } + + /// String for the UI: a pinned-identity mismatch gets the documented banner, + /// everything else is the underlying snow/framing message. + pub fn into_message(self) -> String { + if self.mismatch { + crate::tui::fingerprint_mismatch_banner().to_string() + } else { + self.msg + } + } } impl std::fmt::Display for Error { diff --git a/src/store.rs b/src/store.rs index 1be94f3..c8a8e9b 100644 --- a/src/store.rs +++ b/src/store.rs @@ -40,6 +40,15 @@ impl From for Error { } } +/// The store error is a message and nothing else, and the rest of the crate +/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the +/// outbox boundary — no per-call `map_err`. +impl From for String { + fn from(e: Error) -> Self { + e.0 + } +} + pub struct Store { conn: Connection, msg_key: [u8; 32], @@ -88,6 +97,64 @@ pub struct Payment { pub created_at: i64, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OutboxStatus { + Queued, + Sending, + Sent, + /// Terminal: transport or protocol failure that will not be retried. + Failed(String), +} + +impl OutboxStatus { + pub fn is_terminal(&self) -> bool { + matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_)) + } + + /// Column encoding for the `outbox.status` CHECK constraint. + pub fn as_db_str(&self) -> &'static str { + match self { + OutboxStatus::Queued => "queued", + OutboxStatus::Sending => "sending", + OutboxStatus::Sent => "sent", + OutboxStatus::Failed(_) => "failed", + } + } + + pub fn from_db(status: &str, last_error: Option<&str>) -> Self { + match status { + "sending" => OutboxStatus::Sending, + "sent" => OutboxStatus::Sent, + "failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()), + _ => OutboxStatus::Queued, + } + } +} + +impl std::fmt::Display for OutboxStatus { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + OutboxStatus::Failed(why) => write!(f, "failed: {why}"), + other => f.write_str(other.as_db_str()), + } + } +} + +/// One queued chat send. The body is not copied: it lives in the `messages` +/// row the outbox row points at, under that row's own AEAD. +#[derive(Debug, Clone)] +pub struct OutboxEntry { + pub id: i64, + pub friend_pk: Vec, + pub message_id: i64, + pub body: Vec, + pub attempts: u32, + pub next_attempt_at: i64, + pub created_at: i64, + pub status: OutboxStatus, + pub last_error: Option, +} + pub struct PaymentWrite<'a> { pub dir: &'a str, pub kind: &'a str, @@ -189,6 +256,18 @@ impl Store { verified INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); + CREATE TABLE IF NOT EXISTS outbox ( + id INTEGER PRIMARY KEY, + friend_id INTEGER NOT NULL REFERENCES friends(id), + message_id INTEGER NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + next_attempt_at INTEGER NOT NULL, + status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')), + last_error TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at); INSERT OR IGNORE INTO self_profile (id) VALUES (1); ", )?; @@ -475,6 +554,20 @@ impl Store { .map_err(Into::into) } + /// Locator → friend. Onions are not unique in the schema (a stale row can + /// hold a rotated address), so the first match wins; the outbox uses this + /// only to pick which queue to flush early. + pub fn friend_by_onion(&self, onion: &str) -> Result> { + self.conn + .query_row( + "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1", + params![onion], + friend_from_row, + ) + .optional() + .map_err(Into::into) + } + pub fn list_friends(&self) -> Result> { let mut stmt = self.conn.prepare( "SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends @@ -699,6 +792,17 @@ impl Store { } pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> { + self.append_message_id(friend_pk, dir, plaintext).map(|_| ()) + } + + /// Same as `append_message`, returning the row id so an outbox row can + /// point at the body instead of storing a second copy. + pub fn append_message_id( + &self, + friend_pk: &[u8], + dir: &str, + plaintext: &[u8], + ) -> Result { if dir != "in" && dir != "out" { return Err(Error("dir must be in or out".into())); } @@ -723,7 +827,7 @@ impl Store { params![blob, row_id], )?; tx.commit()?; - Ok(()) + Ok(row_id) } pub fn list_messages(&self, friend_pk: &[u8]) -> Result> { @@ -752,9 +856,194 @@ impl Store { Ok(out) } + /// Queue one already-stored chat message for retry. `next_attempt_at` is an + /// absolute unix second; `now` is used for created_at/updated_at so the + /// caller and the row agree on the clock. + pub fn enqueue_outbox( + &self, + friend_pk: &[u8], + message_id: i64, + attempts: u32, + next_attempt_at: i64, + last_error: &str, + now: i64, + ) -> Result { + let friend_id: i64 = self + .conn + .query_row( + "SELECT id FROM friends WHERE pubkey = ?1", + params![friend_pk], + |row| row.get(0), + ) + .map_err(|_| Error("friend not found".into()))?; + self.conn.execute( + "INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)", + params![friend_id, message_id, attempts, next_attempt_at, last_error, now], + )?; + Ok(self.conn.last_insert_rowid()) + } + + /// Rows whose backoff has elapsed: the timer trigger for the worker. + pub fn due_outbox(&self, now: i64, limit: i64) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1 + ORDER BY o.next_attempt_at, o.id LIMIT ?2" + ), + params![now, limit], + ) + } + + /// Unscheduleable rows for one friend (queued or mid-attempt): the + /// "we just heard from this peer" trigger, which ignores the backoff. + pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending') + ORDER BY o.id" + ), + params![friend_pk], + ) + } + + /// Every row the worker may still try: the unlock/foreground trigger. + pub fn all_pending_outbox(&self, limit: i64) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE o.status IN ('queued','sending') + ORDER BY o.next_attempt_at, o.id LIMIT ?1" + ), + params![limit], + ) + } + + /// Pending and failed rows for one friend — what a UI shows as not-yet-sent. + /// Delivered rows are deleted, so absence means "sent". + pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result> { + self.outbox_query( + &format!( + "{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed') + ORDER BY o.id" + ), + params![friend_pk], + ) + } + + pub fn outbox_status_of_message(&self, message_id: i64) -> Result> { + let row: Option<(String, Option)> = self + .conn + .query_row( + "SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1", + params![message_id], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref()))) + } + + pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2", + params![now, id], + )?; + Ok(()) + } + + /// Delivered. The row is dropped — the chat history is the record, and a + /// per-message status table would grow without bound. + pub fn mark_outbox_sent(&self, id: i64) -> Result<()> { + self.conn + .execute("DELETE FROM outbox WHERE id = ?1", params![id])?; + Ok(()) + } + + pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3", + params![why, now, id], + )?; + Ok(()) + } + + pub fn mark_outbox_retry( + &self, + id: i64, + attempts: u32, + next_attempt_at: i64, + now: i64, + why: &str, + ) -> Result<()> { + self.conn.execute( + "UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5", + params![attempts, next_attempt_at, why, now, id], + )?; + Ok(()) + } + + /// A row left in 'sending' means we died mid-attempt. Requeue on unlock. + pub fn reset_sending_outbox(&self) -> Result { + let n = self.conn.execute( + "UPDATE outbox SET status = 'queued' WHERE status = 'sending'", + [], + )?; + Ok(n) + } + + fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result> { + let mut stmt = self.conn.prepare(sql)?; + let rows = stmt.query_map(args, |row| { + Ok(( + row.get::<_, i64>(0)?, + row.get::<_, Vec>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, i64>(3)?, + row.get::<_, i64>(4)?, + row.get::<_, String>(5)?, + row.get::<_, Option>(6)?, + row.get::<_, i64>(7)?, + row.get::<_, i64>(8)?, + row.get::<_, String>(9)?, + row.get::<_, Vec>(10)?, + )) + })?; + let mut out = Vec::new(); + for row in rows { + let ( + id, + friend_pk, + message_id, + attempts, + next_attempt_at, + status, + last_error, + created_at, + m_friend_id, + dir, + blob, + ) = row?; + let aad = message_aad(m_friend_id, &dir, message_id); + let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) + .map_err(|_| Error("outbox body decrypt failed".into()))?; + out.push(OutboxEntry { + id, + friend_pk, + message_id, + body, + attempts: attempts as u32, + next_attempt_at, + created_at, + status: OutboxStatus::from_db(&status, last_error.as_deref()), + last_error, + }); + } + Ok(out) + } + /// Drop chat + payments history. Identity + friends stay. /// Not a forensic erase: SSD wear-leveling can keep copies. pub fn wipe_messages(&self) -> Result<()> { + self.conn.execute("DELETE FROM outbox", [])?; self.conn.execute( "UPDATE messages SET plaintext = zeroblob(length(plaintext))", [], @@ -859,6 +1148,12 @@ fn mkdir_700(path: &Path) -> Result<()> { Ok(()) } +/// Base projection for outbox rows: the body comes from the `messages` row the +/// outbox row points at, so it stays under that row's AEAD + AAD. +const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \ + o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \ + FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id"; + /// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64 fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec { let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8); diff --git a/src/tui.rs b/src/tui.rs index 20eb4b6..1a65f37 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1449,8 +1449,10 @@ impl App { let (tx, rx) = mpsc::channel(); self.status_note = Some("sending".into()); std::mem::drop(self.rt.spawn(async move { + // send() now reports `Sent`/`Queued`; surfacing `queued` in the + // footer is a follow-up card, so this arm keeps today's wording. let note = match node.send(&pk, &body).await { - Ok(()) => "sent".to_string(), + Ok(_) => "sent".to_string(), Err(e) => format!("send failed: {e}"), }; let _ = tx.send(note); diff --git a/tests/outbox.rs b/tests/outbox.rs new file mode 100644 index 0000000..3b7cc13 --- /dev/null +++ b/tests/outbox.rs @@ -0,0 +1,312 @@ +//! Local outbox: queue a chat send when the peer's onion is unreachable, retry +//! with exponential backoff, expose a terminal status. All offline — the +//! transport is a fake deliverer, so these run without Tor. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use onionwire::outbox::{ + BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs, + is_permanent_send_error, +}; +use onionwire::Store; + +const PASS: &str = "outbox-pass"; + +fn pk(tag: u8) -> [u8; 32] { + let mut k = [0u8; 32]; + k[0] = tag; + k +} + +/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext. +struct Flaky { + fail_times: AtomicUsize, + err: String, + calls: AtomicUsize, + delivered: Mutex>>, +} + +impl Flaky { + fn new(fail_times: usize, err: &str) -> Arc { + Arc::new(Self { + fail_times: AtomicUsize::new(fail_times), + err: err.into(), + calls: AtomicUsize::new(0), + delivered: Mutex::new(Vec::new()), + }) + } + + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } + + fn delivered(&self) -> Vec> { + self.delivered.lock().unwrap().clone() + } +} + +impl Deliverer for Flaky { + fn deliver<'a>( + &'a self, + _onion: &'a str, + _pinned_id: &'a [u8], + _prekey: &'a [u8], + plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + self.calls.fetch_add(1, Ordering::SeqCst); + let left = self.fail_times.load(Ordering::SeqCst); + if left > 0 { + self.fail_times.fetch_sub(1, Ordering::SeqCst); + let err = self.err.clone(); + return Box::pin(async move { Err(err) }); + } + self.delivered.lock().unwrap().push(plaintext.to_vec()); + Box::pin(async move { Ok(()) }) + } +} + +fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc> { + let store = Store::open_at_with_passphrase(dir, PASS).expect("open store"); + store.upsert_friend(&pk(1), onion, None).unwrap(); + store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap(); + Arc::new(Mutex::new(store)) +} + +fn outbox(store: Arc>, deliverer: Arc, max_attempts: u32) -> Outbox { + Outbox::new(store, deliverer).with_max_attempts(max_attempts) +} + +#[test] +fn backoff_schedule_doubles_from_30s_and_caps_at_30m() { + assert_eq!(BACKOFF_START_SECS, 30); + assert_eq!(BACKOFF_CAP_SECS, 1800); + let got: Vec = (0..9).map(backoff_secs).collect(); + assert_eq!( + got, + vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800], + "exponential backoff, capped" + ); + assert_eq!( + backoff_secs(u32::MAX), + BACKOFF_CAP_SECS, + "no overflow at silly attempt counts" + ); +} + +#[test] +fn transport_errors_are_retryable_protocol_errors_are_not() { + assert!(!is_permanent_send_error( + "connect abc.onion:80: timed out" + )); + assert!(!is_permanent_send_error("connect abc.onion:80: refused")); + assert!(is_permanent_send_error("fingerprint mismatch")); + assert!(is_permanent_send_error("frame too large")); + assert!(is_permanent_send_error("bad version")); + assert!(is_permanent_send_error("bad identity proof")); +} + +#[tokio::test] +async fn send_to_dead_onion_is_queued_and_row_persists() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "dead.onion"); + let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + + let status = ob.send(&pk(1), b"hello dead peer").await.unwrap(); + assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err"); + assert!(!status.is_terminal()); + + let pending = ob.pending(&pk(1)).unwrap(); + assert_eq!(pending.len(), 1, "one outbox row"); + assert_eq!(pending[0].status, OutboxStatus::Queued); + assert_eq!(pending[0].attempts, 1, "the immediate attempt counted"); + assert!( + ob.status_of_message(pending[0].message_id).unwrap().is_some(), + "status is addressable by chat row id" + ); + + // The chat line is already in local history while it waits. + let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap(); + assert_eq!(msgs.len(), 1); + assert_eq!(msgs[0].dir, "out"); + assert_eq!(msgs[0].plaintext, b"hello dead peer"); +} + +#[tokio::test] +async fn flaky_peer_is_flushed_by_the_worker_on_schedule() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "flaky.onion"); + // First dial fails (the immediate one), the rest succeed: "peer came up". + let flaky = Flaky::new(1, "connect flaky.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), flaky.clone(), 8); + + let status = ob.send(&pk(1), b"late hello").await.unwrap(); + assert_eq!(status, OutboxStatus::Queued); + let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at; + assert_eq!( + next - ob.pending(&pk(1)).unwrap()[0].created_at, + BACKOFF_START_SECS, + "first retry waits the start of the schedule" + ); + + // Too early: the worker must not dial out of schedule. + let t0 = next - BACKOFF_START_SECS; + let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap(); + assert!(fired.is_empty(), "not due yet"); + + let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].1, OutboxStatus::Sent); + assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]); + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "delivered rows leave the pending set" + ); +} + +#[tokio::test] +async fn max_attempts_reaches_failed_and_stops_retrying() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "gone.onion"); + let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead.clone(), 3); + + assert_eq!( + ob.send(&pk(1), b"never lands").await.unwrap(), + OutboxStatus::Queued + ); + assert_eq!(dead.calls(), 1, "immediate attempt"); + + // Walk the schedule forward; each tick is one more attempt. + let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at; + let mut last = OutboxStatus::Queued; + for _ in 0..6 { + let fired = ob.tick(now).await.unwrap(); + if let Some((_, st)) = fired.first() { + last = st.clone(); + } + if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) { + break; + } + now += BACKOFF_CAP_SECS; + } + assert_eq!( + last, + OutboxStatus::Failed("connect gone.onion:80: timed out".into()), + "gives up after max_attempts" + ); + assert_eq!(dead.calls(), 3, "attempts stop at the cap"); + + let calls_at_cap = dead.calls(); + for _ in 0..3 { + now += BACKOFF_CAP_SECS; + assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries"); + } + assert_eq!(dead.calls(), calls_at_cap); + + let pending = ob.pending(&pk(1)).unwrap(); + assert_eq!(pending.len(), 1); + assert!(matches!(pending[0].status, OutboxStatus::Failed(_))); + assert!(pending[0].status.is_terminal()); +} + +#[tokio::test] +async fn queued_message_survives_reopen_and_flushes_after_unlock() { + let dir = tempfile::tempdir().unwrap(); + let pk1 = pk(1); + let next_attempt_at = { + let store = store_and_friend(dir.path(), "later.onion"); + let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + assert_eq!( + ob.send(&pk1, b"survives restart").await.unwrap(), + OutboxStatus::Queued + ); + ob.pending(&pk1).unwrap()[0].next_attempt_at + }; + + // Process exit: everything above is dropped and the store is reopened. + let store = Arc::new(Mutex::new( + Store::open_at_with_passphrase(dir.path(), PASS).unwrap(), + )); + let up = Flaky::new(0, ""); + let ob = outbox(Arc::clone(&store), up.clone(), 8); + let fired = ob.flush_all(next_attempt_at).await.unwrap(); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].1, OutboxStatus::Sent); + assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]); + assert!(ob.pending(&pk1).unwrap().is_empty()); +} + +#[tokio::test] +async fn protocol_error_fails_immediately_and_is_not_queued() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "liar.onion"); + let liar = Flaky::new(usize::MAX, "fingerprint mismatch"); + let ob = outbox(Arc::clone(&store), liar, 8); + + let err = ob.send(&pk(1), b"hello liar").await.unwrap_err(); + assert!(err.contains("fingerprint mismatch"), "got {err}"); + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "protocol errors are never queued" + ); + assert!( + store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(), + "a failed protocol send is not written to history" + ); +} + +#[tokio::test] +async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "seen.onion"); + let flaky = Flaky::new(1, "connect seen.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), flaky.clone(), 8); + + assert_eq!( + ob.send(&pk(1), b"you are back").await.unwrap(), + OutboxStatus::Queued + ); + let now = ob.pending(&pk(1)).unwrap()[0].created_at; + let fired = ob.flush_friend(&pk(1), now).await.unwrap(); + assert_eq!(fired.len(), 1, "a live handshake flushes without waiting"); + assert_eq!(fired[0].1, OutboxStatus::Sent); +} + +#[tokio::test] +async fn wipe_clears_outbox_rows() { + let dir = tempfile::tempdir().unwrap(); + let store = store_and_friend(dir.path(), "dead.onion"); + let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out"); + let ob = outbox(Arc::clone(&store), dead, 8); + assert_eq!( + ob.send(&pk(1), b"wipe me").await.unwrap(), + OutboxStatus::Queued + ); + assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1); + + store.lock().unwrap().wipe_messages().unwrap(); + + assert!( + ob.pending(&pk(1)).unwrap().is_empty(), + "wipe must drop queued sends, not only chat" + ); +} + +#[tokio::test] +async fn missing_prekey_is_fatal_not_queued() { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(Mutex::new( + Store::open_at_with_passphrase(dir.path(), PASS).unwrap(), + )); + { + let s = store.lock().unwrap(); + s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap(); + } + let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8); + let err = ob.send(&pk(2), b"hi").await.unwrap_err(); + assert!(err.contains("prekey"), "got {err}"); + assert!(ob.pending(&pk(2)).unwrap().is_empty()); +} From 201aa483448ef3b77e782e2677ea6e7cc08418e9 Mon Sep 17 00:00:00 2001 From: apk-dev Date: Sat, 12 Sep 2026 14:29:02 -0400 Subject: [PATCH 4/7] =?UTF-8?q?feat(core,sdk):=20explicit=20Tor=20lifecycl?= =?UTF-8?q?e=20=E2=80=94=20stop,=20flush,=20observable=20state?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the Kotlin reference left Arti's client, the hosted v3 onion service, the outbox retry worker and the sqlite connection alive, and there was no way to ask where the onion service was. On Android the process is killed without warning by Doze and the background-process killer, so "drop everything when the process dies" is not a lifecycle. Core (`src/node.rs`, `src/hs.rs`): * `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the rendezvous task is aborted and the RunningOnionService dropped), abort the retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is swapped first, so a racing second call is a no-op. * `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one delivery attempt for every queued outbox row, ignoring backoff, then a WAL checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s and the caller is a UI thread. A timeout leaves rows in `sending`; `Outbox::reset_stale` requeues them on the next unlock, same as a process that died mid-attempt. * `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` / `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped, reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving readiness. * Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`, `flush`) fails with a typed error after the node stops, rather than dialing a dead client. * `checkpoint_wal` reaches the database through a short-lived second connection: `Store` owns the write connection and does not lend it out, and a checkpoint is a property of the database, not of one connection. Best effort — WAL replay on open recovers anything committed. The `WorkerHandle` moved into a `Mutex>` so the teardown can *abort* the retry worker instead of only dropping it when the whole `Node` dies. SDK (`crates/onionwire-sdk/src/lib.rs`): * `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`. `Wire` now holds `Mutex>>`, so teardown drops the last reference to the Tor client and the store instead of keeping them alive behind a JNI handle. * `WireError::Stopped` — a second flat variant, so "you must unlock again" is a typed `WireException.Stopped` in Kotlin, not a string match on `Failed`. * No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports `Stopped`, which is the correct recovery (unlock again). * Fixes the crate not compiling on this base at all: `Node::send` has returned `Result` since the outbox landed, and the SDK still mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes `crates/**` from the Rust job, which is why it stayed green. The live Tor test found a real bug in the first version of `tor_state`: Arti's combined status is still `Bootstrapping` after a *successful* probe of our own onion (that mismatch is what the 360s publish wait exists for), and a freshly launched service reports `Shutdown` before its publish reactor starts — so a node that was live and reachable reported `Bootstrapping`, and briefly `Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set when the publish bar is crossed and cleared when `rotate` hard-cuts the service, and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather than terminal. --- crates/onionwire-sdk/src/lib.rs | 260 +++++++++++++++++++++++++++--- src/hs.rs | 58 +++++++ src/node.rs | 273 +++++++++++++++++++++++++++++++- tests/hs.rs | 95 +++++++++++ tests/tor_lifecycle.rs | 96 +++++++++++ 5 files changed, 757 insertions(+), 25 deletions(-) create mode 100644 tests/tor_lifecycle.rs diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index e90c7fa..b81f016 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -13,13 +13,20 @@ //! Orbot pipe. If the onion service cannot publish, this fails closed. //! * Chat bodies are encrypted at rest. Identity keys in sqlite are not. //! +//! Lifecycle: a node is started by [`open_wire`] and stopped by +//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable +//! state and [`Wire::flush`] is "deliver what is deliverable now". A process +//! killed by Doze or the background-process killer never runs `shutdown`, which +//! is exactly why queued sends live in sqlite and not in memory. +//! //! The façade deliberately exposes only plain data (records + hex strings) so //! no TUI/ratatui type leaks into the AAR. use std::path::PathBuf; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; -use onionwire::node::Node; +use onionwire::hs::TorState as CoreTorState; +use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::qr; uniffi::setup_scaffolding!(); @@ -54,6 +61,12 @@ pub fn install_crypto_provider() { pub enum WireError { #[error("{message}")] Failed { message: String }, + /// The node was shut down (or never opened). Distinct from `Failed` so + /// Kotlin can branch on it instead of string-matching a message, and so + /// "you must unlock again" is a different UI state from "the network is + /// broken". + #[error("node stopped: {message}")] + Stopped { message: String }, } impl WireError { @@ -62,6 +75,12 @@ impl WireError { message: e.to_string(), } } + + fn stopped(what: &str) -> Self { + Self::Stopped { + message: format!("{what} called on a shut-down node"), + } + } } type WResult = std::result::Result; @@ -98,10 +117,70 @@ pub struct InviteInfo { pub onion: String, } +/// Observable lifecycle state of the node's onion service. +/// +/// Mirrors Arti's own service status, projected onto the four states a UI +/// actually acts on. It is the same distinction `hs::hs_is_ready` makes when it +/// decides whether the onion is reachable yet. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TorState { + /// Bootstrap or descriptor upload still in flight. Not reliably reachable. + Bootstrapping, + /// Onion service running and its descriptor published. + Published, + /// Reachable, but Arti reports the service degraded. Usable — worth saying + /// so, not identical to `Published`. + DegradedReachable, + /// Shut down: no onion service, no dials, store checkpointed. Every method + /// on the node now returns `WireError.Stopped`. + Stopped, +} + +impl From for TorState { + fn from(s: CoreTorState) -> Self { + match s { + CoreTorState::Bootstrapping => Self::Bootstrapping, + CoreTorState::Published => Self::Published, + CoreTorState::DegradedReachable => Self::DegradedReachable, + CoreTorState::Stopped => Self::Stopped, + } + } +} + +/// What a [`Wire::flush`] managed to do. +#[derive(Debug, Clone, Copy, uniffi::Record)] +pub struct FlushOutcome { + /// Rows the pass started a delivery for. `0` when the pass hit its time + /// budget before finishing — the rows are still queued, we just stopped + /// counting. + pub attempted: u32, + /// Rows delivered now. A message absent from `remaining` was sent. + pub delivered: u32, + /// Rows still queued or terminally failed afterwards. + pub remaining: u32, +} + /// A running OnionWire node: identity + Arti client + hosted v3 onion service. +/// +/// Holds the node handle. [`Wire::shutdown`] takes it out and drops it, which +/// is what lets the last reference to the Tor client and the store go away — +/// there is no hidden global keeping Arti (or the sqlite connection) alive +/// after the UI is gone. #[derive(uniffi::Object)] pub struct Wire { - inner: Arc, + node: Mutex>>, +} + +impl Wire { + /// The live node, or `Stopped` if this handle was shut down. A poisoned + /// mutex is reported the same way rather than panicking: a caller that sees + /// `Stopped` unlocks again, which is the correct recovery either way. + fn node(&self) -> WResult> { + let guard = self.node.lock().map_err(|_| WireError::Stopped { + message: "node handle lock poisoned by a panic; reopen the identity".to_string(), + })?; + guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call")) + } } /// Open (or create) the identity in `home` and start hosting an onion service. @@ -111,6 +190,11 @@ pub struct Wire { /// /// This resolves only once the onion service is published — on a cold network /// that is minutes, not seconds. Call it off the main thread. +/// +/// The returned handle owns the node: it lives until [`Wire::shutdown`], or +/// until the handle itself is dropped (which the JVM does without running the +/// drain, so call `shutdown()` from teardown — see the foreground-service +/// caller). #[uniffi::export(async_runtime = "tokio")] pub async fn open_wire(home: String, passphrase: String) -> WResult> { // Before anything that can build a TLS config: Arti's rustls backend dies @@ -120,7 +204,9 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult> { let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase) .await .map_err(WireError::new)?; - Ok(Arc::new(Wire { inner: node })) + Ok(Arc::new(Wire { + node: Mutex::new(Some(node)), + })) } /// Decode an invite without adding the friend. Verifies the signature. @@ -135,24 +221,76 @@ pub fn decode_invite(invite: String) -> WResult { #[uniffi::export(async_runtime = "tokio")] impl Wire { + /// Stop the node: give every queued outbox row one last bounded delivery + /// attempt, stop the onion service, abort the retry worker, checkpoint the + /// sqlite WAL, and drop the Tor client. + /// + /// Idempotent and safe to call twice, including from two threads: the + /// second call is a no-op returning `Ok`. After it, every other method on + /// this handle — including `send` — returns `WireError.Stopped` instead of + /// touching a dead client or panicking. + /// + /// Never called at all when the process is killed outright (Doze, the + /// background-process killer, a force-stop): that is the case [`flush`] + /// (Self::flush) and the sqlite outbox exist for. Once shut down, this + /// handle is spent — unlock again to get a new one. + pub async fn shutdown(&self) -> WResult<()> { + let node = self.node()?; + node.shutdown().await.map_err(WireError::new)?; + // Drop our handle to the node. With the onion service and the outbox + // worker aborted this is the last reference to the Tor client and the + // store, so Arti's runtime and the sqlite connection are released here. + let mut guard = self.node.lock().map_err(|_| WireError::Stopped { + message: "node handle lock poisoned by a panic".to_string(), + })?; + *guard = None; + Ok(()) + } + + /// Drain the outbox: one delivery attempt for every queued row, now, + /// ignoring its retry backoff, then checkpoint the WAL. + /// + /// Bounded by the SDK (30s): a dead peer's onion can hold a dial for ~20s + /// and this is called from UI/lifecycle threads. Rows that did not go out + /// stay queued; the retry worker keeps its normal schedule. Safe to call + /// repeatedly — use it on unlock, on foreground, and before `shutdown`. + pub async fn flush(&self) -> WResult { + let node = self.node()?; + let out = node.flush().await.map_err(WireError::new)?; + Ok(from_core_flush(out)) + } + + /// Where the onion service is right now. Cheap and read-only, no I/O: a + /// notification or a settings screen can call it directly. + pub fn tor_state(&self) -> TorState { + match self.node.lock() { + Ok(guard) => match guard.as_ref() { + Some(node) => node.tor_state().into(), + None => TorState::Stopped, + }, + // Poisoned: same answer as shut down — the node is unusable. + Err(_) => TorState::Stopped, + } + } + /// Fingerprint of our own identity key. Stable forever for this install. pub async fn fingerprint(&self) -> WResult { - self.inner.fingerprint().map_err(WireError::new) + self.node()?.fingerprint().map_err(WireError::new) } /// Current onion locator. Changes on rotate; identity does not. - pub async fn onion(&self) -> String { - self.inner.onion() + pub async fn onion(&self) -> WResult { + Ok(self.node()?.onion()) } /// `onionwire:v1:…` invite string to hand to the other person out of band. pub async fn invite(&self) -> WResult { - self.inner.qr_payload().map_err(WireError::new) + self.node()?.qr_payload().map_err(WireError::new) } /// Roster, sorted by petname then fingerprint. pub async fn friends(&self) -> WResult> { - let list = self.inner.list_friends().map_err(WireError::new)?; + let list = self.node()?.list_friends().map_err(WireError::new)?; Ok(list .into_iter() .map(|f| FriendInfo { @@ -168,9 +306,10 @@ impl Wire { /// Add a friend from an invite, or update the locator if the key is known. /// Same `k` never creates a second row. pub async fn add_friend(&self, invite: String) -> WResult { - self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?; + let node = self.node()?; + node.add_friend_from_qr(&invite).map_err(WireError::new)?; let p = qr::decode(&invite).map_err(WireError::new)?; - let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?; + let f = node.friend(&p.pubkey).map_err(WireError::new)?; Ok(FriendInfo { pubkey_hex: hex(&f.pubkey), fingerprint: f.fingerprint, @@ -183,26 +322,32 @@ impl Wire { /// Local label. Pass `None` to clear. Never goes on the wire. pub async fn set_petname(&self, pubkey_hex: String, petname: Option) -> WResult<()> { let pk = unhex(&pubkey_hex)?; - self.inner + self.node()? .set_petname(&pk, petname.as_deref()) .map_err(WireError::new) } - /// Send one message. Fail closed: if the peer's onion is down, this errors - /// after retrying. There is no outbox in v1 — no silent spooling. + /// Send one message. Returns once the outcome is known: delivered now, or + /// queued for retry because the peer's onion is unreachable. A protocol + /// error (bad signature, bad frame) still fails immediately and is never + /// queued. Use [`flush`](Self::flush) to retry the queue on demand. pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { let pk = unhex(&pubkey_hex)?; - self.inner + self.node()? .send(&pk, body.as_bytes()) .await - .map_err(WireError::new) + .map_err(WireError::new)?; + Ok(()) } /// Chat history for a friend, oldest first. Bodies are decrypted here; /// they are stored encrypted at rest. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; - let rows = self.inner.list_messages(&pk).map_err(WireError::new)?; + let rows = self + .node()? + .list_messages(&pk) + .map_err(WireError::new)?; Ok(rows .into_iter() .map(|m| ChatMessage { @@ -214,7 +359,7 @@ impl Wire { /// Delete every message body. Identity and friends survive. pub async fn wipe_messages(&self) -> WResult<()> { - self.inner.wipe_messages().map_err(WireError::new) + self.node()?.wipe_messages().map_err(WireError::new) } /// Publish a NEW onion service and hard-cut the old one, then push a signed @@ -224,7 +369,7 @@ impl Wire { /// you until they rescan your invite — that is the documented v1 behaviour, /// not a bug. Confirm with a typed phrase in the UI; never one tap. pub async fn rotate_onion(&self) -> WResult { - let r = self.inner.rotate().await.map_err(WireError::new)?; + let r = self.node()?.rotate().await.map_err(WireError::new)?; Ok(RotateOutcome { notified: r.notified as u32, friends: r.friends as u32, @@ -237,6 +382,14 @@ impl Wire { } } +fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { + FlushOutcome { + attempted: o.attempted as u32, + delivered: o.delivered as u32, + remaining: o.remaining as u32, + } +} + fn hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2); for b in bytes { @@ -256,3 +409,72 @@ fn unhex(s: &str) -> WResult> { }) .collect() } + +#[cfg(test)] +mod tests { + //! No Tor here on purpose: these exercise the *lifecycle* contract of the + //! handle, which is what a shut-down node must guarantee. A `Wire` with no + //! node is exactly the state `shutdown()` leaves behind. + + use super::*; + + fn stopped_wire() -> Wire { + Wire { + node: Mutex::new(None), + } + } + + fn block_on(f: F) -> F::Output { + // No `macros` feature on tokio in this crate, so build the runtime. + tokio::runtime::Builder::new_current_thread() + .build() + .expect("runtime") + .block_on(f) + } + + #[test] + fn tor_state_of_a_stopped_handle_is_stopped() { + assert_eq!(stopped_wire().tor_state(), TorState::Stopped); + } + + #[test] + fn calls_after_shutdown_are_typed_errors_not_panics() { + let wire = stopped_wire(); + + let err = block_on(wire.flush()).expect_err("flush after shutdown must fail"); + assert!( + matches!(err, WireError::Stopped { .. }), + "flush returned {err:?}, want WireError::Stopped" + ); + + let err = block_on(wire.send("00".repeat(32), "hi".to_string())) + .expect_err("send after shutdown must fail"); + assert!( + matches!(err, WireError::Stopped { .. }), + "send returned {err:?}, want WireError::Stopped" + ); + + let err = block_on(wire.friends()).expect_err("friends after shutdown must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + + let err = block_on(wire.shutdown()).expect_err("second shutdown must not re-run"); + assert!( + matches!(err, WireError::Stopped { .. }), + "second shutdown returned {err:?}" + ); + } + + #[test] + fn tor_state_maps_every_core_state() { + assert_eq!( + TorState::from(CoreTorState::Bootstrapping), + TorState::Bootstrapping + ); + assert_eq!(TorState::from(CoreTorState::Published), TorState::Published); + assert_eq!( + TorState::from(CoreTorState::DegradedReachable), + TorState::DegradedReachable + ); + assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); + } +} diff --git a/src/hs.rs b/src/hs.rs index 159e53d..f87f932 100644 --- a/src/hs.rs +++ b/src/hs.rs @@ -96,6 +96,64 @@ pub fn hs_is_ready(state: State, probe_ok: bool) -> bool { } } +/// Observable lifecycle state of the node's onion service. +/// +/// This is the four-state projection callers actually act on: is the onion +/// service serving, is it serving but unhealthy, is it still coming up, or did +/// we stop it. A process that gets killed by the Android background-process +/// killer never observes `Stopped` — that is why `Wire.flush()` exists — but a +/// clean teardown always does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TorState { + /// Bootstrap or HsDir descriptor upload is still in flight: the service is + /// not reliably reachable yet. + Bootstrapping, + /// The onion service is running and its descriptor is published. + Published, + /// Reachable through the service, but Arti reports the service degraded. + /// Usable, worth surfacing, not identical to `Published`. + DegradedReachable, + /// The node was shut down: no onion service, no client dials, and the + /// store is checkpointed. + Stopped, +} + +/// Project an Arti onion-service status onto [`TorState`]. +/// +/// Deliberately mirrors `hs_is_ready`: `Running` and `DegradedReachable` are +/// the states a probe could already reach, everything transient is +/// `Bootstrapping`, and a shut-down service is `Stopped`. +/// +/// `reachable` is the same evidence `wait_until_published` accepts from a +/// probe: a successful connect to our own onion means some HsDir already has +/// the descriptor even though Arti's combined status is still `Bootstrapping` +/// (that mismatch is exactly what the 360s publish wait exists for). Without +/// it, a node that is live and reachable would report `Bootstrapping` for +/// another few minutes. +/// +/// Two statuses look terminal but are not: +/// * `Shutdown` on a *live* node is transient — a freshly launched service +/// reports it before its publish reactor starts, which is why a live node +/// reads `Bootstrapping` there and only the explicit stop flag produces +/// `Stopped`. (Caught on device-real conditions by the live test: the +/// first `tor_state()` after `start()` returned `Shutdown`.) +/// * `Broken` maps to `Bootstrapping` rather than a state of its own: Arti +/// reads `Broken` while the HsDir retry loop is still going, and +/// `wait_until_published` is where a genuinely dead service surfaces as an +/// error instead of a flag the UI would have to poll for. +pub fn tor_state_of(state: State, stopped: bool, reachable: bool) -> TorState { + if stopped { + return TorState::Stopped; + } + match state { + State::Running => TorState::Published, + State::DegradedReachable => TorState::DegradedReachable, + State::Broken | State::Shutdown => TorState::Bootstrapping, + _ if reachable => TorState::Published, + _ => TorState::Bootstrapping, + } +} + pub async fn wait_until_published( client: &Client, svc: &RunningOnionService, diff --git a/src/node.rs b/src/node.rs index 9c3e931..60c490d 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,6 +1,7 @@ //! Two-node onion session: host HS, Noise IK, persist plaintext locally. use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -12,7 +13,7 @@ use tor_hsservice::{RunningOnionService, handle_rend_requests}; use crate::dispatch::{self, Kind}; use crate::file; use crate::frame; -use crate::hs::{self, Client, HS_PORT}; +use crate::hs::{self, Client, HS_PORT, TorState}; use crate::loc; use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; @@ -29,8 +30,27 @@ pub struct RotateResult { pub friends: usize, } +/// What a `flush` actually managed to do, for UI surfacing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FlushOutcome { + /// Outbox rows we tried to deliver in this pass. + pub attempted: usize, + /// Rows delivered now — their outbox rows are gone. + pub delivered: usize, + /// Rows still queued or terminally failed after the pass. + pub remaining: usize, +} + +/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead +/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and +/// the retry worker picks it up on its normal schedule. +pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30); +/// The drain inside `shutdown` gets a shorter budget: teardown must not hang +/// the caller behind a Tor dial. Undelivered rows survive in sqlite. +pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); + struct HsHandle { - _svc: Arc, + svc: Arc, rend: tokio::task::JoinHandle<()>, } @@ -60,7 +80,17 @@ pub struct Node { incoming_limit: Mutex, inbox: Mutex, outbox: Arc, - _outbox_worker: WorkerHandle, + worker: Mutex>, + /// Set by `shutdown`. Checked before any operation that would touch Tor or + /// the store, so a stopped node fails cleanly instead of dialing. + stopped: AtomicBool, + /// Has this node's onion service ever crossed the reachability bar (status + /// `Running`/`DegradedReachable`, or a successful probe of our own onion)? + /// Arti's combined status can stay `Bootstrapping` for minutes *after* the + /// descriptor is downloadable, so without this the UI would keep saying + /// "starting" long past the point where friends can reach us. Cleared when + /// `rotate` hard-cuts the service. + onion_reachable: AtomicBool, } impl Node { @@ -110,7 +140,9 @@ impl Node { incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), outbox: Arc::clone(&outbox), - _outbox_worker: WorkerHandle(outbox.spawn_worker()), + worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))), + stopped: AtomicBool::new(false), + onion_reachable: AtomicBool::new(false), }); // Unlock trigger: flush anything queued by a previous run now, in the // background, rather than waiting out its backoff. @@ -119,10 +151,14 @@ impl Node { // while combined status is still Bootstrapping. let rend = spawn_rend(Arc::clone(&node), rend); *node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle { - _svc: Arc::clone(&svc), + svc: Arc::clone(&svc), rend, }); hs::wait_until_published(&node.client, &svc, &onion).await?; + // Published by the same bar `wait_until_published` uses — a probe + // success counts, which is the whole reason `tor_state` tracks it + // separately from Arti's (slower, flappier) combined status. + node.onion_reachable.store(true, Ordering::SeqCst); node.store .lock() .map_err(|e| e.to_string())? @@ -131,6 +167,141 @@ impl Node { Ok(node) } + /// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` / + /// `DegradedReachable` / `Stopped`. + /// + /// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a + /// foreground-service notification can poll it instead of guessing from a + /// timer. A poisoned handle is reported as `Stopped` rather than panicking: + /// the node is unusable either way, and the caller is often a UI thread. + pub fn tor_state(&self) -> TorState { + let stopped = self.stopped.load(Ordering::SeqCst); + let reachable = self.onion_reachable.load(Ordering::SeqCst); + match self.hs.lock() { + Ok(guard) => match guard.as_ref() { + Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable), + // Between `rotate`'s hard cut and the new service being + // installed there is no handle; before the first publish there + // is none either. Both are "not serving *yet*" unless we stopped. + None if stopped => TorState::Stopped, + None => TorState::Bootstrapping, + }, + Err(_) => TorState::Stopped, + } + } + + /// Drain the outbox: one delivery attempt for every outstanding row, now, + /// ignoring its retry schedule. Then checkpoint the WAL. + /// + /// This is the "deliver what is deliverable before we lose the process" + /// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a + /// dial for ~20s and the caller is usually a UI thread. Rows that could not + /// be delivered stay queued and are picked up by the retry worker on its + /// normal backoff. + pub async fn flush(&self) -> Result { + self.ensure_running()?; + let outcome = self.drain(FLUSH_TIMEOUT).await?; + self.checkpoint(); + Ok(outcome) + } + + /// Stop the node. + /// + /// Order matters: drain the outbox while the Tor client is still alive, + /// then drop the onion service (its rendezvous task is aborted and the v3 + /// service goes down), then abort the retry worker so nothing dials after + /// this, then checkpoint the WAL. + /// + /// Idempotent: the flag is swapped first, so a second call — or a call + /// racing another teardown — returns `Ok(())` without touching anything + /// twice. Every other method on a stopped node returns a clean `Err`, never + /// a panic. A process killed outright never gets here at all, which is why + /// [`flush`](Self::flush) exists. + pub async fn shutdown(&self) -> Result<(), String> { + if self.stopped.swap(true, Ordering::SeqCst) { + return Ok(()); + } + // Bounded: teardown must not hang behind a Tor dial. Undelivered rows + // survive in sqlite and are retried on the next unlock. + match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await { + Ok(o) if o.remaining > 0 => { + eprintln!("shutdown: {} outbox row(s) still pending", o.remaining) + } + Ok(_) => {} + Err(e) => eprintln!("shutdown: drain failed: {e}"), + } + match self.hs.lock() { + Ok(mut g) => *g = None, + Err(_) => eprintln!("shutdown: onion-service lock poisoned"), + } + match self.worker.lock() { + Ok(mut g) => drop(g.take()), + Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"), + } + self.checkpoint(); + Ok(()) + } + + /// One bounded pass over every outstanding outbox row. + /// + /// A timeout cancels the pass mid-flight, which can leave a row in + /// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the + /// same recovery the parent uses for a process that died mid-attempt. + async fn drain(&self, budget: Duration) -> Result { + let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await { + Ok(Ok(rows)) => Some(rows), + Ok(Err(e)) => return Err(e), + Err(_) => { + eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued"); + None + } + }; + let delivered = attempted + .as_ref() + .map(|rows| { + rows.iter() + .filter(|(_, s)| matches!(s, OutboxStatus::Sent)) + .count() + }) + .unwrap_or(0); + Ok(FlushOutcome { + // `None` means the pass was cancelled: we know how many rows are + // still queued, not how many were started. + attempted: attempted.as_ref().map(Vec::len).unwrap_or(0), + delivered, + remaining: self.pending_rows()?, + }) + } + + /// Rows the outbox still holds for every friend, queued or terminally + /// failed. A message absent here was delivered. + fn pending_rows(&self) -> Result { + let friends = self.list_friends()?; + let mut n = 0usize; + for f in &friends { + n += self.outbox.pending(&f.pubkey)?.len(); + } + Ok(n) + } + + /// Checkpoint the sqlite WAL into the main db file and truncate it. + /// + /// Best effort on purpose: WAL replay on open recovers everything committed, + /// so this is about leaving less to replay (and less on disk) if the + /// process is killed right after teardown — not about correctness. + fn checkpoint(&self) { + if let Err(e) = checkpoint_wal(&self.home) { + eprintln!("wal checkpoint: {e}"); + } + } + + fn ensure_running(&self) -> Result<(), String> { + if self.stopped.load(Ordering::SeqCst) { + return Err("node is stopped — open the identity again".to_string()); + } + Ok(()) + } + pub fn onion(&self) -> String { self.onion.lock().map(|g| g.clone()).unwrap_or_default() } @@ -431,6 +602,7 @@ impl Node { } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { + self.ensure_running()?; let (onion, prekey) = { let f = self.friend(friend_pk)?; if f.prekey.len() != 32 { @@ -444,6 +616,7 @@ impl Node { /// Dial a peer's onion. Success is evidence the peer is up, which is one of /// the outbox retry triggers. pub async fn connect_onion(&self, onion: &str) -> Result<(), String> { + self.ensure_running()?; tokio::time::timeout( Duration::from_secs(20), self.client.connect((onion, HS_PORT)), @@ -463,6 +636,7 @@ impl Node { } pub async fn rotate(self: &Arc) -> Result { + self.ensure_running()?; let old_nick = self .store .lock() @@ -479,12 +653,16 @@ impl Node { let onion = hs::onion_string(&svc)?; // ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping. *self.hs.lock().map_err(|e| e.to_string())? = None; + // The new service is not reachable until it publishes: the locator in + // flight is dead until then, so do not carry the old verdict over. + self.onion_reachable.store(false, Ordering::SeqCst); let rend = spawn_rend(Arc::clone(self), rend); *self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle { - _svc: Arc::clone(&svc), + svc: Arc::clone(&svc), rend, }); hs::wait_until_published(&self.client, &svc, &onion).await?; + self.onion_reachable.store(true, Ordering::SeqCst); { let store = self.store.lock().map_err(|e| e.to_string())?; store.set_onion(&onion).map_err(|e| e.to_string())?; @@ -546,6 +724,7 @@ impl Node { /// backoff. A real protocol error (signature mismatch, unknown/short/oversize /// frame) still fails immediately and is never retried. pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.ensure_running()?; self.outbox.send(friend_pk, plaintext).await } @@ -854,6 +1033,34 @@ fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { }); } +/// Checkpoint the sqlite WAL into the main db file and truncate it. +/// +/// `Store` owns the write connection and deliberately does not lend it out, and +/// a checkpoint is a property of the *database*, not of one connection — so a +/// short-lived second connection to the same file is the least invasive way to +/// reach it from the node without widening `Store`'s API. The checkpoint needs +/// no passphrase: it moves already-committed pages, it does not decrypt them. +fn checkpoint_wal(home: &Path) -> Result<(), String> { + let db = home.join("onionwire.db"); + if !db.exists() { + return Ok(()); + } + let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?; + let (busy, log, checkpointed): (i64, i64, i64) = conn + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .map_err(|e| format!("wal_checkpoint: {e}"))?; + if busy != 0 { + // Another connection is reading/writing: pages are still safe in the + // WAL, they just were not moved this time. + return Err(format!( + "busy ({checkpointed}/{log} pages moved, another connection active)" + )); + } + Ok(()) +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") @@ -896,3 +1103,57 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } false } + +#[cfg(test)] +mod lifecycle_tests { + //! Offline half of the shutdown contract. The live-Tor half lives in + //! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI. + + use super::*; + + /// `checkpoint_wal` reaches the database through a *second* connection, + /// because `Store` owns the write one. That assumption is the whole reason + /// the helper can live in `node.rs`, so prove it against a real WAL. + #[test] + fn checkpoint_wal_truncates_a_live_wal() { + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path(); + let db = home.join("onionwire.db"); + let conn = rusqlite::Connection::open(&db).expect("open db"); + let mode: String = conn + .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)) + .expect("wal mode"); + assert_eq!(mode.to_lowercase(), "wal"); + conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);") + .expect("create table"); + for _ in 0..64 { + conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]]) + .expect("insert"); + } + + let wal = home.join("onionwire.db-wal"); + let before = std::fs::metadata(&wal).expect("wal file").len(); + assert!(before > 0, "expected pending WAL frames, got {before}"); + + checkpoint_wal(home).expect("checkpoint"); + + let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); + + // The rows are still there — a checkpoint moves pages, it never drops + // committed data. + let n: i64 = conn + .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)) + .expect("count"); + assert_eq!(n, 64); + } + + /// A home directory with no store yet is not an error: `shutdown` and + /// `flush` are safe to call on a node whose db was never created (tests, + /// wiped installs). + #[test] + fn checkpoint_wal_is_a_no_op_without_a_database() { + let root = tempfile::tempdir().expect("tempdir"); + checkpoint_wal(root.path()).expect("no db, no error"); + } +} diff --git a/tests/hs.rs b/tests/hs.rs index 334620c..d6fb620 100644 --- a/tests/hs.rs +++ b/tests/hs.rs @@ -69,6 +69,101 @@ fn broken_or_shutdown_never_ready() { assert!(!hs::hs_is_ready(State::Shutdown, true)); } +#[test] +fn tor_state_maps_every_arti_status() { + // The four states the Android UI branches on, derived from the same status + // union `hs_is_ready` reads. + assert_eq!( + hs::tor_state_of(State::Running, false, false), + hs::TorState::Published + ); + assert_eq!( + hs::tor_state_of(State::DegradedReachable, false, false), + hs::TorState::DegradedReachable + ); + assert_eq!( + hs::tor_state_of(State::Bootstrapping, false, false), + hs::TorState::Bootstrapping + ); + assert_eq!( + hs::tor_state_of(State::DegradedUnreachable, false, false), + hs::TorState::Bootstrapping + ); + // A freshly launched service reports Shutdown before its publish reactor + // starts. Mapping that to Stopped would make a live node look dead for the + // first seconds after unlock — caught on a real Tor network. + assert_eq!( + hs::tor_state_of(State::Shutdown, false, false), + hs::TorState::Bootstrapping + ); + // Arti reads `Broken` while the HsDir retry loop is still going; a dead + // service surfaces as an error from `wait_until_published`, not as a state + // the UI has to poll for. + assert_eq!( + hs::tor_state_of(State::Broken, false, false), + hs::TorState::Bootstrapping + ); +} + +#[test] +fn reachable_statuses_report_published_while_arti_says_bootstrapping() { + // `wait_until_published` returns on a successful probe while Arti's + // combined status is still Bootstrapping (see `hs_is_ready`). Reporting + // Bootstrapping there would keep the UI saying "starting" for minutes after + // friends can actually reach us. + assert_eq!( + hs::tor_state_of(State::Bootstrapping, false, true), + hs::TorState::Published + ); + assert_eq!( + hs::tor_state_of(State::DegradedUnreachable, false, true), + hs::TorState::Published + ); + // Broken stays Broken, reachable or not: `hs_is_ready` refuses it too. + assert_eq!( + hs::tor_state_of(State::Broken, false, true), + hs::TorState::Bootstrapping + ); +} + +#[test] +fn stopped_outranks_whatever_arti_reports() { + // A node that has been told to stop is Stopped even if Arti's status cache + // still says Running, and even if it was reachable a moment ago: the flag + // is set before the service is dropped. + for state in [ + State::Running, + State::DegradedReachable, + State::DegradedUnreachable, + State::Bootstrapping, + State::Broken, + State::Shutdown, + ] { + for reachable in [false, true] { + assert_eq!( + hs::tor_state_of(state, true, reachable), + hs::TorState::Stopped, + "wrong state for {state:?} (reachable={reachable}) on a stopped node" + ); + } + } +} + +#[test] +fn ready_states_are_the_published_ones() { + // Published/degraded must not drift from the readiness bar: anything + // `hs_is_ready` accepts without a probe is a state the UI calls up. + let ready = [State::Running, State::DegradedReachable]; + for state in ready { + assert!(hs::hs_is_ready(state, false), "{state:?} must be ready"); + assert_ne!( + hs::tor_state_of(state, false, false), + hs::TorState::Bootstrapping, + "{state:?} is ready but reported as still coming up" + ); + } +} + #[test] fn hs_log_label_is_not_the_full_v3_onion() { // Public v3 address; checksum is valid so HsId::from_str works. diff --git a/tests/tor_lifecycle.rs b/tests/tor_lifecycle.rs new file mode 100644 index 0000000..c74b081 --- /dev/null +++ b/tests/tor_lifecycle.rs @@ -0,0 +1,96 @@ +//! Lifecycle: a node stops when told to, says so, and refuses further work +//! with an error instead of panicking. +//! +//! Needs a live Tor network to publish the onion service, so `cargo test` skips +//! it. Run it on a networked machine with: +//! +//! ```text +//! cargo test --test tor_lifecycle -- --ignored --nocapture +//! ``` +//! +//! The offline half of this contract — the Arti-status projection, the WAL +//! checkpoint, and the SDK's typed error after shutdown — runs in the normal +//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`). + +use onionwire::node::{FlushOutcome, Node}; +use onionwire::hs::TorState; + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs live Tor network"] +async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() { + let _ = tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .with_test_writer() + .try_init(); + + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path().join("alice"); + unsafe { + std::env::set_var("ONIONWIRE_STORE_PASSPHRASE", "onionwire-test"); + } + + let node = Node::start(home.clone()).await.expect("start"); + + // `start` returns only after `wait_until_published`, so the node is + // reachable by the time a caller can call this — which must not read as + // `Stopped` or `Bootstrapping`. `DegradedReachable` is the honest answer + // when Arti says the service is degraded. + // + // This caught a real bug: `tor_state()` originally projected Arti's raw + // combined status, which is still `Bootstrapping` after a *successful* + // probe (that mismatch is what the 360s publish wait exists for), and which + // reads `Shutdown` on a service that has not started its reactor yet — so a + // live node reported `Stopped`. See `onion_reachable` in `src/node.rs`. + let started_state = node.tor_state(); + assert!( + matches!( + started_state, + TorState::Published | TorState::DegradedReachable + ), + "start returned Ok but tor_state() is {started_state:?}" + ); + + // A flush with nothing queued is a no-op that reports it, not an error. + let drained: FlushOutcome = node.flush().await.expect("flush on a live node"); + assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}"); + + node.shutdown().await.expect("shutdown"); + + assert_eq!( + node.tor_state(), + TorState::Stopped, + "tor_state must report Stopped after shutdown" + ); + + // Second shutdown: idempotent at the node level — no panic, no repeat work. + node.shutdown().await.expect("shutdown is idempotent"); + + let err = node + .flush() + .await + .expect_err("flush after shutdown must be an error"); + assert!(err.contains("stopped"), "flush error was {err:?}"); + + let err = node + .send(&[0u8; 32], b"after shutdown") + .await + .expect_err("send after shutdown must be an error"); + assert!(err.contains("stopped"), "send error was {err:?}"); + + // `RotateResult` is not `Debug`, so match on the error instead of + // `expect_err`. + let err = node + .rotate() + .await + .err() + .expect("rotate after shutdown must be an error"); + assert!(err.contains("stopped"), "rotate error was {err:?}"); + + // The store file survives the checkpoint: stopping is not wiping. + assert!( + home.join("onionwire.db").exists(), + "shutdown must not delete the store" + ); +} \ No newline at end of file From 3d41ffceb37d9165d1da037cacfd5b65c643b31a Mon Sep 17 00:00:00 2001 From: apk-dev Date: Sat, 12 Sep 2026 14:29:39 -0400 Subject: [PATCH 5/7] feat(android): stop the node when the UI goes away MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all, so neither the user pressing Lock nor the Activity finishing stopped anything: Arti kept its client and the hosted onion service, the outbox worker kept dialing, and the sqlite connection stayed open behind the JNI handle. Both paths now go through `stopNode(Wire)`: 1. `flush()` — one last bounded drain, so a queued message gets its chance before the process may lose its socket. 2. `shutdown()` — drain again with a shorter budget, stop the onion service, abort the retry worker, checkpoint the WAL, and take the node handle out of the `Wire` (which is what releases the last Arc to the Tor client and the store). Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`) because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors are deliberately swallowed there: the UI is gone, and the SDK reports a second teardown as the typed `WireException.Stopped` rather than a panic. `unlock()` joins any in-flight teardown before opening again. The old node holds the sqlite file and Arti's state lock until its teardown returns, and racing it makes the next `openWire` fail. A process killed outright (Doze, background-process killer, force-stop) still never runs any of this — that is what the sqlite outbox and the new `flush()` are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from the ViewModel to the service. --- .../siriusdevops/onionwire/WireViewModel.kt | 58 ++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 90cbf32..2e0560d 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -3,6 +3,10 @@ package com.siriusdevops.onionwire import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -32,6 +36,14 @@ sealed interface Phase { data class Failed(val message: String) : Phase } +/** + * Teardown work must outlive the ViewModel: `onCleared()` runs *after* + * `viewModelScope` is already cancelled, and stopping the node means draining + * the outbox and shutting Arti down, not just dropping a reference. One + * process-wide scope is enough — there is one node per process. + */ +private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO) + /** * Owns the single Wire node for the process. * @@ -51,6 +63,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private var wire: Wire? = null + /** + * The in-flight teardown, if any. Unlocking again has to wait for it: the + * old node holds the sqlite file and Arti's state lock until `shutdown()` + * returns, and racing it makes the new node fail to open. + */ + private var stopping: Job? = null + /** * Opens (or on first run, creates) the identity and starts hosting. * @@ -58,10 +77,12 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { * it is not a "skip" path. */ fun unlock(passphrase: String) { - if (_phase.value is Phase.Opening) return + if (_phase.value is Phase.Opening || wire != null) return _phase.value = Phase.Opening viewModelScope.launch { try { + // Any previous node must be fully stopped first. + stopping?.join() val w = openWire(home.absolutePath, passphrase) wire = w _phase.value = Phase.Ready( @@ -76,11 +97,44 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } } - /** Drops our handle. The onion service stops; nothing is sent after this. */ + /** + * Stops the node and drops our handle. Nothing is sent after this. + * + * Flush first — the outbox is the whole point of losing the process — then + * `shutdown()`, which stops the onion service, aborts the retry worker and + * checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this + * runs from an `onClick`. + */ fun lock() { + val w = wire ?: return wire = null _friends.value = emptyList() _phase.value = Phase.Locked + stopping = TEARDOWN.launch { stopNode(w) } + } + + /** + * The node must not outlive the UI. Doze and the background-process killer + * skip this entirely (that is what the outbox is for), but a normal finish + * tears Tor down here instead of leaving Arti running behind a dead screen. + */ + override fun onCleared() { + val w = wire + wire = null + if (w != null) stopping = TEARDOWN.launch { stopNode(w) } + super.onCleared() + } + + private suspend fun stopNode(w: Wire) { + // Best effort, both steps: teardown runs on a process-scope job after + // the UI is gone, so there is nobody to show an error to and nothing + // useful to retry. `shutdown()` drains again with a shorter budget, so + // a flush that times out is not fatal. + runCatching { w.flush() } + // A second shutdown — `lock()` and then `onCleared()`, say — lands here + // too: the SDK reports it as a typed WireException.Stopped, never a + // panic, so swallowing it is correct. + runCatching { w.shutdown() } } private fun requireWire(): Wire = wire ?: error("locked") From 6e0226e3861f78b0f22c9ee236c2c9d1af48f18a Mon Sep 17 00:00:00 2001 From: apk-dev Date: Sat, 12 Sep 2026 14:29:02 -0400 Subject: [PATCH 6/7] =?UTF-8?q?feat(core,sdk):=20explicit=20Tor=20lifecycl?= =?UTF-8?q?e=20=E2=80=94=20stop,=20flush,=20observable=20state?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the Kotlin reference left Arti's client, the hosted v3 onion service, the outbox retry worker and the sqlite connection alive, and there was no way to ask where the onion service was. On Android the process is killed without warning by Doze and the background-process killer, so "drop everything when the process dies" is not a lifecycle. Core (`src/node.rs`, `src/hs.rs`): * `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the rendezvous task is aborted and the RunningOnionService dropped), abort the retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is swapped first, so a racing second call is a no-op. * `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one delivery attempt for every queued outbox row, ignoring backoff, then a WAL checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s and the caller is a UI thread. A timeout leaves rows in `sending`; `Outbox::reset_stale` requeues them on the next unlock, same as a process that died mid-attempt. * `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` / `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped, reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving readiness. * Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`, `flush`) fails with a typed error after the node stops, rather than dialing a dead client. * `checkpoint_wal` reaches the database through a short-lived second connection: `Store` owns the write connection and does not lend it out, and a checkpoint is a property of the database, not of one connection. Best effort — WAL replay on open recovers anything committed. The `WorkerHandle` moved into a `Mutex>` so the teardown can *abort* the retry worker instead of only dropping it when the whole `Node` dies. SDK (`crates/onionwire-sdk/src/lib.rs`): * `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`. `Wire` now holds `Mutex>>`, so teardown drops the last reference to the Tor client and the store instead of keeping them alive behind a JNI handle. * `WireError::Stopped` — a second flat variant, so "you must unlock again" is a typed `WireException.Stopped` in Kotlin, not a string match on `Failed`. * No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports `Stopped`, which is the correct recovery (unlock again). * Fixes the crate not compiling on this base at all: `Node::send` has returned `Result` since the outbox landed, and the SDK still mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes `crates/**` from the Rust job, which is why it stayed green. The live Tor test found a real bug in the first version of `tor_state`: Arti's combined status is still `Bootstrapping` after a *successful* probe of our own onion (that mismatch is what the 360s publish wait exists for), and a freshly launched service reports `Shutdown` before its publish reactor starts — so a node that was live and reachable reported `Bootstrapping`, and briefly `Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set when the publish bar is crossed and cleared when `rotate` hard-cuts the service, and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather than terminal. --- crates/onionwire-sdk/src/lib.rs | 260 +++++++++++++++++++++++++--- src/hs.rs | 58 +++++++ src/node.rs | 288 +++++++++++++++++++++++++++++++- tests/hs.rs | 95 +++++++++++ tests/tor_lifecycle.rs | 96 +++++++++++ 5 files changed, 772 insertions(+), 25 deletions(-) create mode 100644 tests/tor_lifecycle.rs diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index e90c7fa..b81f016 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -13,13 +13,20 @@ //! Orbot pipe. If the onion service cannot publish, this fails closed. //! * Chat bodies are encrypted at rest. Identity keys in sqlite are not. //! +//! Lifecycle: a node is started by [`open_wire`] and stopped by +//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable +//! state and [`Wire::flush`] is "deliver what is deliverable now". A process +//! killed by Doze or the background-process killer never runs `shutdown`, which +//! is exactly why queued sends live in sqlite and not in memory. +//! //! The façade deliberately exposes only plain data (records + hex strings) so //! no TUI/ratatui type leaks into the AAR. use std::path::PathBuf; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; -use onionwire::node::Node; +use onionwire::hs::TorState as CoreTorState; +use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::qr; uniffi::setup_scaffolding!(); @@ -54,6 +61,12 @@ pub fn install_crypto_provider() { pub enum WireError { #[error("{message}")] Failed { message: String }, + /// The node was shut down (or never opened). Distinct from `Failed` so + /// Kotlin can branch on it instead of string-matching a message, and so + /// "you must unlock again" is a different UI state from "the network is + /// broken". + #[error("node stopped: {message}")] + Stopped { message: String }, } impl WireError { @@ -62,6 +75,12 @@ impl WireError { message: e.to_string(), } } + + fn stopped(what: &str) -> Self { + Self::Stopped { + message: format!("{what} called on a shut-down node"), + } + } } type WResult = std::result::Result; @@ -98,10 +117,70 @@ pub struct InviteInfo { pub onion: String, } +/// Observable lifecycle state of the node's onion service. +/// +/// Mirrors Arti's own service status, projected onto the four states a UI +/// actually acts on. It is the same distinction `hs::hs_is_ready` makes when it +/// decides whether the onion is reachable yet. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TorState { + /// Bootstrap or descriptor upload still in flight. Not reliably reachable. + Bootstrapping, + /// Onion service running and its descriptor published. + Published, + /// Reachable, but Arti reports the service degraded. Usable — worth saying + /// so, not identical to `Published`. + DegradedReachable, + /// Shut down: no onion service, no dials, store checkpointed. Every method + /// on the node now returns `WireError.Stopped`. + Stopped, +} + +impl From for TorState { + fn from(s: CoreTorState) -> Self { + match s { + CoreTorState::Bootstrapping => Self::Bootstrapping, + CoreTorState::Published => Self::Published, + CoreTorState::DegradedReachable => Self::DegradedReachable, + CoreTorState::Stopped => Self::Stopped, + } + } +} + +/// What a [`Wire::flush`] managed to do. +#[derive(Debug, Clone, Copy, uniffi::Record)] +pub struct FlushOutcome { + /// Rows the pass started a delivery for. `0` when the pass hit its time + /// budget before finishing — the rows are still queued, we just stopped + /// counting. + pub attempted: u32, + /// Rows delivered now. A message absent from `remaining` was sent. + pub delivered: u32, + /// Rows still queued or terminally failed afterwards. + pub remaining: u32, +} + /// A running OnionWire node: identity + Arti client + hosted v3 onion service. +/// +/// Holds the node handle. [`Wire::shutdown`] takes it out and drops it, which +/// is what lets the last reference to the Tor client and the store go away — +/// there is no hidden global keeping Arti (or the sqlite connection) alive +/// after the UI is gone. #[derive(uniffi::Object)] pub struct Wire { - inner: Arc, + node: Mutex>>, +} + +impl Wire { + /// The live node, or `Stopped` if this handle was shut down. A poisoned + /// mutex is reported the same way rather than panicking: a caller that sees + /// `Stopped` unlocks again, which is the correct recovery either way. + fn node(&self) -> WResult> { + let guard = self.node.lock().map_err(|_| WireError::Stopped { + message: "node handle lock poisoned by a panic; reopen the identity".to_string(), + })?; + guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call")) + } } /// Open (or create) the identity in `home` and start hosting an onion service. @@ -111,6 +190,11 @@ pub struct Wire { /// /// This resolves only once the onion service is published — on a cold network /// that is minutes, not seconds. Call it off the main thread. +/// +/// The returned handle owns the node: it lives until [`Wire::shutdown`], or +/// until the handle itself is dropped (which the JVM does without running the +/// drain, so call `shutdown()` from teardown — see the foreground-service +/// caller). #[uniffi::export(async_runtime = "tokio")] pub async fn open_wire(home: String, passphrase: String) -> WResult> { // Before anything that can build a TLS config: Arti's rustls backend dies @@ -120,7 +204,9 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult> { let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase) .await .map_err(WireError::new)?; - Ok(Arc::new(Wire { inner: node })) + Ok(Arc::new(Wire { + node: Mutex::new(Some(node)), + })) } /// Decode an invite without adding the friend. Verifies the signature. @@ -135,24 +221,76 @@ pub fn decode_invite(invite: String) -> WResult { #[uniffi::export(async_runtime = "tokio")] impl Wire { + /// Stop the node: give every queued outbox row one last bounded delivery + /// attempt, stop the onion service, abort the retry worker, checkpoint the + /// sqlite WAL, and drop the Tor client. + /// + /// Idempotent and safe to call twice, including from two threads: the + /// second call is a no-op returning `Ok`. After it, every other method on + /// this handle — including `send` — returns `WireError.Stopped` instead of + /// touching a dead client or panicking. + /// + /// Never called at all when the process is killed outright (Doze, the + /// background-process killer, a force-stop): that is the case [`flush`] + /// (Self::flush) and the sqlite outbox exist for. Once shut down, this + /// handle is spent — unlock again to get a new one. + pub async fn shutdown(&self) -> WResult<()> { + let node = self.node()?; + node.shutdown().await.map_err(WireError::new)?; + // Drop our handle to the node. With the onion service and the outbox + // worker aborted this is the last reference to the Tor client and the + // store, so Arti's runtime and the sqlite connection are released here. + let mut guard = self.node.lock().map_err(|_| WireError::Stopped { + message: "node handle lock poisoned by a panic".to_string(), + })?; + *guard = None; + Ok(()) + } + + /// Drain the outbox: one delivery attempt for every queued row, now, + /// ignoring its retry backoff, then checkpoint the WAL. + /// + /// Bounded by the SDK (30s): a dead peer's onion can hold a dial for ~20s + /// and this is called from UI/lifecycle threads. Rows that did not go out + /// stay queued; the retry worker keeps its normal schedule. Safe to call + /// repeatedly — use it on unlock, on foreground, and before `shutdown`. + pub async fn flush(&self) -> WResult { + let node = self.node()?; + let out = node.flush().await.map_err(WireError::new)?; + Ok(from_core_flush(out)) + } + + /// Where the onion service is right now. Cheap and read-only, no I/O: a + /// notification or a settings screen can call it directly. + pub fn tor_state(&self) -> TorState { + match self.node.lock() { + Ok(guard) => match guard.as_ref() { + Some(node) => node.tor_state().into(), + None => TorState::Stopped, + }, + // Poisoned: same answer as shut down — the node is unusable. + Err(_) => TorState::Stopped, + } + } + /// Fingerprint of our own identity key. Stable forever for this install. pub async fn fingerprint(&self) -> WResult { - self.inner.fingerprint().map_err(WireError::new) + self.node()?.fingerprint().map_err(WireError::new) } /// Current onion locator. Changes on rotate; identity does not. - pub async fn onion(&self) -> String { - self.inner.onion() + pub async fn onion(&self) -> WResult { + Ok(self.node()?.onion()) } /// `onionwire:v1:…` invite string to hand to the other person out of band. pub async fn invite(&self) -> WResult { - self.inner.qr_payload().map_err(WireError::new) + self.node()?.qr_payload().map_err(WireError::new) } /// Roster, sorted by petname then fingerprint. pub async fn friends(&self) -> WResult> { - let list = self.inner.list_friends().map_err(WireError::new)?; + let list = self.node()?.list_friends().map_err(WireError::new)?; Ok(list .into_iter() .map(|f| FriendInfo { @@ -168,9 +306,10 @@ impl Wire { /// Add a friend from an invite, or update the locator if the key is known. /// Same `k` never creates a second row. pub async fn add_friend(&self, invite: String) -> WResult { - self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?; + let node = self.node()?; + node.add_friend_from_qr(&invite).map_err(WireError::new)?; let p = qr::decode(&invite).map_err(WireError::new)?; - let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?; + let f = node.friend(&p.pubkey).map_err(WireError::new)?; Ok(FriendInfo { pubkey_hex: hex(&f.pubkey), fingerprint: f.fingerprint, @@ -183,26 +322,32 @@ impl Wire { /// Local label. Pass `None` to clear. Never goes on the wire. pub async fn set_petname(&self, pubkey_hex: String, petname: Option) -> WResult<()> { let pk = unhex(&pubkey_hex)?; - self.inner + self.node()? .set_petname(&pk, petname.as_deref()) .map_err(WireError::new) } - /// Send one message. Fail closed: if the peer's onion is down, this errors - /// after retrying. There is no outbox in v1 — no silent spooling. + /// Send one message. Returns once the outcome is known: delivered now, or + /// queued for retry because the peer's onion is unreachable. A protocol + /// error (bad signature, bad frame) still fails immediately and is never + /// queued. Use [`flush`](Self::flush) to retry the queue on demand. pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { let pk = unhex(&pubkey_hex)?; - self.inner + self.node()? .send(&pk, body.as_bytes()) .await - .map_err(WireError::new) + .map_err(WireError::new)?; + Ok(()) } /// Chat history for a friend, oldest first. Bodies are decrypted here; /// they are stored encrypted at rest. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; - let rows = self.inner.list_messages(&pk).map_err(WireError::new)?; + let rows = self + .node()? + .list_messages(&pk) + .map_err(WireError::new)?; Ok(rows .into_iter() .map(|m| ChatMessage { @@ -214,7 +359,7 @@ impl Wire { /// Delete every message body. Identity and friends survive. pub async fn wipe_messages(&self) -> WResult<()> { - self.inner.wipe_messages().map_err(WireError::new) + self.node()?.wipe_messages().map_err(WireError::new) } /// Publish a NEW onion service and hard-cut the old one, then push a signed @@ -224,7 +369,7 @@ impl Wire { /// you until they rescan your invite — that is the documented v1 behaviour, /// not a bug. Confirm with a typed phrase in the UI; never one tap. pub async fn rotate_onion(&self) -> WResult { - let r = self.inner.rotate().await.map_err(WireError::new)?; + let r = self.node()?.rotate().await.map_err(WireError::new)?; Ok(RotateOutcome { notified: r.notified as u32, friends: r.friends as u32, @@ -237,6 +382,14 @@ impl Wire { } } +fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { + FlushOutcome { + attempted: o.attempted as u32, + delivered: o.delivered as u32, + remaining: o.remaining as u32, + } +} + fn hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2); for b in bytes { @@ -256,3 +409,72 @@ fn unhex(s: &str) -> WResult> { }) .collect() } + +#[cfg(test)] +mod tests { + //! No Tor here on purpose: these exercise the *lifecycle* contract of the + //! handle, which is what a shut-down node must guarantee. A `Wire` with no + //! node is exactly the state `shutdown()` leaves behind. + + use super::*; + + fn stopped_wire() -> Wire { + Wire { + node: Mutex::new(None), + } + } + + fn block_on(f: F) -> F::Output { + // No `macros` feature on tokio in this crate, so build the runtime. + tokio::runtime::Builder::new_current_thread() + .build() + .expect("runtime") + .block_on(f) + } + + #[test] + fn tor_state_of_a_stopped_handle_is_stopped() { + assert_eq!(stopped_wire().tor_state(), TorState::Stopped); + } + + #[test] + fn calls_after_shutdown_are_typed_errors_not_panics() { + let wire = stopped_wire(); + + let err = block_on(wire.flush()).expect_err("flush after shutdown must fail"); + assert!( + matches!(err, WireError::Stopped { .. }), + "flush returned {err:?}, want WireError::Stopped" + ); + + let err = block_on(wire.send("00".repeat(32), "hi".to_string())) + .expect_err("send after shutdown must fail"); + assert!( + matches!(err, WireError::Stopped { .. }), + "send returned {err:?}, want WireError::Stopped" + ); + + let err = block_on(wire.friends()).expect_err("friends after shutdown must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + + let err = block_on(wire.shutdown()).expect_err("second shutdown must not re-run"); + assert!( + matches!(err, WireError::Stopped { .. }), + "second shutdown returned {err:?}" + ); + } + + #[test] + fn tor_state_maps_every_core_state() { + assert_eq!( + TorState::from(CoreTorState::Bootstrapping), + TorState::Bootstrapping + ); + assert_eq!(TorState::from(CoreTorState::Published), TorState::Published); + assert_eq!( + TorState::from(CoreTorState::DegradedReachable), + TorState::DegradedReachable + ); + assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); + } +} diff --git a/src/hs.rs b/src/hs.rs index 159e53d..f87f932 100644 --- a/src/hs.rs +++ b/src/hs.rs @@ -96,6 +96,64 @@ pub fn hs_is_ready(state: State, probe_ok: bool) -> bool { } } +/// Observable lifecycle state of the node's onion service. +/// +/// This is the four-state projection callers actually act on: is the onion +/// service serving, is it serving but unhealthy, is it still coming up, or did +/// we stop it. A process that gets killed by the Android background-process +/// killer never observes `Stopped` — that is why `Wire.flush()` exists — but a +/// clean teardown always does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TorState { + /// Bootstrap or HsDir descriptor upload is still in flight: the service is + /// not reliably reachable yet. + Bootstrapping, + /// The onion service is running and its descriptor is published. + Published, + /// Reachable through the service, but Arti reports the service degraded. + /// Usable, worth surfacing, not identical to `Published`. + DegradedReachable, + /// The node was shut down: no onion service, no client dials, and the + /// store is checkpointed. + Stopped, +} + +/// Project an Arti onion-service status onto [`TorState`]. +/// +/// Deliberately mirrors `hs_is_ready`: `Running` and `DegradedReachable` are +/// the states a probe could already reach, everything transient is +/// `Bootstrapping`, and a shut-down service is `Stopped`. +/// +/// `reachable` is the same evidence `wait_until_published` accepts from a +/// probe: a successful connect to our own onion means some HsDir already has +/// the descriptor even though Arti's combined status is still `Bootstrapping` +/// (that mismatch is exactly what the 360s publish wait exists for). Without +/// it, a node that is live and reachable would report `Bootstrapping` for +/// another few minutes. +/// +/// Two statuses look terminal but are not: +/// * `Shutdown` on a *live* node is transient — a freshly launched service +/// reports it before its publish reactor starts, which is why a live node +/// reads `Bootstrapping` there and only the explicit stop flag produces +/// `Stopped`. (Caught on device-real conditions by the live test: the +/// first `tor_state()` after `start()` returned `Shutdown`.) +/// * `Broken` maps to `Bootstrapping` rather than a state of its own: Arti +/// reads `Broken` while the HsDir retry loop is still going, and +/// `wait_until_published` is where a genuinely dead service surfaces as an +/// error instead of a flag the UI would have to poll for. +pub fn tor_state_of(state: State, stopped: bool, reachable: bool) -> TorState { + if stopped { + return TorState::Stopped; + } + match state { + State::Running => TorState::Published, + State::DegradedReachable => TorState::DegradedReachable, + State::Broken | State::Shutdown => TorState::Bootstrapping, + _ if reachable => TorState::Published, + _ => TorState::Bootstrapping, + } +} + pub async fn wait_until_published( client: &Client, svc: &RunningOnionService, diff --git a/src/node.rs b/src/node.rs index 9c3e931..3d528be 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,6 +1,7 @@ //! Two-node onion session: host HS, Noise IK, persist plaintext locally. use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -12,7 +13,7 @@ use tor_hsservice::{RunningOnionService, handle_rend_requests}; use crate::dispatch::{self, Kind}; use crate::file; use crate::frame; -use crate::hs::{self, Client, HS_PORT}; +use crate::hs::{self, Client, HS_PORT, TorState}; use crate::loc; use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; @@ -29,8 +30,27 @@ pub struct RotateResult { pub friends: usize, } +/// What a `flush` actually managed to do, for UI surfacing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FlushOutcome { + /// Outbox rows we tried to deliver in this pass. + pub attempted: usize, + /// Rows delivered now — their outbox rows are gone. + pub delivered: usize, + /// Rows still queued or terminally failed after the pass. + pub remaining: usize, +} + +/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead +/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and +/// the retry worker picks it up on its normal schedule. +pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30); +/// The drain inside `shutdown` gets a shorter budget: teardown must not hang +/// the caller behind a Tor dial. Undelivered rows survive in sqlite. +pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); + struct HsHandle { - _svc: Arc, + svc: Arc, rend: tokio::task::JoinHandle<()>, } @@ -60,7 +80,17 @@ pub struct Node { incoming_limit: Mutex, inbox: Mutex, outbox: Arc, - _outbox_worker: WorkerHandle, + worker: Mutex>, + /// Set by `shutdown`. Checked before any operation that would touch Tor or + /// the store, so a stopped node fails cleanly instead of dialing. + stopped: AtomicBool, + /// Has this node's onion service ever crossed the reachability bar (status + /// `Running`/`DegradedReachable`, or a successful probe of our own onion)? + /// Arti's combined status can stay `Bootstrapping` for minutes *after* the + /// descriptor is downloadable, so without this the UI would keep saying + /// "starting" long past the point where friends can reach us. Cleared when + /// `rotate` hard-cuts the service. + onion_reachable: AtomicBool, } impl Node { @@ -110,7 +140,9 @@ impl Node { incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), outbox: Arc::clone(&outbox), - _outbox_worker: WorkerHandle(outbox.spawn_worker()), + worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))), + stopped: AtomicBool::new(false), + onion_reachable: AtomicBool::new(false), }); // Unlock trigger: flush anything queued by a previous run now, in the // background, rather than waiting out its backoff. @@ -119,10 +151,14 @@ impl Node { // while combined status is still Bootstrapping. let rend = spawn_rend(Arc::clone(&node), rend); *node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle { - _svc: Arc::clone(&svc), + svc: Arc::clone(&svc), rend, }); hs::wait_until_published(&node.client, &svc, &onion).await?; + // Published by the same bar `wait_until_published` uses — a probe + // success counts, which is the whole reason `tor_state` tracks it + // separately from Arti's (slower, flappier) combined status. + node.onion_reachable.store(true, Ordering::SeqCst); node.store .lock() .map_err(|e| e.to_string())? @@ -131,6 +167,141 @@ impl Node { Ok(node) } + /// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` / + /// `DegradedReachable` / `Stopped`. + /// + /// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a + /// foreground-service notification can poll it instead of guessing from a + /// timer. A poisoned handle is reported as `Stopped` rather than panicking: + /// the node is unusable either way, and the caller is often a UI thread. + pub fn tor_state(&self) -> TorState { + let stopped = self.stopped.load(Ordering::SeqCst); + let reachable = self.onion_reachable.load(Ordering::SeqCst); + match self.hs.lock() { + Ok(guard) => match guard.as_ref() { + Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable), + // Between `rotate`'s hard cut and the new service being + // installed there is no handle; before the first publish there + // is none either. Both are "not serving *yet*" unless we stopped. + None if stopped => TorState::Stopped, + None => TorState::Bootstrapping, + }, + Err(_) => TorState::Stopped, + } + } + + /// Drain the outbox: one delivery attempt for every outstanding row, now, + /// ignoring its retry schedule. Then checkpoint the WAL. + /// + /// This is the "deliver what is deliverable before we lose the process" + /// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a + /// dial for ~20s and the caller is usually a UI thread. Rows that could not + /// be delivered stay queued and are picked up by the retry worker on its + /// normal backoff. + pub async fn flush(&self) -> Result { + self.ensure_running()?; + let outcome = self.drain(FLUSH_TIMEOUT).await?; + self.checkpoint(); + Ok(outcome) + } + + /// Stop the node. + /// + /// Order matters: drain the outbox while the Tor client is still alive, + /// then drop the onion service (its rendezvous task is aborted and the v3 + /// service goes down), then abort the retry worker so nothing dials after + /// this, then checkpoint the WAL. + /// + /// Idempotent: the flag is swapped first, so a second call — or a call + /// racing another teardown — returns `Ok(())` without touching anything + /// twice. Every other method on a stopped node returns a clean `Err`, never + /// a panic. A process killed outright never gets here at all, which is why + /// [`flush`](Self::flush) exists. + pub async fn shutdown(&self) -> Result<(), String> { + if self.stopped.swap(true, Ordering::SeqCst) { + return Ok(()); + } + // Bounded: teardown must not hang behind a Tor dial. Undelivered rows + // survive in sqlite and are retried on the next unlock. + match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await { + Ok(o) if o.remaining > 0 => { + eprintln!("shutdown: {} outbox row(s) still pending", o.remaining) + } + Ok(_) => {} + Err(e) => eprintln!("shutdown: drain failed: {e}"), + } + match self.hs.lock() { + Ok(mut g) => *g = None, + Err(_) => eprintln!("shutdown: onion-service lock poisoned"), + } + match self.worker.lock() { + Ok(mut g) => drop(g.take()), + Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"), + } + self.checkpoint(); + Ok(()) + } + + /// One bounded pass over every outstanding outbox row. + /// + /// A timeout cancels the pass mid-flight, which can leave a row in + /// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the + /// same recovery the parent uses for a process that died mid-attempt. + async fn drain(&self, budget: Duration) -> Result { + let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await { + Ok(Ok(rows)) => Some(rows), + Ok(Err(e)) => return Err(e), + Err(_) => { + eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued"); + None + } + }; + let delivered = attempted + .as_ref() + .map(|rows| { + rows.iter() + .filter(|(_, s)| matches!(s, OutboxStatus::Sent)) + .count() + }) + .unwrap_or(0); + Ok(FlushOutcome { + // `None` means the pass was cancelled: we know how many rows are + // still queued, not how many were started. + attempted: attempted.as_ref().map(Vec::len).unwrap_or(0), + delivered, + remaining: self.pending_rows()?, + }) + } + + /// Rows the outbox still holds for every friend, queued or terminally + /// failed. A message absent here was delivered. + fn pending_rows(&self) -> Result { + let friends = self.list_friends()?; + let mut n = 0usize; + for f in &friends { + n += self.outbox.pending(&f.pubkey)?.len(); + } + Ok(n) + } + + /// Checkpoint the sqlite WAL into the main db file and truncate it. + /// + /// Best effort on purpose: WAL replay on open recovers everything committed, + /// so this is about leaving less to replay (and less on disk) if the + /// process is killed right after teardown — not about correctness. + fn checkpoint(&self) { + if let Err(e) = checkpoint_wal(&self.home) { + eprintln!("wal checkpoint: {e}"); + } + } + + fn ensure_running(&self) -> Result<(), String> { + if self.stopped.load(Ordering::SeqCst) { + return Err("node is stopped — open the identity again".to_string()); + } + Ok(()) + } + pub fn onion(&self) -> String { self.onion.lock().map(|g| g.clone()).unwrap_or_default() } @@ -431,6 +602,7 @@ impl Node { } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { + self.ensure_running()?; let (onion, prekey) = { let f = self.friend(friend_pk)?; if f.prekey.len() != 32 { @@ -444,6 +616,7 @@ impl Node { /// Dial a peer's onion. Success is evidence the peer is up, which is one of /// the outbox retry triggers. pub async fn connect_onion(&self, onion: &str) -> Result<(), String> { + self.ensure_running()?; tokio::time::timeout( Duration::from_secs(20), self.client.connect((onion, HS_PORT)), @@ -463,6 +636,7 @@ impl Node { } pub async fn rotate(self: &Arc) -> Result { + self.ensure_running()?; let old_nick = self .store .lock() @@ -479,12 +653,16 @@ impl Node { let onion = hs::onion_string(&svc)?; // ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping. *self.hs.lock().map_err(|e| e.to_string())? = None; + // The new service is not reachable until it publishes: the locator in + // flight is dead until then, so do not carry the old verdict over. + self.onion_reachable.store(false, Ordering::SeqCst); let rend = spawn_rend(Arc::clone(self), rend); *self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle { - _svc: Arc::clone(&svc), + svc: Arc::clone(&svc), rend, }); hs::wait_until_published(&self.client, &svc, &onion).await?; + self.onion_reachable.store(true, Ordering::SeqCst); { let store = self.store.lock().map_err(|e| e.to_string())?; store.set_onion(&onion).map_err(|e| e.to_string())?; @@ -546,6 +724,7 @@ impl Node { /// backoff. A real protocol error (signature mismatch, unknown/short/oversize /// frame) still fails immediately and is never retried. pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.ensure_running()?; self.outbox.send(friend_pk, plaintext).await } @@ -854,6 +1033,49 @@ fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { }); } +/// Checkpoint the sqlite WAL into the main db file and truncate it. +/// +/// `Store` owns the write connection and deliberately does not lend it out, and +/// a checkpoint is a property of the *database*, not of one connection — so a +/// short-lived second connection to the same file is the least invasive way to +/// reach it from the node without widening `Store`'s API. +/// +/// That works because the connection needs no passphrase: it moves +/// already-committed pages, it does not decrypt them. It stops working the +/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only +/// inside `Store` and a second connection cannot read the file at all. That case +/// is detected and reported as a skip rather than a failure: nothing is lost +/// (sqlite folds the WAL into the db when the last connection closes) — the +/// explicit truncation just has to move inside `Store` to happen here. +fn checkpoint_wal(home: &Path) -> Result<(), String> { + let db = home.join("onionwire.db"); + if !db.exists() { + return Ok(()); + } + let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?; + let (busy, log, checkpointed): (i64, i64, i64) = conn + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .map_err(|e| { + let msg = e.to_string(); + if msg.contains("not a database") { + // SQLCipher store: no key here, so this connection sees noise. + format!("store is SQLCipher-encrypted — skipped ({msg})") + } else { + format!("wal_checkpoint: {msg}") + } + })?; + if busy != 0 { + // Another connection is reading/writing: pages are still safe in the + // WAL, they just were not moved this time. + return Err(format!( + "busy ({checkpointed}/{log} pages moved, another connection active)" + )); + } + Ok(()) +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") @@ -896,3 +1118,57 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } false } + +#[cfg(test)] +mod lifecycle_tests { + //! Offline half of the shutdown contract. The live-Tor half lives in + //! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI. + + use super::*; + + /// `checkpoint_wal` reaches the database through a *second* connection, + /// because `Store` owns the write one. That assumption is the whole reason + /// the helper can live in `node.rs`, so prove it against a real WAL. + #[test] + fn checkpoint_wal_truncates_a_live_wal() { + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path(); + let db = home.join("onionwire.db"); + let conn = rusqlite::Connection::open(&db).expect("open db"); + let mode: String = conn + .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)) + .expect("wal mode"); + assert_eq!(mode.to_lowercase(), "wal"); + conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);") + .expect("create table"); + for _ in 0..64 { + conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]]) + .expect("insert"); + } + + let wal = home.join("onionwire.db-wal"); + let before = std::fs::metadata(&wal).expect("wal file").len(); + assert!(before > 0, "expected pending WAL frames, got {before}"); + + checkpoint_wal(home).expect("checkpoint"); + + let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); + + // The rows are still there — a checkpoint moves pages, it never drops + // committed data. + let n: i64 = conn + .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)) + .expect("count"); + assert_eq!(n, 64); + } + + /// A home directory with no store yet is not an error: `shutdown` and + /// `flush` are safe to call on a node whose db was never created (tests, + /// wiped installs). + #[test] + fn checkpoint_wal_is_a_no_op_without_a_database() { + let root = tempfile::tempdir().expect("tempdir"); + checkpoint_wal(root.path()).expect("no db, no error"); + } +} diff --git a/tests/hs.rs b/tests/hs.rs index 334620c..d6fb620 100644 --- a/tests/hs.rs +++ b/tests/hs.rs @@ -69,6 +69,101 @@ fn broken_or_shutdown_never_ready() { assert!(!hs::hs_is_ready(State::Shutdown, true)); } +#[test] +fn tor_state_maps_every_arti_status() { + // The four states the Android UI branches on, derived from the same status + // union `hs_is_ready` reads. + assert_eq!( + hs::tor_state_of(State::Running, false, false), + hs::TorState::Published + ); + assert_eq!( + hs::tor_state_of(State::DegradedReachable, false, false), + hs::TorState::DegradedReachable + ); + assert_eq!( + hs::tor_state_of(State::Bootstrapping, false, false), + hs::TorState::Bootstrapping + ); + assert_eq!( + hs::tor_state_of(State::DegradedUnreachable, false, false), + hs::TorState::Bootstrapping + ); + // A freshly launched service reports Shutdown before its publish reactor + // starts. Mapping that to Stopped would make a live node look dead for the + // first seconds after unlock — caught on a real Tor network. + assert_eq!( + hs::tor_state_of(State::Shutdown, false, false), + hs::TorState::Bootstrapping + ); + // Arti reads `Broken` while the HsDir retry loop is still going; a dead + // service surfaces as an error from `wait_until_published`, not as a state + // the UI has to poll for. + assert_eq!( + hs::tor_state_of(State::Broken, false, false), + hs::TorState::Bootstrapping + ); +} + +#[test] +fn reachable_statuses_report_published_while_arti_says_bootstrapping() { + // `wait_until_published` returns on a successful probe while Arti's + // combined status is still Bootstrapping (see `hs_is_ready`). Reporting + // Bootstrapping there would keep the UI saying "starting" for minutes after + // friends can actually reach us. + assert_eq!( + hs::tor_state_of(State::Bootstrapping, false, true), + hs::TorState::Published + ); + assert_eq!( + hs::tor_state_of(State::DegradedUnreachable, false, true), + hs::TorState::Published + ); + // Broken stays Broken, reachable or not: `hs_is_ready` refuses it too. + assert_eq!( + hs::tor_state_of(State::Broken, false, true), + hs::TorState::Bootstrapping + ); +} + +#[test] +fn stopped_outranks_whatever_arti_reports() { + // A node that has been told to stop is Stopped even if Arti's status cache + // still says Running, and even if it was reachable a moment ago: the flag + // is set before the service is dropped. + for state in [ + State::Running, + State::DegradedReachable, + State::DegradedUnreachable, + State::Bootstrapping, + State::Broken, + State::Shutdown, + ] { + for reachable in [false, true] { + assert_eq!( + hs::tor_state_of(state, true, reachable), + hs::TorState::Stopped, + "wrong state for {state:?} (reachable={reachable}) on a stopped node" + ); + } + } +} + +#[test] +fn ready_states_are_the_published_ones() { + // Published/degraded must not drift from the readiness bar: anything + // `hs_is_ready` accepts without a probe is a state the UI calls up. + let ready = [State::Running, State::DegradedReachable]; + for state in ready { + assert!(hs::hs_is_ready(state, false), "{state:?} must be ready"); + assert_ne!( + hs::tor_state_of(state, false, false), + hs::TorState::Bootstrapping, + "{state:?} is ready but reported as still coming up" + ); + } +} + #[test] fn hs_log_label_is_not_the_full_v3_onion() { // Public v3 address; checksum is valid so HsId::from_str works. diff --git a/tests/tor_lifecycle.rs b/tests/tor_lifecycle.rs new file mode 100644 index 0000000..c74b081 --- /dev/null +++ b/tests/tor_lifecycle.rs @@ -0,0 +1,96 @@ +//! Lifecycle: a node stops when told to, says so, and refuses further work +//! with an error instead of panicking. +//! +//! Needs a live Tor network to publish the onion service, so `cargo test` skips +//! it. Run it on a networked machine with: +//! +//! ```text +//! cargo test --test tor_lifecycle -- --ignored --nocapture +//! ``` +//! +//! The offline half of this contract — the Arti-status projection, the WAL +//! checkpoint, and the SDK's typed error after shutdown — runs in the normal +//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`). + +use onionwire::node::{FlushOutcome, Node}; +use onionwire::hs::TorState; + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs live Tor network"] +async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() { + let _ = tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .with_test_writer() + .try_init(); + + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path().join("alice"); + unsafe { + std::env::set_var("ONIONWIRE_STORE_PASSPHRASE", "onionwire-test"); + } + + let node = Node::start(home.clone()).await.expect("start"); + + // `start` returns only after `wait_until_published`, so the node is + // reachable by the time a caller can call this — which must not read as + // `Stopped` or `Bootstrapping`. `DegradedReachable` is the honest answer + // when Arti says the service is degraded. + // + // This caught a real bug: `tor_state()` originally projected Arti's raw + // combined status, which is still `Bootstrapping` after a *successful* + // probe (that mismatch is what the 360s publish wait exists for), and which + // reads `Shutdown` on a service that has not started its reactor yet — so a + // live node reported `Stopped`. See `onion_reachable` in `src/node.rs`. + let started_state = node.tor_state(); + assert!( + matches!( + started_state, + TorState::Published | TorState::DegradedReachable + ), + "start returned Ok but tor_state() is {started_state:?}" + ); + + // A flush with nothing queued is a no-op that reports it, not an error. + let drained: FlushOutcome = node.flush().await.expect("flush on a live node"); + assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}"); + + node.shutdown().await.expect("shutdown"); + + assert_eq!( + node.tor_state(), + TorState::Stopped, + "tor_state must report Stopped after shutdown" + ); + + // Second shutdown: idempotent at the node level — no panic, no repeat work. + node.shutdown().await.expect("shutdown is idempotent"); + + let err = node + .flush() + .await + .expect_err("flush after shutdown must be an error"); + assert!(err.contains("stopped"), "flush error was {err:?}"); + + let err = node + .send(&[0u8; 32], b"after shutdown") + .await + .expect_err("send after shutdown must be an error"); + assert!(err.contains("stopped"), "send error was {err:?}"); + + // `RotateResult` is not `Debug`, so match on the error instead of + // `expect_err`. + let err = node + .rotate() + .await + .err() + .expect("rotate after shutdown must be an error"); + assert!(err.contains("stopped"), "rotate error was {err:?}"); + + // The store file survives the checkpoint: stopping is not wiping. + assert!( + home.join("onionwire.db").exists(), + "shutdown must not delete the store" + ); +} \ No newline at end of file From b053bed7029f6bf6476ca0d2fa25ba94e9b4a3fe Mon Sep 17 00:00:00 2001 From: apk-dev Date: Sat, 12 Sep 2026 14:29:39 -0400 Subject: [PATCH 7/7] feat(android): stop the node when the UI goes away MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all, so neither the user pressing Lock nor the Activity finishing stopped anything: Arti kept its client and the hosted onion service, the outbox worker kept dialing, and the sqlite connection stayed open behind the JNI handle. Both paths now go through `stopNode(Wire)`: 1. `flush()` — one last bounded drain, so a queued message gets its chance before the process may lose its socket. 2. `shutdown()` — drain again with a shorter budget, stop the onion service, abort the retry worker, checkpoint the WAL, and take the node handle out of the `Wire` (which is what releases the last Arc to the Tor client and the store). Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`) because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors are deliberately swallowed there: the UI is gone, and the SDK reports a second teardown as the typed `WireException.Stopped` rather than a panic. `unlock()` joins any in-flight teardown before opening again. The old node holds the sqlite file and Arti's state lock until its teardown returns, and racing it makes the next `openWire` fail. A process killed outright (Doze, background-process killer, force-stop) still never runs any of this — that is what the sqlite outbox and the new `flush()` are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from the ViewModel to the service. --- .../siriusdevops/onionwire/WireViewModel.kt | 58 ++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 90cbf32..2e0560d 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -3,6 +3,10 @@ package com.siriusdevops.onionwire import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -32,6 +36,14 @@ sealed interface Phase { data class Failed(val message: String) : Phase } +/** + * Teardown work must outlive the ViewModel: `onCleared()` runs *after* + * `viewModelScope` is already cancelled, and stopping the node means draining + * the outbox and shutting Arti down, not just dropping a reference. One + * process-wide scope is enough — there is one node per process. + */ +private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO) + /** * Owns the single Wire node for the process. * @@ -51,6 +63,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private var wire: Wire? = null + /** + * The in-flight teardown, if any. Unlocking again has to wait for it: the + * old node holds the sqlite file and Arti's state lock until `shutdown()` + * returns, and racing it makes the new node fail to open. + */ + private var stopping: Job? = null + /** * Opens (or on first run, creates) the identity and starts hosting. * @@ -58,10 +77,12 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { * it is not a "skip" path. */ fun unlock(passphrase: String) { - if (_phase.value is Phase.Opening) return + if (_phase.value is Phase.Opening || wire != null) return _phase.value = Phase.Opening viewModelScope.launch { try { + // Any previous node must be fully stopped first. + stopping?.join() val w = openWire(home.absolutePath, passphrase) wire = w _phase.value = Phase.Ready( @@ -76,11 +97,44 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } } - /** Drops our handle. The onion service stops; nothing is sent after this. */ + /** + * Stops the node and drops our handle. Nothing is sent after this. + * + * Flush first — the outbox is the whole point of losing the process — then + * `shutdown()`, which stops the onion service, aborts the retry worker and + * checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this + * runs from an `onClick`. + */ fun lock() { + val w = wire ?: return wire = null _friends.value = emptyList() _phase.value = Phase.Locked + stopping = TEARDOWN.launch { stopNode(w) } + } + + /** + * The node must not outlive the UI. Doze and the background-process killer + * skip this entirely (that is what the outbox is for), but a normal finish + * tears Tor down here instead of leaving Arti running behind a dead screen. + */ + override fun onCleared() { + val w = wire + wire = null + if (w != null) stopping = TEARDOWN.launch { stopNode(w) } + super.onCleared() + } + + private suspend fun stopNode(w: Wire) { + // Best effort, both steps: teardown runs on a process-scope job after + // the UI is gone, so there is nobody to show an error to and nothing + // useful to retry. `shutdown()` drains again with a shorter budget, so + // a flush that times out is not fatal. + runCatching { w.flush() } + // A second shutdown — `lock()` and then `onCleared()`, say — lands here + // too: the SDK reports it as a typed WireException.Stopped, never a + // panic, so swallowing it is correct. + runCatching { w.shutdown() } } private fun requireWire(): Wire = wire ?: error("locked")