2026-09-10 02:07:40 -04:00
|
|
|
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
|
|
|
|
|
|
|
|
|
|
use std::path::{Path, PathBuf};
|
2026-09-15 12:29:16 -04:00
|
|
|
use std::process::Command;
|
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::atomic::{AtomicBool, Ordering};
|
2026-09-10 02:07:40 -04:00
|
|
|
use std::sync::{Arc, Mutex};
|
2026-09-10 02:43:45 -04:00
|
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
2026-09-10 02:07:40 -04:00
|
|
|
|
|
|
|
|
use futures::StreamExt;
|
|
|
|
|
use futures::io::{AsyncRead, AsyncWrite};
|
|
|
|
|
use tor_cell::relaycell::msg::Connected;
|
|
|
|
|
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
2026-09-12 13:36:21 -04:00
|
|
|
use zeroize::Zeroizing;
|
2026-09-10 02:07:40 -04:00
|
|
|
|
2026-09-10 14:18:06 -04:00
|
|
|
use crate::dispatch::{self, Kind};
|
2026-09-10 23:32:06 -04:00
|
|
|
use crate::file;
|
2026-09-10 02:07:40 -04:00
|
|
|
use crate::frame;
|
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 crate::hs::{self, Client, HS_PORT, TorState};
|
2026-09-10 02:43:45 -04:00
|
|
|
use crate::loc;
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
2026-09-10 14:37:43 -04:00
|
|
|
use crate::pay;
|
2026-09-10 14:25:31 -04:00
|
|
|
use crate::profile;
|
2026-09-10 02:07:40 -04:00
|
|
|
use crate::qr;
|
2026-09-10 14:50:01 -04:00
|
|
|
use crate::ratelimit::TokenBucket;
|
2026-09-11 23:42:48 -04:00
|
|
|
use crate::sanitize;
|
2026-09-10 02:07:40 -04:00
|
|
|
use crate::session::{self, Keys};
|
node: read-only Node::list_payments(friend_pk) for the TUI payment history
Re-exposes the existing Store::list_payments as one typed read method so
src/tui.rs can render a friend's payment history without ever touching the
store. Maps the store error to Result<_, String> exactly like the
neighbouring list_messages / wallet_recent_transfers, and returns
store::Payment as-is (id, dir, kind, amount_atomic, address, memo, txid,
verified, created_at).
Read-only: no schema change, no migration, no new frame, no new column, no
docs/PROTOCOL.md change, and no store handle becomes reachable from the TUI.
An unknown friend is empty history (Ok(vec![])), not an error.
Test placement deviates from the card, deliberately: it lives in
src/node.rs's #[cfg(test)] mod tests instead of tests/pay.rs, because Node
has no constructor that avoids Tor (Node::start* is the only public one) and
ingest_receipt is private, so tests/pay.rs cannot build a Node at all. The
test uses an unbootstrapped Arti client plus a null deliverer over a real
encrypted store in a temp dir, writes the outbound row directly and drives
the inbound row through the node's own ingest_receipt.
2026-09-15 15:10:38 -04:00
|
|
|
use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store};
|
2026-09-15 12:29:16 -04:00
|
|
|
use crate::wallet::{self, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
|
|
|
|
|
use crate::wallet_child::{self, WalletChild};
|
2026-09-10 02:43:45 -04:00
|
|
|
|
|
|
|
|
pub struct RotateResult {
|
|
|
|
|
pub notified: usize,
|
|
|
|
|
pub friends: usize,
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
/// What a `flush` actually managed to do, for UI surfacing.
|
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
|
|
|
pub struct FlushOutcome {
|
|
|
|
|
/// Outbox rows we tried to deliver in this pass.
|
|
|
|
|
pub attempted: usize,
|
|
|
|
|
/// Rows delivered now — their outbox rows are gone.
|
|
|
|
|
pub delivered: usize,
|
|
|
|
|
/// Rows still queued or terminally failed after the pass.
|
|
|
|
|
pub remaining: usize,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
|
|
|
|
|
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
|
|
|
|
|
/// the retry worker picks it up on its normal schedule.
|
|
|
|
|
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
|
|
|
|
|
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
|
|
|
|
|
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
|
|
|
|
|
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
struct HsHandle {
|
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
|
|
|
svc: Arc<RunningOnionService>,
|
2026-09-10 02:43:45 -04:00
|
|
|
rend: tokio::task::JoinHandle<()>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Drop for HsHandle {
|
|
|
|
|
fn drop(&mut self) {
|
|
|
|
|
self.rend.abort();
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-09-10 02:07:40 -04:00
|
|
|
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
/// Abort the outbox worker when the node goes away.
|
|
|
|
|
struct WorkerHandle(tokio::task::JoinHandle<()>);
|
|
|
|
|
|
|
|
|
|
impl Drop for WorkerHandle {
|
|
|
|
|
fn drop(&mut self) {
|
|
|
|
|
self.0.abort();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-15 12:29:16 -04:00
|
|
|
/// Whether the app-owned wallet child pair is running.
|
|
|
|
|
///
|
|
|
|
|
/// The *choice* of chain source is separate: it lives in the sealed store
|
|
|
|
|
/// record and survives a restart even if no child was ever started.
|
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
|
|
|
pub enum WalletChildState {
|
|
|
|
|
/// Receive-only, or nothing chosen yet: no daemon, nothing to start.
|
|
|
|
|
Off,
|
|
|
|
|
/// A chain source is configured, but no child of ours is alive.
|
|
|
|
|
Stopped,
|
|
|
|
|
/// A child this app spawned is still up.
|
|
|
|
|
Running,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// How far along the chain the configured daemon says it is.
|
|
|
|
|
///
|
|
|
|
|
/// `reachable == false` means **unknown**, never "synced": a daemon we cannot
|
|
|
|
|
/// ask must not let the wallet screen claim the chain is current.
|
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
|
|
|
pub struct DaemonSync {
|
|
|
|
|
pub reachable: bool,
|
|
|
|
|
pub height: u64,
|
|
|
|
|
pub target_height: u64,
|
|
|
|
|
/// Why there is no answer (receive-only, no SOCKS listener, a failed dial).
|
|
|
|
|
pub note: Option<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl DaemonSync {
|
|
|
|
|
/// Synced means the daemon answered and reported a target it had reached.
|
|
|
|
|
/// Unreachable is *not* synced.
|
|
|
|
|
pub fn synced(&self) -> bool {
|
|
|
|
|
self.reachable && self.target_height > 0 && self.height >= self.target_height
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn unknown(note: impl Into<String>) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
reachable: false,
|
|
|
|
|
height: 0,
|
|
|
|
|
target_height: 0,
|
|
|
|
|
note: Some(note.into()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:07:40 -04:00
|
|
|
pub struct Node {
|
|
|
|
|
home: PathBuf,
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
store: Arc<Mutex<Store>>,
|
2026-09-10 02:07:40 -04:00
|
|
|
client: Client,
|
2026-09-10 02:43:45 -04:00
|
|
|
hs: Mutex<Option<HsHandle>>,
|
|
|
|
|
onion: Mutex<String>,
|
2026-09-10 14:50:01 -04:00
|
|
|
keys: Mutex<Keys>,
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
/// Behind a lock because the F7 screen can re-point it at a saved config
|
|
|
|
|
/// without a restart. Clone it out (`wallet_snapshot`) before awaiting: a
|
|
|
|
|
/// `std::sync::Mutex` guard must not live across an `.await`.
|
|
|
|
|
wallet: Mutex<Wallet>,
|
|
|
|
|
/// Last probe result, for the draw path. Cheap to read, never dials.
|
|
|
|
|
wallet_status: Mutex<WalletStatus>,
|
2026-09-15 12:29:16 -04:00
|
|
|
/// The app-owned child pair (`monerod` when the source is local,
|
|
|
|
|
/// `monero-wallet-rpc` always). `None` until `wallet_child_start`: the
|
|
|
|
|
/// chain-source *choice* lives in the sealed store record, not here.
|
|
|
|
|
child: Mutex<Option<WalletChild>>,
|
2026-09-10 14:50:01 -04:00
|
|
|
incoming_limit: Mutex<TokenBucket>,
|
2026-09-10 23:32:06 -04:00
|
|
|
inbox: Mutex<file::Inbox>,
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
outbox: Arc<Outbox>,
|
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
|
|
|
worker: Mutex<Option<WorkerHandle>>,
|
|
|
|
|
/// Set by `shutdown`. Checked before any operation that would touch Tor or
|
|
|
|
|
/// the store, so a stopped node fails cleanly instead of dialing.
|
|
|
|
|
stopped: AtomicBool,
|
|
|
|
|
/// Has this node's onion service ever crossed the reachability bar (status
|
|
|
|
|
/// `Running`/`DegradedReachable`, or a successful probe of our own onion)?
|
|
|
|
|
/// Arti's combined status can stay `Bootstrapping` for minutes *after* the
|
|
|
|
|
/// descriptor is downloadable, so without this the UI would keep saying
|
|
|
|
|
/// "starting" long past the point where friends can reach us. Cleared when
|
|
|
|
|
/// `rotate` hard-cuts the service.
|
|
|
|
|
onion_reachable: AtomicBool,
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Node {
|
|
|
|
|
pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> {
|
2026-09-12 13:36:21 -04:00
|
|
|
let pass = Zeroizing::new(
|
|
|
|
|
std::env::var("ONIONWIRE_STORE_PASSPHRASE")
|
|
|
|
|
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?,
|
|
|
|
|
);
|
2026-09-10 17:19:50 -04:00
|
|
|
if pass.is_empty() {
|
|
|
|
|
return Err("empty passphrase".into());
|
|
|
|
|
}
|
2026-09-12 13:36:21 -04:00
|
|
|
Self::start_with_passphrase(home, pass.as_str()).await
|
2026-09-10 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn start_with_passphrase(
|
|
|
|
|
home: PathBuf,
|
|
|
|
|
passphrase: &str,
|
|
|
|
|
) -> Result<Arc<Self>, String> {
|
|
|
|
|
let store = Store::open_at_with_passphrase(&home, passphrase).map_err(|e| e.to_string())?;
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
// Stored config first (the F7 screen's), env as the migration path.
|
|
|
|
|
let stored_wallet = store.load_wallet_config().map_err(|e| e.to_string())?;
|
|
|
|
|
let wallet = Wallet::for_boot(stored_wallet.as_ref());
|
|
|
|
|
let wallet_status = WalletStatus::idle(wallet.configured());
|
2026-09-10 02:07:40 -04:00
|
|
|
let me = store.self_identity().map_err(|e| e.to_string())?;
|
|
|
|
|
let keys = Keys::from_self(&me).map_err(|e| e.to_string())?;
|
2026-09-10 02:43:45 -04:00
|
|
|
let nickname = store.hs_nickname().map_err(|e| e.to_string())?;
|
2026-09-10 02:07:40 -04:00
|
|
|
let state = home.join("arti");
|
|
|
|
|
let cache = home.join("cache");
|
|
|
|
|
let client = hs::bootstrapped(&state, &cache).await?;
|
|
|
|
|
let launched = client
|
2026-09-10 02:43:45 -04:00
|
|
|
.launch_onion_service(hs::hs_config(&nickname)?)
|
2026-09-10 02:07:40 -04:00
|
|
|
.map_err(|e| format!("launch_onion_service: {e}"))?
|
|
|
|
|
.ok_or_else(|| "onion service disabled in config — fail closed".to_string())?;
|
|
|
|
|
let (svc, rend) = launched;
|
|
|
|
|
let onion = hs::onion_string(&svc)?;
|
2026-09-10 23:32:06 -04:00
|
|
|
let inbox = file::Inbox::new(home.join("inbox"));
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
let store = Arc::new(Mutex::new(store));
|
|
|
|
|
let outbox = Arc::new(Outbox::new(
|
|
|
|
|
Arc::clone(&store),
|
|
|
|
|
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
|
|
|
|
|
));
|
|
|
|
|
if let Err(e) = outbox.reset_stale() {
|
|
|
|
|
eprintln!("outbox: {e}");
|
|
|
|
|
}
|
2026-09-10 02:07:40 -04:00
|
|
|
let node = Arc::new(Self {
|
|
|
|
|
home,
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
store,
|
2026-09-10 02:07:40 -04:00
|
|
|
client,
|
2026-09-10 02:43:45 -04:00
|
|
|
hs: Mutex::new(None),
|
2026-09-10 16:14:10 -04:00
|
|
|
onion: Mutex::new(onion.clone()),
|
2026-09-10 14:50:01 -04:00
|
|
|
keys: Mutex::new(keys),
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
wallet: Mutex::new(wallet),
|
|
|
|
|
wallet_status: Mutex::new(wallet_status),
|
2026-09-15 12:29:16 -04:00
|
|
|
child: Mutex::new(None),
|
2026-09-10 14:50:01 -04:00
|
|
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
2026-09-10 23:32:06 -04:00
|
|
|
inbox: Mutex::new(inbox),
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
outbox: Arc::clone(&outbox),
|
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
|
|
|
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
|
|
|
|
|
stopped: AtomicBool::new(false),
|
|
|
|
|
onion_reachable: AtomicBool::new(false),
|
2026-09-10 02:07:40 -04:00
|
|
|
});
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
// Unlock trigger: flush anything queued by a previous run now, in the
|
|
|
|
|
// background, rather than waiting out its backoff.
|
|
|
|
|
spawn_flush_all(Arc::clone(&node.outbox));
|
2026-09-10 16:14:10 -04:00
|
|
|
// Accept rens before waiting so a reachability probe can succeed
|
|
|
|
|
// while combined status is still Bootstrapping.
|
2026-09-10 02:43:45 -04:00
|
|
|
let rend = spawn_rend(Arc::clone(&node), rend);
|
2026-09-10 16:14:10 -04:00
|
|
|
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
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
|
|
|
svc: Arc::clone(&svc),
|
2026-09-10 16:14:10 -04:00
|
|
|
rend,
|
|
|
|
|
});
|
2026-09-10 20:30:18 -04:00
|
|
|
hs::wait_until_published(&node.client, &svc, &onion).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
|
|
|
// Published by the same bar `wait_until_published` uses — a probe
|
|
|
|
|
// success counts, which is the whole reason `tor_state` tracks it
|
|
|
|
|
// separately from Arti's (slower, flappier) combined status.
|
|
|
|
|
node.onion_reachable.store(true, Ordering::SeqCst);
|
2026-09-10 16:14:10 -04:00
|
|
|
node.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.set_onion(&onion)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
2026-09-10 02:07:40 -04:00
|
|
|
Ok(node)
|
|
|
|
|
}
|
|
|
|
|
|
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 onion/Tor lifecycle state: `Bootstrapping` / `Published` /
|
|
|
|
|
/// `DegradedReachable` / `Stopped`.
|
|
|
|
|
///
|
|
|
|
|
/// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a
|
|
|
|
|
/// foreground-service notification can poll it instead of guessing from a
|
|
|
|
|
/// timer. A poisoned handle is reported as `Stopped` rather than panicking:
|
|
|
|
|
/// the node is unusable either way, and the caller is often a UI thread.
|
|
|
|
|
pub fn tor_state(&self) -> TorState {
|
|
|
|
|
let stopped = self.stopped.load(Ordering::SeqCst);
|
|
|
|
|
let reachable = self.onion_reachable.load(Ordering::SeqCst);
|
|
|
|
|
match self.hs.lock() {
|
|
|
|
|
Ok(guard) => match guard.as_ref() {
|
|
|
|
|
Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable),
|
|
|
|
|
// Between `rotate`'s hard cut and the new service being
|
|
|
|
|
// installed there is no handle; before the first publish there
|
|
|
|
|
// is none either. Both are "not serving *yet*" unless we stopped.
|
|
|
|
|
None if stopped => TorState::Stopped,
|
|
|
|
|
None => TorState::Bootstrapping,
|
|
|
|
|
},
|
|
|
|
|
Err(_) => TorState::Stopped,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Drain the outbox: one delivery attempt for every outstanding row, now,
|
|
|
|
|
/// ignoring its retry schedule. Then checkpoint the WAL.
|
|
|
|
|
///
|
|
|
|
|
/// This is the "deliver what is deliverable before we lose the process"
|
|
|
|
|
/// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a
|
|
|
|
|
/// dial for ~20s and the caller is usually a UI thread. Rows that could not
|
|
|
|
|
/// be delivered stay queued and are picked up by the retry worker on its
|
|
|
|
|
/// normal backoff.
|
|
|
|
|
pub async fn flush(&self) -> Result<FlushOutcome, String> {
|
|
|
|
|
self.ensure_running()?;
|
|
|
|
|
let outcome = self.drain(FLUSH_TIMEOUT).await?;
|
|
|
|
|
self.checkpoint();
|
|
|
|
|
Ok(outcome)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Stop the node.
|
|
|
|
|
///
|
|
|
|
|
/// Order matters: drain the outbox while the Tor client is still alive,
|
|
|
|
|
/// then drop the onion service (its rendezvous task is aborted and the v3
|
|
|
|
|
/// service goes down), then abort the retry worker so nothing dials after
|
|
|
|
|
/// this, then checkpoint the WAL.
|
|
|
|
|
///
|
|
|
|
|
/// Idempotent: the flag is swapped first, so a second call — or a call
|
|
|
|
|
/// racing another teardown — returns `Ok(())` without touching anything
|
|
|
|
|
/// twice. Every other method on a stopped node returns a clean `Err`, never
|
|
|
|
|
/// a panic. A process killed outright never gets here at all, which is why
|
|
|
|
|
/// [`flush`](Self::flush) exists.
|
|
|
|
|
pub async fn shutdown(&self) -> Result<(), String> {
|
|
|
|
|
if self.stopped.swap(true, Ordering::SeqCst) {
|
|
|
|
|
return Ok(());
|
|
|
|
|
}
|
|
|
|
|
// Bounded: teardown must not hang behind a Tor dial. Undelivered rows
|
|
|
|
|
// survive in sqlite and are retried on the next unlock.
|
|
|
|
|
match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await {
|
|
|
|
|
Ok(o) if o.remaining > 0 => {
|
|
|
|
|
eprintln!("shutdown: {} outbox row(s) still pending", o.remaining)
|
|
|
|
|
}
|
|
|
|
|
Ok(_) => {}
|
|
|
|
|
Err(e) => eprintln!("shutdown: drain failed: {e}"),
|
|
|
|
|
}
|
|
|
|
|
match self.hs.lock() {
|
|
|
|
|
Ok(mut g) => *g = None,
|
|
|
|
|
Err(_) => eprintln!("shutdown: onion-service lock poisoned"),
|
|
|
|
|
}
|
|
|
|
|
match self.worker.lock() {
|
|
|
|
|
Ok(mut g) => drop(g.take()),
|
|
|
|
|
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
|
|
|
|
|
}
|
2026-09-15 12:29:16 -04:00
|
|
|
// The app owns the chain children; nothing else will reap them.
|
|
|
|
|
if let Err(e) = self.wallet_child_stop() {
|
|
|
|
|
eprintln!("shutdown: wallet child: {e}");
|
|
|
|
|
}
|
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.checkpoint();
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// One bounded pass over every outstanding outbox row.
|
|
|
|
|
///
|
|
|
|
|
/// A timeout cancels the pass mid-flight, which can leave a row in
|
|
|
|
|
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
|
|
|
|
|
/// same recovery the parent uses for a process that died mid-attempt.
|
|
|
|
|
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).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
|
|
|
Ok(Ok(rows)) => Some(rows),
|
|
|
|
|
Ok(Err(e)) => return Err(e),
|
|
|
|
|
Err(_) => {
|
|
|
|
|
eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued");
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
let delivered = attempted
|
|
|
|
|
.as_ref()
|
|
|
|
|
.map(|rows| {
|
|
|
|
|
rows.iter()
|
|
|
|
|
.filter(|(_, s)| matches!(s, OutboxStatus::Sent))
|
|
|
|
|
.count()
|
|
|
|
|
})
|
|
|
|
|
.unwrap_or(0);
|
|
|
|
|
Ok(FlushOutcome {
|
|
|
|
|
// `None` means the pass was cancelled: we know how many rows are
|
|
|
|
|
// still queued, not how many were started.
|
|
|
|
|
attempted: attempted.as_ref().map(Vec::len).unwrap_or(0),
|
|
|
|
|
delivered,
|
|
|
|
|
remaining: self.pending_rows()?,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Rows the outbox still holds for every friend, queued or terminally
|
|
|
|
|
/// failed. A message absent here was delivered.
|
|
|
|
|
fn pending_rows(&self) -> Result<usize, String> {
|
|
|
|
|
let friends = self.list_friends()?;
|
|
|
|
|
let mut n = 0usize;
|
|
|
|
|
for f in &friends {
|
|
|
|
|
n += self.outbox.pending(&f.pubkey)?.len();
|
|
|
|
|
}
|
|
|
|
|
Ok(n)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Checkpoint the sqlite WAL into the main db file and truncate it.
|
|
|
|
|
///
|
|
|
|
|
/// Best effort on purpose: WAL replay on open recovers everything committed,
|
|
|
|
|
/// so this is about leaving less to replay (and less on disk) if the
|
|
|
|
|
/// process is killed right after teardown — not about correctness.
|
|
|
|
|
fn checkpoint(&self) {
|
2026-09-12 15:56:33 -04:00
|
|
|
let store = match self.store.lock() {
|
|
|
|
|
Ok(s) => s,
|
|
|
|
|
Err(e) => {
|
|
|
|
|
eprintln!("wal checkpoint: store lock poisoned: {e}");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
if let Err(e) = store.checkpoint_wal() {
|
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
|
|
|
eprintln!("wal checkpoint: {e}");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn ensure_running(&self) -> Result<(), String> {
|
|
|
|
|
if self.stopped.load(Ordering::SeqCst) {
|
|
|
|
|
return Err("node is stopped — open the identity again".to_string());
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
pub fn onion(&self) -> String {
|
|
|
|
|
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
|
|
|
|
|
2026-09-10 14:50:01 -04:00
|
|
|
fn keys(&self) -> Result<Keys, String> {
|
|
|
|
|
self.keys
|
|
|
|
|
.lock()
|
|
|
|
|
.map(|g| g.clone())
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:07:40 -04:00
|
|
|
pub fn identity_pk(&self) -> [u8; 32] {
|
2026-09-10 14:50:01 -04:00
|
|
|
self.keys().map(|k| k.identity_pk).unwrap_or([0; 32])
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn arti_dir(&self) -> PathBuf {
|
|
|
|
|
self.home.join("arti")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn cache_dir(&self) -> PathBuf {
|
|
|
|
|
self.home.join("cache")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn qr_payload(&self) -> Result<String, String> {
|
2026-09-10 14:50:01 -04:00
|
|
|
let k = self.keys()?;
|
|
|
|
|
qr::encode(&k.identity_sk, &self.onion(), &k.prekey_pk).map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn write_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
|
|
|
|
|
use std::io::Write;
|
|
|
|
|
use std::os::unix::fs::OpenOptionsExt;
|
|
|
|
|
let k = self.keys()?;
|
|
|
|
|
let blob = crate::backup::seal(
|
|
|
|
|
passphrase,
|
|
|
|
|
&crate::backup::BackupKeys {
|
|
|
|
|
identity_sk: k.identity_sk,
|
|
|
|
|
identity_pk: k.identity_pk,
|
|
|
|
|
prekey_sk: k.prekey_sk,
|
|
|
|
|
prekey_pk: k.prekey_pk,
|
|
|
|
|
},
|
|
|
|
|
)?;
|
|
|
|
|
let mut f = std::fs::OpenOptions::new()
|
|
|
|
|
.write(true)
|
|
|
|
|
.create(true)
|
|
|
|
|
.truncate(true)
|
|
|
|
|
.mode(0o600)
|
|
|
|
|
.open(path)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
f.write_all(&blob).map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn restore_backup(&self, path: &str, passphrase: &str) -> Result<(), String> {
|
|
|
|
|
let blob = std::fs::read(path).map_err(|e| e.to_string())?;
|
|
|
|
|
let k = crate::backup::open(passphrase, &blob)?;
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.replace_identity_keys(&k.identity_sk, &k.identity_pk, &k.prekey_sk, &k.prekey_pk)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
*self.keys.lock().map_err(|e| e.to_string())? = Keys {
|
|
|
|
|
identity_sk: k.identity_sk,
|
|
|
|
|
identity_pk: k.identity_pk,
|
|
|
|
|
prekey_sk: k.prekey_sk,
|
|
|
|
|
prekey_pk: k.prekey_pk,
|
|
|
|
|
};
|
|
|
|
|
Ok(())
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn add_friend_from_qr(&self, raw: &str) -> Result<(), String> {
|
|
|
|
|
let p = qr::decode(raw).map_err(|e| e.to_string())?;
|
2026-09-10 02:43:45 -04:00
|
|
|
self.add_friend_payload(&p)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> {
|
2026-09-10 02:07:40 -04:00
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.upsert_friend(&p.pubkey, &p.onion, None)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.set_friend_prekey(&p.pubkey, &p.signed_prekey)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
pub fn get_friend(&self, pubkey: &[u8]) -> Result<Option<Friend>, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.get_friend(pubkey)
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn list_friends(&self) -> Result<Vec<Friend>, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.list_friends()
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
feat(android): SDK AAR (UniFFI) + Compose APK, Arti rustls feature split
Adds the Android product alongside the existing Linux TUI, in one repo.
SDK — crates/onionwire-sdk is a UniFFI facade over the very same `onionwire`
crate the TUI runs on. Identity, invite, friend upsert, send/receive, rotate
and wipe all delegate; no protocol is reimplemented, so an Android peer and a
Linux peer interoperate. It is its own Cargo workspace because Arti's TLS
backends are non-additive: the TUI keeps native-tls (OpenSSL), Android needs
rustls + static-sqlite (no OpenSSL, no system libsqlite3 in the NDK).
android/ — Gradle project. :sdk produces the AAR (Kotlin bindings generated at
build time + libonionwire_sdk.so via cargo-ndk), :app is a Kotlin/Compose/M3
messenger depending on :sdk only. minSdk 26, targetSdk/compileSdk 36,
INTERNET-only, data in filesDir, backups excluded.
Root Cargo.toml grows `native-tls` (default) and `rustls` features so exactly
one Arti TLS backend is selected per build graph. The default build is
unchanged: same backend, ratatui still a normal dependency, src/tui.rs
untouched.
Also: Store::self_fingerprint/set_petname + Node wrappers (additive only),
scripts/build-android-local.sh, README sections, .gitignore for local SDK paths.
2026-09-10 18:20:19 -04:00
|
|
|
/// Fingerprint of our own identity key (identity = pubkey).
|
|
|
|
|
pub fn fingerprint(&self) -> Result<String, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.self_fingerprint()
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Local-only label. Does not go on the wire.
|
|
|
|
|
pub fn set_petname(&self, pubkey: &[u8], petname: Option<&str>) -> Result<(), String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.set_petname(pubkey, petname)
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
pub fn friend(&self, pubkey: &[u8]) -> Result<Friend, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.get_friend(pubkey)
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.ok_or_else(|| "friend not found".into())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:07:40 -04:00
|
|
|
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.list_messages(friend_pk)
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
node: read-only Node::list_payments(friend_pk) for the TUI payment history
Re-exposes the existing Store::list_payments as one typed read method so
src/tui.rs can render a friend's payment history without ever touching the
store. Maps the store error to Result<_, String> exactly like the
neighbouring list_messages / wallet_recent_transfers, and returns
store::Payment as-is (id, dir, kind, amount_atomic, address, memo, txid,
verified, created_at).
Read-only: no schema change, no migration, no new frame, no new column, no
docs/PROTOCOL.md change, and no store handle becomes reachable from the TUI.
An unknown friend is empty history (Ok(vec![])), not an error.
Test placement deviates from the card, deliberately: it lives in
src/node.rs's #[cfg(test)] mod tests instead of tests/pay.rs, because Node
has no constructor that avoids Tor (Node::start* is the only public one) and
ingest_receipt is private, so tests/pay.rs cannot build a Node at all. The
test uses an unbootstrapped Arti client plus a null deliverer over a real
encrypted store in a temp dir, writes the outbound row directly and drives
the inbound row through the node's own ingest_receipt.
2026-09-15 15:10:38 -04:00
|
|
|
/// Every payment row with this friend, in the store's existing order.
|
|
|
|
|
/// Read-only: the TUI payment-history screen reads this and never touches
|
|
|
|
|
/// the store itself. An unknown friend is empty history, not an error.
|
|
|
|
|
pub fn list_payments(&self, friend_pk: &[u8]) -> Result<Vec<Payment>, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.list_payments(friend_pk)
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
/// The live wallet, cloned out of its lock. Every wallet call goes through
|
|
|
|
|
/// this so a `std::sync::Mutex` guard never lives across an `.await`, and so
|
|
|
|
|
/// the F7 screen can re-point the wallet mid-session.
|
|
|
|
|
fn wallet_snapshot(&self) -> Wallet {
|
|
|
|
|
self.wallet
|
|
|
|
|
.lock()
|
|
|
|
|
.map(|w| w.clone())
|
|
|
|
|
.unwrap_or_else(|_| Wallet::disabled())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The snapshot the TUI draws. Cheap: no dial, no lock on the RPC. It says
|
|
|
|
|
/// "configured, not probed" (`connected == false`) until a probe has run.
|
|
|
|
|
pub fn wallet_status(&self) -> WalletStatus {
|
|
|
|
|
self.wallet_status
|
|
|
|
|
.lock()
|
|
|
|
|
.map(|s| s.clone())
|
|
|
|
|
.unwrap_or_else(|_| WalletStatus::idle(self.wallet_snapshot().configured()))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Probe the configured endpoint once and fold the result into the snapshot.
|
|
|
|
|
/// This is the only thing that can flip `connected` to true.
|
|
|
|
|
pub async fn wallet_refresh(&self) -> WalletStatus {
|
|
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
let status = w.status().await;
|
|
|
|
|
if let Ok(mut slot) = self.wallet_status.lock() {
|
|
|
|
|
*slot = status.clone();
|
|
|
|
|
}
|
|
|
|
|
status
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The pay/tip readiness guard. Blocking-friendly: the TUI calls this from
|
|
|
|
|
/// its key handler with `rt.block_on`, like `send_pay`/`send_tip` do.
|
|
|
|
|
///
|
|
|
|
|
/// It never dials Tor. It also never dials the wallet when the answer is
|
|
|
|
|
/// already known locally — an unconfigured wallet and a `/tip` on a
|
|
|
|
|
/// view-only wallet are refused before any socket is opened.
|
|
|
|
|
pub async fn wallet_readiness(&self, is_tip: bool) -> Readiness {
|
|
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if !w.configured() {
|
|
|
|
|
return Readiness::NotConfigured;
|
|
|
|
|
}
|
|
|
|
|
if is_tip && w.no_spend() {
|
|
|
|
|
return Readiness::NoSpend;
|
|
|
|
|
}
|
|
|
|
|
let status = self.wallet_refresh().await;
|
|
|
|
|
wallet::readiness(status.configured, status.connected, w.no_spend(), is_tip)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The config screen's Test-connection button: one shot against the endpoint
|
|
|
|
|
/// the user is typing. It does not touch the live wallet or the snapshot —
|
|
|
|
|
/// a test of an untyped endpoint is not the wallet we are running.
|
|
|
|
|
pub async fn wallet_test_connection(
|
|
|
|
|
&self,
|
|
|
|
|
rpc_url: &str,
|
|
|
|
|
rpc_login: &str,
|
|
|
|
|
) -> wallet::PingResult {
|
|
|
|
|
Wallet::ping(rpc_url, rpc_login).await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The config the F7 screen should show: the stored one, or the env-derived
|
|
|
|
|
/// one when only env set the wallet (the migration path).
|
|
|
|
|
pub fn wallet_config(&self) -> Option<WalletConfig> {
|
|
|
|
|
if let Ok(store) = self.store.lock()
|
|
|
|
|
&& let Ok(Some(cfg)) = store.load_wallet_config()
|
|
|
|
|
{
|
|
|
|
|
return Some(cfg);
|
|
|
|
|
}
|
|
|
|
|
self.wallet_snapshot().config()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Persist the config screen's Save and re-read it: the live wallet and the
|
|
|
|
|
/// snapshot both follow, so "saved · not connected" is visible without a
|
|
|
|
|
/// restart. Validation happens before anything is written, so a rejected
|
|
|
|
|
/// config leaves the running wallet exactly as it was.
|
|
|
|
|
pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> {
|
|
|
|
|
Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?;
|
|
|
|
|
{
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store.save_wallet_config(cfg).map_err(|e| e.to_string())?;
|
|
|
|
|
}
|
|
|
|
|
// Re-read from the store rather than trusting the caller's copy.
|
|
|
|
|
let stored = self
|
|
|
|
|
.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.load_wallet_config()
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let wallet = Wallet::for_boot(stored.as_ref());
|
|
|
|
|
let configured = wallet.configured();
|
|
|
|
|
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
|
|
|
|
|
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-15 12:29:16 -04:00
|
|
|
/// The chain source the user chose, read from the sealed store record.
|
|
|
|
|
///
|
|
|
|
|
/// A store that cannot be read reports receive-only rather than an error:
|
|
|
|
|
/// nothing has been started in that case either, so the screen must not
|
|
|
|
|
/// claim a daemon the app does not have.
|
|
|
|
|
pub fn wallet_chain_source(&self) -> ChainSource {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.ok()
|
|
|
|
|
.and_then(|s| wallet_child::load_chain_source(&s).ok().flatten())
|
|
|
|
|
.unwrap_or(ChainSource::None)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Persist the picker's choice. Nothing is spawned: the user may pick a
|
|
|
|
|
/// source and start it later — or never, which is the receive-only path.
|
|
|
|
|
///
|
|
|
|
|
/// Refused while a child is running: re-pointing a live wallet child's
|
|
|
|
|
/// chain would leave the argv it was spawned with describing something
|
|
|
|
|
/// else, so stop it first.
|
|
|
|
|
pub fn wallet_set_chain_source(&self, source: &ChainSource) -> Result<(), String> {
|
|
|
|
|
if self.wallet_child_state() == WalletChildState::Running {
|
|
|
|
|
return Err("stop the wallet child before changing its chain source".into());
|
|
|
|
|
}
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
wallet_child::save_chain_source(&store, source).map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// What "spawn a local monerod" means for this identity: the daemon binary
|
|
|
|
|
/// resolved from `PATH` (this app does not install one), with the chain in
|
|
|
|
|
/// this identity's own directory rather than a shared `/var/lib`.
|
|
|
|
|
pub fn default_local_chain_source(&self) -> ChainSource {
|
|
|
|
|
ChainSource::Local {
|
|
|
|
|
monerod_bin: PathBuf::from("monerod"),
|
|
|
|
|
datadir: self.home.join("chain"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The state the wallet screen draws. Cheap: no dial, no spawn.
|
|
|
|
|
pub fn wallet_child_state(&self) -> WalletChildState {
|
|
|
|
|
// Read the (store-backed) choice first: never hold the child lock while
|
|
|
|
|
// taking the store lock.
|
|
|
|
|
let configured = !matches!(self.wallet_chain_source(), ChainSource::None);
|
|
|
|
|
let Ok(guard) = self.child.lock() else {
|
|
|
|
|
return WalletChildState::Stopped;
|
|
|
|
|
};
|
|
|
|
|
match guard.as_ref() {
|
|
|
|
|
Some(child) if child.running() => WalletChildState::Running,
|
|
|
|
|
_ if configured => WalletChildState::Stopped,
|
|
|
|
|
_ => WalletChildState::Off,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Spawn the configured children — `monerod` for a local source,
|
|
|
|
|
/// `monero-wallet-rpc` always — and re-point the app's wallet at the child
|
|
|
|
|
/// this app owns.
|
|
|
|
|
///
|
|
|
|
|
/// Owning the child is the whole point: balance, receive address, `/tip` and
|
|
|
|
|
/// receipt verification then all go through it, so a "start node" button
|
|
|
|
|
/// cannot describe a daemon the wallet does not use.
|
|
|
|
|
pub fn wallet_child_start(&self) -> Result<(), String> {
|
|
|
|
|
self.ensure_running()?;
|
|
|
|
|
let source = self.wallet_chain_source();
|
|
|
|
|
if matches!(source, ChainSource::None) {
|
|
|
|
|
return Err("receive-only: there is no daemon to start".into());
|
|
|
|
|
}
|
|
|
|
|
if self.wallet_child_state() == WalletChildState::Running {
|
|
|
|
|
return Err("wallet child already running".into());
|
|
|
|
|
}
|
|
|
|
|
let child = WalletChild::new(source, self.home.join("wallet"), None)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let client = {
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
match child.start(&store) {
|
|
|
|
|
Ok(client) => client,
|
|
|
|
|
Err(e) => {
|
|
|
|
|
// A half-spawned pair (monerod up, wallet rpc refused) must
|
|
|
|
|
// not outlive the error.
|
|
|
|
|
let _ = child.stop();
|
|
|
|
|
return Err(e.to_string());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
if let Some(client) = client {
|
|
|
|
|
let wallet = client.into_wallet();
|
|
|
|
|
let configured = wallet.configured();
|
|
|
|
|
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
|
|
|
|
|
*self.wallet_status.lock().map_err(|e| e.to_string())? =
|
|
|
|
|
WalletStatus::idle(configured);
|
|
|
|
|
}
|
|
|
|
|
*self.child.lock().map_err(|e| e.to_string())? = Some(child);
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Stop the children this app spawned. Idempotent.
|
|
|
|
|
pub fn wallet_child_stop(&self) -> Result<(), String> {
|
|
|
|
|
let child = self.child.lock().map_err(|e| e.to_string())?.take();
|
|
|
|
|
match child {
|
|
|
|
|
Some(child) => child.stop().map_err(|e| e.to_string()),
|
|
|
|
|
None => Ok(()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Ask the configured daemon how far along the chain is, bounded by
|
|
|
|
|
/// `budget`. Never fabricates a height: a daemon we cannot ask — or must not
|
|
|
|
|
/// dial — comes back unreachable with the reason.
|
wallet: typed chain-daemon client for the Cuprate parity gaps
The chain probe was a hand-rolled brace-scanner in `src/node.rs`. Cuprate
breaks three of its assumptions, all measured in Spike A
(`docs/cuprate-launch-spike.md` §Parity gaps, evidence in that spike's
`rpc-evidence/`):
1. **A height above the tip is a bare HTTP 500 with an empty body.** monerod
answers a JSON-RPC error object instead (`TOO_BIG_HEIGHT`, code -2). The
client now parses the HTTP status once, de-chunks `Transfer-Encoding:
chunked` bodies (axum/hyper; the old brace-scan is not a parse once a blob
spans more than one chunk), and maps both spellings of the height failure to
one typed `WalletError::DaemonHeightOutOfRange`. `get_height` and `get_block`
are height-addressed: their 5xx is the height error. `get_info` is not: its
5xx is `WalletError::DaemonHttpStatus`.
2. **`get_info` metrics are not measurements.** Cuprate reports zero peers while
it downloads blocks, its restricted server answers a placeholder
`database_size` (exactly 5 GiB) and an empty `version`, and `free_space` is
`u64::MAX` on both servers. `DaemonInfo` carries height and target only, so
there is no field for a placeholder to reach the UI. The wallet screen's sync
line is now built from block-height movement between two probes: "connected
to P2P" needs the height to have moved, "no new blocks" is what a stalled
daemon gets, and Cuprate's at-rest `synchronized = true` with
`target_height = 0` reads as unknown instead of `1160/0`.
3. **`get_height` is a URI endpoint**: `{"method":"get_height"}` over
`/json_rpc` is rejected with 422, so the client uses `GET /get_height`, which
both daemons answer. The wallet-child routing rule is pinned too: it dials
the daemon's *unrestricted* listener (monerod's `--rpc-bind-port`, and
whatever port an in-process Cuprate binds for `[rpc.unrestricted]`), never the
restricted one — a restricted listener answers, so a mix-up shows up as a
wrong number rather than as an error.
Scope deviations, stated plainly:
- the card names `src/wallet.rs` + the TUI bindings. The probe itself lived in
`src/node.rs`; it now delegates (net -100 lines there), and the routing
constant/test live in `src/wallet_child.rs`. Tests are in `tests/wallet.rs`,
`tests/tui_spec.rs` and `src/wallet_child.rs`'s test module.
- `daemon_get_block()` is **not called by anything yet**: it is the entry point
the wallet's own block scan (Phase 2) needs, and the out-of-range answer it has
to survive is item 1, so the mapping lives with the client.
- the card's item 3 gives the unrestricted port as 18089 and the restricted one
as 28089. In monerod's numbering 18089 *is* the restricted port; the app's
local source already dials the unrestricted 18081. The rule is what is pinned,
not those numbers.
- `docs/cuprate-launch-spike.md` merged to `main` after this branch's base
commit, so it is not in this tree and its Recommendation bullets are not
updated here.
- based on `feat/wallet-create-import` (the wallet line, unmerged): the daemon
client has no home on `main`. Retarget to `main` when that line lands.
Proof: `cargo test --locked` 306 passed / 0 failed, `cargo clippy --locked
--all-targets -- -D warnings` clean, `rustfmt --edition 2024 --check` adds no
hunk to any file (the inherited hunks in `src/node.rs`/`src/tui.rs`/
`tests/tui_spec.rs` are unchanged in count or region).
2026-09-17 00:24:09 -04:00
|
|
|
///
|
|
|
|
|
/// The call itself lives in [`crate::wallet::daemon_get_info`], where the
|
|
|
|
|
/// Cuprate parity gaps are handled (a bare HTTP 500 on a height-addressed
|
|
|
|
|
/// call, `get_height` as a URI endpoint, and the placeholder `get_info`
|
|
|
|
|
/// metrics this struct has no field for).
|
2026-09-15 12:29:16 -04:00
|
|
|
pub async fn wallet_chain_sync(&self, budget: Duration) -> DaemonSync {
|
|
|
|
|
let Some(addr) = WalletChild::daemon_address(&self.wallet_chain_source()) else {
|
|
|
|
|
return DaemonSync::unknown("receive-only: no daemon");
|
|
|
|
|
};
|
|
|
|
|
if is_onion_daemon(&addr) {
|
|
|
|
|
return DaemonSync::unknown(
|
|
|
|
|
"remote .onion daemon needs a local SOCKS listener (not wired yet)",
|
|
|
|
|
);
|
|
|
|
|
}
|
wallet: typed chain-daemon client for the Cuprate parity gaps
The chain probe was a hand-rolled brace-scanner in `src/node.rs`. Cuprate
breaks three of its assumptions, all measured in Spike A
(`docs/cuprate-launch-spike.md` §Parity gaps, evidence in that spike's
`rpc-evidence/`):
1. **A height above the tip is a bare HTTP 500 with an empty body.** monerod
answers a JSON-RPC error object instead (`TOO_BIG_HEIGHT`, code -2). The
client now parses the HTTP status once, de-chunks `Transfer-Encoding:
chunked` bodies (axum/hyper; the old brace-scan is not a parse once a blob
spans more than one chunk), and maps both spellings of the height failure to
one typed `WalletError::DaemonHeightOutOfRange`. `get_height` and `get_block`
are height-addressed: their 5xx is the height error. `get_info` is not: its
5xx is `WalletError::DaemonHttpStatus`.
2. **`get_info` metrics are not measurements.** Cuprate reports zero peers while
it downloads blocks, its restricted server answers a placeholder
`database_size` (exactly 5 GiB) and an empty `version`, and `free_space` is
`u64::MAX` on both servers. `DaemonInfo` carries height and target only, so
there is no field for a placeholder to reach the UI. The wallet screen's sync
line is now built from block-height movement between two probes: "connected
to P2P" needs the height to have moved, "no new blocks" is what a stalled
daemon gets, and Cuprate's at-rest `synchronized = true` with
`target_height = 0` reads as unknown instead of `1160/0`.
3. **`get_height` is a URI endpoint**: `{"method":"get_height"}` over
`/json_rpc` is rejected with 422, so the client uses `GET /get_height`, which
both daemons answer. The wallet-child routing rule is pinned too: it dials
the daemon's *unrestricted* listener (monerod's `--rpc-bind-port`, and
whatever port an in-process Cuprate binds for `[rpc.unrestricted]`), never the
restricted one — a restricted listener answers, so a mix-up shows up as a
wrong number rather than as an error.
Scope deviations, stated plainly:
- the card names `src/wallet.rs` + the TUI bindings. The probe itself lived in
`src/node.rs`; it now delegates (net -100 lines there), and the routing
constant/test live in `src/wallet_child.rs`. Tests are in `tests/wallet.rs`,
`tests/tui_spec.rs` and `src/wallet_child.rs`'s test module.
- `daemon_get_block()` is **not called by anything yet**: it is the entry point
the wallet's own block scan (Phase 2) needs, and the out-of-range answer it has
to survive is item 1, so the mapping lives with the client.
- the card's item 3 gives the unrestricted port as 18089 and the restricted one
as 28089. In monerod's numbering 18089 *is* the restricted port; the app's
local source already dials the unrestricted 18081. The rule is what is pinned,
not those numbers.
- `docs/cuprate-launch-spike.md` merged to `main` after this branch's base
commit, so it is not in this tree and its Recommendation bullets are not
updated here.
- based on `feat/wallet-create-import` (the wallet line, unmerged): the daemon
client has no home on `main`. Retarget to `main` when that line lands.
Proof: `cargo test --locked` 306 passed / 0 failed, `cargo clippy --locked
--all-targets -- -D warnings` clean, `rustfmt --edition 2024 --check` adds no
hunk to any file (the inherited hunks in `src/node.rs`/`src/tui.rs`/
`tests/tui_spec.rs` are unchanged in count or region).
2026-09-17 00:24:09 -04:00
|
|
|
match wallet::daemon_get_info(&addr, budget).await {
|
|
|
|
|
Ok(info) => DaemonSync {
|
2026-09-15 12:29:16 -04:00
|
|
|
reachable: true,
|
wallet: typed chain-daemon client for the Cuprate parity gaps
The chain probe was a hand-rolled brace-scanner in `src/node.rs`. Cuprate
breaks three of its assumptions, all measured in Spike A
(`docs/cuprate-launch-spike.md` §Parity gaps, evidence in that spike's
`rpc-evidence/`):
1. **A height above the tip is a bare HTTP 500 with an empty body.** monerod
answers a JSON-RPC error object instead (`TOO_BIG_HEIGHT`, code -2). The
client now parses the HTTP status once, de-chunks `Transfer-Encoding:
chunked` bodies (axum/hyper; the old brace-scan is not a parse once a blob
spans more than one chunk), and maps both spellings of the height failure to
one typed `WalletError::DaemonHeightOutOfRange`. `get_height` and `get_block`
are height-addressed: their 5xx is the height error. `get_info` is not: its
5xx is `WalletError::DaemonHttpStatus`.
2. **`get_info` metrics are not measurements.** Cuprate reports zero peers while
it downloads blocks, its restricted server answers a placeholder
`database_size` (exactly 5 GiB) and an empty `version`, and `free_space` is
`u64::MAX` on both servers. `DaemonInfo` carries height and target only, so
there is no field for a placeholder to reach the UI. The wallet screen's sync
line is now built from block-height movement between two probes: "connected
to P2P" needs the height to have moved, "no new blocks" is what a stalled
daemon gets, and Cuprate's at-rest `synchronized = true` with
`target_height = 0` reads as unknown instead of `1160/0`.
3. **`get_height` is a URI endpoint**: `{"method":"get_height"}` over
`/json_rpc` is rejected with 422, so the client uses `GET /get_height`, which
both daemons answer. The wallet-child routing rule is pinned too: it dials
the daemon's *unrestricted* listener (monerod's `--rpc-bind-port`, and
whatever port an in-process Cuprate binds for `[rpc.unrestricted]`), never the
restricted one — a restricted listener answers, so a mix-up shows up as a
wrong number rather than as an error.
Scope deviations, stated plainly:
- the card names `src/wallet.rs` + the TUI bindings. The probe itself lived in
`src/node.rs`; it now delegates (net -100 lines there), and the routing
constant/test live in `src/wallet_child.rs`. Tests are in `tests/wallet.rs`,
`tests/tui_spec.rs` and `src/wallet_child.rs`'s test module.
- `daemon_get_block()` is **not called by anything yet**: it is the entry point
the wallet's own block scan (Phase 2) needs, and the out-of-range answer it has
to survive is item 1, so the mapping lives with the client.
- the card's item 3 gives the unrestricted port as 18089 and the restricted one
as 28089. In monerod's numbering 18089 *is* the restricted port; the app's
local source already dials the unrestricted 18081. The rule is what is pinned,
not those numbers.
- `docs/cuprate-launch-spike.md` merged to `main` after this branch's base
commit, so it is not in this tree and its Recommendation bullets are not
updated here.
- based on `feat/wallet-create-import` (the wallet line, unmerged): the daemon
client has no home on `main`. Retarget to `main` when that line lands.
Proof: `cargo test --locked` 306 passed / 0 failed, `cargo clippy --locked
--all-targets -- -D warnings` clean, `rustfmt --edition 2024 --check` adds no
hunk to any file (the inherited hunks in `src/node.rs`/`src/tui.rs`/
`tests/tui_spec.rs` are unchanged in count or region).
2026-09-17 00:24:09 -04:00
|
|
|
height: info.height,
|
|
|
|
|
target_height: info.target_height,
|
2026-09-15 12:29:16 -04:00
|
|
|
note: None,
|
|
|
|
|
},
|
wallet: typed chain-daemon client for the Cuprate parity gaps
The chain probe was a hand-rolled brace-scanner in `src/node.rs`. Cuprate
breaks three of its assumptions, all measured in Spike A
(`docs/cuprate-launch-spike.md` §Parity gaps, evidence in that spike's
`rpc-evidence/`):
1. **A height above the tip is a bare HTTP 500 with an empty body.** monerod
answers a JSON-RPC error object instead (`TOO_BIG_HEIGHT`, code -2). The
client now parses the HTTP status once, de-chunks `Transfer-Encoding:
chunked` bodies (axum/hyper; the old brace-scan is not a parse once a blob
spans more than one chunk), and maps both spellings of the height failure to
one typed `WalletError::DaemonHeightOutOfRange`. `get_height` and `get_block`
are height-addressed: their 5xx is the height error. `get_info` is not: its
5xx is `WalletError::DaemonHttpStatus`.
2. **`get_info` metrics are not measurements.** Cuprate reports zero peers while
it downloads blocks, its restricted server answers a placeholder
`database_size` (exactly 5 GiB) and an empty `version`, and `free_space` is
`u64::MAX` on both servers. `DaemonInfo` carries height and target only, so
there is no field for a placeholder to reach the UI. The wallet screen's sync
line is now built from block-height movement between two probes: "connected
to P2P" needs the height to have moved, "no new blocks" is what a stalled
daemon gets, and Cuprate's at-rest `synchronized = true` with
`target_height = 0` reads as unknown instead of `1160/0`.
3. **`get_height` is a URI endpoint**: `{"method":"get_height"}` over
`/json_rpc` is rejected with 422, so the client uses `GET /get_height`, which
both daemons answer. The wallet-child routing rule is pinned too: it dials
the daemon's *unrestricted* listener (monerod's `--rpc-bind-port`, and
whatever port an in-process Cuprate binds for `[rpc.unrestricted]`), never the
restricted one — a restricted listener answers, so a mix-up shows up as a
wrong number rather than as an error.
Scope deviations, stated plainly:
- the card names `src/wallet.rs` + the TUI bindings. The probe itself lived in
`src/node.rs`; it now delegates (net -100 lines there), and the routing
constant/test live in `src/wallet_child.rs`. Tests are in `tests/wallet.rs`,
`tests/tui_spec.rs` and `src/wallet_child.rs`'s test module.
- `daemon_get_block()` is **not called by anything yet**: it is the entry point
the wallet's own block scan (Phase 2) needs, and the out-of-range answer it has
to survive is item 1, so the mapping lives with the client.
- the card's item 3 gives the unrestricted port as 18089 and the restricted one
as 28089. In monerod's numbering 18089 *is* the restricted port; the app's
local source already dials the unrestricted 18081. The rule is what is pinned,
not those numbers.
- `docs/cuprate-launch-spike.md` merged to `main` after this branch's base
commit, so it is not in this tree and its Recommendation bullets are not
updated here.
- based on `feat/wallet-create-import` (the wallet line, unmerged): the daemon
client has no home on `main`. Retarget to `main` when that line lands.
Proof: `cargo test --locked` 306 passed / 0 failed, `cargo clippy --locked
--all-targets -- -D warnings` clean, `rustfmt --edition 2024 --check` adds no
hunk to any file (the inherited hunks in `src/node.rs`/`src/tui.rs`/
`tests/tui_spec.rs` are unchanged in count or region).
2026-09-17 00:24:09 -04:00
|
|
|
Err(e) => DaemonSync::unknown(e.to_string()),
|
2026-09-15 12:29:16 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Free space on the filesystem a *local* daemon would store the chain on,
|
|
|
|
|
/// in whole GiB. `None` for a remote source (their disk, not ours) and when
|
|
|
|
|
/// the answer cannot be read — never a guessed number.
|
|
|
|
|
pub fn wallet_chain_free_gb(&self) -> Option<u64> {
|
|
|
|
|
let ChainSource::Local { datadir, .. } = &self.wallet_chain_source() else {
|
|
|
|
|
return None;
|
|
|
|
|
};
|
|
|
|
|
// monerod creates the datadir on first run; before that, the volume that
|
|
|
|
|
// will hold it is the one `home` is on.
|
|
|
|
|
let path = if datadir.exists() { datadir } else { &self.home };
|
|
|
|
|
let out = Command::new("df").arg("-Pk").arg(path).output().ok()?;
|
|
|
|
|
if !out.status.success() {
|
|
|
|
|
return None;
|
|
|
|
|
}
|
|
|
|
|
parse_df_avail_kb(&String::from_utf8_lossy(&out.stdout)).map(|kb| kb / (1024 * 1024))
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-12 22:53:58 -04:00
|
|
|
/// Current wallet balance as a human-readable XMR string, or `off` when the
|
|
|
|
|
/// wallet is not configured.
|
|
|
|
|
pub async fn wallet_balance(&self) -> String {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if !w.configured() {
|
2026-09-12 22:53:58 -04:00
|
|
|
return "off".into();
|
|
|
|
|
}
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
match w.get_balance().await {
|
2026-09-12 22:53:58 -04:00
|
|
|
Ok(b) => crate::pay::atomic_to_xmr_str(&b),
|
|
|
|
|
Err(_) => "err".into(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:49:42 -04:00
|
|
|
pub fn wipe_messages(&self) -> Result<(), String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.wipe_messages()
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 14:25:31 -04:00
|
|
|
pub fn self_profile(&self) -> Result<FriendProfile, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.self_profile()
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn friend_profile(&self, pubkey: &[u8]) -> Result<Option<FriendProfile>, String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.friend_profile(pubkey)
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn set_self_profile(
|
|
|
|
|
&self,
|
|
|
|
|
display_name: &str,
|
|
|
|
|
bio: &str,
|
|
|
|
|
xmr_addr: &str,
|
|
|
|
|
) -> Result<(), String> {
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.set_self_profile(display_name, bio, xmr_addr)
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// One-shot signed `prf` to a friend. Fail closed; no retry, no outbox.
|
|
|
|
|
pub async fn push_self_profile(&self, friend_pk: &[u8]) -> Result<(), String> {
|
|
|
|
|
let me = self.self_profile()?;
|
2026-09-10 14:50:01 -04:00
|
|
|
let k = self.keys()?;
|
2026-09-10 14:25:31 -04:00
|
|
|
let prf = profile::sign(
|
2026-09-10 14:50:01 -04:00
|
|
|
&k.identity_sk,
|
2026-09-10 14:25:31 -04:00
|
|
|
&me.display_name,
|
|
|
|
|
&me.bio,
|
|
|
|
|
&me.xmr_addr,
|
|
|
|
|
me.updated_at,
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let pt = profile::encode(&prf);
|
|
|
|
|
let (onion, prekey) = {
|
|
|
|
|
let f = self.friend(friend_pk)?;
|
|
|
|
|
if f.prekey.len() != 32 {
|
|
|
|
|
return Err("friend missing prekey".into());
|
|
|
|
|
}
|
|
|
|
|
(f.onion, f.prekey)
|
|
|
|
|
};
|
|
|
|
|
self.try_send(&onion, friend_pk, &prekey, &pt).await
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 14:37:43 -04:00
|
|
|
/// Invoice to receive. Wallet subaddress if up, else self_profile.xmr_addr.
|
|
|
|
|
pub async fn pay_invoice(
|
|
|
|
|
&self,
|
|
|
|
|
friend_pk: &[u8],
|
|
|
|
|
atomic: &str,
|
|
|
|
|
memo: &str,
|
|
|
|
|
) -> Result<(), String> {
|
|
|
|
|
let address = self.invoice_address().await?;
|
2026-09-10 14:50:01 -04:00
|
|
|
let k = self.keys()?;
|
|
|
|
|
let inv = pay::sign_invoice(&k.identity_sk, atomic, &address, memo, unix_now())
|
2026-09-10 14:37:43 -04:00
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let pt = pay::encode_invoice(&inv);
|
|
|
|
|
self.send_once(friend_pk, &pt).await?;
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.insert_payment(
|
|
|
|
|
friend_pk,
|
|
|
|
|
PaymentWrite {
|
|
|
|
|
dir: "out",
|
|
|
|
|
kind: "invoice",
|
|
|
|
|
amount_atomic: atomic,
|
|
|
|
|
address: &address,
|
|
|
|
|
memo,
|
|
|
|
|
txid: None,
|
|
|
|
|
verified: false,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.append_message(
|
|
|
|
|
friend_pk,
|
|
|
|
|
"out",
|
|
|
|
|
pay::invoice_chat_line(atomic, memo).as_bytes(),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Pay selected friend via wallet RPC, then signed receipt.
|
|
|
|
|
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, _memo: &str) -> Result<(), String> {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if !w.configured() {
|
|
|
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
2026-09-10 14:37:43 -04:00
|
|
|
}
|
|
|
|
|
let address = self
|
|
|
|
|
.friend_profile(friend_pk)?
|
|
|
|
|
.map(|p| p.xmr_addr)
|
|
|
|
|
.unwrap_or_default();
|
|
|
|
|
if address.is_empty() {
|
|
|
|
|
return Err("friend has no Monero address — they must /profile".into());
|
|
|
|
|
}
|
|
|
|
|
pay::check_address(&address).map_err(|e| e.to_string())?;
|
|
|
|
|
let amount: u64 = atomic
|
|
|
|
|
.parse()
|
|
|
|
|
.map_err(|_| "amount too large for wallet RPC".to_string())?;
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let txid = w
|
2026-09-10 14:37:43 -04:00
|
|
|
.transfer(&address, amount)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
2026-09-10 14:50:01 -04:00
|
|
|
let k = self.keys()?;
|
|
|
|
|
let rcp = pay::sign_receipt(&k.identity_sk, &txid, atomic, &address, unix_now())
|
2026-09-10 14:37:43 -04:00
|
|
|
.map_err(|e| e.to_string())?;
|
2026-09-12 22:53:58 -04:00
|
|
|
let rcp_pt = pay::encode_receipt(&rcp);
|
|
|
|
|
let tip = pay::sign_tip(&k.identity_sk, &txid, atomic, &address, _memo, unix_now())
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let tip_pt = pay::encode_tip(&tip);
|
|
|
|
|
self.send_once(friend_pk, &rcp_pt).await?;
|
|
|
|
|
self.send_once(friend_pk, &tip_pt).await?;
|
2026-09-10 14:37:43 -04:00
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.insert_payment(
|
|
|
|
|
friend_pk,
|
|
|
|
|
PaymentWrite {
|
|
|
|
|
dir: "out",
|
|
|
|
|
kind: "receipt",
|
|
|
|
|
amount_atomic: atomic,
|
|
|
|
|
address: &address,
|
|
|
|
|
memo: "",
|
|
|
|
|
txid: Some(&txid),
|
|
|
|
|
verified: true,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.append_message(
|
|
|
|
|
friend_pk,
|
|
|
|
|
"out",
|
|
|
|
|
pay::receipt_chat_line(atomic, true).as_bytes(),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn invoice_address(&self) -> Result<String, String> {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if w.configured()
|
|
|
|
|
&& let Ok(addr) = w.create_address().await
|
2026-09-10 14:37:43 -04:00
|
|
|
&& pay::check_address(&addr).is_ok()
|
|
|
|
|
{
|
|
|
|
|
return Ok(addr);
|
|
|
|
|
}
|
|
|
|
|
let profile_addr = self.self_profile()?.xmr_addr;
|
|
|
|
|
if profile_addr.is_empty() {
|
|
|
|
|
return Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into());
|
|
|
|
|
}
|
|
|
|
|
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(profile_addr)
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-12 22:53:58 -04:00
|
|
|
/// 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.
|
|
|
|
|
pub async fn wallet_receive_address(&self) -> Result<String, String> {
|
|
|
|
|
let profile_addr = self.self_profile()?.xmr_addr;
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if w.configured()
|
|
|
|
|
&& let Ok(addr) = w.get_address().await
|
2026-09-12 22:53:58 -04:00
|
|
|
&& pay::check_address(&addr).is_ok()
|
|
|
|
|
{
|
|
|
|
|
return Ok(addr);
|
|
|
|
|
}
|
|
|
|
|
if !profile_addr.is_empty() {
|
|
|
|
|
pay::check_address(&profile_addr).map_err(|e| e.to_string())?;
|
|
|
|
|
return Ok(profile_addr);
|
|
|
|
|
}
|
|
|
|
|
Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Formatted balance for the wallet screen, or "off" when the wallet is not
|
|
|
|
|
/// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses
|
|
|
|
|
/// piconero itself.
|
|
|
|
|
pub async fn wallet_balance_line(&self) -> String {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if w.configured() {
|
|
|
|
|
match w.get_balance().await {
|
2026-09-12 22:53:58 -04:00
|
|
|
Ok(b) if !b.is_empty() => {
|
|
|
|
|
let xmr = pay::atomic_to_xmr_str(&b);
|
|
|
|
|
if xmr == "0" {
|
|
|
|
|
"balance 0 XMR".to_string()
|
|
|
|
|
} else {
|
|
|
|
|
format!("balance {xmr} XMR")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(_) => "balance —".to_string(),
|
|
|
|
|
Err(_) => "balance —".to_string(),
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
"wallet off".to_string()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Recent in/out transfers for the wallet screen, newest first, capped to a
|
|
|
|
|
/// small window. Returns the same `TransferRow` shape the existing tests
|
|
|
|
|
/// already cover.
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
pub async fn wallet_recent_transfers(
|
|
|
|
|
&self,
|
|
|
|
|
cap: usize,
|
|
|
|
|
) -> Result<Vec<wallet::TransferRow>, String> {
|
|
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if !w.configured() {
|
2026-09-12 22:53:58 -04:00
|
|
|
return Ok(Vec::new());
|
|
|
|
|
}
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let rows = w.get_transfers().await.map_err(|e| e.to_string())?;
|
2026-09-12 22:53:58 -04:00
|
|
|
let mut rows = rows;
|
|
|
|
|
rows.sort_by(|a, b| b.txid.cmp(&a.txid));
|
|
|
|
|
Ok(rows.into_iter().take(cap).collect())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-13 23:25:25 -04:00
|
|
|
/// Create a new spend-capable wallet. Returns the seed once for backup.
|
|
|
|
|
/// The user never pastes a key on this path.
|
|
|
|
|
pub async fn wallet_create(&self, password: &str) -> Result<String, String> {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if !w.configured() {
|
|
|
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
2026-09-13 23:25:25 -04:00
|
|
|
}
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password)
|
2026-09-13 23:25:25 -04:00
|
|
|
.await
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Import a wallet from an existing 25-word seed. This is the only path
|
|
|
|
|
/// that takes a user-supplied secret.
|
|
|
|
|
pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
if !w.configured() {
|
|
|
|
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
2026-09-13 23:25:25 -04:00
|
|
|
}
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed)
|
2026-09-13 23:25:25 -04:00
|
|
|
.await
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
}
|
2026-09-12 22:53:58 -04:00
|
|
|
|
2026-09-10 14:37:43 -04:00
|
|
|
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), 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.ensure_running()?;
|
2026-09-10 14:37:43 -04:00
|
|
|
let (onion, prekey) = {
|
|
|
|
|
let f = self.friend(friend_pk)?;
|
|
|
|
|
if f.prekey.len() != 32 {
|
|
|
|
|
return Err("friend missing prekey".into());
|
|
|
|
|
}
|
|
|
|
|
(f.onion, f.prekey)
|
|
|
|
|
};
|
|
|
|
|
self.try_send(&onion, friend_pk, &prekey, plaintext).await
|
|
|
|
|
}
|
|
|
|
|
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
|
|
|
|
|
/// the outbox retry triggers.
|
2026-09-10 02:43:45 -04:00
|
|
|
pub async fn connect_onion(&self, onion: &str) -> Result<(), 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.ensure_running()?;
|
2026-09-10 02:43:45 -04:00
|
|
|
tokio::time::timeout(
|
|
|
|
|
Duration::from_secs(20),
|
|
|
|
|
self.client.connect((onion, HS_PORT)),
|
|
|
|
|
)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
|
|
|
|
|
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
if let Ok(Some(friend)) = self
|
|
|
|
|
.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
|
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
|
|
|
|
|
{
|
|
|
|
|
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
|
|
|
|
|
}
|
2026-09-10 02:43:45 -04:00
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, 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.ensure_running()?;
|
2026-09-10 02:43:45 -04:00
|
|
|
let old_nick = self
|
|
|
|
|
.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.hs_nickname()
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let new_nick = next_hs_nickname(&old_nick);
|
|
|
|
|
let launched = self
|
|
|
|
|
.client
|
|
|
|
|
.launch_onion_service(hs::hs_config(&new_nick)?)
|
|
|
|
|
.map_err(|e| format!("launch_onion_service: {e}"))?
|
|
|
|
|
.ok_or_else(|| "onion service disabled in config — fail closed".to_string())?;
|
|
|
|
|
let (svc, rend) = launched;
|
|
|
|
|
let onion = hs::onion_string(&svc)?;
|
|
|
|
|
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
|
|
|
|
|
*self.hs.lock().map_err(|e| e.to_string())? = None;
|
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 new service is not reachable until it publishes: the locator in
|
|
|
|
|
// flight is dead until then, so do not carry the old verdict over.
|
|
|
|
|
self.onion_reachable.store(false, Ordering::SeqCst);
|
2026-09-10 02:43:45 -04:00
|
|
|
let rend = spawn_rend(Arc::clone(self), rend);
|
2026-09-10 16:14:10 -04:00
|
|
|
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
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
|
|
|
svc: Arc::clone(&svc),
|
2026-09-10 16:14:10 -04:00
|
|
|
rend,
|
|
|
|
|
});
|
2026-09-10 20:30:18 -04:00
|
|
|
hs::wait_until_published(&self.client, &svc, &onion).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
|
|
|
self.onion_reachable.store(true, Ordering::SeqCst);
|
2026-09-10 02:43:45 -04:00
|
|
|
{
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store.set_onion(&onion).map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.set_hs_nickname(&new_nick)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
}
|
|
|
|
|
*self.onion.lock().map_err(|e| e.to_string())? = onion.clone();
|
|
|
|
|
|
|
|
|
|
let ts = unix_now();
|
2026-09-10 14:50:01 -04:00
|
|
|
let k = self.keys()?;
|
|
|
|
|
let loc = loc::sign(&k.identity_sk, &onion, ts).map_err(|e| e.to_string())?;
|
2026-09-10 02:43:45 -04:00
|
|
|
let loc_pt = loc::encode(&loc);
|
|
|
|
|
let friends = self
|
|
|
|
|
.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.list_friends()
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
let mut notified = 0;
|
|
|
|
|
for f in &friends {
|
|
|
|
|
if self
|
|
|
|
|
.push_loc(&f.pubkey, &f.onion, &f.prekey, &loc_pt)
|
|
|
|
|
.await
|
|
|
|
|
.is_ok()
|
|
|
|
|
{
|
|
|
|
|
notified += 1;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(RotateResult {
|
|
|
|
|
notified,
|
|
|
|
|
friends: friends.len(),
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 23:32:06 -04:00
|
|
|
/// One-shot file to a friend. Fail closed; no outbox, no resume.
|
2026-09-11 23:49:29 -04:00
|
|
|
/// Chunks are paced (`file::CHUNK_PACE`) with bounded per-chunk retry so
|
|
|
|
|
/// a 1 MiB transfer fits the receiver's rendezvous token bucket.
|
2026-09-10 23:32:06 -04:00
|
|
|
pub async fn send_file(&self, friend_pk: &[u8], path: &Path) -> Result<String, String> {
|
|
|
|
|
let (name, bytes) = file::read_limited(path).map_err(|e| e.to_string())?;
|
|
|
|
|
let chunks = file::chunks(&name, &bytes).map_err(|e| e.to_string())?;
|
2026-09-11 23:49:29 -04:00
|
|
|
let frames: Vec<Vec<u8>> = chunks.iter().map(file::encode).collect();
|
|
|
|
|
file::send_chunks(frames.len(), |i| self.send_once(friend_pk, &frames[i])).await?;
|
2026-09-10 23:32:06 -04:00
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.append_message(
|
|
|
|
|
friend_pk,
|
|
|
|
|
"out",
|
|
|
|
|
file::chat_line(&name, bytes.len()).as_bytes(),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(name)
|
|
|
|
|
}
|
|
|
|
|
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
|
|
|
|
|
/// when the peer's onion is unreachable — the outbox worker then retries with
|
|
|
|
|
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
|
|
|
|
/// frame) still fails immediately and is never retried.
|
|
|
|
|
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, 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.ensure_running()?;
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
self.outbox.send(friend_pk, plaintext).await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
|
|
|
|
/// Delivered rows are dropped, so a message absent here was sent.
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
pub fn outbox_pending(
|
|
|
|
|
&self,
|
|
|
|
|
friend_pk: &[u8],
|
|
|
|
|
) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
self.outbox.pending(friend_pk)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn outbox_status_of_message(
|
|
|
|
|
&self,
|
|
|
|
|
message_id: i64,
|
|
|
|
|
) -> Result<Option<OutboxStatus>, String> {
|
|
|
|
|
self.outbox.status_of_message(message_id)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Foreground/unlock trigger: try every outstanding queued send now.
|
|
|
|
|
pub fn flush_outbox(&self) {
|
|
|
|
|
spawn_flush_all(Arc::clone(&self.outbox));
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
async fn push_loc(
|
|
|
|
|
&self,
|
|
|
|
|
friend_pk: &[u8],
|
|
|
|
|
onion: &str,
|
|
|
|
|
prekey: &[u8],
|
|
|
|
|
loc_pt: &[u8],
|
|
|
|
|
) -> Result<(), String> {
|
|
|
|
|
if prekey.len() != 32 {
|
|
|
|
|
return Err("friend missing prekey".into());
|
|
|
|
|
}
|
|
|
|
|
let deadline = Instant::now() + Duration::from_secs(180);
|
|
|
|
|
let mut last = None::<String>;
|
|
|
|
|
while Instant::now() < deadline {
|
|
|
|
|
match self.try_send(onion, friend_pk, prekey, loc_pt).await {
|
|
|
|
|
Ok(()) => return Ok(()),
|
|
|
|
|
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
|
|
|
|
|
Err(e) => last = Some(e),
|
|
|
|
|
}
|
|
|
|
|
tokio::time::sleep(Duration::from_secs(3)).await;
|
|
|
|
|
}
|
|
|
|
|
Err(last.unwrap_or_else(|| "loc push timed out".into()))
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:07:40 -04:00
|
|
|
async fn try_send(
|
|
|
|
|
&self,
|
|
|
|
|
onion: &str,
|
|
|
|
|
pinned_id: &[u8],
|
|
|
|
|
remote_prekey: &[u8],
|
|
|
|
|
plaintext: &[u8],
|
|
|
|
|
) -> Result<(), String> {
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
self.outbox
|
|
|
|
|
.deliverer()
|
|
|
|
|
.deliver(onion, pinned_id, remote_prekey, plaintext)
|
2026-09-10 02:07:40 -04:00
|
|
|
.await
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
|
|
|
|
|
where
|
|
|
|
|
S: AsyncRead + AsyncWrite + Unpin,
|
|
|
|
|
{
|
|
|
|
|
let store = &self.store;
|
2026-09-10 14:50:01 -04:00
|
|
|
let keys = self.keys()?;
|
|
|
|
|
let mut sess = session::handshake_responder(stream, &keys, |spk| {
|
2026-09-10 02:07:40 -04:00
|
|
|
let Ok(g) = store.lock() else {
|
|
|
|
|
return None;
|
|
|
|
|
};
|
|
|
|
|
g.get_friend_by_prekey(spk).ok().flatten().map(|f| f.pubkey)
|
|
|
|
|
})
|
|
|
|
|
.await
|
|
|
|
|
.map_err(session_err)?;
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
// Trigger (c): the peer just proved they are online. Try their queued
|
|
|
|
|
// sends now instead of waiting out the backoff, off this stream's path.
|
|
|
|
|
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
|
2026-09-10 02:07:40 -04:00
|
|
|
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
|
|
|
|
|
let pt = sess.decrypt(&ct).map_err(session_err)?;
|
2026-09-10 14:18:06 -04:00
|
|
|
match dispatch::classify(&pt) {
|
|
|
|
|
Kind::Loc => {
|
|
|
|
|
if let Some(loc) = loc::decode(&pt) {
|
|
|
|
|
let applied = store.lock().map_err(|e| e.to_string())?.apply_loc(
|
|
|
|
|
&sess.peer_identity,
|
|
|
|
|
&loc.onion,
|
|
|
|
|
loc.ts,
|
|
|
|
|
&loc.sig,
|
|
|
|
|
);
|
|
|
|
|
match applied {
|
|
|
|
|
Ok(true) => {}
|
2026-09-10 14:25:31 -04:00
|
|
|
Ok(false) => {
|
|
|
|
|
eprintln!("loc dropped (bad sig, stale ts, or unknown friend)")
|
|
|
|
|
}
|
|
|
|
|
Err(e) => return Err(e.to_string()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
Kind::Profile => {
|
|
|
|
|
if let Some(prf) = profile::decode(&pt) {
|
|
|
|
|
let applied = store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.apply_profile(&sess.peer_identity, &prf);
|
|
|
|
|
match applied {
|
|
|
|
|
Ok(true) => {}
|
|
|
|
|
Ok(false) => {
|
|
|
|
|
eprintln!("prf dropped (bad sig, stale ts, or unknown friend)")
|
|
|
|
|
}
|
2026-09-10 14:18:06 -04:00
|
|
|
Err(e) => return Err(e.to_string()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
Kind::Chat => {
|
|
|
|
|
store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
2026-09-11 23:42:48 -04:00
|
|
|
.append_message(
|
|
|
|
|
&sess.peer_identity,
|
|
|
|
|
"in",
|
|
|
|
|
sanitize::display_text(&pt).as_bytes(),
|
|
|
|
|
)
|
2026-09-10 14:18:06 -04:00
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
2026-09-10 02:43:45 -04:00
|
|
|
}
|
2026-09-10 14:37:43 -04:00
|
|
|
Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await,
|
|
|
|
|
Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await,
|
2026-09-12 22:53:58 -04:00
|
|
|
Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await,
|
2026-09-10 23:32:06 -04:00
|
|
|
Kind::File => self.ingest_file(&sess.peer_identity, &pt),
|
2026-09-10 14:37:43 -04:00
|
|
|
Kind::Ping | Kind::Drop => Ok(()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 23:32:06 -04:00
|
|
|
fn ingest_file(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
|
|
|
|
let Some(chunk) = file::decode(pt) else {
|
|
|
|
|
return Ok(());
|
|
|
|
|
};
|
|
|
|
|
let fp: String = peer.iter().map(|b| format!("{b:02x}")).collect();
|
|
|
|
|
let done = {
|
|
|
|
|
let mut inbox = self.inbox.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
match inbox.ingest(&fp, &chunk) {
|
|
|
|
|
Ok(p) => p,
|
|
|
|
|
Err(e) => {
|
|
|
|
|
eprintln!("fil dropped ({e})");
|
|
|
|
|
return Ok(());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
if let Some(path) = done {
|
|
|
|
|
let nbytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) as usize;
|
|
|
|
|
let name = path
|
|
|
|
|
.file_name()
|
|
|
|
|
.and_then(|s| s.to_str())
|
|
|
|
|
.unwrap_or(&chunk.filename);
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
2026-09-11 23:42:48 -04:00
|
|
|
.append_message(
|
|
|
|
|
peer,
|
|
|
|
|
"in",
|
|
|
|
|
sanitize::display_text(file::chat_line(name, nbytes).as_bytes()).as_bytes(),
|
|
|
|
|
)
|
2026-09-10 23:32:06 -04:00
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 14:37:43 -04:00
|
|
|
async fn ingest_invoice(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
|
|
|
|
let Some(inv) = pay::decode_invoice(pt) else {
|
|
|
|
|
return Ok(());
|
|
|
|
|
};
|
|
|
|
|
if !pay::verify_invoice(peer, &inv) {
|
|
|
|
|
eprintln!("inv dropped (bad sig)");
|
|
|
|
|
return Ok(());
|
|
|
|
|
}
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.insert_payment(
|
|
|
|
|
peer,
|
|
|
|
|
PaymentWrite {
|
|
|
|
|
dir: "in",
|
|
|
|
|
kind: "invoice",
|
|
|
|
|
amount_atomic: &inv.amount_atomic,
|
|
|
|
|
address: &inv.address,
|
|
|
|
|
memo: &inv.memo,
|
|
|
|
|
txid: None,
|
|
|
|
|
verified: false,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.append_message(
|
|
|
|
|
peer,
|
|
|
|
|
"in",
|
|
|
|
|
pay::invoice_chat_line(&inv.amount_atomic, &inv.memo).as_bytes(),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn ingest_receipt(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
|
|
|
|
let Some(rcp) = pay::decode_receipt(pt) else {
|
|
|
|
|
return Ok(());
|
|
|
|
|
};
|
|
|
|
|
if !pay::verify_receipt(peer, &rcp) {
|
|
|
|
|
eprintln!("rcp dropped (bad sig)");
|
|
|
|
|
return Ok(());
|
2026-09-10 02:43:45 -04:00
|
|
|
}
|
2026-09-10 14:37:43 -04:00
|
|
|
let id = {
|
|
|
|
|
let store = self.store.lock().map_err(|e| e.to_string())?;
|
|
|
|
|
store
|
|
|
|
|
.insert_payment(
|
|
|
|
|
peer,
|
|
|
|
|
PaymentWrite {
|
|
|
|
|
dir: "in",
|
|
|
|
|
kind: "receipt",
|
|
|
|
|
amount_atomic: &rcp.amount_atomic,
|
|
|
|
|
address: &rcp.address,
|
|
|
|
|
memo: "",
|
|
|
|
|
txid: Some(&rcp.txid),
|
|
|
|
|
verified: false,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
};
|
|
|
|
|
let mut verified = false;
|
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
|
|
|
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
|
|
|
|
// get_transfers "miss" would be a lie. Until the chain is ready the
|
|
|
|
|
// receipt stays verified=0 — that is the correct state, not an error.
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
let w = self.wallet_snapshot();
|
|
|
|
|
let ready = w.configured() && w.can_verify_receipts().await;
|
wallet: app-owned child lifecycle + user-chosen ChainSource
The app now owns monero-wallet-rpc (and monerod when the chain source is
local) instead of requiring the user to start them and export
ONIONWIRE_WALLET_RPC.
- ChainSource enum: None / Local { monerod_bin, datadir } / Remote { host,
port }. No default remote node; Remote is only constructed from explicit
user input. A .onion Remote is refused without a SOCKS proxy (separate
card).
- WalletChild in src/wallet_child.rs spawns monero-wallet-rpc with
--rpc-bind-ip 127.0.0.1, a random free loopback port, generated
--rpc-login, and --wallet-dir /wallet; monerod too for a
local source. --trusted-daemon is never passed.
- Generated RPC creds are sealed in the encrypted SQLCipher store
(wallet_child table, AEAD on top of whole-db encryption), never a
plaintext file. The Wallet client is built from the generated loopback
URL, not from_env.
- Readiness predicate: chain_ready() requires synchronized==true, height>0,
height>=target_height; can_spend() and can_verify_receipts() gate on it.
Unsynced -> receipts stay verified=0, spend refused with a clear message.
- Backend-aware timeouts: local management calls keep 5s; chain-dependent
calls (get_info, get_transfers, transfer) get 60s (CHAIN_RPC_TIMEOUT),
because a first sync or a remote daemon outlasts 5s and a 5s cap there
is what left receipts permanently unverified.
- node.rs ingest_receipt gates on can_verify_receipts() instead of
configured() alone.
- docs/WALLET.md rewritten for the child lifecycle + chain source.
Base: feat/wallet-create-import (PR #66). Do not rebase onto main.
Co-Authored-By: Hermes Agent <agent@local>
2026-09-14 18:55:07 -04:00
|
|
|
if ready {
|
wallet: stored config (F7), WalletStatus snapshot, pay/tip readiness guard
The only input path for the wallet was env. Add the same three remote-mode
fields as stored config so the F7 screen can set them and headless runs read
one source of truth:
- `wallet_config` table in the encrypted store (one row; the login is sealed
with the store data key under `onionwire/wallet-config/v1`, on top of
SQLCipher). Empty URL clears it. `Store::load_wallet_config` /
`save_wallet_config`.
- `WalletConfig { rpc_url, rpc_login: Zeroizing<String>, no_spend }` with a
redacting `Debug`; `Wallet::from_config`, and `Wallet::for_boot` which
prefers stored config, falls back to env, and refuses to dial a bad stored
endpoint. Node::start* now reads the store before constructing the wallet.
- `WalletStatus { configured, connected, last_error, balance_line,
receive_address }`: `connected` only ever comes from a probe
(`Wallet::status`, get_address + get_balance); config alone leaves it false.
`Node::wallet_status` is the cheap draw-path read, `wallet_refresh` the
probe that folds into it.
- One-shot `Wallet::ping(rpc_url, rpc_login) -> PingResult { ok, status,
error }` for the Test-connection button: same loopback/digest rules, errors
redacted and capped.
- `readiness(configured, connected, no_spend, is_tip) -> Readiness` plus
`Node::wallet_readiness` (async, block_on-friendly): not configured →
NOT_CONFIGURED_MSG; /tip on a no-spend wallet → VIEW_ONLY_MSG before any
dial; configured but not connected → NOT_CONNECTED_MSG; else ready.
- `Node::wallet_save_config` persists, validates first, then re-reads so the
live wallet and snapshot follow a Save without a restart.
- `Node::wallet` is now a Mutex<Wallet> (cloned out before each await) so the
wallet can be re-pointed mid-session.
Local-mode fields stay reserved: the child lifecycle is t_69ce8e46 and is not
wired here. docs/WALLET.md documents the stored config, boot precedence and
the exact guard copy.
Tests: 38 in tests/wallet.rs including exact-refusal-copy, boot precedence,
sealed-on-disk login, ping sanitization and connected-only-after-probe.
2026-09-14 23:39:57 -04:00
|
|
|
match w.get_transfers().await {
|
2026-09-10 14:37:43 -04:00
|
|
|
Ok(rows)
|
|
|
|
|
if wallet::transfers_match(
|
|
|
|
|
&rows,
|
|
|
|
|
&rcp.txid,
|
|
|
|
|
&rcp.amount_atomic,
|
|
|
|
|
&rcp.address,
|
|
|
|
|
) =>
|
|
|
|
|
{
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.mark_verified(id)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
verified = true;
|
|
|
|
|
}
|
|
|
|
|
Ok(_) => {}
|
|
|
|
|
Err(e) => eprintln!("receipt unverified: {e}"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if !verified {
|
|
|
|
|
eprintln!("receipt unverified");
|
|
|
|
|
}
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.append_message(
|
|
|
|
|
peer,
|
|
|
|
|
"in",
|
|
|
|
|
pay::receipt_chat_line(&rcp.amount_atomic, verified).as_bytes(),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
2026-09-12 22:53:58 -04:00
|
|
|
|
|
|
|
|
async fn ingest_tip(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
|
|
|
|
let Some(tip) = pay::decode_tip(pt) else {
|
|
|
|
|
return Ok(());
|
|
|
|
|
};
|
|
|
|
|
if !pay::verify_tip(peer, &tip) {
|
|
|
|
|
eprintln!("tip dropped (bad sig)");
|
|
|
|
|
return Ok(());
|
|
|
|
|
}
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.insert_payment(
|
|
|
|
|
peer,
|
|
|
|
|
PaymentWrite {
|
|
|
|
|
dir: "in",
|
|
|
|
|
kind: "tip",
|
|
|
|
|
amount_atomic: &tip.amount_atomic,
|
|
|
|
|
address: &tip.address,
|
|
|
|
|
memo: &tip.memo,
|
|
|
|
|
txid: Some(&tip.txid),
|
|
|
|
|
verified: false,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
self.store
|
|
|
|
|
.lock()
|
|
|
|
|
.map_err(|e| e.to_string())?
|
|
|
|
|
.append_message(
|
|
|
|
|
peer,
|
|
|
|
|
"in",
|
|
|
|
|
pay::tip_chat_line(&tip.amount_atomic, &tip.memo, false).as_bytes(),
|
|
|
|
|
)
|
|
|
|
|
.map_err(|e| e.to_string())?;
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
2026-09-10 02:07:40 -04:00
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
fn spawn_rend(
|
|
|
|
|
node: Arc<Node>,
|
|
|
|
|
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,
|
|
|
|
|
) -> tokio::task::JoinHandle<()> {
|
|
|
|
|
tokio::spawn(async move {
|
|
|
|
|
let mut requests = std::pin::pin!(handle_rend_requests(rend));
|
|
|
|
|
while let Some(req) = requests.next().await {
|
2026-09-10 14:50:01 -04:00
|
|
|
let allow = node
|
|
|
|
|
.incoming_limit
|
|
|
|
|
.lock()
|
|
|
|
|
.map(|mut b| b.try_acquire())
|
|
|
|
|
.unwrap_or(false);
|
|
|
|
|
if !allow {
|
|
|
|
|
eprintln!("rate-limit drop");
|
|
|
|
|
drop(req);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-09-10 02:43:45 -04:00
|
|
|
let serve = Arc::clone(&node);
|
|
|
|
|
tokio::spawn(async move {
|
|
|
|
|
let Ok(mut stream) = req.accept(Connected::new_empty()).await else {
|
|
|
|
|
return;
|
|
|
|
|
};
|
|
|
|
|
if let Err(e) = serve.handle_incoming(&mut stream).await {
|
|
|
|
|
eprintln!("incoming: {e}");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
feat(outbox): local retry queue for chat sends
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.
- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
messages row, under that row's existing AEAD + AAD), append_message_id(),
queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
Err on transport failure; protocol errors still fail immediately and are
never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
add the seizure/cadence delta to the threat model.
src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 13:35:10 -04:00
|
|
|
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
|
|
|
|
|
fn spawn_flush_all(outbox: Arc<Outbox>) {
|
|
|
|
|
tokio::spawn(async move {
|
|
|
|
|
if let Err(e) = outbox.flush_all(unix_now()).await {
|
|
|
|
|
eprintln!("outbox: {e}");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// We just saw this peer (handshake or successful dial): try their queue now.
|
|
|
|
|
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
|
|
|
|
|
tokio::spawn(async move {
|
|
|
|
|
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
|
|
|
|
|
eprintln!("outbox: {e}");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:43:45 -04:00
|
|
|
fn next_hs_nickname(cur: &str) -> String {
|
|
|
|
|
let n = cur
|
|
|
|
|
.strip_prefix("ow")
|
|
|
|
|
.and_then(|s| s.parse::<u32>().ok())
|
|
|
|
|
.unwrap_or(0);
|
|
|
|
|
format!("ow{}", n.saturating_add(1))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn unix_now() -> i64 {
|
|
|
|
|
SystemTime::now()
|
|
|
|
|
.duration_since(UNIX_EPOCH)
|
|
|
|
|
.map(|d| d.as_secs() as i64)
|
|
|
|
|
.unwrap_or(0)
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-10 02:07:40 -04:00
|
|
|
fn session_err(e: session::Error) -> String {
|
|
|
|
|
if e.is_fingerprint_mismatch() {
|
|
|
|
|
crate::tui::fingerprint_mismatch_banner().to_string()
|
|
|
|
|
} else {
|
|
|
|
|
e.to_string()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
|
|
|
|
let mut stack = vec![dir.to_path_buf()];
|
|
|
|
|
while let Some(p) = stack.pop() {
|
|
|
|
|
let Ok(rd) = std::fs::read_dir(&p) else {
|
|
|
|
|
continue;
|
|
|
|
|
};
|
|
|
|
|
for ent in rd.flatten() {
|
|
|
|
|
let path = ent.path();
|
|
|
|
|
if path.is_dir() {
|
|
|
|
|
stack.push(path);
|
|
|
|
|
} else if let Ok(bytes) = std::fs::read(&path)
|
|
|
|
|
&& bytes.windows(needle.len()).any(|w| w == needle)
|
|
|
|
|
{
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
false
|
|
|
|
|
}
|
2026-09-15 12:29:16 -04:00
|
|
|
|
|
|
|
|
/// `.onion` daemon addresses must never be resolved locally: the SOCKS listener
|
|
|
|
|
/// is what dials them, and it does not exist yet. So this is a refusal, not a
|
|
|
|
|
/// dial — and it is checked before any socket is opened.
|
|
|
|
|
fn is_onion_daemon(addr: &str) -> bool {
|
|
|
|
|
addr.rsplit_once(':')
|
|
|
|
|
.map(|(host, _)| host)
|
|
|
|
|
.unwrap_or(addr)
|
|
|
|
|
.trim()
|
|
|
|
|
.to_ascii_lowercase()
|
|
|
|
|
.ends_with(".onion")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Available 1K blocks from `df -Pk` output. Separate from the process call so
|
|
|
|
|
/// the parse is testable without a filesystem.
|
|
|
|
|
fn parse_df_avail_kb(stdout: &str) -> Option<u64> {
|
|
|
|
|
stdout.lines().rev().find_map(|line| {
|
|
|
|
|
let mut fields = line.split_whitespace();
|
|
|
|
|
fields.next()?; // filesystem
|
|
|
|
|
fields.next()?; // 1K blocks
|
|
|
|
|
fields.next()?; // used
|
|
|
|
|
fields.next()?.parse().ok() // available
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests {
|
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn onion_daemons_are_refused_before_any_dial() {
|
|
|
|
|
assert!(is_onion_daemon("abc234def.onion:18081"));
|
|
|
|
|
assert!(is_onion_daemon("ABC234DEF.ONION:18081"));
|
|
|
|
|
assert!(!is_onion_daemon("127.0.0.1:18081"));
|
|
|
|
|
assert!(!is_onion_daemon("node.example.com:18089"));
|
|
|
|
|
assert!(!is_onion_daemon("notonion:18081"));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn unavailable_daemon_is_not_synced() {
|
|
|
|
|
let synced = DaemonSync {
|
|
|
|
|
reachable: true,
|
|
|
|
|
height: 3_210_000,
|
|
|
|
|
target_height: 3_210_000,
|
|
|
|
|
note: None,
|
|
|
|
|
};
|
|
|
|
|
assert!(synced.synced());
|
|
|
|
|
let behind = DaemonSync {
|
|
|
|
|
reachable: true,
|
|
|
|
|
height: 3_209_999,
|
|
|
|
|
target_height: 3_210_000,
|
|
|
|
|
note: None,
|
|
|
|
|
};
|
|
|
|
|
assert!(!behind.synced());
|
|
|
|
|
// A daemon that reports no target is not "synced", it is unknown.
|
|
|
|
|
let no_target = DaemonSync {
|
|
|
|
|
reachable: true,
|
|
|
|
|
height: 0,
|
|
|
|
|
target_height: 0,
|
|
|
|
|
note: None,
|
|
|
|
|
};
|
|
|
|
|
assert!(!no_target.synced());
|
|
|
|
|
assert!(!DaemonSync::unknown("no daemon").synced());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn parse_df_avail_reads_the_available_column() {
|
|
|
|
|
let out = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/sda1 100000000 50000000 48000000 52% /\n";
|
|
|
|
|
assert_eq!(parse_df_avail_kb(out), Some(48_000_000));
|
|
|
|
|
// Header only, or a relocated filesystem name: no number, no answer.
|
|
|
|
|
assert_eq!(
|
|
|
|
|
parse_df_avail_kb(
|
|
|
|
|
"Filesystem 1024-blocks Used Available Capacity Mounted on\n"
|
|
|
|
|
),
|
|
|
|
|
None
|
|
|
|
|
);
|
|
|
|
|
assert_eq!(parse_df_avail_kb("garbage"), None);
|
|
|
|
|
}
|
|
|
|
|
|
node: read-only Node::list_payments(friend_pk) for the TUI payment history
Re-exposes the existing Store::list_payments as one typed read method so
src/tui.rs can render a friend's payment history without ever touching the
store. Maps the store error to Result<_, String> exactly like the
neighbouring list_messages / wallet_recent_transfers, and returns
store::Payment as-is (id, dir, kind, amount_atomic, address, memo, txid,
verified, created_at).
Read-only: no schema change, no migration, no new frame, no new column, no
docs/PROTOCOL.md change, and no store handle becomes reachable from the TUI.
An unknown friend is empty history (Ok(vec![])), not an error.
Test placement deviates from the card, deliberately: it lives in
src/node.rs's #[cfg(test)] mod tests instead of tests/pay.rs, because Node
has no constructor that avoids Tor (Node::start* is the only public one) and
ingest_receipt is private, so tests/pay.rs cannot build a Node at all. The
test uses an unbootstrapped Arti client plus a null deliverer over a real
encrypted store in a temp dir, writes the outbound row directly and drives
the inbound row through the node's own ingest_receipt.
2026-09-15 15:10:38 -04:00
|
|
|
// Official mainnet standard address (Monero docs), the same constant the
|
|
|
|
|
// integration tests use. `insert_payment` checks the checksum.
|
|
|
|
|
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
|
|
|
|
|
|
|
|
|
|
/// Never dials. A store-backed read must not touch it.
|
|
|
|
|
struct NullDeliverer;
|
|
|
|
|
|
|
|
|
|
impl crate::outbox::Deliverer for NullDeliverer {
|
|
|
|
|
fn deliver<'a>(
|
|
|
|
|
&'a self,
|
|
|
|
|
_onion: &'a str,
|
|
|
|
|
_pinned_id: &'a [u8],
|
|
|
|
|
_prekey: &'a [u8],
|
|
|
|
|
_plaintext: &'a [u8],
|
|
|
|
|
) -> crate::outbox::BoxFut<'a, Result<(), String>> {
|
|
|
|
|
Box::pin(async { Err("no tor in this test".into()) })
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A `Node` over a real encrypted store with an *unbootstrapped* Arti
|
|
|
|
|
/// client: no Tor, no onion service, no outbox worker. Store-backed reads
|
|
|
|
|
/// (`list_payments`) work; a send would not. Cheap enough for a plain
|
|
|
|
|
/// `#[cfg(test)]` test, which is the only way to reach a `Node` without
|
|
|
|
|
/// bootstrapping Tor (`Node::start*` is the sole public constructor).
|
|
|
|
|
fn offline_node(home: &Path, store: Store) -> Node {
|
|
|
|
|
let cfg = hs::client_config(&home.join("arti"), &home.join("cache"));
|
|
|
|
|
let client = arti_client::TorClient::builder()
|
|
|
|
|
.config(cfg)
|
|
|
|
|
.create_unbootstrapped()
|
|
|
|
|
.expect("unbootstrapped arti client");
|
|
|
|
|
let store = Arc::new(Mutex::new(store));
|
|
|
|
|
let outbox = Arc::new(Outbox::new(Arc::clone(&store), Arc::new(NullDeliverer)));
|
|
|
|
|
Node {
|
|
|
|
|
home: home.to_path_buf(),
|
|
|
|
|
store,
|
|
|
|
|
client,
|
|
|
|
|
hs: Mutex::new(None),
|
|
|
|
|
onion: Mutex::new(String::new()),
|
|
|
|
|
keys: Mutex::new(Keys::generate()),
|
|
|
|
|
wallet: Mutex::new(Wallet::disabled()),
|
|
|
|
|
wallet_status: Mutex::new(WalletStatus::idle(false)),
|
|
|
|
|
child: Mutex::new(None),
|
|
|
|
|
incoming_limit: Mutex::new(TokenBucket::default()),
|
|
|
|
|
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
|
|
|
|
|
outbox,
|
|
|
|
|
worker: Mutex::new(None),
|
|
|
|
|
stopped: AtomicBool::new(false),
|
|
|
|
|
onion_reachable: AtomicBool::new(false),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The payment-history screen reads through this: every row for the friend
|
|
|
|
|
/// with its dir/kind/amount/verification intact, and an empty history (not
|
|
|
|
|
/// an error) for a friend with no rows or an unknown pubkey.
|
|
|
|
|
#[tokio::test]
|
|
|
|
|
async fn list_payments_returns_the_friends_rows_and_empty_for_an_unknown_friend() {
|
|
|
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
|
|
|
|
let home = dir.path().join("home");
|
|
|
|
|
std::fs::create_dir_all(&home).expect("home");
|
|
|
|
|
let store = Store::open_at_with_passphrase(&home, "onionwire-test").expect("open store");
|
|
|
|
|
let keys = Keys::generate();
|
|
|
|
|
let peer = keys.identity_pk;
|
|
|
|
|
store
|
|
|
|
|
.upsert_friend(&peer, "peer.onion", None)
|
|
|
|
|
.expect("friend");
|
|
|
|
|
// Outbound, the row shape `pay_invoice` writes.
|
|
|
|
|
let out_id = store
|
|
|
|
|
.insert_payment(
|
|
|
|
|
&peer,
|
|
|
|
|
PaymentWrite {
|
|
|
|
|
dir: "out",
|
|
|
|
|
kind: "invoice",
|
|
|
|
|
amount_atomic: "120000000000",
|
|
|
|
|
address: ADDR,
|
|
|
|
|
memo: "coffee",
|
|
|
|
|
txid: None,
|
|
|
|
|
verified: false,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
.expect("outbound row");
|
|
|
|
|
let node = offline_node(&home, store);
|
|
|
|
|
// Inbound through the node's own ingest path, signing as the peer.
|
|
|
|
|
let rcp = pay::sign_receipt(&keys.identity_sk, "deadbeef", "5", ADDR, unix_now())
|
|
|
|
|
.expect("sign receipt");
|
|
|
|
|
node.ingest_receipt(&peer, &pay::encode_receipt(&rcp))
|
|
|
|
|
.await
|
|
|
|
|
.expect("ingest receipt");
|
|
|
|
|
|
|
|
|
|
let rows = node.list_payments(&peer).expect("list_payments");
|
|
|
|
|
assert_eq!(rows.len(), 2, "{rows:?}");
|
|
|
|
|
assert_eq!(rows[0].id, out_id);
|
|
|
|
|
assert_eq!(rows[0].dir, "out");
|
|
|
|
|
assert_eq!(rows[0].kind, "invoice");
|
|
|
|
|
assert_eq!(rows[0].amount_atomic, "120000000000");
|
|
|
|
|
assert_eq!(rows[0].address, ADDR);
|
|
|
|
|
assert_eq!(rows[0].memo, "coffee");
|
|
|
|
|
assert_eq!(rows[0].txid, None);
|
|
|
|
|
assert!(!rows[0].verified);
|
|
|
|
|
assert!(rows[0].created_at > 0);
|
|
|
|
|
assert_eq!(rows[1].dir, "in");
|
|
|
|
|
assert_eq!(rows[1].kind, "receipt");
|
|
|
|
|
assert_eq!(rows[1].amount_atomic, "5");
|
|
|
|
|
assert_eq!(rows[1].address, ADDR);
|
|
|
|
|
assert_eq!(rows[1].txid.as_deref(), Some("deadbeef"));
|
|
|
|
|
// No wallet is configured here, so nothing verified the receipt.
|
|
|
|
|
assert!(!rows[1].verified);
|
|
|
|
|
|
|
|
|
|
// Unknown pubkey: empty history, not an error.
|
|
|
|
|
let none = node.list_payments(&[9u8; 32]).expect("unknown friend");
|
|
|
|
|
assert!(none.is_empty(), "{none:?}");
|
|
|
|
|
}
|
2026-09-15 12:29:16 -04:00
|
|
|
}
|