The TUI can say why a queued row is still queued ('queued (try n/8,
retry 45s)') because it reads OutboxEntry::attempts and next_attempt_at
directly. The SDK exposed neither: ChatMessage.delivery is a flat
'queued'/'sending'/'failed: <reason>' string and Wire had no outbox
accessor, so an Android chat row could only invent a countdown.
Adds OutboxRow { message_id, status, attempts, next_attempt_at,
last_error } and Wire::outbox(pubkey_hex) over Node::outbox_pending, plus
outbox_max_attempts() so the client renders 'try n/8' against the core's
own budget instead of a hardcoded 8. Additive: Wire::send() and
ChatMessage.delivery are untouched.
# Conflicts:
# crates/onionwire-sdk/src/lib.rs
723 lines
28 KiB
Rust
723 lines
28 KiB
Rust
//! OnionWire Android/Kotlin SDK.
|
|
//!
|
|
//! UniFFI façade over the existing `onionwire` library — the same crate the
|
|
//! Linux TUI runs on. Nothing about the wire protocol is reimplemented here:
|
|
//! an Android peer and a Linux peer that exchange invites interoperate.
|
|
//!
|
|
//! Locked facts this surface assumes:
|
|
//! * Identity is an ed25519 pubkey. Fingerprint is a display of that key.
|
|
//! * `onionwire:v1:k=…:o=…:spk=…:sig=…` — the onion is a *locator* and can
|
|
//! change; re-scanning the same `k` updates the locator, never duplicates
|
|
//! the friend.
|
|
//! * Transport is in-process Arti. There is no `tor` binary, no torrc, no
|
|
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
|
//! * Chat bodies are encrypted at rest, and the whole sqlite file is
|
|
//! SQLCipher on top of that (see the root crate).
|
|
//! * A chat send that cannot reach the peer's onion is queued in a local
|
|
//! outbox and retried — see [`SendState`]. Nothing leaves the device.
|
|
//!
|
|
//! 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, Mutex, OnceLock};
|
|
|
|
use onionwire::hs::TorState as CoreTorState;
|
|
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
|
use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
|
|
use onionwire::qr;
|
|
|
|
uniffi::setup_scaffolding!();
|
|
|
|
/// Install rustls's process-level default `CryptoProvider`, exactly once.
|
|
///
|
|
/// Belt and braces. `Cargo.toml` pins `rustls` with the `ring` feature, which
|
|
/// is what actually fixes the missing-provider failure: with it, rustls
|
|
/// resolves a provider from crate features on its own. This function exists
|
|
/// because the cdylib is loaded into a process we do not own — an explicitly
|
|
/// installed provider makes the SDK independent of how the surrounding app's
|
|
/// feature graph happens to resolve rustls.
|
|
///
|
|
/// Idempotent and cheap after the first call (`OnceLock` short-circuits it).
|
|
/// An `Err` means some provider is already installed process-wide, which is the
|
|
/// outcome we want, so it is deliberately ignored — including the case of a
|
|
/// consumer that installed `aws-lc-rs` itself. A genuine *conflict* — both
|
|
/// provider features compiled in — is a build-graph bug, not something to
|
|
/// paper over here; `Cargo.toml` enables `ring` only.
|
|
///
|
|
/// Not exported over UniFFI: it is Rust-side plumbing, not part of the Kotlin
|
|
/// surface.
|
|
pub fn install_crypto_provider() {
|
|
static INSTALLED: OnceLock<()> = OnceLock::new();
|
|
INSTALLED.get_or_init(|| {
|
|
let _ = rustls::crypto::ring::default_provider().install_default();
|
|
});
|
|
}
|
|
|
|
#[derive(Debug, thiserror::Error, uniffi::Error)]
|
|
#[uniffi(flat_error)]
|
|
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 {
|
|
fn new(e: impl std::fmt::Display) -> Self {
|
|
Self::Failed {
|
|
message: e.to_string(),
|
|
}
|
|
}
|
|
|
|
fn stopped(what: &str) -> Self {
|
|
Self::Stopped {
|
|
message: format!("{what} called on a shut-down node"),
|
|
}
|
|
}
|
|
}
|
|
|
|
type WResult<T> = std::result::Result<T, WireError>;
|
|
|
|
#[derive(Debug, Clone, uniffi::Record)]
|
|
pub struct FriendInfo {
|
|
/// ed25519 identity pubkey, lowercase hex. This is the roster key.
|
|
pub pubkey_hex: String,
|
|
/// Display form of the same key.
|
|
pub fingerprint: String,
|
|
/// Local label. Never sent on the wire.
|
|
pub petname: Option<String>,
|
|
/// Current locator. May be stale if the peer rotated while you were down.
|
|
pub onion: String,
|
|
pub last_connect_ok: bool,
|
|
}
|
|
|
|
/// What `send()` did with the message.
|
|
///
|
|
/// The core has a local outbox: when a friend's onion is unreachable the
|
|
/// message is written to the local sqlite store and a background worker
|
|
/// retries it with backoff. Nothing is handed to a third party — every attempt
|
|
/// is a fresh handshake straight to that friend's onion — but until a circuit
|
|
/// takes it the message exists only on this device. A consumer must not render
|
|
/// `Queued` as delivered.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
|
pub enum SendState {
|
|
/// The frame reached the peer's onion service during this call.
|
|
Sent,
|
|
/// The peer's onion was unreachable: the message is in the local outbox,
|
|
/// local-only until the retry worker delivers it (or it ends `Failed`).
|
|
Queued,
|
|
}
|
|
|
|
#[derive(Debug, Clone, uniffi::Record)]
|
|
pub struct ChatMessage {
|
|
/// "in" or "out".
|
|
pub direction: String,
|
|
pub body: String,
|
|
/// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or
|
|
/// `"failed: <reason>"`. `None` for incoming messages. An outgoing row with
|
|
/// no outbox row is one the peer accepted on the first attempt, so it reads
|
|
/// `"sent"` — never treat a missing value as "delivered" on the app side,
|
|
/// read this field.
|
|
pub delivery: Option<String>,
|
|
}
|
|
|
|
/// One row of the local outbox for a friend: a chat send the core has not
|
|
/// finished delivering.
|
|
///
|
|
/// The join key is `message_id` — the `messages.id` a [`ChatMessage`] belongs
|
|
/// to — so a client matches these against its own list instead of matching
|
|
/// bodies. Delivered rows are deleted, which is why a message with no row here
|
|
/// was accepted by the peer and never needed a retry.
|
|
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
|
|
pub struct OutboxRow {
|
|
/// `messages.id` of the chat row this outbox row belongs to.
|
|
pub message_id: i64,
|
|
/// `"queued"`, `"sending"` or `"failed"` — the store's own encoding of
|
|
/// `OutboxStatus`, the same string [`ChatMessage::delivery`] uses.
|
|
/// `"sent"` does not occur: a delivered row is deleted before this is read.
|
|
pub status: String,
|
|
/// Attempts already spent on this row. Compare against
|
|
/// [`outbox_max_attempts`] to render `try n/8`.
|
|
pub attempts: u32,
|
|
/// Absolute unix seconds of the next attempt, so the client renders its own
|
|
/// countdown from `now` instead of a stale number baked into a record.
|
|
/// Only meaningful while `status == "queued"`: a `"failed"` row is terminal
|
|
/// and keeps the last time it was scheduled for, which must not be shown as
|
|
/// a countdown.
|
|
pub next_attempt_at: i64,
|
|
/// Why the last attempt failed, as the core reported it. `None` until the
|
|
/// row has been attempted once.
|
|
pub last_error: Option<String>,
|
|
}
|
|
|
|
/// Retry budget after which a queued message turns terminally `"failed"` — the
|
|
/// denominator in `try n/8`.
|
|
///
|
|
/// A constant of the core's outbox, not per-node state, so it is a free
|
|
/// function: fetch it once and render `attempts` against it. It is exposed at
|
|
/// all because the client cannot read the Rust constant.
|
|
#[uniffi::export]
|
|
pub fn outbox_max_attempts() -> u32 {
|
|
DEFAULT_MAX_ATTEMPTS
|
|
}
|
|
|
|
#[derive(Debug, Clone, uniffi::Record)]
|
|
pub struct RotateOutcome {
|
|
pub notified: u32,
|
|
pub friends: u32,
|
|
}
|
|
|
|
#[derive(Debug, Clone, uniffi::Record)]
|
|
pub struct InviteInfo {
|
|
pub pubkey_hex: String,
|
|
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<CoreTorState> 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 {
|
|
node: Mutex<Option<Arc<Node>>>,
|
|
}
|
|
|
|
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<Arc<Node>> {
|
|
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.
|
|
///
|
|
/// `home` must be app-private storage (`context.filesDir`), not external.
|
|
/// `passphrase` wraps the local message key; an empty passphrase fails closed.
|
|
///
|
|
/// 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<Arc<Wire>> {
|
|
// Before anything that can build a TLS config: Arti's rustls backend dies
|
|
// with "Could not automatically determine the process-level CryptoProvider"
|
|
// if no provider is resolvable. See `install_crypto_provider`.
|
|
install_crypto_provider();
|
|
let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase)
|
|
.await
|
|
.map_err(WireError::new)?;
|
|
Ok(Arc::new(Wire {
|
|
node: Mutex::new(Some(node)),
|
|
}))
|
|
}
|
|
|
|
/// Decode an invite without adding the friend. Verifies the signature.
|
|
#[uniffi::export]
|
|
pub fn decode_invite(invite: String) -> WResult<InviteInfo> {
|
|
let p = qr::decode(&invite).map_err(WireError::new)?;
|
|
Ok(InviteInfo {
|
|
pubkey_hex: hex(&p.pubkey),
|
|
onion: p.onion,
|
|
})
|
|
}
|
|
|
|
#[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.
|
|
///
|
|
/// The *node* teardown is idempotent: a second `Node::shutdown()` returns
|
|
/// `Ok` without repeating the work. This handle is spent by the first call,
|
|
/// so a second `Wire::shutdown()` — or two concurrent teardowns — returns
|
|
/// the typed `WireError.Stopped` instead of a silent `Ok`: a double
|
|
/// teardown is a caller bug worth surfacing, and `Stopped` is already the
|
|
/// answer every other method gives. It never panics.
|
|
///
|
|
/// After it, every other method on this handle — including `send` —
|
|
/// returns `WireError.Stopped` instead of touching a dead client.
|
|
///
|
|
/// 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<FlushOutcome> {
|
|
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<String> {
|
|
self.node()?.fingerprint().map_err(WireError::new)
|
|
}
|
|
|
|
/// Current onion locator. Changes on rotate; identity does not.
|
|
pub async fn onion(&self) -> WResult<String> {
|
|
Ok(self.node()?.onion())
|
|
}
|
|
|
|
/// `onionwire:v1:…` invite string to hand to the other person out of band.
|
|
pub async fn invite(&self) -> WResult<String> {
|
|
self.node()?.qr_payload().map_err(WireError::new)
|
|
}
|
|
|
|
/// Roster, sorted by petname then fingerprint.
|
|
pub async fn friends(&self) -> WResult<Vec<FriendInfo>> {
|
|
let list = self.node()?.list_friends().map_err(WireError::new)?;
|
|
Ok(list
|
|
.into_iter()
|
|
.map(|f| FriendInfo {
|
|
pubkey_hex: hex(&f.pubkey),
|
|
fingerprint: f.fingerprint,
|
|
petname: f.petname,
|
|
onion: f.onion,
|
|
last_connect_ok: f.last_connect_ok,
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
/// 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<FriendInfo> {
|
|
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 = node.friend(&p.pubkey).map_err(WireError::new)?;
|
|
Ok(FriendInfo {
|
|
pubkey_hex: hex(&f.pubkey),
|
|
fingerprint: f.fingerprint,
|
|
petname: f.petname,
|
|
onion: f.onion,
|
|
last_connect_ok: f.last_connect_ok,
|
|
})
|
|
}
|
|
|
|
/// Local label. Pass `None` to clear. Never goes on the wire.
|
|
pub async fn set_petname(&self, pubkey_hex: String, petname: Option<String>) -> WResult<()> {
|
|
let pk = unhex(&pubkey_hex)?;
|
|
self.node()?
|
|
.set_petname(&pk, petname.as_deref())
|
|
.map_err(WireError::new)
|
|
}
|
|
|
|
/// Send one chat message.
|
|
///
|
|
/// Returns [`SendState::Sent`] when the frame reached the peer's onion
|
|
/// service during this call, and [`SendState::Queued`] when it did not: the
|
|
/// message is then in the local outbox and a background worker retries it
|
|
/// with exponential backoff (30s doubling, capped at 30 min, 8 attempts)
|
|
/// until it lands or ends terminally failed. A queued send is local-only —
|
|
/// show it as pending, not delivered.
|
|
///
|
|
/// A protocol error (signature mismatch, malformed or oversize frame) is
|
|
/// not retryable and still fails here; nothing is queued in that case.
|
|
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<SendState> {
|
|
let pk = unhex(&pubkey_hex)?;
|
|
let status = self
|
|
.node()?
|
|
.send(&pk, body.as_bytes())
|
|
.await
|
|
.map_err(WireError::new)?;
|
|
Ok(send_state(status)) }
|
|
|
|
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
|
/// they are stored encrypted at rest. Outgoing rows carry their delivery
|
|
/// state in [`ChatMessage::delivery`].
|
|
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
|
let pk = unhex(&pubkey_hex)?;
|
|
let rows = self.node()?.list_messages(&pk).map_err(WireError::new)?;
|
|
let mut out = Vec::with_capacity(rows.len());
|
|
for m in rows {
|
|
let status = self
|
|
.node()?
|
|
.outbox_status_of_message(m.id)
|
|
.map_err(WireError::new)?;
|
|
out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(),
|
|
delivery: delivery_of(&m.dir, status),
|
|
direction: m.dir,
|
|
});
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Outbox rows for one friend that the core has not delivered yet: the
|
|
/// `"queued"` / `"sending"` / `"failed"` rows behind
|
|
/// [`ChatMessage::delivery`], with the core's own attempt counter and next
|
|
/// attempt time attached.
|
|
///
|
|
/// This is what lets a chat row say *why* it is still queued — `try 3/8,
|
|
/// retry 45s` — instead of a flat `"queued"`: [`OutboxRow::attempts`] and
|
|
/// [`OutboxRow::next_attempt_at`] are read from the store, never guessed by
|
|
/// the client. An empty result means nothing is outstanding for that friend.
|
|
pub async fn outbox(&self, pubkey_hex: String) -> WResult<Vec<OutboxRow>> {
|
|
let pk = unhex(&pubkey_hex)?;
|
|
let rows = self.node()?.outbox_pending(&pk).map_err(WireError::new)?;
|
|
Ok(rows.iter().map(outbox_row).collect())
|
|
}
|
|
|
|
/// Delete every message body. Identity and friends survive.
|
|
pub async fn wipe_messages(&self) -> WResult<()> {
|
|
self.node()?.wipe_messages().map_err(WireError::new)
|
|
}
|
|
|
|
/// Publish a NEW onion service and hard-cut the old one, then push a signed
|
|
/// location update to every reachable friend.
|
|
///
|
|
/// The identity key does not change. Friends who are offline cannot find
|
|
/// 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<RotateOutcome> {
|
|
let r = self.node()?.rotate().await.map_err(WireError::new)?;
|
|
Ok(RotateOutcome {
|
|
notified: r.notified as u32,
|
|
friends: r.friends as u32,
|
|
})
|
|
}
|
|
|
|
/// SDK version, for diagnostics.
|
|
pub async fn version(&self) -> String {
|
|
env!("CARGO_PKG_VERSION").to_string()
|
|
}
|
|
}
|
|
|
|
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 {
|
|
s.push_str(&format!("{b:02x}"));
|
|
}
|
|
s
|
|
}
|
|
|
|
fn unhex(s: &str) -> WResult<Vec<u8>> {
|
|
if s.is_empty() || !s.len().is_multiple_of(2) || !s.bytes().all(|c| c.is_ascii_hexdigit()) {
|
|
return Err(WireError::new("pubkey_hex must be even-length hex"));
|
|
}
|
|
(0..s.len())
|
|
.step_by(2)
|
|
.map(|i| {
|
|
u8::from_str_radix(&s[i..i + 2], 16).map_err(|e| WireError::new(format!("hex: {e}")))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist
|
|
/// only on stored outbox rows. Everything that is not a completed send maps to
|
|
/// `Queued`, so a status this build does not know about is never reported as
|
|
/// delivered — the fail-safe direction for a caller that hides its retry UI.
|
|
fn send_state(status: OutboxStatus) -> SendState {
|
|
match status {
|
|
OutboxStatus::Sent => SendState::Sent,
|
|
_ => SendState::Queued,
|
|
}
|
|
}
|
|
|
|
/// Delivery string for one stored chat row. `None` for incoming rows. An
|
|
/// outgoing row with no outbox row was accepted on the first attempt, so it is
|
|
/// reported as `"sent"` rather than left blank.
|
|
fn delivery_of(dir: &str, status: Option<OutboxStatus>) -> Option<String> {
|
|
if dir != "out" {
|
|
return None;
|
|
}
|
|
Some(match status {
|
|
None | Some(OutboxStatus::Sent) => "sent".to_string(),
|
|
Some(other) => other.to_string(),
|
|
})
|
|
}
|
|
|
|
/// One core outbox row as the record a client renders.
|
|
///
|
|
/// Field-for-field, so the client shows the store's numbers instead of a
|
|
/// timeout it invented: the row is keyed by `message_id` (the chat row to
|
|
/// patch), carries the store's own status string, and next-attempt as an
|
|
/// absolute unix second for the client to count down from.
|
|
fn outbox_row(entry: &OutboxEntry) -> OutboxRow {
|
|
OutboxRow {
|
|
message_id: entry.message_id,
|
|
status: entry.status.as_db_str().to_string(),
|
|
attempts: entry.attempts,
|
|
next_attempt_at: entry.next_attempt_at,
|
|
last_error: entry.last_error.clone(),
|
|
}
|
|
}
|
|
|
|
#[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::*;
|
|
use onionwire::outbox::OutboxStatus;
|
|
|
|
fn stopped_wire() -> Wire {
|
|
Wire {
|
|
node: Mutex::new(None),
|
|
}
|
|
}
|
|
|
|
fn block_on<F: std::future::Future>(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);
|
|
}
|
|
|
|
#[test]
|
|
fn sent_is_sent_everything_else_is_queued() {
|
|
assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent);
|
|
assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued);
|
|
// `Node::send` never returns these today, but they exist on stored
|
|
// rows. Unknown states map to `Queued` — the safe direction: never
|
|
// report a send as delivered unless the core says `Sent`.
|
|
assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued);
|
|
assert_eq!(
|
|
send_state(OutboxStatus::Failed("no route".into())),
|
|
SendState::Queued
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn delivery_is_reported_for_outgoing_rows_only() {
|
|
assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None);
|
|
// Outgoing row with no outbox row: delivered on the first attempt.
|
|
assert_eq!(delivery_of("out", None).as_deref(), Some("sent"));
|
|
assert_eq!(
|
|
delivery_of("out", Some(OutboxStatus::Sent)).as_deref(),
|
|
Some("sent")
|
|
);
|
|
assert_eq!(
|
|
delivery_of("out", Some(OutboxStatus::Queued)).as_deref(),
|
|
Some("queued")
|
|
);
|
|
assert_eq!(
|
|
delivery_of("out", Some(OutboxStatus::Sending)).as_deref(),
|
|
Some("sending")
|
|
);
|
|
assert_eq!(
|
|
delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(),
|
|
Some("failed: no route")
|
|
);
|
|
}
|
|
|
|
/// One core outbox row with only the fields a record carries filled in
|
|
/// interestingly. `id`, `friend_pk`, `body` and `created_at` do not cross
|
|
/// UniFFI, so their values are irrelevant.
|
|
fn entry(status: OutboxStatus, attempts: u32, last_error: Option<&str>) -> OutboxEntry {
|
|
OutboxEntry {
|
|
id: 3,
|
|
friend_pk: vec![0xaa; 32],
|
|
message_id: 42,
|
|
body: b"hello".to_vec(),
|
|
attempts,
|
|
next_attempt_at: 1_700_000_045,
|
|
created_at: 1_700_000_000,
|
|
status,
|
|
last_error: last_error.map(str::to_string),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn outbox_row_carries_the_join_key_the_attempt_count_and_the_next_attempt_time() {
|
|
let row = outbox_row(&entry(
|
|
OutboxStatus::Queued,
|
|
3,
|
|
Some("peer onion unreachable"),
|
|
));
|
|
assert_eq!(row.message_id, 42);
|
|
assert_eq!(row.status, "queued");
|
|
assert_eq!(row.attempts, 3);
|
|
assert_eq!(row.next_attempt_at, 1_700_000_045);
|
|
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
|
|
}
|
|
|
|
#[test]
|
|
fn outbox_row_keeps_the_stores_own_status_encoding() {
|
|
// These four strings are the `outbox.status` CHECK constraint in
|
|
// `src/store.rs`; a client switches on them verbatim.
|
|
for (status, want) in [
|
|
(OutboxStatus::Queued, "queued"),
|
|
(OutboxStatus::Sending, "sending"),
|
|
(OutboxStatus::Sent, "sent"),
|
|
(
|
|
OutboxStatus::Failed("peer onion unreachable".into()),
|
|
"failed",
|
|
),
|
|
] {
|
|
assert_eq!(outbox_row(&entry(status, 0, None)).status, want);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_failed_outbox_row_carries_the_cores_reason_verbatim() {
|
|
let row = outbox_row(&entry(
|
|
OutboxStatus::Failed("peer onion unreachable".into()),
|
|
8,
|
|
Some("peer onion unreachable"),
|
|
));
|
|
assert_eq!(row.status, "failed");
|
|
assert_eq!(row.attempts, 8);
|
|
assert_eq!(row.last_error.as_deref(), Some("peer onion unreachable"));
|
|
}
|
|
|
|
#[test]
|
|
fn outbox_max_attempts_is_the_denominator_a_client_renders_against() {
|
|
// The Android chat row renders `try n/8`. Pin the number so the SDK and
|
|
// the core's retry budget cannot drift apart silently.
|
|
assert_eq!(outbox_max_attempts(), 8);
|
|
}
|
|
}
|
|
|