onionwire/crates/onionwire-sdk/src/lib.rs

2090 lines
81 KiB
Rust
Raw Normal View History

//! 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.
//!
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
//! 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::{Path, PathBuf};
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
use std::sync::{Arc, Mutex, OnceLock};
use onionwire::Message;
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
use onionwire::hs::TorState as CoreTorState;
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus};
use onionwire::pay;
use onionwire::qr;
use onionwire::wallet::{ChainNetwork, ChainSource};
use onionwire::wallet_child::{ChildConfig, WalletChildState};
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 },
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
/// 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(),
}
}
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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 {
/// `messages.id` of the stored row. This is the join key an
/// [`OutboxRow::message_id`] refers to, so a client matches an outbox row to
/// this message by id instead of matching bodies or counting rows. Stable
/// for the life of the row; never `0`.
pub id: i64,
/// "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,
}
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
/// 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.
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
///
/// 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 {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
node: Mutex<Option<Arc<Node>>>,
/// `$ONIONWIRE_HOME` exactly as [`open_wire`] was given it. The SDK resolves
/// the per-identity defaults a caller cannot know (the in-process chain
/// data directory) against it, so Kotlin never has to invent a path.
home: PathBuf,
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
}
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"))
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
}
}
/// 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.
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
///
/// 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 home = PathBuf::from(home);
let node = Node::start_with_passphrase(home.clone(), &passphrase)
.await
.map_err(WireError::new)?;
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
Ok(Arc::new(Wire {
node: Mutex::new(Some(node)),
home,
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
}))
}
/// 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 {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
/// 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.
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
///
/// 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> {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
self.node()?.fingerprint().map_err(WireError::new)
}
/// Current onion locator. Changes on rotate; identity does not.
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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> {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
self.node()?.qr_payload().map_err(WireError::new)
}
/// Roster, sorted by petname then fingerprint.
pub async fn friends(&self) -> WResult<Vec<FriendInfo>> {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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> {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
let node = self.node()?;
node.add_friend_from_qr(&invite).map_err(WireError::new)?;
let p = qr::decode(&invite).map_err(WireError::new)?;
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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)?;
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
.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(chat_message(m, status));
}
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<()> {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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> {
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
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()
}
// ---- Wallet / payment surface (v1 Monero features) ----
/// Current wallet balance as a display string, or `"off"` / `"err"`.
///
/// Returns `"off"` when the wallet is not configured (no `ONIONWIRE_WALLET_RPC`),
/// `"err"` when the wallet RPC call failed, and `"balance X.X XMR"` on success.
/// A stopped node (shut-down handle) returns `"off"` — the wallet is not
/// accessible without a live node, and the UI treats "off" as "wallet not
/// available" rather than an error state.
pub async fn wallet_balance(&self) -> String {
match self.node() {
Ok(node) => node.wallet_balance().await,
Err(_) => "off".to_string(),
}
}
/// Receive address for the wallet screen: a freshly created subaddress when
/// the wallet is configured, else the profile `xmr_addr` fallback.
///
/// Returns the raw address (not a `monero:` URI) so the QR render path can
/// decide how to wrap it. Returns `WireError.Stopped` on a shut-down handle,
/// `WireError.Failed` on RPC/profile errors.
pub async fn wallet_receive_address(&self) -> WResult<String> {
let node = self.node()?;
node.wallet_receive_address().await.map_err(WireError::new)
}
/// Recent in/out transfers for the wallet screen, newest first, capped to `cap`.
///
/// Returns an empty list when the wallet is not configured (no transfers to show).
/// `amount` is formatted XMR, not raw piconero.
pub async fn wallet_recent_transfers(&self, cap: u32) -> WResult<Vec<TransferRow>> {
let node = self.node()?;
let rows = node
.wallet_recent_transfers(cap as usize)
.await
.map_err(WireError::new)?;
Ok(rows
.into_iter()
.map(|r| TransferRow {
txid: r.txid,
amount: pay::atomic_to_xmr_str(&r.amount),
address: r.address,
})
.collect())
}
/// Send an invoice to a friend: sign an invoice for my receive address and send
/// the frame one-shot. Peer onion down → this fails; invoices are not queued.
///
/// `amount_xmr` is a user-facing XMR amount (e.g. `"0.5"`) — validated and
/// converted to piconero internally. `memo` may be empty. The invoice uses the
/// wallet subaddress if available, else the profile `xmr_addr` fallback.
pub async fn send_invoice(
&self,
pubkey_hex: String,
amount_xmr: String,
memo: String,
) -> WResult<()> {
let pk = unhex(&pubkey_hex)?;
let atomic = pay::xmr_to_atomic(&amount_xmr).map_err(WireError::new)?;
self.node()?
.pay_invoice(&pk, &atomic, &memo)
.await
.map_err(WireError::new)
}
/// Send a tip to a friend: transfer XMR from my wallet, then send a signed
/// receipt and tip frame, both one-shot. Peer onion down → this fails after
/// the chain transfer; tips are not queued.
///
/// `amount_xmr` is a user-facing XMR amount. `memo` may be empty. The
/// recipient's Monero address is read from their profile.
///
/// Requires the wallet to be configured (`ONIONWIRE_WALLET_RPC`). Fails when
/// the wallet is not connected, the friend has no Monero address, or the
/// amount is invalid.
pub async fn send_tip(
&self,
pubkey_hex: String,
amount_xmr: String,
memo: String,
) -> WResult<()> {
let pk = unhex(&pubkey_hex)?;
let atomic = pay::xmr_to_atomic(&amount_xmr).map_err(WireError::new)?;
self.node()?
.tip(&pk, &atomic, &memo)
.await
.map_err(WireError::new)
}
/// Create a new spend-capable wallet. Returns the 25-word seed once so the
/// UI can show a backup screen. The user does not paste a key on this path.
/// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC.
pub async fn create_wallet(&self, password: String) -> WResult<String> {
self.node()?
.wallet_create(&password)
.await
.map_err(WireError::new)
}
/// Import a wallet from an existing 25-word seed. This is the only path
/// that takes a user-supplied secret.
pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> {
self.node()?
.wallet_restore(&password, &seed)
.await
.map_err(WireError::new)
}
/// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for
/// a local chain source and `arti proxy` for a `.onion` daemon) and point
/// this node's wallet at it, then probe it once and return what it reached.
///
/// The spawn itself is synchronous inside the node: argv is built, the
/// process is spawned, and a `.onion` source waits up to 20s for the SOCKS
/// listener. An in-process Cuprate launch is the same shape and can take
/// much longer. That work runs on `spawn_blocking` so it does not stall the
/// UniFFI tokio worker (Android: a blocked worker is a Start tap that never
/// returns).
///
/// Idempotent: a live child is reported, not respawned. Fails with
/// `WireError.Failed` when no chain source is configured
/// (`set_chain_source`), when a binary cannot be spawned, or when the SOCKS
/// listener never came up. `WireError.Stopped` after `shutdown`.
///
/// The returned state is `connecting` at best on the first call — the wallet
/// RPC is not answering the instant the process exists. Report it as it is,
/// and call [`Wire::wallet_status`] (or start again) for the later states.
pub async fn start_wallet_child(&self) -> WResult<WalletChildStatus> {
let node = self.node()?;
let blocking = node.clone();
tokio::task::spawn_blocking(move || blocking.start_wallet_child())
.await
.map_err(|e| WireError::new(format!("start wallet child join: {e}")))?
.map_err(WireError::new)?;
let source = node.wallet_child_config().source;
Ok(child_status(node.wallet_child_refresh().await, &source))
}
/// Stop the wallet child and its daemon/SOCKS siblings. Idempotent: stopping
/// what is not running is `Ok(())`. The wallet falls back to the stored or
/// env `monero-wallet-rpc` config, if any.
pub fn stop_wallet_child(&self) -> WResult<()> {
self.node()?.stop_wallet_child().map_err(WireError::new)
}
/// The last observable wallet-child state. Never dials, never spawns:
/// `state` is `off` / `connecting` / `syncing` / `ready` / `exited`, and
/// `ready` is only ever written by a probe that saw a synced chain.
///
/// Synchronous on purpose — it is safe to call from a UI refresh loop.
pub fn wallet_status(&self) -> WResult<WalletChildStatus> {
let node = self.node()?;
let source = node.wallet_child_config().source;
Ok(child_status(node.wallet_child_status(), &source))
}
/// One live probe of the app-owned wallet child, returning the same record
/// [`Wire::wallet_status`] reports — from a snapshot that was just taken
/// rather than one left behind by the last start.
///
/// It dials: the child's loopback wallet RPC, and the configured local
/// daemon's `get_info` when the wallet RPC does not answer. That is what
/// makes the chain's height and target move between calls.
///
/// It never spawns and never starts a child: a node with no child is not
/// launched for this call.
///
/// Safe to call from a UI refresh loop, but not free — it makes network
/// calls, so a caller should poll on the order of seconds rather than every
/// frame. [`Wire::wallet_status`] stays the cheap, non-dialing read for
/// first paint.
///
/// The honest limit: with no live child, the core short-circuits and returns
/// the cached `off` / `exited` snapshot, so this can never invent `ready` or
/// any other live state for a child that is not there. `WireError.Stopped`
/// after `shutdown`.
pub async fn wallet_child_refresh(&self) -> WResult<WalletChildStatus> {
let node = self.node()?;
let source = node.wallet_child_config().source;
Ok(child_status(node.wallet_child_refresh().await, &source))
}
/// The chain-source + binary settings the child spawns with, as stored.
/// Returns the defaults (receive-only, binaries by name) when nothing was
/// ever set, so a settings screen can prefill from it safely.
pub fn chain_source(&self) -> WResult<ChainConfig> {
Ok(chain_config(&self.node()?.wallet_child_config()))
}
/// Set the chain source and the binaries the child runs. Validated before
/// anything is written: a rejected config leaves the stored one untouched
/// and a running child untouched (the change applies on the next start).
///
/// This is a stored setting, not a start: call [`Wire::start_wallet_child`]
/// after it. `wallet_rpc_bin` / `arti_bin` take absolute paths on Android
/// (`context.applicationInfo.nativeLibraryDir`); the core never resolves a
/// binary the caller named explicitly.
pub fn set_chain_source(&self, config: ChainConfig) -> WResult<()> {
self.node()?
.set_wallet_child_config(&child_config(config, &self.home))
.map_err(WireError::new)
}
feat(sdk): sign/encode/decode/verify invoice, receipt and tip frames The SDK could already send an invoice or a tip through Node::pay_invoice / Node::tip, but it could not touch the payment frames themselves: pay::sign_* take the ed25519 identity secret and Node exposed only identity_pk(), so the signing half lived nowhere the SDK could reach. Add the signing surface to the node instead of exporting the key: * Node::sign_invoice / sign_receipt / sign_tip sign with the node's own identity key and return the core frame struct. The secret never leaves the process and there is no API that hands it out. * pay_invoice and tip now call those methods rather than signing inline, so there is one signing path, not two. SDK (crates/onionwire-sdk), all backward compatible: * Records Invoice, Receipt, Tip mirroring src/pay.rs, sig as raw bytes so a frame re-encodes byte-for-byte. * Wire::sign_invoice / sign_receipt / sign_tip (async, over the node). * Free functions encode_invoice / encode_receipt / encode_tip, decode_invoice / decode_receipt / decode_tip (None on a foreign or truncated frame), verify_invoice / verify_receipt / verify_tip against the sender's pubkey hex (false on a bad key, never a panic). Tests: 8 new SDK unit tests (record round-trips through the core encoders, signer-key-only verification, tamper rejection, foreign/truncated frame, typed Stopped error after shutdown). SDK 27 passed, 0 failed; SDK clippy --all-targets -D warnings clean; root clippy --all-targets -D warnings clean; root lib tests 14 passed; tests/pay.rs 11 passed.
2026-09-15 12:45:49 -04:00
/// Sign an invoice frame with this node's identity key.
///
/// The ed25519 secret stays inside the node: this is the only way the SDK
/// signs a payment frame and there is no method that hands the key out.
/// `amount_atomic` is piconero (`xmr_to_atomic` converts a typed amount).
/// Signing does not touch the network — carry the result with
/// [`encode_invoice`] and send it as chat bytes, or use the one-shot
/// [`Wire::send_invoice`], which signs, sends and records the chat line.
pub async fn sign_invoice(
&self,
amount_atomic: String,
address: String,
memo: String,
) -> WResult<Invoice> {
self.node()?
.sign_invoice(&amount_atomic, &address, &memo)
.map(invoice_record)
.map_err(WireError::new)
}
/// Sign a receipt frame for a transfer that already happened. Signing only,
/// never a transfer: this does not move funds.
pub async fn sign_receipt(
&self,
txid: String,
amount_atomic: String,
address: String,
) -> WResult<Receipt> {
self.node()?
.sign_receipt(&txid, &amount_atomic, &address)
.map(receipt_record)
.map_err(WireError::new)
}
/// Sign a tip frame (receipt plus memo) for a transfer that already
/// happened. Signing only, never a transfer.
pub async fn sign_tip(
&self,
txid: String,
amount_atomic: String,
address: String,
memo: String,
) -> WResult<Tip> {
self.node()?
.sign_tip(&txid, &amount_atomic, &address, &memo)
.map(tip_record)
.map_err(WireError::new)
}
/// Spend-authority warning shown before create. Not a tooltip.
pub fn spend_authority_warning(&self) -> String {
onionwire::wallet::SPEND_AUTHORITY_WARNING.to_string()
}
}
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome {
FlushOutcome {
attempted: o.attempted as u32,
delivered: o.delivered as u32,
remaining: o.remaining as u32,
}
}
/// The core child settings a [`ChainConfig`] describes.
///
/// `home` is the `$ONIONWIRE_HOME` the identity was opened with. An in-process
/// chain source with an empty `monerod_datadir` resolves to `home/chain` — the
/// per-identity directory the core documents for a local chain — so a Kotlin
/// caller never has to invent an absolute path. Every other kind uses exactly
/// what it was given (or the core's own default), unchanged.
fn cuprate_chain_dir(home: &Path, mainnet: bool, prune: bool) -> PathBuf {
let name = match (mainnet, prune) {
(true, true) => "mainnet-pruned",
(true, false) => "mainnet-full",
(false, _) => "testnet",
};
home.join("chain").join(name)
}
fn child_config(cfg: ChainConfig, home: &Path) -> ChildConfig {
let source = match cfg.kind {
ChainChoice::None => ChainSource::None,
ChainChoice::Local => ChainSource::Local {
monerod_bin: PathBuf::from(cfg.monerod_bin),
datadir: PathBuf::from(cfg.monerod_datadir),
prune: cfg.prune,
},
ChainChoice::InProcessCuprate => {
let network = if cfg.mainnet {
ChainNetwork::Mainnet
} else {
ChainNetwork::Testnet
};
let prune = cfg.mainnet && cfg.prune;
ChainSource::InProcessCuprate {
datadir: if cfg.monerod_datadir.trim().is_empty() {
cuprate_chain_dir(home, cfg.mainnet, prune)
} else {
PathBuf::from(cfg.monerod_datadir)
},
network,
prune,
}
}
ChainChoice::Remote => ChainSource::Remote {
host: cfg.host,
port: cfg.port,
},
};
ChildConfig {
source,
wallet_rpc_bin: PathBuf::from(cfg.wallet_rpc_bin),
arti_bin: PathBuf::from(cfg.arti_bin),
wallet_filename: cfg.wallet_filename,
}
}
fn chain_config(cfg: &ChildConfig) -> ChainConfig {
let (kind, host, port, monerod_bin, monerod_datadir, mainnet, prune) = match &cfg.source {
ChainSource::None => (
ChainChoice::None,
String::new(),
0,
String::new(),
String::new(),
false,
false,
),
ChainSource::Local {
monerod_bin,
datadir,
prune,
} => (
ChainChoice::Local,
String::new(),
0,
monerod_bin.display().to_string(),
datadir.display().to_string(),
true,
*prune,
),
ChainSource::InProcessCuprate {
datadir,
network,
prune,
} => (
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
ChainChoice::InProcessCuprate,
String::new(),
0,
String::new(),
datadir.display().to_string(),
matches!(network, ChainNetwork::Mainnet),
*prune,
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
),
ChainSource::Remote { host, port } => (
ChainChoice::Remote,
host.clone(),
*port,
String::new(),
String::new(),
false,
false,
),
};
ChainConfig {
kind,
monerod_bin,
monerod_datadir,
host,
port,
wallet_rpc_bin: cfg.wallet_rpc_bin.display().to_string(),
arti_bin: cfg.arti_bin.display().to_string(),
wallet_filename: cfg.wallet_filename.clone(),
mainnet,
prune,
}
}
/// The core child snapshot as the SDK record.
///
/// `source` is the configured chain source the snapshot came from: it is what
/// makes the node-scoped fields possible without the core exposing a second
/// liveness signal for the in-process daemon.
fn child_status(
status: onionwire::wallet_child::WalletChildStatus,
source: &ChainSource,
) -> WalletChildStatus {
let in_process = matches!(source, ChainSource::InProcessCuprate { .. });
WalletChildStatus {
state: status.state.as_str().to_string(),
running: status.running,
configured: status.configured,
chain_source: status.chain_source,
chain_in_process: in_process,
node_available: onionwire::cuprate::available(),
node_state: if in_process {
node_state(status.state).to_string()
} else {
String::new()
},
height: status.height,
target_height: status.target_height,
last_error: status.last_error,
}
}
/// The node-scoped word for the in-process daemon, derived from the core's own
/// child state. A projection, not a second state machine: no input here is a
/// timer, an env var, or a file.
///
/// For an in-process source the wallet child is a client of *this app's* node,
/// so the core's own sequence is the node's: it cannot answer before the
/// daemon's loopback RPC is up (`connecting`), it answers but is behind the tip
/// while the daemon syncs (`syncing`), and `ready` requires a synced chain.
///
/// Limit, stated rather than papered over: the core exposes no separate
/// liveness signal for the in-process node (it is a value this app owns, not a
/// process with a pid), so a daemon that dies *after* its wallet child came up
/// cannot be reported as `exited` — the chain probe fails and the state stays
/// `syncing`. It is never reported `ready`, and `exited` still means what it
/// says: the `monero-wallet-rpc` child is gone.
fn node_state(state: WalletChildState) -> &'static str {
match state {
WalletChildState::Off => "off",
WalletChildState::Connecting => "starting",
WalletChildState::Syncing => "syncing",
WalletChildState::Ready => "ready",
WalletChildState::Exited => "exited",
}
}
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()
}
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
/// `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,
}
}
/// One stored chat row as the record a client renders. `id` is copied through
/// untouched: it is the `messages.id` an [`OutboxRow::message_id`] joins to.
fn chat_message(m: Message, status: Option<OutboxStatus>) -> ChatMessage {
ChatMessage {
id: m.id,
direction: m.dir.clone(),
body: String::from_utf8_lossy(&m.plaintext).into_owned(),
delivery: delivery_of(&m.dir, status),
}
}
/// 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(),
}
}
/// A Monero transfer row for the wallet screen.
///
/// `amount` is formatted XMR (not raw piconero) — the SDK formats it from the
/// core's piconero string so the UI never parses atomic units.
#[derive(Debug, Clone, uniffi::Record)]
pub struct TransferRow {
pub txid: String,
pub amount: String,
pub address: String,
}
/// Where the app-owned wallet child gets its chain from. Mirrors the core's
/// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum ChainChoice {
/// Receive-only: no child, no daemon, no spend.
None,
/// The app spawns `monerod` on this device.
Local,
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
/// The chain daemon runs **inside this app** (Cuprate). No `monerod` binary.
/// Testnet only, and pre-production software — see the core's
/// `ChainSource::InProcessCuprate`. `monerod_datadir` is the chain data
/// directory for it, and no binary path is needed.
InProcessCuprate,
/// A daemon address the user supplied (loopback, `.onion`, or clearnet).
Remote,
}
/// The wallet-child settings, as the Kotlin side sets them.
///
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
/// One record for all four kinds: the fields a kind does not use are ignored
/// by that kind (`None` needs no binaries, `Local` needs `monerod_bin` and
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
/// `monerod_datadir`, `InProcessCuprate` needs only `monerod_datadir` as its
/// chain directory, `Remote` needs `host` and `port`). Persisted in the
/// encrypted store, so it survives a restart without env vars.
#[derive(Debug, Clone, uniffi::Record)]
pub struct ChainConfig {
pub kind: ChainChoice,
/// `Local` only. Absolute path on Android (`nativeLibraryDir`); a bare name
/// resolves on `PATH` on desktop.
pub monerod_bin: String,
/// `Local` only. Data directory for the local daemon.
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
///
/// `InProcessCuprate` also uses this field, as the chain data directory the
/// in-process daemon stores its (fjall) chain in. For that kind an empty
/// string means "use the per-identity default" (`$ONIONWIRE_HOME/chain`,
/// resolved by the SDK), so Kotlin never has to invent an absolute path;
/// `Local` still requires a real one.
pub monerod_datadir: String,
/// `Remote` only. Daemon host.
pub host: String,
/// `Remote` only. Daemon port.
pub port: u16,
/// `monero-wallet-rpc`. Absolute path on Android, else resolved on `PATH`.
pub wallet_rpc_bin: String,
/// `arti`, run as the SOCKS child for a `.onion` daemon only.
pub arti_bin: String,
/// Wallet file name inside `$ONIONWIRE_HOME/wallet`.
pub wallet_filename: String,
/// Cuprate / local `monerod`: mainnet when true, testnet when false.
/// Ignored for Remote and None. Old records without the field stay testnet.
pub mainnet: bool,
/// Cuprate / local `monerod`: prune the chain. Ignored for Remote and None.
/// Once a Cuprate store is pruned it cannot be un-pruned — we keep pruned
/// and full in separate datadirs.
pub prune: bool,
}
/// One snapshot of the app-owned wallet child.
///
/// Derived from the real child process plus the last probe, never from env-var
/// presence. `state` is one of `off`, `connecting`, `syncing`, `ready`,
/// `exited`. `chain_source` is the label of the configured source:
wallet: land the in-process Cuprate chain source on main `ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P, consensus and RandomX run inside the OnionWire process instead of as a spawned `monerod`. The wallet layer does not move — the daemon binds the same loopback unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment frames and the receipt-verification path are untouched. - Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the `cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is disabled (`default-features = false`): its arti-client 0.44 cannot unify with this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in the process. `Cargo.lock` gains the graph; a default build's `cargo tree --locked -e normal -i cuprated` still says "did not match any packages", and only `arti-client v0.46.0` is in the lock. - src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML (testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P off), launches it on a runtime it owns, and owns the node. `launch` is synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its blocking thread, UniFFI calls it from an async context) and a runtime cannot be started from inside a runtime, so the launch runs on a thread of its own and the node + its runtime come back over a channel. Dropping the value asks the node to shut down and `shutdown_background`s the runtime, which is the only exit that cannot panic when the value is dropped inside another runtime. The type exists in every build (feature off: `launch` fails with the feature name), so the chain-source type, its stored record and its copy do not fork on a cargo feature. - src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon client the wallet line carried (typed `WalletError`, de-chunked HTTP, `get_height` over the URI endpoint, an above-the-tip height as one typed error). Cuprate answers those three differently from monerod and the in-process source is what makes them the *local* case. - src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the free-space/ownership question, the honest `chain_copy` line, `kind = "cuprate"` in the sealed record, and `ChildConfig::validate` for it. - src/tui.rs: the wallet screen's chain line carries the testnet caveat when the configured source is the in-process one. It computes the line at draw time, so `Screen::Wallet`'s shape (which tests construct) does not change. - docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the feature flag and how to enable it, where the (fjall) chain store lives, the **measured** +11.8 MiB delta, the pre-production/testnet caveat, and the in-repo aarch64-linux-android proof with exit codes. Scope deviations, stated plainly: - `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's allowed list; the card's own deliverable describes the module's behaviour. - `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a `pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the root CI `sdk` job runs on every PR. One variant plus two match arms land here so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card owns the rest — feature passthrough, the config field's semantics, the label and its tests, and the Android check. - `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched: main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7 work, and `docs/WALLET.md` says so rather than describing a picker that does not exist). Proof (all on this tree): - Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345 passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0. - Feature on: `cargo test --locked --features cuprate-daemon --target x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with `--features cuprate-daemon` exit 0. The two extra tests are the real thing: `wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down` and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client` — the latter launches the node, drives `get_info` / `get_height` / `get_block` through the typed client, checks the above-the-tip 500 maps to `DaemonHeightOutOfRange`, checks the chain store is under the chain datadir, and checks the listener dies with the node. - aarch64: `cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0 (`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26, built by NDK r28c`. - Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and 37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure `docs/WALLET.md` now quotes.
2026-09-18 13:45:59 -04:00
/// `receive-only`, `local node`, `in-process node`, `remote onion daemon`, or
/// `remote daemon`.
#[derive(Debug, Clone, uniffi::Record)]
pub struct WalletChildStatus {
/// `off` until the child is started and again after it is stopped; `exited`
/// when a started child has died; `connecting` while its wallet RPC has not
/// answered; `syncing` once it has but the chain is behind; `ready` when
/// both hold. `ready` is never reported for a dead child.
pub state: String,
/// A `monero-wallet-rpc` child is alive right now.
pub running: bool,
/// A chain source is configured (anything but receive-only).
pub configured: bool,
/// The chain-source label.
pub chain_source: String,
/// The configured source runs the chain daemon **inside this app** (Cuprate)
/// rather than spawning `monerod` or dialling a remote one. When true,
/// `state` — and `node_state` — describe this app's own node *and* its
/// wallet child: there is no separate daemon process to report on, and the
/// wallet child is a client of the in-process node, not a peer of one.
pub chain_in_process: bool,
/// This build can actually start the in-process daemon (`cuprate-daemon`).
/// `false` means the option is offered by the store but a start can only
/// fail — grey it out before the user commits, do not start and catch.
pub node_available: bool,
/// The in-process daemon's own state, for a status line that names the
/// node: `off` / `starting` / `syncing` / `ready` / `exited`. Empty for
/// every other chain source, so a Kotlin line shows no node segment for a
/// spawned `monerod`. `starting` is the core's `connecting` read from the
/// node's side (the daemon's loopback RPC has not answered yet); it is
/// never persisted, polled from a file, or inferred from a timeout.
pub node_state: String,
/// Blocks the chain daemon had at the last probe, as the wallet RPC (or the
/// daemon itself, over loopback) reported them. `0` means unknown: never
/// probed, the child is off/exited, or the probe failed — it is not the
/// same as caught up, and it is never a wallet-scan height.
pub height: u64,
/// Blocks the daemon was syncing towards. `0` means the daemon reported
/// none (also not the same as caught up).
pub target_height: u64,
/// The last failure, display-ready. Never carries the generated login.
pub last_error: Option<String>,
}
feat(sdk): sign/encode/decode/verify invoice, receipt and tip frames The SDK could already send an invoice or a tip through Node::pay_invoice / Node::tip, but it could not touch the payment frames themselves: pay::sign_* take the ed25519 identity secret and Node exposed only identity_pk(), so the signing half lived nowhere the SDK could reach. Add the signing surface to the node instead of exporting the key: * Node::sign_invoice / sign_receipt / sign_tip sign with the node's own identity key and return the core frame struct. The secret never leaves the process and there is no API that hands it out. * pay_invoice and tip now call those methods rather than signing inline, so there is one signing path, not two. SDK (crates/onionwire-sdk), all backward compatible: * Records Invoice, Receipt, Tip mirroring src/pay.rs, sig as raw bytes so a frame re-encodes byte-for-byte. * Wire::sign_invoice / sign_receipt / sign_tip (async, over the node). * Free functions encode_invoice / encode_receipt / encode_tip, decode_invoice / decode_receipt / decode_tip (None on a foreign or truncated frame), verify_invoice / verify_receipt / verify_tip against the sender's pubkey hex (false on a bad key, never a panic). Tests: 8 new SDK unit tests (record round-trips through the core encoders, signer-key-only verification, tamper rejection, foreign/truncated frame, typed Stopped error after shutdown). SDK 27 passed, 0 failed; SDK clippy --all-targets -D warnings clean; root clippy --all-targets -D warnings clean; root lib tests 14 passed; tests/pay.rs 11 passed.
2026-09-15 12:45:49 -04:00
/// One signed invoice frame: "pay me `amount_atomic` piconero at `address`".
///
/// Mirrors `pay::Invoice`. `sig` is the raw 64-byte ed25519 signature, not hex,
/// so the frame re-encodes byte-for-byte. Sign it with [`Wire::sign_invoice`]
/// (the identity key never leaves the node), carry it with [`encode_invoice`],
/// and check an inbound one against the sender's pubkey with [`verify_invoice`].
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct Invoice {
/// Piconero as a decimal string. `xmr_to_atomic("0.5")` is the form to
/// build this from a typed amount.
pub amount_atomic: String,
pub address: String,
/// May be empty; must not contain a newline.
pub memo: String,
/// Unix seconds the frame was signed at.
pub ts: i64,
pub sig: Vec<u8>,
}
/// One signed receipt frame: "transaction `txid` paid `amount_atomic` to
/// `address`". Mirrors `pay::Receipt`; same signing rules as [`Invoice`].
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct Receipt {
pub txid: String,
pub amount_atomic: String,
pub address: String,
pub ts: i64,
pub sig: Vec<u8>,
}
/// One signed tip frame: a receipt plus the memo the sender attached. Mirrors
/// `pay::Tip`; same signing rules as [`Invoice`].
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct Tip {
pub txid: String,
pub amount_atomic: String,
pub address: String,
pub memo: String,
pub ts: i64,
pub sig: Vec<u8>,
}
fn invoice_record(inv: pay::Invoice) -> Invoice {
Invoice {
amount_atomic: inv.amount_atomic,
address: inv.address,
memo: inv.memo,
ts: inv.ts,
sig: inv.sig,
}
}
fn invoice_core(rec: Invoice) -> pay::Invoice {
pay::Invoice {
amount_atomic: rec.amount_atomic,
address: rec.address,
memo: rec.memo,
ts: rec.ts,
sig: rec.sig,
}
}
fn receipt_record(rcp: pay::Receipt) -> Receipt {
Receipt {
txid: rcp.txid,
amount_atomic: rcp.amount_atomic,
address: rcp.address,
ts: rcp.ts,
sig: rcp.sig,
}
}
fn receipt_core(rec: Receipt) -> pay::Receipt {
pay::Receipt {
txid: rec.txid,
amount_atomic: rec.amount_atomic,
address: rec.address,
ts: rec.ts,
sig: rec.sig,
}
}
fn tip_record(tip: pay::Tip) -> Tip {
Tip {
txid: tip.txid,
amount_atomic: tip.amount_atomic,
address: tip.address,
memo: tip.memo,
ts: tip.ts,
sig: tip.sig,
}
}
fn tip_core(rec: Tip) -> pay::Tip {
pay::Tip {
txid: rec.txid,
amount_atomic: rec.amount_atomic,
address: rec.address,
memo: rec.memo,
ts: rec.ts,
sig: rec.sig,
}
}
/// Encode an invoice as the wire frame the peer decodes with
/// [`decode_invoice`]. Pass the bytes to [`Wire::send`].
#[uniffi::export]
pub fn encode_invoice(invoice: Invoice) -> Vec<u8> {
pay::encode_invoice(&invoice_core(invoice))
}
/// Decode an invoice frame. `None` for another frame kind, a truncated frame or
/// other malformed bytes — decoding never panics.
#[uniffi::export]
pub fn decode_invoice(frame: Vec<u8>) -> Option<Invoice> {
pay::decode_invoice(&frame).map(invoice_record)
}
/// Verify an invoice against the sender's ed25519 identity pubkey (lowercase
/// hex — the same key [`FriendInfo::pubkey_hex`] carries). `false` for a bad
/// signature, an edited frame, or a malformed key.
#[uniffi::export]
pub fn verify_invoice(pubkey_hex: String, invoice: Invoice) -> bool {
match unhex(&pubkey_hex) {
Ok(pk) => pay::verify_invoice(&pk, &invoice_core(invoice)),
Err(_) => false,
}
}
/// Encode a receipt as the wire frame the peer decodes with
/// [`decode_receipt`].
#[uniffi::export]
pub fn encode_receipt(receipt: Receipt) -> Vec<u8> {
pay::encode_receipt(&receipt_core(receipt))
}
/// Decode a receipt frame. `None` for another frame kind or malformed bytes.
#[uniffi::export]
pub fn decode_receipt(frame: Vec<u8>) -> Option<Receipt> {
pay::decode_receipt(&frame).map(receipt_record)
}
/// Verify a receipt against the sender's ed25519 identity pubkey (hex).
#[uniffi::export]
pub fn verify_receipt(pubkey_hex: String, receipt: Receipt) -> bool {
match unhex(&pubkey_hex) {
Ok(pk) => pay::verify_receipt(&pk, &receipt_core(receipt)),
Err(_) => false,
}
}
/// Encode a tip as the wire frame the peer decodes with [`decode_tip`].
#[uniffi::export]
pub fn encode_tip(tip: Tip) -> Vec<u8> {
pay::encode_tip(&tip_core(tip))
}
/// Decode a tip frame. `None` for another frame kind or malformed bytes.
#[uniffi::export]
pub fn decode_tip(frame: Vec<u8>) -> Option<Tip> {
pay::decode_tip(&frame).map(tip_record)
}
/// Verify a tip against the sender's ed25519 identity pubkey (hex).
#[uniffi::export]
pub fn verify_tip(pubkey_hex: String, tip: Tip) -> bool {
match unhex(&pubkey_hex) {
Ok(pk) => pay::verify_tip(&pk, &tip_core(tip)),
Err(_) => false,
}
}
/// Convert a user-facing XMR amount string to a piconero string.
///
/// Accepts `"0.5"`, `"1"`, `"0.001"` etc. Returns the piconero string on
/// success so the caller can pass it to the payment send methods. Fails on
/// empty, non-numeric, zero, or out-of-range input.
#[uniffi::export]
pub fn xmr_to_atomic(amount_xmr: String) -> WResult<String> {
pay::xmr_to_atomic(&amount_xmr).map_err(WireError::new)
}
/// Format a piconero string as a human-readable XMR string.
///
/// The core stores amounts as piconero strings; this is what the wallet screen
/// renders. `"0"` → `"0"`, `"1000000000000"` → `"1"`, `"150000000000"` → `"0.15"`.
#[uniffi::export]
pub fn atomic_to_xmr_str(amount_atomic: String) -> String {
pay::atomic_to_xmr_str(&amount_atomic)
}
/// Check whether a string is a valid Monero address.
///
/// Validates checksum and prefix byte. Used by the UI to reject typos before
/// sending a payment. Both standard and integrated addresses are accepted.
#[uniffi::export]
pub fn check_address(address: String) -> WResult<()> {
pay::check_address(&address).map_err(WireError::new)
}
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
#[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::Store;
use onionwire::outbox::OutboxStatus;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
fn stopped_wire() -> Wire {
Wire {
node: Mutex::new(None),
home: PathBuf::from("/tmp/onionwire-sdk-stopped"),
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state 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<Option<...>>` 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<Option<Arc<Node>>>`, 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<OutboxStatus, String>` 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.
2026-09-12 14:29:02 -04:00
}
}
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(),
payload: None,
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);
}
/// An empty dir for a store-backed test. `tempfile` is not a dependency of
/// this crate and a store only needs somewhere private to live.
fn temp_home() -> PathBuf {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let dir = std::env::temp_dir().join(format!(
"onionwire-sdk-join-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&dir);
dir
}
/// The property the Android client joins on: a chat row and the outbox row
/// behind it report the same `messages.id`. Reads both sides out of a real
/// store through the same helpers `Wire::messages` / `Wire::outbox` use, so
/// a client can match on the id instead of counting rows.
#[test]
fn a_chat_row_joins_to_its_outbox_row_by_message_id() {
let home = temp_home();
let store = Store::open_at_with_passphrase(&home, "join-key-pass").unwrap();
let friend = [0x11u8; 32];
store.upsert_friend(&friend, "peer.onion", None).unwrap();
let row_id = store
.append_message_id(&friend, "out", b"still queued")
.unwrap();
store
.enqueue_outbox(
&friend,
row_id,
3,
1_700_000_045,
"peer onion unreachable",
1_700_000_000,
)
.unwrap();
// Same two reads `Wire::messages` / `Wire::outbox` do.
let mut messages = Vec::new();
for m in store.list_messages(&friend).unwrap() {
let status = store.outbox_status_of_message(m.id).unwrap();
messages.push(chat_message(m, status));
}
let rows: Vec<OutboxRow> = store
.pending_outbox(&friend)
.unwrap()
.iter()
.map(outbox_row)
.collect();
assert_eq!(messages.len(), 1);
assert_eq!(rows.len(), 1);
// The outbox side really is the stored row (not a defaulted id) …
assert_eq!(rows[0].message_id, row_id);
// … and the id the client gets on the message is that same row id.
assert_eq!(messages[0].id, rows[0].message_id);
// Both sides describe the same row, queued with its attempt count.
assert_eq!(messages[0].delivery.as_deref(), Some("queued"));
assert_eq!(rows[0].attempts, 3);
std::fs::remove_dir_all(&home).ok();
}
#[test]
fn wallet_balance_on_stopped_handle_returns_off() {
// A stopped/shut-down handle has no node, so the wallet is inaccessible.
// The UI treats "off" as "wallet not available" — same as "not configured".
assert_eq!(block_on(stopped_wire().wallet_balance()), "off");
}
#[test]
fn wallet_receive_address_on_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_receive_address()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn wallet_recent_transfers_on_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_recent_transfers(8)).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
#[test]
fn xmr_to_atomic_rejects_zero() {
assert!(xmr_to_atomic("0".to_string()).is_err());
}
#[test]
fn xmr_to_atomic_accepts_one_xmr() {
assert_eq!(xmr_to_atomic("1".to_string()).unwrap(), "1000000000000");
}
#[test]
fn xmr_to_atomic_accepts_fractional_xmr() {
assert_eq!(xmr_to_atomic("0.5".to_string()).unwrap(), "500000000000");
}
#[test]
fn atomic_to_xmr_str_formats_correctly() {
assert_eq!(atomic_to_xmr_str("1000000000000".to_string()), "1");
assert_eq!(atomic_to_xmr_str("500000000000".to_string()), "0.5");
assert_eq!(atomic_to_xmr_str("0".to_string()), "0");
}
#[test]
fn check_address_accepts_valid_address() {
// Standard mainnet address from tests/pay.rs (same spend/view keys).
assert!(check_address(
"4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge"
.to_string()
)
.is_ok());
}
#[test]
fn check_address_rejects_invalid_address() {
assert!(check_address("not-an-address".to_string()).is_err());
}
feat(sdk): sign/encode/decode/verify invoice, receipt and tip frames The SDK could already send an invoice or a tip through Node::pay_invoice / Node::tip, but it could not touch the payment frames themselves: pay::sign_* take the ed25519 identity secret and Node exposed only identity_pk(), so the signing half lived nowhere the SDK could reach. Add the signing surface to the node instead of exporting the key: * Node::sign_invoice / sign_receipt / sign_tip sign with the node's own identity key and return the core frame struct. The secret never leaves the process and there is no API that hands it out. * pay_invoice and tip now call those methods rather than signing inline, so there is one signing path, not two. SDK (crates/onionwire-sdk), all backward compatible: * Records Invoice, Receipt, Tip mirroring src/pay.rs, sig as raw bytes so a frame re-encodes byte-for-byte. * Wire::sign_invoice / sign_receipt / sign_tip (async, over the node). * Free functions encode_invoice / encode_receipt / encode_tip, decode_invoice / decode_receipt / decode_tip (None on a foreign or truncated frame), verify_invoice / verify_receipt / verify_tip against the sender's pubkey hex (false on a bad key, never a panic). Tests: 8 new SDK unit tests (record round-trips through the core encoders, signer-key-only verification, tamper rejection, foreign/truncated frame, typed Stopped error after shutdown). SDK 27 passed, 0 failed; SDK clippy --all-targets -D warnings clean; root clippy --all-targets -D warnings clean; root lib tests 14 passed; tests/pay.rs 11 passed.
2026-09-15 12:45:49 -04:00
// ---- pay.rs surface: Invoice / Receipt / Tip frames ----
/// A throwaway identity for the signing half, without Arti or a store:
/// `session::Keys::generate` is the core's own generator and hands out both
/// the secret half the signer needs and the public half a verifier needs.
fn test_keys() -> onionwire::session::Keys {
onionwire::session::Keys::generate()
}
/// Same mainnet address the address tests use.
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
fn signed_invoice(k: &onionwire::session::Keys) -> pay::Invoice {
pay::sign_invoice(&k.identity_sk, "500000000000", ADDR, "lunch", 1_700_000_000)
.expect("sign_invoice")
}
fn signed_receipt(k: &onionwire::session::Keys) -> pay::Receipt {
pay::sign_receipt(&k.identity_sk, "ab12", "500000000000", ADDR, 1_700_000_000)
.expect("sign_receipt")
}
fn signed_tip(k: &onionwire::session::Keys) -> pay::Tip {
pay::sign_tip(
&k.identity_sk,
"ab12",
"500000000000",
ADDR,
"lunch",
1_700_000_000,
)
.expect("sign_tip")
}
#[test]
fn invoice_record_round_trips_through_encode_and_decode() {
let k = test_keys();
let core = signed_invoice(&k);
let rec = invoice_record(core.clone());
// The record carries the core's fields, not defaults.
assert_eq!(rec.amount_atomic, "500000000000");
assert_eq!(rec.address, ADDR);
assert_eq!(rec.memo, "lunch");
assert_eq!(rec.ts, 1_700_000_000);
assert_eq!(rec.sig, core.sig);
// Encoding the record is byte-identical to encoding the core frame …
let pt = encode_invoice(rec.clone());
assert_eq!(pt, pay::encode_invoice(&core));
// … and the frame decodes back to the same record.
assert_eq!(decode_invoice(pt).as_ref(), Some(&rec));
}
#[test]
fn receipt_record_round_trips_through_encode_and_decode() {
let k = test_keys();
let core = signed_receipt(&k);
let rec = receipt_record(core.clone());
assert_eq!(rec.txid, "ab12");
assert_eq!(rec.amount_atomic, "500000000000");
assert_eq!(rec.address, ADDR);
assert_eq!(rec.ts, 1_700_000_000);
let pt = encode_receipt(rec.clone());
assert_eq!(pt, pay::encode_receipt(&core));
assert_eq!(decode_receipt(pt).as_ref(), Some(&rec));
}
#[test]
fn tip_record_round_trips_through_encode_and_decode() {
let k = test_keys();
let core = signed_tip(&k);
let rec = tip_record(core.clone());
assert_eq!(rec.txid, "ab12");
assert_eq!(rec.memo, "lunch");
let pt = encode_tip(rec.clone());
assert_eq!(pt, pay::encode_tip(&core));
assert_eq!(decode_tip(pt).as_ref(), Some(&rec));
}
#[test]
fn a_frame_verifies_against_the_signers_pubkey_only() {
let k = test_keys();
let other = test_keys();
let rec = invoice_record(signed_invoice(&k));
assert!(verify_invoice(hex(&k.identity_pk), rec.clone()));
assert!(!verify_invoice(hex(&other.identity_pk), rec.clone()));
// A malformed key is a failed verification, not a panic.
assert!(!verify_invoice("zz".to_string(), rec));
}
#[test]
fn receipt_and_tip_verify_against_the_signers_pubkey_only() {
let k = test_keys();
let other = test_keys();
let pk = hex(&k.identity_pk);
let wrong = hex(&other.identity_pk);
let rcp = receipt_record(signed_receipt(&k));
assert!(verify_receipt(pk.clone(), rcp.clone()));
assert!(!verify_receipt(wrong.clone(), rcp));
let tip = tip_record(signed_tip(&k));
assert!(verify_tip(pk, tip.clone()));
assert!(!verify_tip(wrong, tip));
}
#[test]
fn verification_rejects_a_frame_whose_amount_was_edited() {
let k = test_keys();
let pk = hex(&k.identity_pk);
let mut inv = invoice_record(signed_invoice(&k));
inv.amount_atomic = "900000000000".to_string();
assert!(!verify_invoice(pk.clone(), inv));
let mut tip = tip_record(signed_tip(&k));
tip.address = ADDR.replace("4AdUnd", "4AdUne");
assert!(!verify_tip(pk, tip));
}
#[test]
fn decode_rejects_a_foreign_or_truncated_frame() {
let k = test_keys();
assert_eq!(decode_invoice(b"nonsense".to_vec()), None);
// A tip frame is not an invoice frame.
assert_eq!(decode_invoice(encode_tip(tip_record(signed_tip(&k)))), None);
// The prefix without its fields is not a frame either.
let mut truncated = encode_receipt(receipt_record(signed_receipt(&k)));
truncated.truncate(10);
assert_eq!(decode_receipt(truncated), None);
}
#[test]
fn payment_signing_after_shutdown_is_a_typed_error() {
let wire = stopped_wire();
for err in [
block_on(wire.sign_invoice("500000000000".into(), ADDR.into(), String::new()))
.unwrap_err(),
block_on(wire.sign_receipt("ab12".into(), "500000000000".into(), ADDR.into()))
.unwrap_err(),
block_on(wire.sign_tip(
"ab12".into(),
"500000000000".into(),
ADDR.into(),
String::new(),
))
.unwrap_err(),
] {
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
}
/// The `$ONIONWIRE_HOME` a caller opened the identity with. `Wire` keeps it
/// internally; these tests drive the same two pure helpers
/// `set_chain_source` / `chain_source` go through.
fn sdk_home() -> PathBuf {
PathBuf::from("/data/user/0/dev.sirius.onionwire/files")
}
/// A request as Kotlin builds one: only the fields the chosen kind uses are
/// set.
fn request(kind: ChainChoice, datadir: &str) -> ChainConfig {
ChainConfig {
kind,
monerod_bin: String::new(),
monerod_datadir: datadir.to_string(),
host: String::new(),
port: 0,
wallet_rpc_bin: "/data/app/nativeLibraryDir/libmonerowalletrpc.so".to_string(),
arti_bin: "/data/app/nativeLibraryDir/libarti.so".to_string(),
wallet_filename: "wallet".to_string(),
mainnet: false,
prune: false,
}
}
/// Kotlin must not have to invent a chain data directory: an empty
/// `monerod_datadir` on the in-process source resolves to the per-identity
/// `chain` directory the core documents (`$ONIONWIRE_HOME/chain`), and no
/// binary path is involved at all.
#[test]
fn an_empty_in_process_datadir_resolves_under_the_wire_home() {
let child = child_config(request(ChainChoice::InProcessCuprate, ""), &sdk_home());
assert_eq!(
child.source,
ChainSource::InProcessCuprate {
datadir: sdk_home().join("chain").join("testnet"),
network: ChainNetwork::Testnet,
prune: false,
}
);
assert_eq!(child.source_label(), "in-process testnet");
}
#[test]
fn child_config_mainnet_pruned_uses_its_own_datadir() {
let mut req = request(ChainChoice::InProcessCuprate, "");
req.mainnet = true;
req.prune = true;
let child = child_config(req, &sdk_home());
assert_eq!(
child.source,
ChainSource::InProcessCuprate {
datadir: sdk_home().join("chain").join("mainnet-pruned"),
network: ChainNetwork::Mainnet,
prune: true,
}
);
assert_eq!(child.source_label(), "in-process mainnet pruned");
let back = chain_config(&child);
assert!(back.mainnet);
assert!(back.prune);
}
#[test]
fn child_config_mainnet_full_uses_its_own_datadir() {
let mut req = request(ChainChoice::InProcessCuprate, "");
req.mainnet = true;
req.prune = false;
let child = child_config(req, &sdk_home());
assert_eq!(
child.source,
ChainSource::InProcessCuprate {
datadir: sdk_home().join("chain").join("mainnet-full"),
network: ChainNetwork::Mainnet,
prune: false,
}
);
assert_eq!(child.source_label(), "in-process mainnet full");
}
#[test]
fn an_explicit_in_process_datadir_is_taken_as_given() {
let given = "/data/user/0/dev.sirius.onionwire/files/chain-heavy";
let child = child_config(request(ChainChoice::InProcessCuprate, given), &sdk_home());
assert_eq!(
child.source,
ChainSource::InProcessCuprate {
datadir: PathBuf::from(given),
network: ChainNetwork::Testnet,
prune: false,
}
);
}
/// Every kind survives the round trip a settings screen does (`ChainConfig`
/// -> core `ChildConfig` -> `ChainConfig`), so a prefill shows what was
/// stored rather than a default.
#[test]
fn every_chain_choice_round_trips_through_the_sdk_mapping() {
for kind in [
ChainChoice::None,
ChainChoice::Local,
ChainChoice::InProcessCuprate,
ChainChoice::Remote,
] {
let mut req = request(kind, "");
match kind {
ChainChoice::Local => {
req.monerod_bin = "/data/app/nativeLibraryDir/libmonerod.so".to_string();
req.monerod_datadir = sdk_home().join("chain").display().to_string();
}
ChainChoice::Remote => {
req.host = "peer.onion".to_string();
req.port = 18081;
}
ChainChoice::None | ChainChoice::InProcessCuprate => {}
}
let back = chain_config(&child_config(req.clone(), &sdk_home()));
assert_eq!(back.kind, kind, "kind lost for {kind:?}");
assert_eq!(back.wallet_rpc_bin, req.wallet_rpc_bin);
assert_eq!(back.arti_bin, req.arti_bin);
assert_eq!(back.wallet_filename, req.wallet_filename);
match kind {
ChainChoice::InProcessCuprate => {
assert_eq!(
back.monerod_datadir,
sdk_home().join("chain").join("testnet").display().to_string()
);
assert!(
back.monerod_bin.is_empty(),
"no binary for an in-process node"
);
}
ChainChoice::Local => {
assert_eq!(back.monerod_bin, req.monerod_bin);
assert_eq!(back.monerod_datadir, req.monerod_datadir);
}
ChainChoice::Remote => {
assert_eq!(back.host, "peer.onion");
assert_eq!(back.port, 18081);
}
ChainChoice::None => {
assert_eq!(back.monerod_datadir, "");
assert_eq!(back.host, "");
}
}
}
}
fn core_status(state: WalletChildState) -> onionwire::wallet_child::WalletChildStatus {
onionwire::wallet_child::WalletChildStatus {
state,
running: true,
configured: true,
chain_source: "in-process node".to_string(),
height: 0,
target_height: 0,
last_error: None,
}
}
/// `wallet_status` speaks about the app's own node for the in-process
/// source: the five core states map to node-scoped words, and no state
/// becomes `ready` that the core did not report as ready.
#[test]
fn node_state_names_the_apps_own_chain_for_the_in_process_source() {
let source = ChainSource::InProcessCuprate {
datadir: sdk_home().join("chain").join("testnet"),
network: ChainNetwork::Testnet,
prune: false,
};
let cases = [
(WalletChildState::Off, "off"),
(WalletChildState::Connecting, "starting"),
(WalletChildState::Syncing, "syncing"),
(WalletChildState::Ready, "ready"),
(WalletChildState::Exited, "exited"),
];
for (state, want) in cases {
let status = child_status(core_status(state), &source);
assert_eq!(status.node_state, want, "state {state:?}");
assert!(status.chain_in_process, "state {state:?}");
// The core's own word is still carried verbatim, for a caller that
// renders `state` instead.
assert_eq!(status.state, state.as_str());
}
}
/// A source that is not the in-process node reports no node segment, so a
/// Kotlin status line cannot show a node word for a spawned `monerod` or a
/// remote daemon — and `state` still passes straight through.
#[test]
fn node_state_is_empty_for_every_other_chain_source() {
for source in [
ChainSource::None,
ChainSource::Local {
monerod_bin: PathBuf::from("monerod"),
datadir: PathBuf::from("/chain"),
prune: false,
},
ChainSource::Remote {
host: "peer.onion".to_string(),
port: 18081,
},
] {
let status = child_status(core_status(WalletChildState::Ready), &source);
assert!(
!status.chain_in_process,
"{} is not in-process",
source.label()
);
assert_eq!(
status.node_state,
"",
"{} must have no node state",
source.label()
);
assert_eq!(status.state, "ready");
}
}
/// Whether *this* build can start the node is a build fact the picker greys
/// the option out with before a start is attempted.
#[test]
fn node_available_reports_whether_this_build_has_the_daemon() {
let status = child_status(core_status(WalletChildState::Off), &ChainSource::None);
assert_eq!(status.node_available, onionwire::cuprate::available());
}
/// The chain's own progress reaches Kotlin: a snapshot that carries the
/// daemon's height and target copies both numbers onto the record, so an
/// Android status line can show `1160/3090939` without a second probe.
#[test]
fn the_daemons_height_and_target_reach_the_sdk_record() {
let mut core = core_status(WalletChildState::Connecting);
core.height = 1160;
core.target_height = 3_090_939;
let status = child_status(core, &ChainSource::None);
assert_eq!(status.height, 1160);
assert_eq!(status.target_height, 3_090_939);
// The core's own word still passes straight through: the numbers are an
// addition, not a second state machine.
assert_eq!(status.state, "connecting");
}
/// A snapshot with nothing to report keeps `0/0`: unknown is not caught up,
/// and no percentage is invented on the way out.
#[test]
fn an_unprobed_child_reports_an_unknown_chain_progress() {
let status = child_status(core_status(WalletChildState::Off), &ChainSource::None);
assert_eq!(status.height, 0);
assert_eq!(status.target_height, 0);
}
/// A live probe on a node with no child is `off` — the same record the
/// cheap read reports — never an error and never an invented state.
///
/// This crate cannot build the node half of that: `open_wire` is the only
/// constructor of `Wire` and it bootstraps Arti and publishes an onion
/// service, so there is no offline `Node` for a test to hold. What is
/// pinned here is the half the SDK owns — both exported reads hand the same
/// core snapshot to the same `child_status` mapper — plus the record shape,
/// written as an exhaustive literal so a new field on `WalletChildStatus`
/// stops this test compiling. The core's own short-circuit (`wallet_child`
/// is `None` ⇒ return the cached snapshot) is what `src/node.rs`'s tests
/// exercise.
#[test]
fn an_unprobed_child_is_off_whichever_read_reports_it() {
let core = onionwire::wallet_child::WalletChildStatus {
state: WalletChildState::Off,
running: false,
configured: false,
chain_source: "receive-only".to_string(),
height: 0,
target_height: 0,
last_error: None,
};
let source = ChainSource::None;
let want = WalletChildStatus {
state: "off".to_string(),
running: false,
configured: false,
chain_source: "receive-only".to_string(),
chain_in_process: false,
node_available: onionwire::cuprate::available(),
node_state: String::new(),
height: 0,
target_height: 0,
last_error: None,
};
// `wallet_status` maps it once, `wallet_child_refresh` maps the same
// snapshot the same way: one mapper, no second state machine.
for got in [
child_status(core.clone(), &source),
child_status(core, &source),
] {
assert_eq!(got.state, want.state);
assert_eq!(got.running, want.running);
assert_eq!(got.configured, want.configured);
assert_eq!(got.chain_source, want.chain_source);
assert_eq!(got.chain_in_process, want.chain_in_process);
assert_eq!(got.node_available, want.node_available);
assert_eq!(got.node_state, want.node_state);
assert_eq!(got.height, want.height);
assert_eq!(got.target_height, want.target_height);
assert_eq!(got.last_error, want.last_error);
}
}
/// The live probe is an error, not a panic, once the handle is shut down:
/// it goes through the same `node()` accessor as every other call.
#[test]
fn wallet_child_refresh_on_a_stopped_handle_is_stopped_error() {
let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
}
}