Compare commits

...
Author SHA1 Message Date
t
d256d3bb8e
docs: describe the SQLCipher store, not the pre-#43 design
The v0.2 banner and the "Seized laptop" section still claimed only chat
bodies were encrypted, that `self.identity_sk` and the roster were
plaintext, and that "sqlcipher is out of v1". That has been false since
#43.

- README banner: whole store is encrypted at rest with SQLCipher, with the
  row-bound AEAD layer kept on top.
- "Seized laptop": whole-file SQLCipher (Argon2id key over the 16-byte
  `store_salt`, raw `PRAGMA key`), identity/friends/locators inside the
  encrypted file, fail-closed unlock and `store_salt`-missing refusal, and
  the in-place v0.2.1 upgrade. Kept the honest caveats: no defense against
  a live compromise or a known passphrase, `/wipe` is not a forensic erase
  (SSD wear-levelling), and THREAT_MODEL.md stays the reference.
- "Not in v1": drop `sqlcipher` (shipped in #43).
- docs/SECURITY_AUDIT.md "Still true" bullet repeated the same plaintext
  claim; restated it as the residual risk that actually remains.

No code change. Evidence: cargo test --test store (21 passed, incl.
whole_store_file_is_encrypted_at_rest) and cargo test --lib -- store::
(6 passed, incl. the plaintext->SQLCipher upgrade and the wrong-passphrase
no-op).

Card: t_f2fc5190
2026-09-12 17:20:56 -04:00
02b531625f Merge pull request 'feat(sdk): explicit Tor lifecycle — Wire.shutdown / flush / torState + observable state' (#49) from feat/tor-lifecycle into main
All checks were successful
ci / test (push) Successful in 4m17s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m55s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 11s
Reviewed-on: #49
2026-09-12 20:58:31 +00:00
cecad2b364 Merge pull request 'feat(tui): per-message outbox delivery state (queued/sending/sent/failed) + N queued footer' (#48) from feat/tui-outbox-state into main
All checks were successful
release / x86_64 (push) Successful in 1m52s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 12s
ci / test (push) Successful in 6m1s
release / version (push) Successful in 2s
Reviewed-on: #48
2026-09-12 20:32:39 +00:00
a50df7ee43 Merge pull request 'feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer' (#47) from feat/zeroize-tui-profile into main
Some checks failed
release / version (push) Waiting to run
release / aarch64 (push) Blocked by required conditions
release / x86_64 (push) Blocked by required conditions
release / publish (push) Blocked by required conditions
ci / test (push) Has been cancelled
Reviewed-on: #47
2026-09-12 20:31:46 +00:00
beb523bdde Merge pull request 'wallet: no-spend (view-only) mode + RPC view-only detection + docs/WALLET.md' (#41) from feat/wallet-no-spend-view-only into main
All checks were successful
ci / test (push) Successful in 4m2s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 1m51s
release / aarch64 (push) Successful in 2m28s
release / publish (push) Successful in 10s
Reviewed-on: #41
2026-09-12 20:08:08 +00:00
t
e3be8ffdd0
feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer
All checks were successful
ci / test (pull_request) Successful in 4m14s
The Ed25519 identity secret was still copied into a bare [u8; 32] on the
stack in two signers (profile::sign, loc::sign), and the TUI kept the
typed backup/restore passphrase in a plain String for the life of the
screen. Both now go through Zeroizing:

- profile::signing_key_bytes() builds the 32-byte copy into a
  Zeroizing<[u8; 32]> (same pattern as pay::sign_bytes / qr::encode,
  but with copy_from_slice so no Copy temporary is left behind);
  loc::sign shares the helper instead of making its own copy.
- Screen::Passphrase now owns a PassphraseEntry whose buffers are
  Zeroizing<String>. Every exit path (Enter, mismatch, Esc) calls
  close(), which wipes both buffers eagerly; a drop — including Ctrl-Q
  and a panic — is the backstop.

Evidence: tests/zeroize.rs gains a drop probe (ManuallyDrop +
drop_in_place + read_volatile) on the Zeroizing signing buffer and a
length-rejection test; src/tui.rs gains unit tests asserting the buffer
types and that close() leaves every byte of the passphrase's heap
capacity zeroed.
2026-09-12 15:41:54 -04:00
Sirius DevOps
323100b162
wallet: no-spend mode + view-only detection over RPC
All checks were successful
ci / test (pull_request) Successful in 4m11s
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.

When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.

New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 15:41:33 -04:00
agent
48c06df2cf
docs(sdk): Wire::shutdown doc said the second call returns Ok; it returns Stopped
All checks were successful
ci / test (pull_request) Successful in 4m22s
The handle-level call takes the node out on the first shutdown, so a second
call reports the typed `WireError::Stopped` (covered by
`calls_after_shutdown_are_typed_errors_not_panics`). Only the node-level
`Node::shutdown()` is Ok-idempotent. The rustdoc claimed otherwise.
2026-09-12 15:26:17 -04:00
apk-dev
c068e292a0
feat(android): stop the node when the UI goes away
`WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all,
so neither the user pressing Lock nor the Activity finishing stopped anything:
Arti kept its client and the hosted onion service, the outbox worker kept
dialing, and the sqlite connection stayed open behind the JNI handle.

Both paths now go through `stopNode(Wire)`:

1. `flush()` — one last bounded drain, so a queued message gets its chance
   before the process may lose its socket.
2. `shutdown()` — drain again with a shorter budget, stop the onion service,
   abort the retry worker, checkpoint the WAL, and take the node handle out of
   the `Wire` (which is what releases the last Arc to the Tor client and the
   store).

Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`)
because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors
are deliberately swallowed there: the UI is gone, and the SDK reports a second
teardown as the typed `WireException.Stopped` rather than a panic.

`unlock()` joins any in-flight teardown before opening again. The old node holds
the sqlite file and Arti's state lock until its teardown returns, and racing it
makes the next `openWire` fail.

A process killed outright (Doze, background-process killer, force-stop) still
never runs any of this — that is what the sqlite outbox and the new `flush()`
are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from
the ViewModel to the service.
2026-09-12 15:10:29 -04:00
apk-dev
38fde75d40
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 15:10:29 -04:00
t
b79f1fd6f3
feat(tui): per-message outbox delivery state + N queued footer
All checks were successful
ci / test (pull_request) Successful in 4m9s
Chat rows now carry the state the local outbox actually holds: `✓` delivered,
`◷ queued (try n/8, retry 45s)` while the retry worker still has it, `» sending`
mid-attempt and `✗ failed: <short reason>` once attempts are exhausted. The
footer replaces the flat `sent` / `send failed` copy with the live count
(`2 queued`), and keeps a fail-closed `send failed: …` statement as long as any
row is terminally failed.

States come from the outbox API (`Node::outbox_pending` → `Queued` / `Sending` /
`Failed`; a delivered row is deleted, so absence is `Sent`). No parallel state
model, no new wire prefix. Every new glyph has an ASCII fallback (`ok` plus the
state word) exercised by a test.

- `chat_with_delivery()` / `delivery_tag()` / `retry_in_text()` /
  `short_send_reason()` / `OutboxSummary::note()` are pure and unit-tested.
- `draw_chat()` is now the real chat-pane renderer (extracted from
  `App::draw_main`) so width/wrap is testable without a `Node`.
- docs/TUI.md: delivery markers, copy, and the 80x24 floor / 120x40 target.

Verified: cargo test 26/26 suites ok (tui_spec 20/20, incl. a real Store +
Outbox::send -> pending() -> render path); clippy --all-targets -D warnings clean.
2026-09-12 14:44:35 -04:00
18 changed files with 2303 additions and 147 deletions

View file

@ -3,7 +3,7 @@
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
No hosted server. Identity is a public key; the onion is only a locator.
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. Chat bodies are encrypted at rest; identity keys in sqlite are still plaintext.
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
@ -222,14 +222,11 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
## Seized laptop
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD bound to `friend_id`, `dir`, and row id, wrapped by a passphrase-derived Argon2id key. A disk grep of `onionwire.db` must not yield the message log. Empty-AAD v0.2 blobs are rewrapped once on unlock.
The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched.
Still plaintext on disk (unless you add OS/FDE):
Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`, plus a random 32-byte data key in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Empty-AAD v0.2 blobs are rewrapped once on unlock.
- your identity secret key (`self.identity_sk`)
- friend public keys and current locators
The message key is **not** wrapped with `identity_sk` (that key is in the same file). sqlcipher is out of v1. `/wipe` deletes chat and payments history; it is not a forensic erase. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows are in process memory, and SQLCipher's page cache holds decrypted pages. It also does not stop an attacker who has your passphrase. `/wipe` deletes chat and payments history; it is not a forensic erase — SSD wear-levelling can keep copies. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
@ -316,7 +313,7 @@ Do not run `cargo publish`; `publish = false`. CI needs the repo secret
## Not in v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, sqlcipher, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
## License

View file

@ -7,7 +7,10 @@ import com.siriusdevops.onionwire.crypto.KeyBacking
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
import com.siriusdevops.onionwire.crypto.StoreSecret
import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@ -55,6 +58,14 @@ sealed interface Unlock {
data class OneTap(val backing: KeyBacking) : Unlock
}
/**
* Teardown work must outlive the ViewModel: `onCleared()` runs *after*
* `viewModelScope` is already cancelled, and stopping the node means draining
* the outbox and stopping Arti, not just dropping a reference. One process-wide
* scope is enough — there is one node per process.
*/
private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/**
* Owns the single Wire node for the process.
*
@ -87,6 +98,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
private var wire: Wire? = null
/**
* The in-flight teardown, if any. Unlocking again has to wait for it: the
* old node holds the sqlite file and Arti's state lock until `shutdown()`
* returns, and racing it makes the new node fail to open.
*/
private var stopping: Job? = null
init {
// Probe on a background dispatcher: this touches the Keystore and does
// a full GCM decrypt. Doing it here means a killed Keystore key is
@ -143,12 +161,45 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
}
}
/** Drops our handle. The onion service stops; nothing is sent after this. */
/**
* Stops the node and drops our handle. Nothing is sent after this.
*
* Flush first — the outbox is the whole point of losing the process — then
* `shutdown()`, which stops the onion service, aborts the retry worker and
* checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this
* runs from an `onClick`.
*/
fun lock() {
val w = wire ?: return
wire = null
_friends.value = emptyList()
_phase.value = Phase.Locked
refreshUnlockState()
stopping = TEARDOWN.launch { stopNode(w) }
}
/**
* The node must not outlive the UI. Doze and the background-process killer
* skip this entirely (that is what the outbox is for), but a normal finish
* tears Tor down here instead of leaving Arti running behind a dead screen.
*/
override fun onCleared() {
val w = wire
wire = null
if (w != null) stopping = TEARDOWN.launch { stopNode(w) }
super.onCleared()
}
private suspend fun stopNode(w: Wire) {
// Best effort, both steps: teardown runs on a process-scope job after
// the UI is gone, so there is nobody to show an error to and nothing
// useful to retry. `shutdown()` drains again with a shorter budget, so
// a flush that times out is not fatal.
runCatching { w.flush() }
// A second shutdown — `lock()` and then `onCleared()`, say — lands here
// too: the SDK reports it as a typed WireException.Stopped, never a
// panic, so swallowing it is correct.
runCatching { w.shutdown() }
}
private fun refreshUnlockState() {
@ -180,13 +231,17 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
* follow-up SDK signature this card cannot make itself.
*/
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
if (secret.isEmpty() || _phase.value is Phase.Opening) {
if (secret.isEmpty() || _phase.value is Phase.Opening || wire != null) {
StoreSecret.wipe(secret)
return
}
_phase.value = Phase.Opening
viewModelScope.launch {
try {
// Any previous node must be fully stopped first: the old node
// holds the sqlite file and Arti's state lock until its teardown
// returns, and racing it makes this open fail.
stopping?.join()
val w = openWire(home.absolutePath, secret.concatToString())
wire = w
if (storeAfterwards) store(secret)

View file

@ -13,13 +13,20 @@
//! Orbot pipe. If the onion service cannot publish, this fails closed.
//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not.
//!
//! Lifecycle: a node is started by [`open_wire`] and stopped by
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
//! state and [`Wire::flush`] is "deliver what is deliverable now". A process
//! killed by Doze or the background-process killer never runs `shutdown`, which
//! is exactly why queued sends live in sqlite and not in memory.
//!
//! The façade deliberately exposes only plain data (records + hex strings) so
//! no TUI/ratatui type leaks into the AAR.
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};
use std::sync::{Arc, Mutex, OnceLock};
use onionwire::node::Node;
use onionwire::hs::TorState as CoreTorState;
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
use onionwire::qr;
uniffi::setup_scaffolding!();
@ -54,6 +61,12 @@ pub fn install_crypto_provider() {
pub enum WireError {
#[error("{message}")]
Failed { message: String },
/// The node was shut down (or never opened). Distinct from `Failed` so
/// Kotlin can branch on it instead of string-matching a message, and so
/// "you must unlock again" is a different UI state from "the network is
/// broken".
#[error("node stopped: {message}")]
Stopped { message: String },
}
impl WireError {
@ -62,6 +75,12 @@ impl WireError {
message: e.to_string(),
}
}
fn stopped(what: &str) -> Self {
Self::Stopped {
message: format!("{what} called on a shut-down node"),
}
}
}
type WResult<T> = std::result::Result<T, WireError>;
@ -98,10 +117,70 @@ pub struct InviteInfo {
pub onion: String,
}
/// Observable lifecycle state of the node's onion service.
///
/// Mirrors Arti's own service status, projected onto the four states a UI
/// actually acts on. It is the same distinction `hs::hs_is_ready` makes when it
/// decides whether the onion is reachable yet.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum TorState {
/// Bootstrap or descriptor upload still in flight. Not reliably reachable.
Bootstrapping,
/// Onion service running and its descriptor published.
Published,
/// Reachable, but Arti reports the service degraded. Usable — worth saying
/// so, not identical to `Published`.
DegradedReachable,
/// Shut down: no onion service, no dials, store checkpointed. Every method
/// on the node now returns `WireError.Stopped`.
Stopped,
}
impl From<CoreTorState> for TorState {
fn from(s: CoreTorState) -> Self {
match s {
CoreTorState::Bootstrapping => Self::Bootstrapping,
CoreTorState::Published => Self::Published,
CoreTorState::DegradedReachable => Self::DegradedReachable,
CoreTorState::Stopped => Self::Stopped,
}
}
}
/// What a [`Wire::flush`] managed to do.
#[derive(Debug, Clone, Copy, uniffi::Record)]
pub struct FlushOutcome {
/// Rows the pass started a delivery for. `0` when the pass hit its time
/// budget before finishing — the rows are still queued, we just stopped
/// counting.
pub attempted: u32,
/// Rows delivered now. A message absent from `remaining` was sent.
pub delivered: u32,
/// Rows still queued or terminally failed afterwards.
pub remaining: u32,
}
/// A running OnionWire node: identity + Arti client + hosted v3 onion service.
///
/// Holds the node handle. [`Wire::shutdown`] takes it out and drops it, which
/// is what lets the last reference to the Tor client and the store go away —
/// there is no hidden global keeping Arti (or the sqlite connection) alive
/// after the UI is gone.
#[derive(uniffi::Object)]
pub struct Wire {
inner: Arc<Node>,
node: Mutex<Option<Arc<Node>>>,
}
impl Wire {
/// The live node, or `Stopped` if this handle was shut down. A poisoned
/// mutex is reported the same way rather than panicking: a caller that sees
/// `Stopped` unlocks again, which is the correct recovery either way.
fn node(&self) -> WResult<Arc<Node>> {
let guard = self.node.lock().map_err(|_| WireError::Stopped {
message: "node handle lock poisoned by a panic; reopen the identity".to_string(),
})?;
guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call"))
}
}
/// Open (or create) the identity in `home` and start hosting an onion service.
@ -111,6 +190,11 @@ pub struct Wire {
///
/// This resolves only once the onion service is published — on a cold network
/// that is minutes, not seconds. Call it off the main thread.
///
/// The returned handle owns the node: it lives until [`Wire::shutdown`], or
/// until the handle itself is dropped (which the JVM does without running the
/// drain, so call `shutdown()` from teardown — see the foreground-service
/// caller).
#[uniffi::export(async_runtime = "tokio")]
pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
// Before anything that can build a TLS config: Arti's rustls backend dies
@ -120,7 +204,9 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase)
.await
.map_err(WireError::new)?;
Ok(Arc::new(Wire { inner: node }))
Ok(Arc::new(Wire {
node: Mutex::new(Some(node)),
}))
}
/// Decode an invite without adding the friend. Verifies the signature.
@ -135,24 +221,81 @@ pub fn decode_invite(invite: String) -> WResult<InviteInfo> {
#[uniffi::export(async_runtime = "tokio")]
impl Wire {
/// Stop the node: give every queued outbox row one last bounded delivery
/// attempt, stop the onion service, abort the retry worker, checkpoint the
/// sqlite WAL, and drop the Tor client.
///
/// The *node* teardown is idempotent: a second `Node::shutdown()` returns
/// `Ok` without repeating the work. This handle is spent by the first call,
/// so a second `Wire::shutdown()` — or two concurrent teardowns — returns
/// the typed `WireError.Stopped` instead of a silent `Ok`: a double
/// teardown is a caller bug worth surfacing, and `Stopped` is already the
/// answer every other method gives. It never panics.
///
/// After it, every other method on this handle — including `send` —
/// returns `WireError.Stopped` instead of touching a dead client.
///
/// Never called at all when the process is killed outright (Doze, the
/// background-process killer, a force-stop): that is the case [`flush`]
/// (Self::flush) and the sqlite outbox exist for. Once shut down, this
/// handle is spent — unlock again to get a new one.
pub async fn shutdown(&self) -> WResult<()> {
let node = self.node()?;
node.shutdown().await.map_err(WireError::new)?;
// Drop our handle to the node. With the onion service and the outbox
// worker aborted this is the last reference to the Tor client and the
// store, so Arti's runtime and the sqlite connection are released here.
let mut guard = self.node.lock().map_err(|_| WireError::Stopped {
message: "node handle lock poisoned by a panic".to_string(),
})?;
*guard = None;
Ok(())
}
/// Drain the outbox: one delivery attempt for every queued row, now,
/// ignoring its retry backoff, then checkpoint the WAL.
///
/// Bounded by the SDK (30s): a dead peer's onion can hold a dial for ~20s
/// and this is called from UI/lifecycle threads. Rows that did not go out
/// stay queued; the retry worker keeps its normal schedule. Safe to call
/// repeatedly — use it on unlock, on foreground, and before `shutdown`.
pub async fn flush(&self) -> WResult<FlushOutcome> {
let node = self.node()?;
let out = node.flush().await.map_err(WireError::new)?;
Ok(from_core_flush(out))
}
/// Where the onion service is right now. Cheap and read-only, no I/O: a
/// notification or a settings screen can call it directly.
pub fn tor_state(&self) -> TorState {
match self.node.lock() {
Ok(guard) => match guard.as_ref() {
Some(node) => node.tor_state().into(),
None => TorState::Stopped,
},
// Poisoned: same answer as shut down — the node is unusable.
Err(_) => TorState::Stopped,
}
}
/// Fingerprint of our own identity key. Stable forever for this install.
pub async fn fingerprint(&self) -> WResult<String> {
self.inner.fingerprint().map_err(WireError::new)
self.node()?.fingerprint().map_err(WireError::new)
}
/// Current onion locator. Changes on rotate; identity does not.
pub async fn onion(&self) -> String {
self.inner.onion()
pub async fn onion(&self) -> WResult<String> {
Ok(self.node()?.onion())
}
/// `onionwire:v1:…` invite string to hand to the other person out of band.
pub async fn invite(&self) -> WResult<String> {
self.inner.qr_payload().map_err(WireError::new)
self.node()?.qr_payload().map_err(WireError::new)
}
/// Roster, sorted by petname then fingerprint.
pub async fn friends(&self) -> WResult<Vec<FriendInfo>> {
let list = self.inner.list_friends().map_err(WireError::new)?;
let list = self.node()?.list_friends().map_err(WireError::new)?;
Ok(list
.into_iter()
.map(|f| FriendInfo {
@ -168,9 +311,10 @@ impl Wire {
/// Add a friend from an invite, or update the locator if the key is known.
/// Same `k` never creates a second row.
pub async fn add_friend(&self, invite: String) -> WResult<FriendInfo> {
self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?;
let node = self.node()?;
node.add_friend_from_qr(&invite).map_err(WireError::new)?;
let p = qr::decode(&invite).map_err(WireError::new)?;
let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?;
let f = node.friend(&p.pubkey).map_err(WireError::new)?;
Ok(FriendInfo {
pubkey_hex: hex(&f.pubkey),
fingerprint: f.fingerprint,
@ -183,26 +327,32 @@ impl Wire {
/// Local label. Pass `None` to clear. Never goes on the wire.
pub async fn set_petname(&self, pubkey_hex: String, petname: Option<String>) -> WResult<()> {
let pk = unhex(&pubkey_hex)?;
self.inner
self.node()?
.set_petname(&pk, petname.as_deref())
.map_err(WireError::new)
}
/// Send one message. Fail closed: if the peer's onion is down, this errors
/// after retrying. There is no outbox in v1 — no silent spooling.
/// Send one message. Returns once the outcome is known: delivered now, or
/// queued for retry because the peer's onion is unreachable. A protocol
/// error (bad signature, bad frame) still fails immediately and is never
/// queued. Use [`flush`](Self::flush) to retry the queue on demand.
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
let pk = unhex(&pubkey_hex)?;
self.inner
self.node()?
.send(&pk, body.as_bytes())
.await
.map_err(WireError::new)
.map_err(WireError::new)?;
Ok(())
}
/// Chat history for a friend, oldest first. Bodies are decrypted here;
/// they are stored encrypted at rest.
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
let pk = unhex(&pubkey_hex)?;
let rows = self.inner.list_messages(&pk).map_err(WireError::new)?;
let rows = self
.node()?
.list_messages(&pk)
.map_err(WireError::new)?;
Ok(rows
.into_iter()
.map(|m| ChatMessage {
@ -214,7 +364,7 @@ impl Wire {
/// Delete every message body. Identity and friends survive.
pub async fn wipe_messages(&self) -> WResult<()> {
self.inner.wipe_messages().map_err(WireError::new)
self.node()?.wipe_messages().map_err(WireError::new)
}
/// Publish a NEW onion service and hard-cut the old one, then push a signed
@ -224,7 +374,7 @@ impl Wire {
/// you until they rescan your invite — that is the documented v1 behaviour,
/// not a bug. Confirm with a typed phrase in the UI; never one tap.
pub async fn rotate_onion(&self) -> WResult<RotateOutcome> {
let r = self.inner.rotate().await.map_err(WireError::new)?;
let r = self.node()?.rotate().await.map_err(WireError::new)?;
Ok(RotateOutcome {
notified: r.notified as u32,
friends: r.friends as u32,
@ -237,6 +387,14 @@ impl Wire {
}
}
fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome {
FlushOutcome {
attempted: o.attempted as u32,
delivered: o.delivered as u32,
remaining: o.remaining as u32,
}
}
fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
@ -256,3 +414,72 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
})
.collect()
}
#[cfg(test)]
mod tests {
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
//! handle, which is what a shut-down node must guarantee. A `Wire` with no
//! node is exactly the state `shutdown()` leaves behind.
use super::*;
fn stopped_wire() -> Wire {
Wire {
node: Mutex::new(None),
}
}
fn block_on<F: std::future::Future>(f: F) -> F::Output {
// No `macros` feature on tokio in this crate, so build the runtime.
tokio::runtime::Builder::new_current_thread()
.build()
.expect("runtime")
.block_on(f)
}
#[test]
fn tor_state_of_a_stopped_handle_is_stopped() {
assert_eq!(stopped_wire().tor_state(), TorState::Stopped);
}
#[test]
fn calls_after_shutdown_are_typed_errors_not_panics() {
let wire = stopped_wire();
let err = block_on(wire.flush()).expect_err("flush after shutdown must fail");
assert!(
matches!(err, WireError::Stopped { .. }),
"flush returned {err:?}, want WireError::Stopped"
);
let err = block_on(wire.send("00".repeat(32), "hi".to_string()))
.expect_err("send after shutdown must fail");
assert!(
matches!(err, WireError::Stopped { .. }),
"send returned {err:?}, want WireError::Stopped"
);
let err = block_on(wire.friends()).expect_err("friends after shutdown must fail");
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
let err = block_on(wire.shutdown()).expect_err("second shutdown must not re-run");
assert!(
matches!(err, WireError::Stopped { .. }),
"second shutdown returned {err:?}"
);
}
#[test]
fn tor_state_maps_every_core_state() {
assert_eq!(
TorState::from(CoreTorState::Bootstrapping),
TorState::Bootstrapping
);
assert_eq!(TorState::from(CoreTorState::Published), TorState::Published);
assert_eq!(
TorState::from(CoreTorState::DegradedReachable),
TorState::DegradedReachable
);
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
}
}

View file

@ -24,7 +24,7 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests
## Still true / not a “finding we forgot”
- Identity secret key and roster (pubkeys + locators) are **plaintext** in sqlite. Chat bodies are not. Seized laptop without FDE yields who you are and who you talk to.
- At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md).
- Arti onion services are experimental. Fail closed; no C-tor fallback.
- No public third-party audit, no `cargo-audit` gate in CI as of the original pass.
- Invite decode still accepts the legacy concat signature (compatibility).

View file

@ -73,6 +73,18 @@ A signed `prf` frame is shown to people who already have a session with you. App
OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy.
Run it **view-only** (recommended). `/pay` and receipt verification need only
`create_address`/`get_transfers`, which a wallet without a spend key serves
fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC
dial, and a view-only wallet is detected over RPC (`query_key`
`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says
so plainly instead of failing with a raw wallet error. The trade-off is
explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local
spend authority — any process that can read the RPC credentials can move the
balance, and `/tip` gives a chat peer a supported way to ask for a transfer.
Loopback binding is not an authorization boundary. Full setup, view-only wallet
creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md).
## Backup file is the identity
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.

View file

@ -351,6 +351,16 @@ Else RGB as today.
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
| alert prefix | `! ` | `! ` |
| stale | word `stale` | `stale` |
| delivery: delivered | `✓` | `ok` |
| delivery: queued | `◷` | (word) `queued` |
| delivery: sending | `»` | (word) `sending` |
| delivery: failed | `✗` | (word) `failed` |
`queued` / `sending` / `failed` always carry their state word, so the ASCII
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
falls back to `ok`. `delivery_glyph()` /
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
fallback path.
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
on the main header.
@ -401,6 +411,9 @@ Do not soften fail-closed into a loader.
| sending | `sending` (keep, no spinner) |
| sent | `sent` |
| peer down / send err | `send failed: {e}` (visible) |
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
| queued + terminal failure | `{n} queued, send failed: {short}` |
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
| already sending | `already sending` (keep) |
| stale friend | `stale` suffix (keep) |
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
@ -570,3 +583,42 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
`no messages` / `type below, Enter sends`; paste error is `{err}` then
`Enter resubmits Esc back`; alerts truncate to the frame width.
## Delivery state (outbox) — implemented
Per-message state, read from the local outbox. The states are the store's own
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
prefix, no server.
| Row | Marker |
|---|---|
| delivered | `you: ping ✓` |
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
| sending | `you: pong » sending` |
| failed | `you: pong ✗ failed: connection timed out` |
| inbound | `them: pong` (no marker) |
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
`retry now` comes from the stored absolute `next_attempt_at`.
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
capped at 24 cells (`short_send_reason`).
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
- The tag trails the body and wraps with it, so it is never clipped away.
Correlation: a delivered row is deleted from the outbox, so an outbound message
with no row is `Sent`; pending rows are matched to messages by body, newest send
first (`chat_with_delivery`). The outbox holds no message id the UI can join on,
so two identical bodies where only the newer one is still queued attach the
marker to the newer send. An id-bearing accessor would remove that last
ambiguity; see the follow-up card noted in the PR.
### Size floor / target
- **Floor: 80x24.** Everything above must render there.
- **Target: 120x40.**
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
and footer row is `<=` the terminal width, that the markers render, and that
an over-long message wraps instead of being clipped.
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.

184
docs/WALLET.md Normal file
View file

@ -0,0 +1,184 @@
# OnionWire + monero-wallet-rpc
OnionWire is not a wallet. It never holds a seed, a spend key, or a view key.
It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on
loopback, only to:
- hand out a receive subaddress for `/pay` invoices (`create_address`),
- read incoming transfers to verify a peer's receipt (`get_transfers`),
- and — only if you let it — spend for `/tip` (`transfer`).
**Run it view-only, and switch `/tip` off explicitly.** Everything else in this
document explains why, and what breaks when you do.
## Env vars
| Variable | Meaning |
|---|---|
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
`README.md` carries the operator summary; this file is the long form.
## Recommended topology
```
wallet host (this machine)
┌──────────────────────────────────────────────────────────────┐
│ monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-login u:p │
│ ▲ HTTP Digest, loopback only │
│ │ │
│ OnionWire (ONIONWIRE_WALLET_NO_SPEND=1) ── /pay, receipts │
│ └── /tip refused locally │
└──────────────────────────────────────────────────────────────┘
```
Loopback is the only address OnionWire will dial. `.onion` RPC URLs are
rejected: there is no Arti dial for the wallet, and a remote wallet would move
your key material off the box.
## Create a view-only wallet
Either path produces a wallet file with the view key only. Keep the seed /
spend key on a machine that is **not** running OnionWire.
With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard*
address the view key belongs to, then the secret view key):
```bash
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
# Standard address: 4...
# Secret view key: <hex>
```
Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys`
without `spendkey` writes a watch-only wallet):
```bash
curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{
"filename":"viewonly","password":"walletpass",
"address":"4...","viewkey":"<hex>","restore_height":<height>}}'
# → "Watch-only wallet has been generated successfully."
```
Then serve it:
```bash
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret \
--daemon-address "$YOUR_MONEROD:18089"
export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083
export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
export ONIONWIRE_WALLET_NO_SPEND=1
```
Restore the wallet from a height *at or before* its first incoming transaction
— a view-only wallet cannot rescan cheaply from height 0.
## What works, what does not
| Feature | View-only | Spend-capable |
|---|---|---|
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
| Receipt verification (`get_transfers`) | works | works |
| Profile `xmr_addr` fallback when RPC is down | works | works |
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
| OnionWire learns your spend key | never | never (it stays in the wallet) |
With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is
contacted, with:
```
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
```
Without the flag, `/tip` against a view-only wallet fails at the wallet and
OnionWire then asks the wallet directly whether it can spend (see below), so you
get the same sentence instead of a raw RPC error.
## How OnionWire detects view-only over RPC
The signal people usually reach for is `query_key` with `key_type=mnemonic`. It
works, but it is the wrong key to ask for: on a spend-capable wallet it hands
over the whole seed (full spend ability) over loopback HTTP, and it answers
`-43` for wallets that have no mnemonic at all. The spend key is narrower and
just as unambiguous:
```
query_key {"key_type":"spend_key"}
spend-capable → result.key = <hex secret spend key>
view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key."
```
(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the
two agree — OnionWire asks for the spend key because it is the smaller secret.)
- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key)
- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in
[`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h)
- The view-only branch is `on_query_key` in
[`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp)
OnionWire only calls this **after** a `transfer` has already failed — it never
probes a healthy wallet — and it discards `result.key` immediately. There is no
RPC method that reports "view-only" as a plain field; `query_key` is the
documented signal and this is its only cost: a spend-capable wallet answers with
its spend key over loopback HTTP, which is one more reason to run view-only.
Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc`
answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error
unchanged. It never guesses "view-only" from an unrelated failure.
## Why loopback still needs authentication
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it
away from other users or processes on the same machine. Any local process can
`connect(127.0.0.1:18083)`.
- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
refuses URLs without credentials. Unset the credentials and the wallet is open
to every local process — with a spend-capable wallet file, that is a
one-curl drain of your balance.
- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext,
but Digest gives no confidentiality: a local attacker who can sniff loopback
can replay it. Treat loopback as trusted-ish, not safe.
- Do not log the password, and do not put it in a shell history you share.
Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL.
## The spend-authority warning
An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a
local spend authority: any process that can read the RPC credentials (env var,
`/proc/<pid>/environ`, shell history, a stored URL) can spend the wallet's
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
default:
- the wallet file holds no spend key, so a stolen wallet file cannot be used to
move funds;
- the RPC credentials grant only receive-address and history reads;
- `/tip` fails locally with a plain message, so nothing in the UI pretends the
spend path exists.
If you want tips to work, understand that you are deliberately making the
OnionWire process able to spend. Give it a **separate hot wallet with a small
balance**, not your savings wallet.
## References
- Monero Wallet RPC reference:
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
- `on_query_key` (view-only → `-29`):
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp>
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`:
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h>
- `--generate-from-view-key` (incoming-only wallet):
<https://github.com/monero-project/monero/blob/master/src/simplewallet/simplewallet.cpp>
- `generate_from_keys` (watch-only when `spendkey` is omitted):
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#generate_from_keys>

View file

@ -96,6 +96,64 @@ pub fn hs_is_ready(state: State, probe_ok: bool) -> bool {
}
}
/// Observable lifecycle state of the node's onion service.
///
/// This is the four-state projection callers actually act on: is the onion
/// service serving, is it serving but unhealthy, is it still coming up, or did
/// we stop it. A process that gets killed by the Android background-process
/// killer never observes `Stopped` — that is why `Wire.flush()` exists — but a
/// clean teardown always does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TorState {
/// Bootstrap or HsDir descriptor upload is still in flight: the service is
/// not reliably reachable yet.
Bootstrapping,
/// The onion service is running and its descriptor is published.
Published,
/// Reachable through the service, but Arti reports the service degraded.
/// Usable, worth surfacing, not identical to `Published`.
DegradedReachable,
/// The node was shut down: no onion service, no client dials, and the
/// store is checkpointed.
Stopped,
}
/// Project an Arti onion-service status onto [`TorState`].
///
/// Deliberately mirrors `hs_is_ready`: `Running` and `DegradedReachable` are
/// the states a probe could already reach, everything transient is
/// `Bootstrapping`, and a shut-down service is `Stopped`.
///
/// `reachable` is the same evidence `wait_until_published` accepts from a
/// probe: a successful connect to our own onion means some HsDir already has
/// the descriptor even though Arti's combined status is still `Bootstrapping`
/// (that mismatch is exactly what the 360s publish wait exists for). Without
/// it, a node that is live and reachable would report `Bootstrapping` for
/// another few minutes.
///
/// Two statuses look terminal but are not:
/// * `Shutdown` on a *live* node is transient — a freshly launched service
/// reports it before its publish reactor starts, which is why a live node
/// reads `Bootstrapping` there and only the explicit stop flag produces
/// `Stopped`. (Caught on device-real conditions by the live test: the
/// first `tor_state()` after `start()` returned `Shutdown`.)
/// * `Broken` maps to `Bootstrapping` rather than a state of its own: Arti
/// reads `Broken` while the HsDir retry loop is still going, and
/// `wait_until_published` is where a genuinely dead service surfaces as an
/// error instead of a flag the UI would have to poll for.
pub fn tor_state_of(state: State, stopped: bool, reachable: bool) -> TorState {
if stopped {
return TorState::Stopped;
}
match state {
State::Running => TorState::Published,
State::DegradedReachable => TorState::DegradedReachable,
State::Broken | State::Shutdown => TorState::Bootstrapping,
_ if reachable => TorState::Published,
_ => TorState::Bootstrapping,
}
}
pub async fn wait_until_published(
client: &Client,
svc: &RunningOnionService,

View file

@ -23,9 +23,10 @@ pub struct Loc {
const PREFIX: &[u8] = b"loc ";
pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> {
let sk_bytes: [u8; 32] = identity_sk
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
// Same one-shot raw identity-secret copy as `profile::sign`; shared so
// `Zeroize` covers it here too.
let sk_bytes =
crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec();
Ok(Loc {

View file

@ -1,6 +1,7 @@
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@ -13,7 +14,7 @@ use zeroize::Zeroizing;
use crate::dispatch::{self, Kind};
use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT};
use crate::hs::{self, Client, HS_PORT, TorState};
use crate::loc;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
@ -30,8 +31,27 @@ pub struct RotateResult {
pub friends: usize,
}
/// What a `flush` actually managed to do, for UI surfacing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlushOutcome {
/// Outbox rows we tried to deliver in this pass.
pub attempted: usize,
/// Rows delivered now — their outbox rows are gone.
pub delivered: usize,
/// Rows still queued or terminally failed after the pass.
pub remaining: usize,
}
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
/// the retry worker picks it up on its normal schedule.
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
struct HsHandle {
_svc: Arc<RunningOnionService>,
svc: Arc<RunningOnionService>,
rend: tokio::task::JoinHandle<()>,
}
@ -61,7 +81,17 @@ pub struct Node {
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
_outbox_worker: WorkerHandle,
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,
}
impl Node {
@ -113,7 +143,9 @@ impl Node {
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
stopped: AtomicBool::new(false),
onion_reachable: AtomicBool::new(false),
});
// Unlock trigger: flush anything queued by a previous run now, in the
// background, rather than waiting out its backoff.
@ -122,10 +154,14 @@ impl Node {
// while combined status is still Bootstrapping.
let rend = spawn_rend(Arc::clone(&node), rend);
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
_svc: Arc::clone(&svc),
svc: Arc::clone(&svc),
rend,
});
hs::wait_until_published(&node.client, &svc, &onion).await?;
// Published by the same bar `wait_until_published` uses — a probe
// success counts, which is the whole reason `tor_state` tracks it
// separately from Arti's (slower, flappier) combined status.
node.onion_reachable.store(true, Ordering::SeqCst);
node.store
.lock()
.map_err(|e| e.to_string())?
@ -134,6 +170,141 @@ impl Node {
Ok(node)
}
/// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` /
/// `DegradedReachable` / `Stopped`.
///
/// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a
/// foreground-service notification can poll it instead of guessing from a
/// timer. A poisoned handle is reported as `Stopped` rather than panicking:
/// the node is unusable either way, and the caller is often a UI thread.
pub fn tor_state(&self) -> TorState {
let stopped = self.stopped.load(Ordering::SeqCst);
let reachable = self.onion_reachable.load(Ordering::SeqCst);
match self.hs.lock() {
Ok(guard) => match guard.as_ref() {
Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable),
// Between `rotate`'s hard cut and the new service being
// installed there is no handle; before the first publish there
// is none either. Both are "not serving *yet*" unless we stopped.
None if stopped => TorState::Stopped,
None => TorState::Bootstrapping,
},
Err(_) => TorState::Stopped,
}
}
/// Drain the outbox: one delivery attempt for every outstanding row, now,
/// ignoring its retry schedule. Then checkpoint the WAL.
///
/// This is the "deliver what is deliverable before we lose the process"
/// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a
/// dial for ~20s and the caller is usually a UI thread. Rows that could not
/// be delivered stay queued and are picked up by the retry worker on its
/// normal backoff.
pub async fn flush(&self) -> Result<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"),
}
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> {
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await {
Ok(Ok(rows)) => Some(rows),
Ok(Err(e)) => return Err(e),
Err(_) => {
eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued");
None
}
};
let delivered = attempted
.as_ref()
.map(|rows| {
rows.iter()
.filter(|(_, s)| matches!(s, OutboxStatus::Sent))
.count()
})
.unwrap_or(0);
Ok(FlushOutcome {
// `None` means the pass was cancelled: we know how many rows are
// still queued, not how many were started.
attempted: attempted.as_ref().map(Vec::len).unwrap_or(0),
delivered,
remaining: self.pending_rows()?,
})
}
/// Rows the outbox still holds for every friend, queued or terminally
/// failed. A message absent here was delivered.
fn pending_rows(&self) -> Result<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) {
if let Err(e) = checkpoint_wal(&self.home) {
eprintln!("wal checkpoint: {e}");
}
}
fn ensure_running(&self) -> Result<(), String> {
if self.stopped.load(Ordering::SeqCst) {
return Err("node is stopped — open the identity again".to_string());
}
Ok(())
}
pub fn onion(&self) -> String {
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
}
@ -434,6 +605,7 @@ impl Node {
}
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
self.ensure_running()?;
let (onion, prekey) = {
let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 {
@ -447,6 +619,7 @@ impl Node {
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
/// the outbox retry triggers.
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
self.ensure_running()?;
tokio::time::timeout(
Duration::from_secs(20),
self.client.connect((onion, HS_PORT)),
@ -466,6 +639,7 @@ impl Node {
}
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
self.ensure_running()?;
let old_nick = self
.store
.lock()
@ -482,12 +656,16 @@ impl Node {
let onion = hs::onion_string(&svc)?;
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
*self.hs.lock().map_err(|e| e.to_string())? = None;
// The new service is not reachable until it publishes: the locator in
// flight is dead until then, so do not carry the old verdict over.
self.onion_reachable.store(false, Ordering::SeqCst);
let rend = spawn_rend(Arc::clone(self), rend);
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
_svc: Arc::clone(&svc),
svc: Arc::clone(&svc),
rend,
});
hs::wait_until_published(&self.client, &svc, &onion).await?;
self.onion_reachable.store(true, Ordering::SeqCst);
{
let store = self.store.lock().map_err(|e| e.to_string())?;
store.set_onion(&onion).map_err(|e| e.to_string())?;
@ -549,6 +727,7 @@ impl Node {
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
/// frame) still fails immediately and is never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
self.ensure_running()?;
self.outbox.send(friend_pk, plaintext).await
}
@ -857,6 +1036,49 @@ fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
});
}
/// Checkpoint the sqlite WAL into the main db file and truncate it.
///
/// `Store` owns the write connection and deliberately does not lend it out, and
/// a checkpoint is a property of the *database*, not of one connection — so a
/// short-lived second connection to the same file is the least invasive way to
/// reach it from the node without widening `Store`'s API.
///
/// That works because the connection needs no passphrase: it moves
/// already-committed pages, it does not decrypt them. It stops working the
/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only
/// inside `Store` and a second connection cannot read the file at all. That case
/// is detected and reported as a skip rather than a failure: nothing is lost
/// (sqlite folds the WAL into the db when the last connection closes) — the
/// explicit truncation just has to move inside `Store` to happen here.
fn checkpoint_wal(home: &Path) -> Result<(), String> {
let db = home.join("onionwire.db");
if !db.exists() {
return Ok(());
}
let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
let (busy, log, checkpointed): (i64, i64, i64) = conn
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.map_err(|e| {
let msg = e.to_string();
if msg.contains("not a database") {
// SQLCipher store: no key here, so this connection sees noise.
format!("store is SQLCipher-encrypted — skipped ({msg})")
} else {
format!("wal_checkpoint: {msg}")
}
})?;
if busy != 0 {
// Another connection is reading/writing: pages are still safe in the
// WAL, they just were not moved this time.
return Err(format!(
"busy ({checkpointed}/{log} pages moved, another connection active)"
));
}
Ok(())
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")
@ -899,3 +1121,57 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
}
false
}
#[cfg(test)]
mod lifecycle_tests {
//! Offline half of the shutdown contract. The live-Tor half lives in
//! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI.
use super::*;
/// `checkpoint_wal` reaches the database through a *second* connection,
/// because `Store` owns the write one. That assumption is the whole reason
/// the helper can live in `node.rs`, so prove it against a real WAL.
#[test]
fn checkpoint_wal_truncates_a_live_wal() {
let root = tempfile::tempdir().expect("tempdir");
let home = root.path();
let db = home.join("onionwire.db");
let conn = rusqlite::Connection::open(&db).expect("open db");
let mode: String = conn
.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
.expect("wal mode");
assert_eq!(mode.to_lowercase(), "wal");
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
.expect("create table");
for _ in 0..64 {
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]])
.expect("insert");
}
let wal = home.join("onionwire.db-wal");
let before = std::fs::metadata(&wal).expect("wal file").len();
assert!(before > 0, "expected pending WAL frames, got {before}");
checkpoint_wal(home).expect("checkpoint");
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
// The rows are still there — a checkpoint moves pages, it never drops
// committed data.
let n: i64 = conn
.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
.expect("count");
assert_eq!(n, 64);
}
/// A home directory with no store yet is not an error: `shutdown` and
/// `flush` are safe to call on a node whose db was never created (tests,
/// wiped installs).
#[test]
fn checkpoint_wal_is_a_no_op_without_a_database() {
let root = tempfile::tempdir().expect("tempdir");
checkpoint_wal(root.path()).expect("no db, no error");
}
}

