//! 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}; /// Where one dial goes: locator, Noise static, and the friend's ML-KEM key /// (`None` = legacy v1 friend, classical session). type Target = (String, Vec, Option>); /// 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", "prelude required", "unexpected prelude", "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], remote_kem: Option<&'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], remote_kem: Option<&'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, remote_kem) .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. /// /// The bytes on the wire are `plaintext`; the *retry* path is where chat /// differs, so chat uses [`Self::send_payload`]. pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { self.send_inner(friend_pk, plaintext, None).await } /// Same as [`Self::send`], but the wire bytes are an opaque `payload` that /// a retry re-sends verbatim while the chat history keeps `plaintext`. /// /// Chat calls this with its ratchet frame: encoding the frame inside the /// retry loop would advance the sending chain a second time and the peer /// would see a second chat line under a new key. The frame is encoded once /// by the caller, stored on the row, and replayed byte-for-byte. pub async fn send_payload( &self, friend_pk: &[u8], plaintext: &[u8], payload: &[u8], ) -> Result { self.send_inner(friend_pk, plaintext, Some(payload)).await } async fn send_inner( &self, friend_pk: &[u8], plaintext: &[u8], payload: Option<&[u8]>, ) -> Result { let (onion, prekey, kem) = self.target(friend_pk)?; let wire = payload.unwrap_or(plaintext); match self .deliverer .deliver(&onion, friend_pk, &prekey, wire, kem.as_deref()) .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)?; let next = now + backoff_secs(0); match payload { Some(payload) => store.enqueue_outbox_payload( friend_pk, message_id, payload, next, &e, now, )?, None => store.enqueue_outbox(friend_pk, message_id, 1, next, &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, kem) = 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, // Chat stores its frame here; everything else sends its body. entry.payload.as_deref().unwrap_or(&entry.body), kem.as_deref(), ) .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, and KEM encapsulation key. /// Missing prekey means the invite was never completed — retrying cannot /// fix that, so it is fatal. `None` kem is a legacy v1 friend. fn target(&self, friend_pk: &[u8]) -> Result { 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, f.kem_pk)) } 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) }