View file

@ -1,4 +1,5 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
check_fields(display_name, bio, xmr_addr)
}
/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to
/// build a `SigningKey`.
///
/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature);
/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather
/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes`
/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it
/// used to make.
pub fn signing_key_bytes(identity_sk: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
if identity_sk.len() != 32 {
return Err(Error("identity secret key must be 32 bytes".into()));
}
let mut bytes = Zeroizing::new([0u8; 32]);
bytes[..].copy_from_slice(identity_sk);
Ok(bytes)
}
pub fn sign(
identity_sk: &[u8],
display_name: &str,
@ -38,9 +56,7 @@ pub fn sign(
ts: i64,
) -> Result<Profile> {
check_fields(display_name, bio, xmr_addr)?;
let sk_bytes: [u8; 32] = identity_sk
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
let sk_bytes = signing_key_bytes(identity_sk)?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk
.sign(&sign_msg_v2(display_name, bio, xmr_addr, ts))

View file

@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::io::{self, IsTerminal};
use std::sync::{Arc, mpsc};
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
@ -8,11 +9,13 @@ use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::border;
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{DefaultTerminal, Frame};
use zeroize::{Zeroize, Zeroizing};
use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile};
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -116,6 +119,202 @@ pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends"
}
// ---------------------------------------------------------------------------
// Delivery state (outbox)
//
// The outbox is the only source of per-message state: `Queued` / `Sending` /
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
// deleted the moment the send crosses the circuit — so an outbound message with
// no row is `Sent`. No parallel state model, no new wire prefix.
// ---------------------------------------------------------------------------
/// Longest short-form failure reason shown in a chat row.
pub const FAIL_REASON_BUDGET: usize = 24;
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
/// word, so their glyph is dropped rather than invented.
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
let ascii = ascii_chrome();
match status {
OutboxStatus::Sent => {
if ascii {
"ok"
} else {
"✓"
}
}
OutboxStatus::Queued => {
if ascii {
""
} else {
"◷"
}
}
OutboxStatus::Sending => {
if ascii {
""
} else {
"»"
}
}
OutboxStatus::Failed(_) => {
if ascii {
""
} else {
"✗"
}
}
}
}
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
/// outbox stores.
pub fn retry_in_text(next_in_secs: i64) -> String {
if next_in_secs <= 0 {
"retry now".to_string()
} else if next_in_secs < 60 {
format!("retry {next_in_secs}s")
} else {
format!("retry {}m", (next_in_secs + 59) / 60)
}
}
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
/// capped at `budget` cells so one peer's error cannot blow out the row.
pub fn short_send_reason(why: &str, budget: usize) -> String {
let clean = sanitize::display_text(why.as_bytes());
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
let text = if tail.is_empty() { clean.trim() } else { tail };
truncate_chars(text, budget)
}
/// One row's delivery marker, straight from the outbox state.
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
let glyph = delivery_glyph(status);
let body = match status {
OutboxStatus::Sent => String::new(),
OutboxStatus::Queued => format!(
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
retry_in_text(next_in_secs)
),
OutboxStatus::Sending => "sending".to_string(),
OutboxStatus::Failed(why) => {
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
}
};
match (glyph.is_empty(), body.is_empty()) {
(_, true) => glyph.to_string(),
(true, false) => body,
(false, false) => format!("{glyph} {body}"),
}
}
/// Footer summary derived from the outbox rows of the selected friend.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct OutboxSummary {
/// `Queued` + `Sending`: rows the worker may still deliver.
pub queued: usize,
/// Terminal failures — these never retry.
pub failed: usize,
/// First terminal failure, for the fail-closed footer copy.
pub first_error: Option<String>,
}
impl OutboxSummary {
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
/// keeps a `send failed` statement so the fail-closed copy stays visible.
pub fn note(&self) -> Option<String> {
let reason = || {
short_send_reason(
self.first_error.as_deref().unwrap_or("unknown"),
FAIL_REASON_BUDGET,
)
};
match (self.queued, self.failed) {
(0, 0) => None,
(queued, 0) => Some(format!("{queued} queued")),
(0, 1) => Some(format!("send failed: {}", reason())),
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
}
}
}
/// Chat transcript with per-message delivery state, plus the footer summary.
///
/// Pending rows are matched to messages by body, newest send first: an
/// outstanding retry is the most recent send of that text, and the outbox holds
/// no message id the UI could join on.
pub fn chat_with_delivery(
msgs: &[Message],
pending: &[OutboxEntry],
now: i64,
) -> (Vec<String>, OutboxSummary) {
let mut summary = OutboxSummary::default();
for entry in pending {
match &entry.status {
OutboxStatus::Failed(why) => {
summary.failed += 1;
summary.first_error.get_or_insert_with(|| why.clone());
}
_ => summary.queued += 1,
}
}
if msgs.is_empty() {
return (
empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
summary,
);
}
let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new();
for entry in pending {
by_body
.entry(entry.body.as_slice())
.or_default()
.push(entry);
}
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate().rev() {
if msg.dir != "out" {
continue;
}
if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice())
&& let Some(entry) = rows.pop()
{
tags[i] = Some(delivery_tag(
&entry.status,
entry.attempts,
entry.next_attempt_at - now,
));
}
}
let lines = msgs
.iter()
.enumerate()
.map(|(i, msg)| {
let side = if msg.dir == "out" { "you" } else { "them" };
let body = sanitize::display_text(&msg.plaintext);
let tag = match tags[i].clone() {
Some(tag) => tag,
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
None => String::new(),
};
if tag.is_empty() {
format!("{side}: {body}")
} else {
format!("{side}: {body} {tag}")
}
})
.collect();
(lines, summary)
}
/// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err {
@ -761,6 +960,78 @@ impl BackupPrompt {
}
}
/// The in-progress passphrase on the backup/restore screen: the hidden buffer
/// plus the first entry, kept across the second prompt of the backup flow.
///
/// Both are `Zeroizing<String>`, so the passphrase does not sit in a plain
/// heap `String` for the life of the screen; `close()` wipes eagerly on every
/// exit path (submit, mismatch, cancel) instead of waiting for the screen
/// value to be dropped, and the wrapper covers the paths that cannot call it
/// (Ctrl-Q, a panic).
pub struct PassphraseEntry {
first: Option<Zeroizing<String>>,
buf: Zeroizing<String>,
}
impl Default for PassphraseEntry {
fn default() -> Self {
Self {
first: None,
buf: Zeroizing::new(String::new()),
}
}
}
impl PassphraseEntry {
pub fn new() -> Self {
Self::default()
}
/// Second prompt of the backup flow: the first passphrase was already typed.
pub fn with_first(first: &str) -> Self {
Self {
first: Some(Zeroizing::new(first.to_string())),
..Self::default()
}
}
pub fn push(&mut self, c: char) {
self.buf.push(c);
}
pub fn backspace(&mut self) {
self.buf.pop();
}
/// What the screen echoes back — the passphrase itself is not drawn.
pub fn buf(&self) -> &str {
self.buf.as_str()
}
pub fn first(&self) -> Option<&str> {
self.first.as_deref().map(String::as_str)
}
/// Take the typed passphrase for submission, leaving this entry empty.
pub fn take_buf(&mut self) -> Zeroizing<String> {
std::mem::replace(&mut self.buf, Zeroizing::new(String::new()))
}
/// Take the first-passphrase copy for the confirm comparison.
pub fn take_first(&mut self) -> Option<Zeroizing<String>> {
self.first.take()
}
/// Wipe both buffers: the screen is done with them.
pub fn close(&mut self) {
self.buf.zeroize();
if let Some(first) = self.first.as_mut() {
first.zeroize();
}
self.first = None;
}
}
pub fn backup_screen_text() -> &'static str {
"Write encrypted identity backup?\n\
This file is your identity secret. Treat it like the database.\n\
@ -840,8 +1111,7 @@ enum Screen {
Passphrase {
kind: BackupKind,
path: String,
first: Option<String>,
buf: String,
entry: PassphraseEntry,
},
Quit {
prompt: QuitPrompt,
@ -929,6 +1199,7 @@ impl App {
let mut tip_cmd = None;
let mut file_cmd = None;
let mut chat_send = None;
let mut pass_submit = None;
match &mut self.screen {
Screen::Main => match key.code {
KeyCode::Tab => self.focus = self.focus.next(),
@ -1090,8 +1361,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.clone(),
first: None,
buf: String::new(),
entry: PassphraseEntry::new(),
};
}
}
@ -1101,25 +1371,17 @@ impl App {
_ => {}
}
}
Screen::Passphrase {
kind,
path,
first,
buf,
} => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Backspace => {
buf.pop();
Screen::Passphrase { kind, path, entry } => match key.code {
KeyCode::Esc => {
entry.close();
self.screen = Screen::Main;
}
KeyCode::Backspace => entry.backspace(),
KeyCode::Enter => {
let kind = *kind;
let path = path.clone();
let first = first.clone();
let pass = buf.clone();
self.submit_passphrase(kind, &path, first.as_deref(), &pass)?;
pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf()));
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c);
entry.push(c);
}
_ => {}
},
@ -1166,6 +1428,9 @@ impl App {
if let Some(text) = chat_send {
self.send_chat(&text)?;
}
if let Some((kind, path, first, pass)) = pass_submit {
self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?;
}
Ok(None)
}
@ -1279,8 +1544,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.to_string(),
first: Some(pass.to_string()),
buf: String::new(),
entry: PassphraseEntry::with_first(pass),
};
}
}
@ -1449,11 +1713,13 @@ impl App {
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move {
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
// footer is a follow-up card, so this arm keeps today's wording.
// `send()` reports `Sent` when the circuit took it and `Queued` when
// the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
let note = match node.send(&pk, &body).await {
Ok(_) => "sent".to_string(),
Err(e) => format!("send failed: {e}"),
Ok(OutboxStatus::Sent) => "sent".to_string(),
Ok(_) => "queued".to_string(),
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
};
let _ = tx.send(note);
}));
@ -1487,9 +1753,9 @@ impl App {
Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()),
Screen::Profile { editor } => draw_profile(f, editor),
Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()),
Screen::Passphrase {
kind, first, buf, ..
} => draw_passphrase(f, *kind, first.is_some(), buf),
Screen::Passphrase { kind, entry, .. } => {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
}
if self.help_open {
@ -1563,38 +1829,22 @@ impl App {
}
f.render_stateful_widget(roster, panes[0], &mut roster_state);
let chat_lines = self.chat_lines();
let inner_h = panes[1].height.saturating_sub(2);
let nlines = chat_lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = self.chat_scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let chat_title = {
let name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
let mut t = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if self.focus == Pane::Chat { "> " } else { " " };
format!("{mark}{t}")
};
let chat_text = chat_lines.join("\n");
let chat = Paragraph::new(chat_text)
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(self.pane_block(&chat_title, Pane::Chat));
f.render_widget(chat, panes[1]);
let (chat_lines, summary) = self.chat_view();
let chat_name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
draw_chat(
f,
panes[1],
&chat_lines,
chat_name.as_deref(),
self.focus == Pane::Chat,
self.chat_scroll,
);
let mark = if self.focus == Pane::Composer {
"> "
@ -1618,62 +1868,108 @@ impl App {
cols[3],
);
let footer = self.footer_line(area.width);
let footer = self.footer_line(area.width, &summary);
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
}
fn footer_line(&self, width: u16) -> String {
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
// The outbox is the source of truth while anything is outstanding; the
// transient note still covers "sending", "sent file x", "invoice sent".
let note = summary.note().or_else(|| self.status_note.clone());
status_footer(
width,
&self.me_fp,
&self.me_onion,
self.status_note.as_deref(),
note.as_deref(),
footer_hints(&self.screen),
)
}
fn chat_lines(&self) -> Vec<String> {
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
let Some(friend) = self.friends.get(self.selected) else {
return vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
];
return (
vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
],
OutboxSummary::default(),
);
};
match self.node.list_messages(&friend.pubkey) {
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
Ok(msgs) => msgs
.iter()
.map(|m| {
let side = if m.dir == "out" { "you" } else { "them" };
format!("{side}: {}", sanitize::display_text(&m.plaintext))
})
.collect(),
Err(e) => vec![e],
Ok(msgs) => {
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
chat_with_delivery(&msgs, &pending, unix_now_secs())
}
Err(e) => (vec![e], OutboxSummary::default()),
}
}
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
let focused = self.focus == pane;
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
pane_block_for(title, self.focus == pane)
}
}
/// Pane chrome without an `App`: focus is accent border + bold title, never
/// color alone (the `> ` marks come from the callers).
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
}
fn unix_now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
/// delivery-marker behaviour are testable without constructing a `Node`.
pub fn draw_chat(
f: &mut Frame,
area: Rect,
lines: &[String],
name: Option<&str>,
focused: bool,
scroll: u16,
) {
let inner_h = area.height.saturating_sub(2);
let nlines = lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let mut title = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if focused { "> " } else { " " };
let title = format!("{mark}{title}");
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(pane_block_for(&title, focused)),
area,
);
}
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
pub fn status_footer(
width: u16,
@ -1689,7 +1985,7 @@ pub fn status_footer(
let mut note = status_note.unwrap_or("").trim().to_string();
if !note.is_empty()
&& color_mode() == ColorMode::None
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
&& (note.contains("send failed") || note == "fingerprint mismatch")
&& !note.starts_with("! ")
{
note = format!("! {note}");
@ -2017,3 +2313,66 @@ fn to_hex(bytes: &[u8]) -> String {
fn io_err(e: io::Error) -> String {
e.to_string()
}
#[cfg(test)]
mod passphrase_buffer_tests {
use super::*;
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
/// The typed passphrase lives in `Zeroizing` buffers, not in bare
/// `String`s that sit in the heap for the life of the screen.
#[test]
fn passphrase_buffers_are_zeroizing() {
let mut entry = PassphraseEntry::new();
entry.push('x');
let _: &Zeroizing<String> = &entry.buf;
let _: &Option<Zeroizing<String>> = &entry.first;
assert_zeroize_on_drop::<Zeroizing<String>>();
}
/// Closing the screen (submit, mismatch or cancel) must leave nothing of
/// the typed passphrase behind in its heap buffer.
#[test]
fn closing_the_passphrase_screen_wipes_the_typed_secret() {
let mut entry = PassphraseEntry::new();
for c in "hunter2-secret".chars() {
entry.push(c);
}
assert_eq!(entry.buf(), "hunter2-secret");
let ptr = entry.buf.as_ptr();
let cap = entry.buf.capacity();
assert!(cap >= 14, "expected a heap buffer, capacity {cap}");
entry.close();
assert!(entry.buf().is_empty(), "buffer not cleared");
// SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole
// capacity and *keeps* the allocation (`Vec::zeroize`: zero the
// elements, clear the length, zero the spare capacity). `entry` still
// owns that buffer, so these `cap` bytes are live memory.
let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) };
assert!(
bytes.iter().all(|b| *b == 0),
"typed passphrase survived close(): {bytes:?}"
);
}
/// The first entry of the two-step backup flow is a secret too, and the
/// screen holds it across the second prompt.
#[test]
fn closing_the_passphrase_screen_drops_the_first_entry_copy() {
let mut entry = PassphraseEntry::with_first("first-typed");
assert_eq!(entry.first(), Some("first-typed"));
entry.close();
assert_eq!(
entry.first(),
None,
"first passphrase copy survived close()"
);
}
}

View file

@ -42,8 +42,18 @@ impl std::fmt::Debug for Endpoint {
#[derive(Debug, Clone)]
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
}
/// What /tip says when the wallet cannot spend. Same text for the explicit
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
/// RPC, so the operator never has to guess which one it was.
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE: i64 = -29;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRow {
pub txid: String,
@ -55,10 +65,17 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5);
impl Wallet {
pub fn disabled() -> Self {
Self { endpoint: None }
Self {
endpoint: None,
no_spend: false,
}
}
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
/// refused locally, before any RPC dial. `/pay` and receipt verification
/// keep working.
pub fn from_env() -> Self {
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
match std::env::var("ONIONWIRE_WALLET_RPC") {
// The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`.
@ -71,23 +88,41 @@ impl Wallet {
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
Ok(endpoint) => Self {
endpoint: Some(endpoint),
no_spend,
},
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self::disabled()
Self {
endpoint: None,
no_spend,
}
}
}
}
_ => Self::disabled(),
_ => Self {
endpoint: None,
no_spend,
},
}
}
pub fn from_url(url: &str) -> Result<Self> {
Ok(Self {
endpoint: Some(parse_http_url(url, None)?),
no_spend: false,
})
}
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
pub fn with_no_spend(mut self, on: bool) -> Self {
self.no_spend = on;
self
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn configured(&self) -> bool {
self.endpoint.is_some()
}
@ -107,7 +142,10 @@ impl Wallet {
}
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
let v = self
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
let sent = self
.rpc(
"transfer",
serde_json::json!({
@ -115,10 +153,36 @@ impl Wallet {
"account_index": 0
}),
)
.await?;
.await;
let v = match sent {
Ok(v) => v,
// The wallet's own refusal is opaque, so ask the documented
// pre-transfer signal before surfacing it. Fail closed: if the
// probe cannot answer, the original error stands.
Err(e) => {
if self.view_only().await {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(e);
}
};
json_str(&v, "tx_hash")
}
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
/// the signal monero actually exposes for a wallet with no spend key.
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
}
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
.rpc(
@ -189,6 +253,17 @@ fn credentials_required() -> Error {
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
}
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
/// unset) means off.
fn env_flag(name: &str) -> bool {
matches!(
std::env::var(name)
.map(|v| v.trim().to_ascii_lowercase())
.as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
if user.is_empty() || pass.is_empty() {
@ -455,6 +530,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("rpc error");
// The one RPC-level error we translate: a view-only wallet has no
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(Error(msg.into()));
}
json.get("result")

View file

@ -69,6 +69,101 @@ fn broken_or_shutdown_never_ready() {
assert!(!hs::hs_is_ready(State::Shutdown, true));
}
#[test]
fn tor_state_maps_every_arti_status() {
// The four states the Android UI branches on, derived from the same status
// union `hs_is_ready` reads.
assert_eq!(
hs::tor_state_of(State::Running, false, false),
hs::TorState::Published
);
assert_eq!(
hs::tor_state_of(State::DegradedReachable, false, false),
hs::TorState::DegradedReachable
);
assert_eq!(
hs::tor_state_of(State::Bootstrapping, false, false),
hs::TorState::Bootstrapping
);
assert_eq!(
hs::tor_state_of(State::DegradedUnreachable, false, false),
hs::TorState::Bootstrapping
);
// A freshly launched service reports Shutdown before its publish reactor
// starts. Mapping that to Stopped would make a live node look dead for the
// first seconds after unlock — caught on a real Tor network.
assert_eq!(
hs::tor_state_of(State::Shutdown, false, false),
hs::TorState::Bootstrapping
);
// Arti reads `Broken` while the HsDir retry loop is still going; a dead
// service surfaces as an error from `wait_until_published`, not as a state
// the UI has to poll for.
assert_eq!(
hs::tor_state_of(State::Broken, false, false),
hs::TorState::Bootstrapping
);
}
#[test]
fn reachable_statuses_report_published_while_arti_says_bootstrapping() {
// `wait_until_published` returns on a successful probe while Arti's
// combined status is still Bootstrapping (see `hs_is_ready`). Reporting
// Bootstrapping there would keep the UI saying "starting" for minutes after
// friends can actually reach us.
assert_eq!(
hs::tor_state_of(State::Bootstrapping, false, true),
hs::TorState::Published
);
assert_eq!(
hs::tor_state_of(State::DegradedUnreachable, false, true),
hs::TorState::Published
);
// Broken stays Broken, reachable or not: `hs_is_ready` refuses it too.
assert_eq!(
hs::tor_state_of(State::Broken, false, true),
hs::TorState::Bootstrapping
);
}
#[test]
fn stopped_outranks_whatever_arti_reports() {
// A node that has been told to stop is Stopped even if Arti's status cache
// still says Running, and even if it was reachable a moment ago: the flag
// is set before the service is dropped.
for state in [
State::Running,
State::DegradedReachable,
State::DegradedUnreachable,
State::Bootstrapping,
State::Broken,
State::Shutdown,
] {
for reachable in [false, true] {
assert_eq!(
hs::tor_state_of(state, true, reachable),
hs::TorState::Stopped,
"wrong state for {state:?} (reachable={reachable}) on a stopped node"
);
}
}
}
#[test]
fn ready_states_are_the_published_ones() {
// Published/degraded must not drift from the readiness bar: anything
// `hs_is_ready` accepts without a probe is a state the UI calls up.
let ready = [State::Running, State::DegradedReachable];
for state in ready {
assert!(hs::hs_is_ready(state, false), "{state:?} must be ready");
assert_ne!(
hs::tor_state_of(state, false, false),
hs::TorState::Bootstrapping,
"{state:?} is ready but reported as still coming up"
);
}
}
#[test]
fn hs_log_label_is_not_the_full_v3_onion() {
// Public v3 address; checksum is valid so HsId::from_str works.

96
tests/tor_lifecycle.rs Normal file
View file

@ -0,0 +1,96 @@
//! Lifecycle: a node stops when told to, says so, and refuses further work
//! with an error instead of panicking.
//!
//! Needs a live Tor network to publish the onion service, so `cargo test` skips
//! it. Run it on a networked machine with:
//!
//! ```text
//! cargo test --test tor_lifecycle -- --ignored --nocapture
//! ```
//!
//! The offline half of this contract — the Arti-status projection, the WAL
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal
//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`).
use onionwire::node::{FlushOutcome, Node};
use onionwire::hs::TorState;
#[tokio::test(flavor = "multi_thread")]
#[ignore = "needs live Tor network"]
async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() {
let _ = tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
)
.with_test_writer()
.try_init();
let root = tempfile::tempdir().expect("tempdir");
let home = root.path().join("alice");
unsafe {
std::env::set_var("ONIONWIRE_STORE_PASSPHRASE", "onionwire-test");
}
let node = Node::start(home.clone()).await.expect("start");
// `start` returns only after `wait_until_published`, so the node is
// reachable by the time a caller can call this — which must not read as
// `Stopped` or `Bootstrapping`. `DegradedReachable` is the honest answer
// when Arti says the service is degraded.
//
// This caught a real bug: `tor_state()` originally projected Arti's raw
// combined status, which is still `Bootstrapping` after a *successful*
// probe (that mismatch is what the 360s publish wait exists for), and which
// reads `Shutdown` on a service that has not started its reactor yet — so a
// live node reported `Stopped`. See `onion_reachable` in `src/node.rs`.
let started_state = node.tor_state();
assert!(
matches!(
started_state,
TorState::Published | TorState::DegradedReachable
),
"start returned Ok but tor_state() is {started_state:?}"
);
// A flush with nothing queued is a no-op that reports it, not an error.
let drained: FlushOutcome = node.flush().await.expect("flush on a live node");
assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}");
node.shutdown().await.expect("shutdown");
assert_eq!(
node.tor_state(),
TorState::Stopped,
"tor_state must report Stopped after shutdown"
);
// Second shutdown: idempotent at the node level — no panic, no repeat work.
node.shutdown().await.expect("shutdown is idempotent");
let err = node
.flush()
.await
.expect_err("flush after shutdown must be an error");
assert!(err.contains("stopped"), "flush error was {err:?}");
let err = node
.send(&[0u8; 32], b"after shutdown")
.await
.expect_err("send after shutdown must be an error");
assert!(err.contains("stopped"), "send error was {err:?}");
// `RotateResult` is not `Debug`, so match on the error instead of
// `expect_err`.
let err = node
.rotate()
.await
.err()
.expect("rotate after shutdown must be an error");
assert!(err.contains("stopped"), "rotate error was {err:?}");
// The store file survives the checkpoint: stopping is not wiping.
assert!(
home.join("onionwire.db").exists(),
"shutdown must not delete the store"
);
}

View file

@ -1,10 +1,13 @@
//! Spec implementation tests for docs/TUI.md (this card).
//! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::Message;
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::tui::{
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text,
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width,
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
status_footer, wrap_invite,
};
use ratatui::Frame;
@ -376,3 +379,376 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
println!("===== AFTER ascii share 80x24 =====\n{screen}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
// ---------------------------------------------------------------------------
// Outbox delivery state (card t_d9a5b065)
//
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
// prefix, no parallel state model.
// ---------------------------------------------------------------------------
fn out_msg(body: &str) -> Message {
Message {
dir: "out".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn in_msg(body: &str) -> Message {
Message {
dir: "in".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn pending_row(
body: &str,
status: OutboxStatus,
attempts: u32,
next_in: i64,
now: i64,
) -> OutboxEntry {
OutboxEntry {
id: 1,
friend_pk: vec![9u8; 32],
message_id: 1,
body: body.as_bytes().to_vec(),
attempts,
next_attempt_at: now + next_in,
created_at: now,
status,
last_error: None,
}
}
fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
pending_row(body, OutboxStatus::Queued, attempts, next_in, now)
}
fn sending_row(body: &str, now: i64) -> OutboxEntry {
pending_row(body, OutboxStatus::Sending, 1, 0, now)
}
fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry {
pending_row(body, OutboxStatus::Failed(why.into()), 8, 0, now)
}
/// Marker is everything after the two-space separator the render helper uses.
fn marker_of(line: &str) -> &str {
line.rsplit(" ").next().unwrap_or("")
}
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
fn force_unicode_mode() {
unsafe {
std::env::remove_var("ONIONWIRE_ASCII");
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn queued_and_delivered_messages_render_different_markers() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg("ping"), out_msg("pong")];
let pending = vec![queued_row("pong", 2, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('✓'),
"delivered row lost its mark: {:?}",
lines[0]
);
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
assert!(
lines[1].contains('◷'),
"queued row lost its glyph: {:?}",
lines[1]
);
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
assert!(
lines[1].contains("try 2/8"),
"attempt count missing: {:?}",
lines[1]
);
assert!(
lines[1].contains("retry 45s"),
"retry age missing: {:?}",
lines[1]
);
assert_ne!(
marker_of(&lines[0]),
marker_of(&lines[1]),
"queued and delivered must not share a marker"
);
assert_eq!(summary.queued, 1);
assert_eq!(summary.failed, 0);
}
#[test]
fn delivery_markers_have_exercised_ascii_fallbacks() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe {
std::env::set_var("ONIONWIRE_ASCII", "1");
std::env::remove_var("NO_COLOR");
}
let now = 500;
let msgs = vec![
out_msg("alpha"),
out_msg("beta"),
out_msg("gamma"),
out_msg("delta"),
in_msg("epsilon"),
];
let pending = vec![
failed_row("alpha", "connect peer.onion:80: connection timed out", now),
queued_row("beta", 1, 30, now),
sending_row("gamma", now),
];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in &lines {
assert!(
line.is_ascii(),
"ASCII fallback missing, non-ASCII in {line:?}"
);
}
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
assert_eq!(marker_of(&lines[2]), "sending");
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
assert_eq!(summary.failed, 1);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn retry_age_and_failure_reason_are_short_forms() {
assert_eq!(retry_in_text(45), "retry 45s");
assert_eq!(retry_in_text(59), "retry 59s");
assert_eq!(retry_in_text(60), "retry 1m");
assert_eq!(retry_in_text(720), "retry 12m");
assert_eq!(retry_in_text(0), "retry now");
assert_eq!(retry_in_text(-30), "retry now");
assert_eq!(
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
"connection timed out"
);
let long = short_send_reason("a-really-long-failure-description-here", 12);
assert!(long.chars().count() <= 12, "{long:?}");
assert!(
long.contains('…') || long.contains("..."),
"truncation marker missing: {long:?}"
);
assert_eq!(short_send_reason("nope", 24), "nope");
}
#[test]
fn delivery_tag_reads_the_outbox_status_enum() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
assert_eq!(
delivery_tag(&OutboxStatus::Queued, 3, 120),
"◷ queued (try 3/8, retry 2m)"
);
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
assert_eq!(
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
"✗ failed: nope"
);
}
#[test]
fn footer_summary_counts_queued_and_keeps_fail_closed() {
let none = OutboxSummary::default();
assert_eq!(none.note(), None);
let queued = OutboxSummary {
queued: 2,
failed: 0,
first_error: None,
};
assert_eq!(queued.note().as_deref(), Some("2 queued"));
let failed = OutboxSummary {
queued: 0,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let note = failed.note().expect("failed rows must produce a note");
assert!(note.starts_with("send failed:"), "{note:?}");
assert!(note.contains("connection timed out"), "{note:?}");
let mixed = OutboxSummary {
queued: 3,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let mixed_note = mixed.note().expect("mixed rows must produce a note");
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
// Fail-closed copy stays visible in the real footer at the 80-col floor.
let line = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(
line.chars().count() <= 80,
"{} {line:?}",
line.chars().count()
);
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
assert!(queued_line.chars().count() <= 80);
// `! ` ornament (colour off) still lands on the derived failing note.
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let no_color = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(no_color.contains("! send failed"), "{no_color:?}");
unsafe { std::env::remove_var("NO_COLOR") };
}
/// The card's width criterion: draw the real helpers at the documented floor
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
/// that an over-long row wraps in the pane instead of being clipped.
#[test]
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
let msgs = vec![out_msg("ok"), in_msg("pong"), out_msg(long)];
let pending = vec![queued_row(long, 3, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in lines.iter().take(2) {
assert!(
line.chars().count() <= 80,
"short row wider than 80: {} {line:?}",
line.chars().count()
);
}
let footer = status_footer(
80,
FP,
ONION,
summary.note().as_deref(),
main_footer_hints(),
);
assert!(footer.chars().count() <= 80, "{footer:?}");
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
let area = f.area();
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
})
.expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..24u16 {
for x in 0..80u16 {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
for (y, row) in screen.lines().enumerate() {
assert!(
row.chars().count() <= 80,
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
row.chars().count()
);
}
assert!(
screen.contains('◷'),
"queued glyph missing from frame:\n{screen}"
);
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
assert!(
screen.contains("with the roster border"),
"long row was clipped, not wrapped:\n{screen}"
);
assert!(
screen.contains("1 queued"),
"footer summary missing:\n{screen}"
);
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
}
/// The renderer consumes the real outbox API, not a hand-written fixture: a
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
/// the chat line and the footer note are built from.
#[tokio::test]
async fn renders_a_queued_row_from_a_real_outbox_send() {
use onionwire::Store;
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
use std::sync::Arc;
struct Dead;
impl Deliverer for Dead {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
}
}
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
let pk = [1u8; 32];
store
.upsert_friend(&pk, "dead.onion", None)
.expect("friend");
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
let store = Arc::new(std::sync::Mutex::new(store));
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
assert_eq!(
outbox.send(&pk, b"queued for a dead peer").await,
Ok(OutboxStatus::Queued)
);
let pending = outbox.pending(&pk).expect("pending rows");
assert_eq!(pending.len(), 1, "one queued row");
let msgs = store
.lock()
.expect("store lock")
.list_messages(&pk)
.expect("messages");
let now = pending[0].next_attempt_at - 45;
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert_eq!(lines.len(), 1);
assert!(
lines[0].contains("queued (try 1/8, retry 45s)"),
"real outbox row did not render: {:?}",
lines[0]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
// And once a send crosses the circuit the row is gone, so the same message
// renders as delivered.
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}

View file

@ -1,5 +1,7 @@
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
use std::sync::{Arc, Mutex};
use ed25519_dalek::SigningKey;
use onionwire::pay;
use onionwire::wallet::{self, TransferRow, Wallet};
@ -8,6 +10,10 @@ use rand::rngs::OsRng;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
TransferRow {
txid: txid.into(),
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() {
);
}
/// Records every request the client sends, answers the Digest challenge and
/// then replies per RPC method. Lets a test assert on the *request log*.
async fn serve_recording(
listener: TcpListener,
log: Arc<Mutex<Vec<String>>>,
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
) {
loop {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
log.lock().expect("log").push(req.clone());
if req.contains("Authorization:") {
let body = reply(&rpc_method(&req));
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
} else {
let _ = sock.write_all(digest_401().as_bytes()).await;
}
}
}
fn rpc_method(req: &str) -> String {
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
serde_json::from_str::<serde_json::Value>(body.trim())
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.unwrap_or_default()
}
fn http_200_body(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn rpc_error(code: i64, message: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
}
/// JSON-RPC body only (the server wraps it in an HTTP 200).
fn rpc_result(result: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
}
fn recording_wallet(port: u16) -> Wallet {
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
}
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
/// local `transfer` before any socket is opened.
#[tokio::test]
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
));
let w = recording_wallet(port).with_no_spend(true);
assert!(w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(
err.to_ascii_lowercase().contains("view-only"),
"got {err}"
);
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let seen = log.lock().expect("log").clone();
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
// Positive control: the recorder is live, so the emptiness above is real.
let _ = w.get_address().await;
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
}
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
/// with the no-spend flag on — only `transfer` is refused.
#[tokio::test]
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|method| match method {
"create_address" => rpc_result(
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
),
"get_transfers" => rpc_result(
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port).with_no_spend(true);
let created = w.create_address().await.expect("create_address");
assert!(created.starts_with('8'), "got {created}");
let rows = w.get_transfers().await.expect("get_transfers");
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
let seen = log.lock().expect("log").clone();
assert!(
seen.iter()
.any(|r| r.contains("\"method\":\"create_address\"")),
"recorder must have seen the invoice path: {seen:?}"
);
assert!(
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
"transfer must never be dialed in no-spend mode"
);
}
/// A view-only wallet refuses `transfer` with its own opaque error. The
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
#[tokio::test]
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|method| match method {
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
_ => rpc_error(-18, "No transaction created"),
}),
));
let w = recording_wallet(port);
assert!(!w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
let seen = log.lock().expect("log").clone();
assert!(
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
"must ask the RPC-side signal: {seen:?}"
);
}
/// A spend-capable wallet must keep its real error: no fabricated detection.
#[tokio::test]
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method| match method {
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
_ => rpc_error(-18, "No transaction created"),
}),
));
let err = recording_wallet(port)
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("No transaction created"), "got {err}");
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
}
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
#[tokio::test]
async fn open_rpc_without_digest_challenge_is_still_refused() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = http_200_body(
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
);
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(canned.as_bytes()).await;
});
let err = recording_wallet(port)
.get_address()
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
}
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
#[test]
fn from_env_reads_no_spend_flag() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
}
let on = Wallet::from_env();
assert!(on.no_spend(), "flag 1 must mean no-spend");
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
for off in ["0", "no", "off"] {
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
}
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
assert!(!Wallet::from_env().no_spend(), "unset must be off");
}
fn digest_401() -> String {
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
}

View file

@ -5,6 +5,7 @@
//! Noise handshake/transport state that lives inside `snow`.
use onionwire::backup::BackupKeys;
use onionwire::profile;
use onionwire::session::Keys;
use onionwire::wallet::Wallet;
use onionwire::Store;
@ -52,6 +53,20 @@ unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
}
}
/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back.
///
/// SAFETY: only for `ManuallyDrop<Zeroizing<[u8; 32]>>` locals — same contract
/// as `drop_in_place_and_peek_identity_sk`.
unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] {
let p: *const [u8; 32] = &**v;
// SAFETY: the caller guarantees `v` is dropped exactly once and is still
// alive at its own address when read back.
unsafe {
std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>);
std::ptr::read_volatile(p)
}
}
/// Drop behaviour, not a comment: after the value drops, the local secret key
/// material that feeds the Noise IK handshake is gone from its memory.
#[test]
@ -116,3 +131,27 @@ fn wallet_endpoint_debug_redacts_the_rpc_password() {
);
assert!(dbg.contains("<redacted>"), "{dbg}");
}
/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the
/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that
/// stays on the stack until the function returns.
#[test]
fn profile_signing_key_bytes_are_zeroizing_and_wipe() {
let secret = [0x5au8; 32];
let bytes = profile::signing_key_bytes(&secret).expect("32 bytes");
let _: &Zeroizing<[u8; 32]> = &bytes;
assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret");
let mut probe = std::mem::ManuallyDrop::new(bytes);
let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) };
assert_eq!(after, [0u8; 32], "identity secret survived its drop");
}
/// A length-mismatched secret is an error, not a truncated/padded key.
#[test]
fn profile_signing_key_bytes_rejects_a_short_secret() {
assert!(profile::signing_key_bytes(&[7u8; 31]).is_err());
assert!(profile::signing_key_bytes(&[7u8; 33]).is_err());
}