diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index c03ad35..6238005 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -34,8 +34,6 @@ use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus}; use onionwire::pay; use onionwire::qr; -use onionwire::wallet::ChainSource; -use onionwire::wallet_child::ChildConfig; uniffi::setup_scaffolding!(); @@ -597,65 +595,6 @@ impl Wire { .map_err(WireError::new) } - /// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for - /// a local chain source and `arti proxy` for a `.onion` daemon) and point - /// this node's wallet at it, then probe it once and return what it reached. - /// - /// The spawn itself is synchronous inside the node: argv is built, the - /// process is spawned, and a `.onion` source waits up to 20s for the SOCKS - /// listener. Call it off the main thread, like `send_tip`. - /// - /// Idempotent: a live child is reported, not respawned. Fails with - /// `WireError.Failed` when no chain source is configured - /// (`set_chain_source`), when a binary cannot be spawned, or when the SOCKS - /// listener never came up. `WireError.Stopped` after `shutdown`. - /// - /// The returned state is `connecting` at best on the first call — the wallet - /// RPC is not answering the instant the process exists. Report it as it is, - /// and call [`Wire::wallet_status`] (or start again) for the later states. - pub async fn start_wallet_child(&self) -> WResult { - let node = self.node()?; - node.start_wallet_child().map_err(WireError::new)?; - Ok(child_status(node.wallet_child_refresh().await)) - } - - /// Stop the wallet child and its daemon/SOCKS siblings. Idempotent: stopping - /// what is not running is `Ok(())`. The wallet falls back to the stored or - /// env `monero-wallet-rpc` config, if any. - pub fn stop_wallet_child(&self) -> WResult<()> { - self.node()?.stop_wallet_child().map_err(WireError::new) - } - - /// The last observable wallet-child state. Never dials, never spawns: - /// `state` is `off` / `connecting` / `syncing` / `ready` / `exited`, and - /// `ready` is only ever written by a probe that saw a synced chain. - /// - /// Synchronous on purpose — it is safe to call from a UI refresh loop. - pub fn wallet_status(&self) -> WResult { - Ok(child_status(self.node()?.wallet_child_status())) - } - - /// The chain-source + binary settings the child spawns with, as stored. - /// Returns the defaults (receive-only, binaries by name) when nothing was - /// ever set, so a settings screen can prefill from it safely. - pub fn chain_source(&self) -> WResult { - Ok(chain_config(&self.node()?.wallet_child_config())) - } - - /// Set the chain source and the binaries the child runs. Validated before - /// anything is written: a rejected config leaves the stored one untouched - /// and a running child untouched (the change applies on the next start). - /// - /// This is a stored setting, not a start: call [`Wire::start_wallet_child`] - /// after it. `wallet_rpc_bin` / `arti_bin` take absolute paths on Android - /// (`context.applicationInfo.nativeLibraryDir`); the core never resolves a - /// binary the caller named explicitly. - pub fn set_chain_source(&self, config: ChainConfig) -> WResult<()> { - self.node()? - .set_wallet_child_config(&child_config(config)) - .map_err(WireError::new) - } - /// Sign an invoice frame with this node's identity key. /// /// The ed25519 secret stays inside the node: this is the only way the SDK @@ -719,78 +658,6 @@ fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { } } -/// The core child settings a [`ChainConfig`] describes. -fn child_config(cfg: ChainConfig) -> ChildConfig { - let source = match cfg.kind { - ChainChoice::None => ChainSource::None, - ChainChoice::Local => ChainSource::Local { - monerod_bin: PathBuf::from(cfg.monerod_bin), - datadir: PathBuf::from(cfg.monerod_datadir), - }, - ChainChoice::Remote => ChainSource::Remote { - host: cfg.host, - port: cfg.port, - }, - }; - ChildConfig { - source, - wallet_rpc_bin: PathBuf::from(cfg.wallet_rpc_bin), - arti_bin: PathBuf::from(cfg.arti_bin), - wallet_filename: cfg.wallet_filename, - } -} - -/// And back, for the Kotlin prefill. -fn chain_config(cfg: &ChildConfig) -> ChainConfig { - let (kind, host, port, monerod_bin, monerod_datadir) = match &cfg.source { - ChainSource::None => ( - ChainChoice::None, - String::new(), - 0, - String::new(), - String::new(), - ), - ChainSource::Local { - monerod_bin, - datadir, - } => ( - ChainChoice::Local, - String::new(), - 0, - monerod_bin.display().to_string(), - datadir.display().to_string(), - ), - ChainSource::Remote { host, port } => ( - ChainChoice::Remote, - host.clone(), - *port, - String::new(), - String::new(), - ), - }; - ChainConfig { - kind, - monerod_bin, - monerod_datadir, - host, - port, - wallet_rpc_bin: cfg.wallet_rpc_bin.display().to_string(), - arti_bin: cfg.arti_bin.display().to_string(), - wallet_filename: cfg.wallet_filename.clone(), - } -} - -/// The core child snapshot as the SDK record. -fn child_status(status: onionwire::wallet_child::WalletChildStatus) -> WalletChildStatus { - WalletChildStatus { - state: status.state.as_str().to_string(), - running: status.running, - configured: status.configured, - chain_source: status.chain_source, - last_error: status.last_error, - } -} - fn hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2); for b in bytes { @@ -873,67 +740,6 @@ pub struct TransferRow { pub address: String, } -/// Where the app-owned wallet child gets its chain from. Mirrors the core's -/// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied. -#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] -pub enum ChainChoice { - /// Receive-only: no child, no daemon, no spend. - None, - /// The app spawns `monerod` on this device. - Local, - /// A daemon address the user supplied (loopback, `.onion`, or clearnet). - Remote, -} - -/// The wallet-child settings, as the Kotlin side sets them. -/// -/// One record for all three kinds: the fields a kind does not use are ignored -/// by that kind (`None` needs no binaries, `Local` needs `monerod_bin` and -/// `monerod_datadir`, `Remote` needs `host` and `port`). Persisted in the -/// encrypted store, so it survives a restart without env vars. -#[derive(Debug, Clone, uniffi::Record)] -pub struct ChainConfig { - pub kind: ChainChoice, - /// `Local` only. Absolute path on Android (`nativeLibraryDir`); a bare name - /// resolves on `PATH` on desktop. - pub monerod_bin: String, - /// `Local` only. Data directory for the local daemon. - pub monerod_datadir: String, - /// `Remote` only. Daemon host. - pub host: String, - /// `Remote` only. Daemon port. - pub port: u16, - /// `monero-wallet-rpc`. Absolute path on Android, else resolved on `PATH`. - pub wallet_rpc_bin: String, - /// `arti`, run as the SOCKS child for a `.onion` daemon only. - pub arti_bin: String, - /// Wallet file name inside `$ONIONWIRE_HOME/wallet`. - pub wallet_filename: String, -} - -/// One snapshot of the app-owned wallet child. -/// -/// Derived from the real child process plus the last probe, never from env-var -/// presence. `state` is one of `off`, `connecting`, `syncing`, `ready`, -/// `exited`. `chain_source` is the label of the configured source: -/// `receive-only`, `local node`, `remote onion daemon`, or `remote daemon`. -#[derive(Debug, Clone, uniffi::Record)] -pub struct WalletChildStatus { - /// `off` until the child is started and again after it is stopped; `exited` - /// when a started child has died; `connecting` while its wallet RPC has not - /// answered; `syncing` once it has but the chain is behind; `ready` when - /// both hold. `ready` is never reported for a dead child. - pub state: String, - /// A `monero-wallet-rpc` child is alive right now. - pub running: bool, - /// A chain source is configured (anything but receive-only). - pub configured: bool, - /// The chain-source label. - pub chain_source: String, - /// The last failure, display-ready. Never carries the generated login. - pub last_error: Option, -} - /// One signed invoice frame: "pay me `amount_atomic` piconero at `address`". /// /// Mirrors `pay::Invoice`. `sig` is the raw 64-byte ed25519 signature, not hex, diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 52d4506..8b2735c 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -198,17 +198,7 @@ the app does not pick a public remote node for them. - **Loopback** — same privacy as (1); the user owns `monerod`. - **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener the app provides for the wallet child (not the messenger’s Arti - `connect()`, and not a C-tor fallback for chat). That listener is the - bundled `arti` **binary** run as a child (`arti proxy -p `) — a - second, separate Tor client with its own state and cache dirs, because - `arti-client` 0.46 exposes no SOCKS listener API. It is TCP loopback only - (`arti proxy -p` binds `127.0.0.1`/`::1`; arti 2.6.0 / `tor-config` 0.46 - have no Unix-socket listen target — arti#1965), and the port is usable by - any local process at the user's privilege level: it is an app-private port, - not an access-controlled one. The app gates the spawn on the unlocked store - and waits ≤20s for the listener to accept before starting the wallet child, - so a dead proxy fails visibly instead of hanging. The SOCKS child stops - with the wallet child. Tor hides the transport. + `connect()`, and not a C-tor fallback for chat). Tor hides the transport. The daemon operator still sees the wallet’s addresses during sync. The host is the trust boundary. - **Clearnet** — only if the user typed it. Not a default, not implied. @@ -238,11 +228,7 @@ That socket is the app talking to the wallet process, not to the chain. **Chain** traffic is the wallet child’s connection to a Monero daemon. It is off unless the user opted into a wallet and chose a chain source: spawned local `monerod` (loopback), or a daemon address they entered. A `.onion` daemon is -reached through a localhost SOCKS5 proxy used only by that wallet child: the -bundled `arti` binary run as `arti proxy -p `, whose `--proxy` target is -`127.0.0.1` and whose `.onion` name travels inside the SOCKS request (Monero's -SOCKS5 client sends the domain-name form, so no local DNS runs on it). The -messenger's in-process Arti client is never handed to the wallet child. A +reached through a localhost SOCKS5 proxy used only by that wallet child. A clearnet daemon address is an explicit user choice — a clearnet socket they asked for — not the messenger path and not a hidden default. diff --git a/docs/WALLET.md b/docs/WALLET.md index 46a880e..9975bc7 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -10,8 +10,8 @@ receipt checks (`get_transfers`). `/tip` is off. OnionWire a local spend authority for that wallet file — see the spend-authority warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md). -The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, and it can -own that process itself: +The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, whether +that process is one you already run or one the app spawns: - hand out a receive subaddress for `/pay` invoices (`create_address`), - read incoming transfers to verify a peer's receipt (`get_transfers`), @@ -20,281 +20,16 @@ own that process itself: **Prefer view-only until you actually want `/tip`.** Everything else in this document explains why, and what breaks when you do. -## The app-owned wallet child - -`src/wallet_child.rs` owns the child pair instead of asking you to start it and -export an env var: - -- **`monero-wallet-rpc`** is spawned with `--rpc-bind-ip 127.0.0.1`, a **random - free loopback port** (bind `127.0.0.1:0`, read the port, drop the listener, pass - it on — two instances on one box cannot collide), a generated `--rpc-login` - (`user:pass`, random `[a-z0-9]`, no shell or HTTP metacharacters), and - `--wallet-dir $ONIONWIRE_HOME/wallet`. -- **`monerod`** is spawned too when the chain source is *local*: - `--non-interactive --data-dir --rpc-bind-ip 127.0.0.1 --rpc-bind-port - 18081`. One box, one daemon: the wallet child dials it at `127.0.0.1:18081`. -- **`arti`** is spawned as a SOCKS child only when the chain source is a - `.onion` daemon: `arti proxy -p ` (see below). -- `--trusted-daemon` is never passed. A remote daemon stays untrusted. -- The wallet dir is created `0700` and the wallet file is kept `0600` — it is a - spend authority. -- The child is watched by polling (`try_wait`); an exit is reported rather than - hidden, and `stop()` kills both children on shutdown. The next launch starts - them again. Nothing promises "always running", and Android will not. - -### Where the RPC credentials live - -The generated `user:pass` is **sealed with the store data key and kept in the -encrypted SQLCipher store** (`wallet_child` table, AEAD with the store key on top -of whole-db encryption). It is never written to a plaintext file next to the -wallet, and it never appears in `ONIONWIRE_WALLET_RPC`. They persist across -launches, so the child restarts with the same login without asking you again. - -The wallet passphrase is a separate thing: the child prompts/needs it for -`create_wallet` / `restore_deterministic_wallet`, and that is your runtime choice, -not something the app stores for you. - -## Chain source - -The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire -does not pick a public remote node for you. The three shapes are: - -``` -ChainSource::None receive-only; no child, no daemon -ChainSource::Local { monerod_bin, datadir } the app spawns monerod on this box -ChainSource::Remote { host, port } a daemon address you typed -``` - -1. **Local `monerod`.** Chain traffic stays on the box. You accept disk, first - sync, and (on Android) the daemon not always running. -2. **A daemon address you supply** — becomes `--daemon-address` on the wallet - child. Loopback if you already run `monerod`. `.onion` if you want chain - traffic over Tor (see *Chain traffic over Tor* below). Clearnet only if you - type it — your ISP sees Monero-node traffic; it is never a default. - -The port is a convention, not a constant: restricted RPC on `18089` is common, -but you supply it. - -### Chain traffic over Tor (`.onion` daemons) - -A `.onion` daemon cannot be dialled directly, and OnionWire does not fall back -to a clearnet resolve. The wallet child is an external C++ binary, so it reaches -Tor the only way it can: through a SOCKS proxy the app provides. - -- The app runs the **bundled `arti` binary** as a child: - `arti proxy -p `. `arti-client` 0.46 has no SOCKS - listener API — the SOCKS listener lives in the `arti` *binary* — so this is a - second, separate Tor client, not the messenger's in-process one. There is no - C-tor and no system `tor`. -- The listener is **TCP loopback only**. `arti proxy -p ` binds localhost - (`127.0.0.1` and `::1`) and nothing else, and there is nothing safer to - prefer: `arti` 2.6.0 / `tor-config` 0.46 have no Unix-socket listen target - (`Listen` is IP-only; arti's own port record calls AF_UNIX future work, - arti#1965). The port is app-private in practice, but any local process with - user-level access can also use it — that is the honest statement of the - boundary, not a claim of access control. -- The wallet child is then spawned with - `--proxy socks5://127.0.0.1:` **and** `--daemon-address :`. - The `socks5://` scheme is explicit: Monero's `--proxy` defaults to SOCKS4a for - a bare `host:port` (`docs/proxies.md` in the Monero tree). The `.onion` name - goes to the proxy inside the SOCKS request — Monero's SOCKS5 client uses the - domain-name form — so **no local DNS** runs on the onion target. -- The SOCKS child gets **its own state and cache dirs** - (`$ONIONWIRE_HOME/wallet/arti-socks/{state,cache}`). The messenger's Arti - state is not shared with it. -- Starting it is gated on the same credential material as everything else: the - SOCKS child is only spawned from `WalletChild::start(&store)`, which needs the - already-unlocked store. -- The app waits **up to 20s** for the SOCKS listener to accept a connection - before it spawns the wallet child. A dead proxy is a visible error, not a - wallet screen that hangs dialling a daemon. Arti binds its listener before it - bootstraps, so this is a listener check, not a Tor-bootstrap check. -- The SOCKS child stops with the wallet child; a killed wallet child leaves no - orphaned listener behind. - -**Tor hides the transport, not the host.** The daemon operator still sees the -wallet's addresses (and the transaction set it is scanning) during sync. A -`.onion` address protects the path between you and that operator, nothing more. - -The TUI copy for a chain source says this in one line -(`WalletChild::chain_copy`): `.onion` → "over Tor … the daemon operator still -sees your addresses during sync"; clearnet → "the daemon operator and your ISP -see the traffic". - -### Readiness, and why it is not a guess - -`chain_ready()` asks the wallet RPC `get_info` and requires **`synchronized == -true`** with `height > 0` and `height >= target_height`. A missing field is -*not ready* — fail closed, never a silent pass. Until then: - -- **receipt verification stays `verified=0`** (an unsynced wallet cannot see the - tx, so a `get_transfers` miss would be a lie), and -- **spend is refused** with `wallet is not synced — spend refused until the - daemon reaches the chain tip`. - -`spend_ready()` is the stricter signal the spend UI reads: chain-ready *and* -holding an unlocked balance above zero. - -That is the honest state, not a broken flow. Unsynced or unreachable → receipts -unverified and spend refused. - -### Timeouts are the backend's, not a constant - -Loopback management calls (`get_address`, `query_key`, create/import) get a 5s -budget — the child is on the same box. Calls that wait on the chain (`get_info`, -`get_transfers`, `transfer`) get 60s (`CHAIN_RPC_TIMEOUT`), because a first sync -or a remote daemon legitimately outlasts a loopback round trip; a 5s cap there is -what leaves receipts permanently unverified. - ## Env vars | Variable | Meaning | |---|---| -| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]` — for an **externally run** `monero-wallet-rpc`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. The app-owned wallet child does not use this variable. | +| `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. | -These three are the **migration path**, not the only path: a config stored in -the encrypted store wins at boot. See *Stored wallet config* below. - `README.md` carries the operator summary; this file is the long form. -## Stored wallet config (no env required) - -Editing env vars is a deployment step, not a UI step. The same three fields can -be stored instead, so a deployment never needs env at all: - -| Field | Meaning | -|---|---| -| `rpc_url` | `http://host:port[/path]` for an **externally run** `monero-wallet-rpc`. **No** `user:pass` in the URL. Loopback only, same rule as env. | -| `rpc_login` | `user:pass`. Never logged, never in a status line, never on disk in the clear. | -| `no_spend` | View-only deployment. Same semantics as `ONIONWIRE_WALLET_NO_SPEND`. | - -`Store::save_wallet_config` / `Store::load_wallet_config` are the read/write -pair, and `Node::wallet_save_config` re-reads the live wallet after a save so -`configured` / the readouts follow without a restart. **No screen in this -repository calls them yet**: the TUI wallet config screen (F7) and its endpoint -entry, test-connection button and save path ship on -`feat/wallet-create-import`, which is not part of this change — see -*Starting and stopping the app-owned child* below for what this stack does -expose. Until that lands, set the stored config programmatically (or use the env -vars above). - -They live in the **encrypted SQLCipher store** (`wallet_config` table, one row: -the URL and the flag in the clear inside the encrypted db, the login sealed with -the store data key and a `onionwire/wallet-config/v1` AAD on top of whole-db -encryption — the same discipline as the wallet-child creds). Save replaces the -row; clearing the URL deletes it, which is how you turn the stored wallet off -again. - -**Boot precedence is stored → env → disabled.** Stored config wins; the env vars -in the table above remain the migration path (and the only path for headless -runs). A stored config that cannot be used — non-loopback host, `.onion`, -missing login — is reported and then **falls back to env** rather than dialling -the bad endpoint. To override a stored config with env, clear the stored one -first. - -### Wallet status, and how fresh `connected` is - -The app keeps one `WalletStatus` snapshot for the draw path — -`configured`, `connected`, `last_error`, `balance_line`, `receive_address` — -and the TUI only ever reads it; it never dials the wallet from the render path. - -- `configured` is true when a stored **or** env config resolved to a usable - wallet. Config is not reachability: a freshly booted or freshly saved wallet - is `configured = true`, `connected = false`, with `—` readouts. -- `connected` only ever comes from a probe. One probe is `get_address` (cheap, - loopback, and the same call `/pay` invoices need) followed by `get_balance` - for the readout. A success clears `last_error`; a failure sets - `connected = false` and keeps `configured = true`. There is no background - refresh: `connected` is whatever the **last** probe said. -- `last_error` is display copy, not a log line: trimmed, capped at 120 chars, - and with the RPC password redacted (``) if a lower layer ever put it - in a message. - -Two probes exist: - -- `wallet_refresh` / the readiness guard probe the **configured** endpoint and - update the snapshot; -- `wallet_test_connection` probes an endpoint the caller is *currently typing* - (`Wallet::ping`) and returns `{ok, status, error}` without touching the live - wallet or the snapshot — testing an untyped endpoint is not the wallet the app - is running. (The F7 screen that calls it ships on `feat/wallet-create-import`.) - -### The pay/tip readiness guard - -`/tip` and `/pay` run a pre-check before the send. It never dials Tor (wallet -RPC is loopback-only), and it never dials the wallet at all when the answer is -already known locally. The order is fixed and the copy is part of the contract: - -1. **not configured** → `wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC` -2. **`/tip` on a no-spend / view-only wallet** → the existing view-only message - (`wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt - verification still work`), refused **before any dial** — this is the same rule - `transfer` applies, and it is the honest answer whether or not the wallet is - reachable. -3. **configured but not connected** → `wallet not connected — check endpoint, login, daemon` -4. otherwise ready. `/pay` is fine on a view-only wallet. - -The check is cheap enough to run on Enter: steps 1 and 2 are local, and step 3 -is one bounded probe (5s local budget). `wallet_readiness(is_tip)` is `async`; -the TUI calls it from its key handler on both the `/pay` and `/tip` paths before -it sends anything. - -The "open F7" wording inside the not-configured message is the copy that ships -with the F7 screen on `feat/wallet-create-import`; this stack stores the config -and exposes the guard, but no screen writes it yet. - -## Starting and stopping the app-owned child - -Nothing spawns the child by accident: `Node::start_wallet_child` is the only -start path, and it is never called at boot. The desktop TUI drives it from the -wallet screen (F6): - -| Key | Effect | -|---|---| -| `s` | Start the child, then probe it once. | -| `x` | Stop it (idempotent) and fall back to the stored/env wallet config. | -| `p` | Probe the running child: is its wallet RPC answering, is the chain at the tip? | - -The state shown next to the wallet readouts is `off` / `connecting` / `syncing` -/ `ready` / `exited`, plus the chain-source label (`receive-only`, -`local node`, `remote onion daemon`, `remote daemon`). It is derived from the -real process (`try_wait`) and the last probe — **never** from env-var presence, -and `ready` is never reported for a child that has died. - -- **`off`** — nothing started (or stopped). The default state. -- **`connecting`** — the `monero-wallet-rpc` process is alive but has not - answered yet. This is what a fresh `s` reports; the RPC is not up the instant - the process exists. -- **`syncing`** — it answered but `chain_ready()` is false. -- **`ready`** — it answered and the chain is at the tip. -- **`exited`** — a started child has died. Stop and start again; the status is - not stale, it is the process table. - -`start` is idempotent: a live child is reported, not respawned. A start that -cannot spawn the binary is an error and leaves no child behind. - -**The chain source and the binaries are settings, not flags.** They live in the -same sealed `wallet_child` record as the generated RPC creds (see *Where the RPC -credentials live*), so they survive a restart: - -- `src/wallet_child.rs` `ChildConfig` — `source`, `wallet_rpc_bin`, `arti_bin`, - `wallet_filename`; validated before anything is written. -- Core: `Node::wallet_child_config` / `Node::set_wallet_child_config`, then - `Node::start_wallet_child` / `stop_wallet_child` / `wallet_child_status` / - `wallet_child_refresh`. -- Android (UniFFI): `set_chain_source(ChainConfig)` / `chain_source()`, - `start_wallet_child()`, `stop_wallet_child()`, `wallet_status()`. Pass - absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the - core never resolves a binary the caller named explicitly. - -So local mode is **available**, not wired off: a local chain source spawns -`monerod` from the path you set, a `.onion` daemon spawns the `arti` SOCKS -child, and everything else is unchanged. What is still missing is a *screen* to -type those fields on the desktop — the API above is the surface until the F7 -work lands. - ## Create vs import Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks @@ -326,6 +61,23 @@ Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion` wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and a remote wallet RPC would move spend authority off the box. +## Chain source + +The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire +does not pick a public remote node for you. + +1. **Spawn a local `monerod`** (pruned on-device). Chain traffic stays on the + box. You accept disk, first sync, and (on Android) the daemon not always + running. +2. **A daemon address you supply** — `--daemon-address` on the wallet child. + Loopback if you already run `monerod`. `.onion` if you want chain traffic + over Tor (wallet child `--proxy` to a localhost SOCKS listener; the daemon + operator still sees addresses). Clearnet only if you type it — ISP sees + Monero-node traffic; not a default. + +Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable +→ receipts stay unverified and spend is refused. That is the honest state. + ## Create a view-only wallet Either path produces a wallet file with the view key only. Keep the seed / diff --git a/src/lib.rs b/src/lib.rs index fbb8928..d18cbe5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,7 +16,6 @@ pub mod session; mod store; pub mod tui; pub mod wallet; -pub mod wallet_child; pub use store::{ Friend, FriendProfile, Message, Payment, PaymentWrite, SelfIdentity, Store, diff --git a/src/node.rs b/src/node.rs index 1bea43d..b66de04 100644 --- a/src/node.rs +++ b/src/node.rs @@ -29,8 +29,7 @@ use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store}; -use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus}; -use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; +use crate::wallet::{self, Wallet}; pub struct RotateResult { pub notified: usize, @@ -83,21 +82,7 @@ pub struct Node { hs: Mutex>, onion: Mutex, keys: Mutex, - /// Behind a lock because the F7 screen can re-point it at a saved config - /// without a restart. Clone it out (`wallet_snapshot`) before awaiting: a - /// `std::sync::Mutex` guard must not live across an `.await`. - wallet: Mutex, - /// Last probe result, for the draw path. Cheap to read, never dials. - wallet_status: Mutex, - /// The app-owned wallet child, once one has been started. `None` until - /// `start_wallet_child`, and `None` again after `stop_wallet_child` — the - /// child is never started implicitly. - wallet_child: Mutex>>, - /// Did the running child's wallet report a synced chain at the last probe? - /// Only `wallet_child_refresh` writes it; the draw path only reads it. - child_synced: AtomicBool, - /// The last child failure, display-ready. Cleared on a successful start. - child_error: Mutex>, + wallet: Wallet, incoming_limit: Mutex, inbox: Mutex, outbox: Arc, @@ -131,10 +116,6 @@ impl Node { passphrase: &str, ) -> Result, String> { let store = Store::open_at_with_passphrase(&home, passphrase).map_err(|e| e.to_string())?; - // Stored config first (the F7 screen's), env as the migration path. - let stored_wallet = store.load_wallet_config().map_err(|e| e.to_string())?; - let wallet = Wallet::for_boot(stored_wallet.as_ref()); - let wallet_status = WalletStatus::idle(wallet.configured()); let me = store.self_identity().map_err(|e| e.to_string())?; let keys = Keys::from_self(&me).map_err(|e| e.to_string())?; let nickname = store.hs_nickname().map_err(|e| e.to_string())?; @@ -163,11 +144,7 @@ impl Node { hs: Mutex::new(None), onion: Mutex::new(onion.clone()), keys: Mutex::new(keys), - wallet: Mutex::new(wallet), - wallet_status: Mutex::new(wallet_status), - wallet_child: Mutex::new(None), - child_synced: AtomicBool::new(false), - child_error: Mutex::new(None), + wallet: Wallet::from_env(), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), outbox: Arc::clone(&outbox), @@ -269,19 +246,6 @@ impl Node { Ok(mut g) => drop(g.take()), Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"), } - // The app owns these processes: an exit that left `monero-wallet-rpc` - // (a spend authority behind a loopback socket) or `monerod` behind would - // outlive the node that started them. - match self.wallet_child.lock().map(|mut g| g.take()) { - Ok(Some(child)) => { - self.child_synced.store(false, Ordering::Relaxed); - if let Err(e) = child.stop() { - eprintln!("shutdown: wallet child stop failed: {e}"); - } - } - Ok(None) => {} - Err(_) => eprintln!("shutdown: wallet-child lock poisoned"), - } self.checkpoint(); Ok(()) } @@ -292,8 +256,7 @@ impl Node { /// `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 { - let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await - { + 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(_) => { @@ -500,277 +463,19 @@ impl Node { .map_err(|e| e.to_string()) } - /// The live wallet, cloned out of its lock. Every wallet call goes through - /// this so a `std::sync::Mutex` guard never lives across an `.await`, and so - /// the F7 screen can re-point the wallet mid-session. - fn wallet_snapshot(&self) -> Wallet { - self.wallet - .lock() - .map(|w| w.clone()) - .unwrap_or_else(|_| Wallet::disabled()) - } - - /// The snapshot the TUI draws. Cheap: no dial, no lock on the RPC. It says - /// "configured, not probed" (`connected == false`) until a probe has run. - pub fn wallet_status(&self) -> WalletStatus { - self.wallet_status - .lock() - .map(|s| s.clone()) - .unwrap_or_else(|_| WalletStatus::idle(self.wallet_snapshot().configured())) - } - - /// Probe the configured endpoint once and fold the result into the snapshot. - /// This is the only thing that can flip `connected` to true. - pub async fn wallet_refresh(&self) -> WalletStatus { - let w = self.wallet_snapshot(); - let status = w.status().await; - if let Ok(mut slot) = self.wallet_status.lock() { - *slot = status.clone(); - } - status - } - - /// The pay/tip readiness guard. Blocking-friendly: the TUI calls this from - /// its key handler with `rt.block_on`, like `send_pay`/`send_tip` do. - /// - /// It never dials Tor. It also never dials the wallet when the answer is - /// already known locally — an unconfigured wallet and a `/tip` on a - /// view-only wallet are refused before any socket is opened. - pub async fn wallet_readiness(&self, is_tip: bool) -> Readiness { - let w = self.wallet_snapshot(); - if !w.configured() { - return Readiness::NotConfigured; - } - if is_tip && w.no_spend() { - return Readiness::NoSpend; - } - let status = self.wallet_refresh().await; - wallet::readiness(status.configured, status.connected, w.no_spend(), is_tip) - } - - // ----- the app-owned wallet child (`src/wallet_child.rs`) ---------------- - - /// The child settings this node would spawn with: the stored record, or the - /// defaults (receive-only, binaries by name) when nothing was ever set. - pub fn wallet_child_config(&self) -> ChildConfig { - self.store - .lock() - .ok() - .and_then(|store| store.load_wallet_child().ok().flatten()) - .and_then(|raw| ChildConfig::from_record(&raw).ok().flatten()) - .unwrap_or_default() - } - - /// Persist the settings a config screen or the SDK set. Validated first, so - /// a rejected config is never written; the creds already in the record are - /// preserved. A running child is not restarted — the change applies on the - /// next `start_wallet_child`. - pub fn set_wallet_child_config(&self, cfg: &ChildConfig) -> Result<(), String> { - cfg.validate().map_err(|e| e.to_string())?; - let store = self.store.lock().map_err(|e| e.to_string())?; - let existing = store.load_wallet_child().map_err(|e| e.to_string())?; - let record = crate::wallet_child::merge_record(existing.as_deref(), cfg.record_fields()); - store - .save_wallet_child(&record) - .map_err(|e| e.to_string())?; - Ok(()) - } - - /// Start the app-owned wallet child and point this node's wallet at it. - /// - /// Idempotent: a live wallet child is reported, not respawned. Spawning is - /// synchronous — argv is built, the child is spawned, and a `.onion` chain - /// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which - /// is why callers block on it (`rt.block_on` in the TUI). - pub fn start_wallet_child(&self) -> Result<(), String> { - let cfg = self.wallet_child_config(); - if !cfg.is_enabled() { - return Err("no chain source configured — the wallet child is receive-only".into()); - } - let already_running = self - .wallet_child - .lock() - .map_err(|e| e.to_string())? - .as_ref() - .is_some_and(|child| child.wallet_rpc_running()); - if already_running { - return Ok(()); - } - let child = Arc::new( - cfg.build(self.home.join("wallet")) - .map_err(|e| e.to_string())?, - ); - let client = { - let store = self.store.lock().map_err(|e| e.to_string())?; - child.start(&store).map_err(|e| e.to_string())? - }; - let Some(client) = client else { - return Err("chain source is receive-only — nothing to start".into()); - }; - let wallet = client.into_wallet(); - let configured = wallet.configured(); - *self.wallet.lock().map_err(|e| e.to_string())? = wallet; - *self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured); - *self.child_error.lock().map_err(|e| e.to_string())? = None; - self.child_synced.store(false, Ordering::Relaxed); - *self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child); - Ok(()) - } - - /// Stop the app-owned wallet child (idempotent) and put the wallet back on - /// the stored/env config, if any. The next launch starts the child again — - /// nothing promises it stays up across a restart, and Android will not. - pub fn stop_wallet_child(&self) -> Result<(), String> { - let child = self.wallet_child.lock().map_err(|e| e.to_string())?.take(); - if let Some(child) = child { - child.stop().map_err(|e| e.to_string())?; - } - self.child_synced.store(false, Ordering::Relaxed); - let stored = self - .store - .lock() - .map_err(|e| e.to_string())? - .load_wallet_config() - .map_err(|e| e.to_string())?; - let wallet = Wallet::for_boot(stored.as_ref()); - let configured = wallet.configured(); - *self.wallet.lock().map_err(|e| e.to_string())? = wallet; - *self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured); - Ok(()) - } - - /// The child's observable state, derived from the real process plus the last - /// probe — never from env-var presence. Cheap: no dial, safe on a draw path. - pub fn wallet_child_status(&self) -> WalletChildStatus { - let cfg = self.wallet_child_config(); - let child = self - .wallet_child - .lock() - .ok() - .and_then(|guard| guard.clone()); - let running = child - .as_ref() - .is_some_and(|child| child.wallet_rpc_running()); - let connected = self - .wallet_status - .lock() - .map(|s| s.connected) - .unwrap_or(false); - let state = match &child { - None => WalletChildState::Off, - Some(_) if !running => WalletChildState::Exited, - Some(_) if !connected => WalletChildState::Connecting, - Some(_) if self.child_synced.load(Ordering::Relaxed) => WalletChildState::Ready, - Some(_) => WalletChildState::Syncing, - }; - WalletChildStatus { - state, - running, - configured: cfg.is_enabled(), - chain_source: cfg.source_label(), - last_error: self.child_error.lock().ok().and_then(|err| err.clone()), - } - } - - /// The one-line child status a TUI row shows. Empty when nothing is - /// configured, so an unconfigured install renders no row at all. - pub fn wallet_child_line(&self) -> String { - self.wallet_child_status().line() - } - - /// Probe the running child once: is its wallet RPC answering, and is the - /// chain at the tip? Only this (or a failed start) moves the state off - /// `connecting`, and it never invents `ready` for a dead child. - pub async fn wallet_child_refresh(&self) -> WalletChildStatus { - let running = self - .wallet_child - .lock() - .map(|guard| guard.is_some()) - .unwrap_or(false); - if !running { - return self.wallet_child_status(); - } - let w = self.wallet_snapshot(); - if !w.configured() { - return self.wallet_child_status(); - } - let status = w.status().await; - let connected = status.connected; - let error = status.last_error.clone(); - if let Ok(mut slot) = self.wallet_status.lock() { - *slot = status; - } - let synced = if connected { - w.chain_ready().await.unwrap_or(false) - } else { - false - }; - self.child_synced.store(synced, Ordering::Relaxed); - if let Ok(mut slot) = self.child_error.lock() { - *slot = if connected { None } else { error }; - } - self.wallet_child_status() - } - - /// The config screen's Test-connection button: one shot against the endpoint - /// the user is typing. It does not touch the live wallet or the snapshot — - /// a test of an untyped endpoint is not the wallet we are running. - pub async fn wallet_test_connection( - &self, - rpc_url: &str, - rpc_login: &str, - ) -> wallet::PingResult { - Wallet::ping(rpc_url, rpc_login).await - } - - /// The config the F7 screen should show: the stored one, or the env-derived - /// one when only env set the wallet (the migration path). - pub fn wallet_config(&self) -> Option { - if let Ok(store) = self.store.lock() - && let Ok(Some(cfg)) = store.load_wallet_config() - { - return Some(cfg); - } - self.wallet_snapshot().config() - } - - /// Persist the config screen's Save and re-read it: the live wallet and the - /// snapshot both follow, so "saved · not connected" is visible without a - /// restart. Validation happens before anything is written, so a rejected - /// config leaves the running wallet exactly as it was. - pub fn wallet_save_config(&self, cfg: &WalletConfig) -> Result<(), String> { - Wallet::from_config(cfg).map_err(|e| wallet::redact(&e.to_string(), cfg.secret()))?; - { - let store = self.store.lock().map_err(|e| e.to_string())?; - store.save_wallet_config(cfg).map_err(|e| e.to_string())?; - } - // Re-read from the store rather than trusting the caller's copy. - let stored = self - .store - .lock() - .map_err(|e| e.to_string())? - .load_wallet_config() - .map_err(|e| e.to_string())?; - let wallet = Wallet::for_boot(stored.as_ref()); - let configured = wallet.configured(); - *self.wallet.lock().map_err(|e| e.to_string())? = wallet; - *self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured); - Ok(()) - } - /// Current wallet balance as a human-readable XMR string, or `off` when the /// wallet is not configured. pub async fn wallet_balance(&self) -> String { - let w = self.wallet_snapshot(); - if !w.configured() { + if !self.wallet.configured() { return "off".into(); } - match w.get_balance().await { + match self.wallet.get_balance().await { Ok(b) => crate::pay::atomic_to_xmr_str(&b), Err(_) => "err".into(), } } + pub fn wipe_messages(&self) -> Result<(), String> { self.store .lock() @@ -920,9 +625,8 @@ impl Node { /// Pay selected friend via wallet RPC, then signed receipt. pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> { - let w = self.wallet_snapshot(); - if !w.configured() { - return Err(wallet::NOT_CONFIGURED_MSG.into()); + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); } let address = self .friend_profile(friend_pk)? @@ -935,7 +639,8 @@ impl Node { let amount: u64 = atomic .parse() .map_err(|_| "amount too large for wallet RPC".to_string())?; - let txid = w + let txid = self + .wallet .transfer(&address, amount) .await .map_err(|e| e.to_string())?; @@ -984,9 +689,8 @@ impl Node { } async fn invoice_address(&self) -> Result { - let w = self.wallet_snapshot(); - if w.configured() - && let Ok(addr) = w.create_address().await + if self.wallet.configured() + && let Ok(addr) = self.wallet.create_address().await && pay::check_address(&addr).is_ok() { return Ok(addr); @@ -1005,9 +709,10 @@ impl Node { /// how to wrap it. pub async fn wallet_receive_address(&self) -> Result { let profile_addr = self.self_profile()?.xmr_addr; - let w = self.wallet_snapshot(); - if w.configured() - && let Ok(addr) = w.get_address().await + if self + .wallet + .configured() + && let Ok(addr) = self.wallet.get_address().await && pay::check_address(&addr).is_ok() { return Ok(addr); @@ -1023,9 +728,8 @@ impl Node { /// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses /// piconero itself. pub async fn wallet_balance_line(&self) -> String { - let w = self.wallet_snapshot(); - if w.configured() { - match w.get_balance().await { + if self.wallet.configured() { + match self.wallet.get_balance().await { Ok(b) if !b.is_empty() => { let xmr = pay::atomic_to_xmr_str(&b); if xmr == "0" { @@ -1045,15 +749,11 @@ impl Node { /// Recent in/out transfers for the wallet screen, newest first, capped to a /// small window. Returns the same `TransferRow` shape the existing tests /// already cover. - pub async fn wallet_recent_transfers( - &self, - cap: usize, - ) -> Result, String> { - let w = self.wallet_snapshot(); - if !w.configured() { + pub async fn wallet_recent_transfers(&self, cap: usize) -> Result, String> { + if !self.wallet.configured() { return Ok(Vec::new()); } - let rows = w.get_transfers().await.map_err(|e| e.to_string())?; + let rows = self.wallet.get_transfers().await.map_err(|e| e.to_string())?; let mut rows = rows; rows.sort_by(|a, b| b.txid.cmp(&a.txid)); Ok(rows.into_iter().take(cap).collect()) @@ -1062,11 +762,11 @@ impl Node { /// Create a new spend-capable wallet. Returns the seed once for backup. /// The user never pastes a key on this path. pub async fn wallet_create(&self, password: &str) -> Result { - let w = self.wallet_snapshot(); - if !w.configured() { - return Err(wallet::NOT_CONFIGURED_MSG.into()); + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); } - w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + self.wallet + .create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) .await .map_err(|e| e.to_string()) } @@ -1074,11 +774,11 @@ impl Node { /// Import a wallet from an existing 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { - let w = self.wallet_snapshot(); - if !w.configured() { - return Err(wallet::NOT_CONFIGURED_MSG.into()); + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); } - w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + self.wallet + .restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) .await .map_err(|e| e.to_string()) } @@ -1249,10 +949,7 @@ impl Node { /// Pending and failed outbox rows for a friend, for UI surfacing. /// Delivered rows are dropped, so a message absent here was sent. - pub fn outbox_pending( - &self, - friend_pk: &[u8], - ) -> Result, String> { + pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result, String> { self.outbox.pending(friend_pk) } @@ -1482,13 +1179,8 @@ impl Node { .map_err(|e| e.to_string())? }; let mut verified = false; - // Honest prerequisite: an unsynced wallet cannot see the tx, so a - // get_transfers "miss" would be a lie. Until the chain is ready the - // receipt stays verified=0 — that is the correct state, not an error. - let w = self.wallet_snapshot(); - let ready = w.configured() && w.can_verify_receipts().await; - if ready { - match w.get_transfers().await { + if self.wallet.configured() { + match self.wallet.get_transfers().await { Ok(rows) if wallet::transfers_match( &rows, @@ -1781,8 +1473,6 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { mod tests { use super::*; use std::pin::Pin; - - use crate::wallet::ChainSource; use std::task::{Context, Poll}; use futures::io::{AsyncRead, AsyncWrite}; @@ -1870,7 +1560,6 @@ mod tests { .expect("unbootstrapped Tor client"); let store = Arc::new(Mutex::new(store)); let outbox = Arc::new(Outbox::new(Arc::clone(&store), deliverer)); - let wallet_status = WalletStatus::idle(wallet.configured()); Node { home: home.to_path_buf(), store, @@ -1878,11 +1567,7 @@ mod tests { hs: Mutex::new(None), onion: Mutex::new("test.onion".to_string()), keys: Mutex::new(keys), - wallet: Mutex::new(wallet), - wallet_status: Mutex::new(wallet_status), - wallet_child: Mutex::new(None), - child_synced: AtomicBool::new(false), - child_error: Mutex::new(None), + wallet, incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(file::Inbox::new(home.join("inbox"))), outbox, @@ -2096,11 +1781,6 @@ mod tests { /// A wallet child that clears the Digest challenge and answers one /// `transfer` — the two-connection dance `tests/wallet.rs` mocks. - /// A loopback wallet RPC that answers what the tip path actually asks for: - /// a digest challenge, then a synced `get_info` for the readiness gate and - /// `tx_hash` for the transfer. The old single-answer mock stopped covering - /// the path when `Wallet::transfer` started probing the chain tip first — - /// it answered `tx_hash` to `get_info` and every tip was refused as unsynced. async fn mock_wallet() -> Wallet { use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -2109,18 +1789,13 @@ mod tests { .expect("bind mock wallet"); let port = listener.local_addr().expect("mock wallet addr").port(); tokio::spawn(async move { - // Every call starts unauthenticated, so every call gets one - // challenge — the client retries each request with digest auth. - for _ in 0..8 { + for attempt in 0..2 { let Ok((mut sock, _)) = listener.accept().await else { return; }; let mut buf = vec![0u8; 8192]; - let Ok(n) = sock.read(&mut buf).await else { - return; - }; - let req = String::from_utf8_lossy(&buf[..n]).to_string(); - if !req.contains("Authorization:") { + let _ = sock.read(&mut buf).await; + if attempt == 0 { let _ = sock .write_all( b"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", @@ -2128,11 +1803,7 @@ mod tests { .await; continue; } - let body = if req.contains("get_info") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"# - }; + let body = r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#; let _ = sock .write_all( format!( @@ -2313,308 +1984,5 @@ mod tests { assert_eq!(rows[0].dir, "in"); assert_eq!(rows[0].kind, "tip"); } - - /// A stand-in for `monero-wallet-rpc`: it records its argv, then does what - /// the test needs. The wallet child spawns a real process, so this is the - /// only honest way to drive the start path offline. - fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf { - std::fs::create_dir_all(dir).expect("fake bin dir"); - let path = dir.join(name); - let script = format!( - "#!/bin/sh\n: > '{}'\nprintf '%s\\n' \"$0\" >> '{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done\n{body}\n", - log.display(), - log.display(), - log.display() - ); - std::fs::write(&path, script).expect("write fake bin"); - let mut perms = std::fs::metadata(&path).expect("stat").permissions(); - std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700); - std::fs::set_permissions(&path, perms).expect("chmod"); - path - } - - /// A loopback daemon is the one source that spawns no SOCKS child, so the - /// test drives exactly one process. - fn loopback_child_config(bin: PathBuf, filename: &str) -> ChildConfig { - ChildConfig { - source: ChainSource::Remote { - host: "127.0.0.1".into(), - port: 18081, - }, - wallet_rpc_bin: bin, - arti_bin: PathBuf::from("arti"), - wallet_filename: filename.to_string(), - } - } - - fn sealed_creds(node: &Node) -> (String, String) { - let raw = node - .store - .lock() - .expect("store") - .load_wallet_child() - .expect("record") - .expect("a start seals the creds"); - let parsed: serde_json::Value = serde_json::from_str(&raw).expect("json"); - ( - parsed["user"].as_str().expect("user").to_string(), - parsed["pass"].as_str().expect("pass").to_string(), - ) - } - - /// A receive-only node says `off` and starts nothing: the status comes from - /// the real configuration, never from a guess or an env var. - #[tokio::test] - async fn a_receive_only_node_reports_off_and_refuses_to_start_a_child() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - let status = node.wallet_child_status(); - assert_eq!(status.state, WalletChildState::Off); - assert!(!status.running); - assert!(!status.configured); - assert_eq!(status.chain_source, "receive-only"); - assert!(status.last_error.is_none()); - assert_eq!( - node.wallet_child_line(), - "", - "an unconfigured install renders no status row" - ); - let err = node - .start_wallet_child() - .expect_err("receive-only cannot start anything"); - assert!(err.contains("no chain source configured"), "{err}"); - } - - /// The start path honours `with_wallet_rpc_bin` — the configured absolute - /// path is what gets spawned, not a name off `PATH` — and the status tracks - /// the real process. - #[tokio::test] - async fn start_wallet_child_honours_the_configured_binary() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path().join("child"); - let node = offline_node(&home, Arc::new(NoDial)); - let log = dir.path().join("argv.log"); - let bin = fake_child_bin( - &dir.path().join("fake-bins"), - "monero-wallet-rpc", - &log, - "sleep 30", - ); - node.set_wallet_child_config(&loopback_child_config(bin.clone(), "onionwire")) - .expect("set config"); - - node.start_wallet_child().expect("start"); - let status = node.wallet_child_status(); - assert!(status.running, "{status:?}"); - assert_eq!( - status.state, - WalletChildState::Connecting, - "nothing has answered the wallet RPC yet" - ); - assert!(status.configured); - assert_eq!(status.chain_source, "remote daemon"); - - let mut argv: Vec = Vec::new(); - for _ in 0..200 { - argv = std::fs::read_to_string(&log) - .unwrap_or_default() - .lines() - .map(str::to_string) - .collect(); - if !argv.is_empty() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert_eq!( - argv.first().map(String::as_str), - bin.to_str(), - "the configured binary ($0) is what got spawned: {argv:?}" - ); - assert!(argv.iter().any(|a| a == "--wallet-dir"), "{argv:?}"); - assert!( - argv.iter() - .any(|a| a == &home.join("wallet").display().to_string()), - "{argv:?}" - ); - assert!(argv.iter().any(|a| a == "--daemon-address"), "{argv:?}"); - assert!( - !argv.iter().any(|a| a == "--trusted-daemon"), - "a remote daemon is never trusted: {argv:?}" - ); - - // Idempotent: a live child is reported, not respawned. - node.start_wallet_child().expect("second start"); - assert!(node.wallet_child_status().running); - - node.stop_wallet_child().expect("stop"); - let after = node.wallet_child_status(); - assert_eq!(after.state, WalletChildState::Off); - assert!(!after.running, "stop must not leave a process behind"); - } - - /// A child that dies on its own is `exited` — never `ready` — and stopping - /// after that is still a clean no-op. - #[tokio::test] - async fn a_died_child_reports_exited_and_never_ready() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - let log = dir.path().join("argv.log"); - let bin = fake_child_bin( - &dir.path().join("fake-bins"), - "monero-wallet-rpc", - &log, - "exit 0", - ); - node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) - .expect("set config"); - - node.start_wallet_child().expect("start"); - let mut status = node.wallet_child_status(); - for _ in 0..300 { - status = node.wallet_child_status(); - if status.state == WalletChildState::Exited { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert_eq!(status.state, WalletChildState::Exited, "{status:?}"); - assert!(!status.running); - assert_ne!(status.state.as_str(), "ready"); - node.stop_wallet_child() - .expect("stop is a no-op after an exit"); - assert_eq!(node.wallet_child_status().state, WalletChildState::Off); - } - - /// The settings live in the sealed store, so they survive a restart, and - /// re-saving them does not clobber the RPC creds a start already sealed. - #[tokio::test] - async fn chain_source_persists_and_keeps_the_sealed_creds() { - let dir = tempfile::tempdir().unwrap(); - let home = dir.path().join("child"); - let log = dir.path().join("argv.log"); - let bin = fake_child_bin( - &dir.path().join("fake-bins"), - "monero-wallet-rpc", - &log, - "sleep 30", - ); - let saved = loopback_child_config(bin.clone(), "onionwire"); - { - let node = offline_node(&home, Arc::new(NoDial)); - node.set_wallet_child_config(&saved).expect("set config"); - node.start_wallet_child().expect("start"); - let before = sealed_creds(&node); - - let mut other = saved.clone(); - other.source = ChainSource::Remote { - host: "127.0.0.1".into(), - port: 18089, - }; - node.set_wallet_child_config(&other).expect("re-save"); - assert_eq!(sealed_creds(&node), before, "creds survived the rewrite"); - node.stop_wallet_child().expect("stop"); - } - - let node = offline_node(&home, Arc::new(NoDial)); - assert_eq!( - node.wallet_child_config(), - ChildConfig { - source: ChainSource::Remote { - host: "127.0.0.1".into(), - port: 18089, - }, - ..saved - }, - "the saved source outlives the process" - ); - } - - /// A binary that cannot be spawned is an error and leaves no half-started - /// child behind. - #[tokio::test] - async fn a_missing_binary_fails_the_start_and_leaves_no_child() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - node.set_wallet_child_config(&loopback_child_config( - PathBuf::from("/nonexistent/onionwire-wallet-rpc"), - "onionwire", - )) - .expect("set config"); - let err = node - .start_wallet_child() - .expect_err("a missing binary fails"); - assert!(err.contains("spawn"), "{err}"); - let status = node.wallet_child_status(); - assert_eq!(status.state, WalletChildState::Off); - assert!(!status.running); - } - - /// A rejected setting is rejected before it is written: the stored config is - /// unchanged, so a bad form never points the child at nothing. - #[tokio::test] - async fn a_rejected_chain_source_is_not_persisted() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - let bin = dir.path().join("fake-bins").join("monero-wallet-rpc"); - let saved = loopback_child_config(bin.clone(), "onionwire"); - node.set_wallet_child_config(&saved).expect("set config"); - - let mut no_host = saved.clone(); - no_host.source = ChainSource::Remote { - host: " ".into(), - port: 18081, - }; - let err = node - .set_wallet_child_config(&no_host) - .expect_err("an empty host is rejected"); - assert!(err.contains("daemon host required"), "{err}"); - assert_eq!( - node.wallet_child_config(), - saved, - "the stored config is intact" - ); - } - - /// `shutdown` stops the processes the app owns: an exit must not orphan a - /// spend-capable wallet RPC behind a loopback socket. - #[tokio::test] - async fn shutdown_stops_the_wallet_child() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("child"), Arc::new(NoDial)); - let log = dir.path().join("argv.log"); - let pid_file = dir.path().join("child.pid"); - let bin = fake_child_bin( - &dir.path().join("fake-bins"), - "monero-wallet-rpc", - &log, - &format!("echo $$ > '{}'; exec sleep 30", pid_file.display()), - ); - node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) - .expect("set config"); - node.start_wallet_child().expect("start"); - - let mut pid = 0u32; - for _ in 0..200 { - if let Ok(raw) = std::fs::read_to_string(&pid_file) - && let Ok(parsed) = raw.trim().parse::() - { - pid = parsed; - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert!(pid > 0, "the fake child recorded its pid"); - - node.shutdown().await.expect("shutdown"); - let mut gone = false; - for _ in 0..300 { - if !Path::new(&format!("/proc/{pid}")).exists() { - gone = true; - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert!(gone, "shutdown must not leave the wallet child behind"); - } } + diff --git a/src/store.rs b/src/store.rs index 676a1fa..267b6a4 100644 --- a/src/store.rs +++ b/src/store.rs @@ -257,24 +257,6 @@ impl Store { kdf_salt BLOB NOT NULL, wrapped_key BLOB NOT NULL ); - -- The wallet child's RPC creds + chain-source snapshot. One row, - -- sealed with the store data key (see `save_wallet_child`): the - -- creds never touch the filesystem in the clear. - CREATE TABLE IF NOT EXISTS wallet_child ( - id INTEGER PRIMARY KEY CHECK (id = 1), - sealed BLOB NOT NULL, - updated_at INTEGER NOT NULL - ); - -- Remote-mode wallet config the user set in-app (F7): the endpoint, - -- the login, and the view-only flag. One row; the login is sealed - -- with the store data key (see `save_wallet_config`). - CREATE TABLE IF NOT EXISTS wallet_config ( - id INTEGER PRIMARY KEY CHECK (id = 1), - rpc_url TEXT NOT NULL, - sealed_login BLOB NOT NULL, - no_spend INTEGER NOT NULL, - updated_at INTEGER NOT NULL - ); CREATE TABLE IF NOT EXISTS payments ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), @@ -328,96 +310,6 @@ impl Store { .map_err(Into::into) } - /// Seal the wallet child's config (RPC creds + chain-source snapshot) into - /// the encrypted store, replacing the single row. - /// - /// The creds are generated per install and grant spend authority over the - /// wallet child, so they are stored the same way message bodies are: AEAD - /// with the store data key on top of the whole-db SQLCipher layer. They are - /// never written to a plaintext file beside the wallet. - pub fn save_wallet_child(&self, json: &str) -> Result<()> { - let blob = crate::backup::aead_encrypt(&self.msg_key, json.as_bytes(), WALLET_CHILD_AAD) - .map_err(Error)?; - self.conn.execute( - "INSERT INTO wallet_child (id, sealed, updated_at) VALUES (1, ?1, ?2) - ON CONFLICT(id) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at", - params![blob, unix_now()], - )?; - Ok(()) - } - - /// Read back the sealed wallet-child config, or `None` before the first - /// child start. A blob that does not decrypt is an error, never a guess. - pub fn load_wallet_child(&self) -> Result> { - let row: Option> = self - .conn - .query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |row| { - row.get(0) - }) - .optional()?; - let Some(blob) = row else { - return Ok(None); - }; - let plain = crate::backup::aead_decrypt(&self.msg_key, &blob, WALLET_CHILD_AAD) - .map_err(|_| Error("wallet-child config decrypt failed".into()))?; - String::from_utf8(plain) - .map(Some) - .map_err(|_| Error("wallet-child config is not utf-8".into())) - } - - /// Persist the remote-mode wallet config the F7 screen saved. One row, - /// replaced in place; an empty `rpc_url` clears it (that is how a user - /// turns the stored wallet off again). - /// - /// The login is `user:pass` for a wallet that can spend, so it is sealed - /// with the store data key on top of the whole-db SQLCipher layer — the - /// same discipline as the wallet-child creds. - pub fn save_wallet_config(&self, cfg: &crate::wallet::WalletConfig) -> Result<()> { - if cfg.rpc_url.trim().is_empty() { - self.conn.execute("DELETE FROM wallet_config", [])?; - return Ok(()); - } - let sealed = - crate::backup::aead_encrypt(&self.msg_key, cfg.rpc_login.as_bytes(), WALLET_CONFIG_AAD) - .map_err(Error)?; - self.conn.execute( - "INSERT INTO wallet_config (id, rpc_url, sealed_login, no_spend, updated_at) - VALUES (1, ?1, ?2, ?3, ?4) - ON CONFLICT(id) DO UPDATE SET rpc_url = excluded.rpc_url, - sealed_login = excluded.sealed_login, no_spend = excluded.no_spend, - updated_at = excluded.updated_at", - params![cfg.rpc_url.trim(), sealed, cfg.no_spend as i64, unix_now()], - )?; - Ok(()) - } - - /// Read the stored remote-mode config, or `None` when none was ever saved. - /// A blob that does not decrypt is an error, never a guess. - pub fn load_wallet_config(&self) -> Result> { - let row: Option<(String, Vec, i64)> = self - .conn - .query_row( - "SELECT rpc_url, sealed_login, no_spend FROM wallet_config WHERE id = 1", - [], - |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), - ) - .optional()?; - let Some((rpc_url, sealed, no_spend)) = row else { - return Ok(None); - }; - let login = crate::backup::aead_decrypt(&self.msg_key, &sealed, WALLET_CONFIG_AAD) - .map_err(|_| Error("wallet config decrypt failed".into()))?; - // The login is a secret: it must not survive in a bare `String`. - let login = Zeroizing::new( - String::from_utf8(login).map_err(|_| Error("wallet config is not utf-8".into()))?, - ); - Ok(Some(crate::wallet::WalletConfig { - rpc_url, - rpc_login: login, - no_spend: no_spend != 0, - })) - } - pub fn replace_identity_keys( &self, identity_sk: &[u8], @@ -975,13 +867,17 @@ impl Store { } pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> { - self.append_message_id(friend_pk, dir, plaintext) - .map(|_| ()) + self.append_message_id(friend_pk, dir, plaintext).map(|_| ()) } /// Same as `append_message`, returning the row id so an outbox row can /// point at the body instead of storing a second copy. - pub fn append_message_id(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result { + pub fn append_message_id( + &self, + friend_pk: &[u8], + dir: &str, + plaintext: &[u8], + ) -> Result { if dir != "in" && dir != "out" { return Err(Error("dir must be in or out".into())); } @@ -1030,7 +926,11 @@ impl Store { let aad = message_aad(friend_id, &dir, id); let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) .map_err(|_| Error("message decrypt failed".into()))?; - out.push(Message { id, dir, plaintext }); + out.push(Message { + id, + dir, + plaintext, + }); } Ok(out) } @@ -1393,10 +1293,7 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { fn gen_prekey() -> (Zeroizing>, Vec) { let sk = StaticSecret::random_from_rng(OsRng); let pk = X25519Public::from(&sk); - ( - Zeroizing::new(sk.to_bytes().to_vec()), - pk.to_bytes().to_vec(), - ) + (Zeroizing::new(sk.to_bytes().to_vec()), pk.to_bytes().to_vec()) } /// Per-install KDF salt for the whole-database key. Not secret (a salt never @@ -1651,14 +1548,6 @@ fn unix_now() -> i64 { .unwrap_or(0) } -/// AAD for the sealed wallet-child row. Domain-separates it from message and -/// outbox blobs that share the same store data key. -const WALLET_CHILD_AAD: &[u8] = b"onionwire/wallet-child/v1"; - -/// AAD for the sealed remote-mode wallet config row. Same reasoning as the -/// wallet-child AAD: one store key, many domains. -const WALLET_CONFIG_AAD: &[u8] = b"onionwire/wallet-config/v1"; - fn fingerprint(pubkey: &[u8]) -> String { pubkey.iter().map(|b| format!("{b:02x}")).collect() } @@ -1954,16 +1843,22 @@ mod at_rest { params![salt.as_slice(), wrapped], ) .unwrap(); - for (dir, body) in [("in", "legacy-body-xyz"), ("out", "legacy-reply-xyz")] { + for (dir, body) in [ + ("in", "legacy-body-xyz"), + ("out", "legacy-reply-xyz"), + ] { conn.execute( "INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)", params![dir], ) .unwrap(); let id = conn.last_insert_rowid(); - let blob = - crate::backup::aead_encrypt(&data_key, body.as_bytes(), &message_aad(1, dir, id)) - .unwrap(); + let blob = crate::backup::aead_encrypt( + &data_key, + body.as_bytes(), + &message_aad(1, dir, id), + ) + .unwrap(); conn.execute( "UPDATE messages SET plaintext = ?1 WHERE id = ?2", params![blob, id], @@ -1991,8 +1886,7 @@ mod at_rest { "fixture must be a plaintext sqlite file" ); - let store = - Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade"); + let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade"); assert_eq!( store.self_identity().unwrap().identity_sk[..], LEGACY_IDENTITY_SK[..] @@ -2014,10 +1908,7 @@ mod at_rest { ); for (needle, what) in [ (b"legacy-body-xyz".to_vec(), "message body"), - ( - fingerprint(&LEGACY_FRIEND_PK).into_bytes(), - "friend pubkey hex", - ), + (fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"), (LEGACY_IDENTITY_SK.to_vec(), "identity secret"), (b"legacy-friend.onion".to_vec(), "locator"), ] { @@ -2248,64 +2139,4 @@ mod at_rest { Some(&b"fresh-state"[..]) ); } - - /// The wallet-child RPC creds grant spend authority, so they are stored - /// sealed in the encrypted store — never as a plaintext file next to the - /// wallet, and never as a plaintext row. - #[test] - fn wallet_child_creds_round_trip_sealed_and_load_none_before_first_start() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::open_at_with_passphrase(dir.path(), "child-pass").unwrap(); - assert!( - store.load_wallet_child().unwrap().is_none(), - "a fresh store has no wallet-child config" - ); - let cfg = r#"{"user":"owuser","pass":"ow-secret-pass-xyz","wallet_filename":"onionwire"}"#; - store.save_wallet_child(cfg).unwrap(); - assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg)); - - let sealed: Vec = store - .conn - .query_row("SELECT sealed FROM wallet_child WHERE id = 1", [], |r| { - r.get(0) - }) - .unwrap(); - assert_ne!( - sealed.as_slice(), - cfg.as_bytes(), - "row stored the creds as plaintext" - ); - assert!( - !sealed.windows(11).any(|w| w == b"ow-secret-p".as_slice()), - "sealed row leaked the password" - ); - - // Re-sealing replaces the single row instead of stacking rows. - let cfg2 = r#"{"user":"owuser","pass":"second-pass-abc","wallet_filename":"onionwire"}"#; - store.save_wallet_child(cfg2).unwrap(); - assert_eq!(store.load_wallet_child().unwrap().as_deref(), Some(cfg2)); - let rows: i64 = store - .conn - .query_row("SELECT count(*) FROM wallet_child", [], |r| r.get(0)) - .unwrap(); - assert_eq!(rows, 1, "wallet_child must hold exactly one row"); - - store.checkpoint_wal().unwrap(); - drop(store); - for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] { - let path = dir.path().join(name); - let Ok(bytes) = std::fs::read(&path) else { - continue; - }; - for needle in [ - b"second-pass-abc".as_slice(), - b"ow-secret-pass-xyz".as_slice(), - ] { - assert!( - !bytes.windows(needle.len()).any(|w| w == needle), - "{name} contains the wallet-child password in the clear" - ); - } - } - } } diff --git a/src/tui.rs b/src/tui.rs index ef0a0e7..e246b10 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1537,9 +1537,6 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), - KeyCode::Char('s') => self.wallet_child_start(), - KeyCode::Char('x') => self.wallet_child_stop(), - KeyCode::Char('p') => self.wallet_child_probe(), KeyCode::Char('c') => { self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { typed: String::new(), @@ -1787,59 +1784,6 @@ impl App { Ok(()) } - /// The core's pay/tip readiness guard, refused before any dial when the - /// wallet is unconfigured, view-only (for a tip), or not answering. `true` - /// when the send may proceed; the reason is already in the status note when - /// it is not. - fn wallet_ready(&mut self, is_tip: bool) -> bool { - match self - .rt - .block_on(self.node.wallet_readiness(is_tip)) - .refusal() - { - Some(refusal) => { - self.status_note = Some(refusal.to_string()); - false - } - None => true, - } - } - - /// Key `s` on the wallet screen: start the app-owned wallet child. The - /// balance/address readouts refresh on the next F6 — the child's RPC is not - /// answering in the same breath — so this reports the state it reached. - fn wallet_child_start(&mut self) { - self.status_note = Some(match self.node.start_wallet_child() { - Ok(()) => self.wallet_child_note(), - Err(e) => format!("wallet child: {e}"), - }); - } - - /// Key `x`: stop the child (idempotent) and drop back to the stored/env - /// wallet config. - fn wallet_child_stop(&mut self) { - self.status_note = Some(match self.node.stop_wallet_child() { - Ok(()) => "wallet child stopped".into(), - Err(e) => format!("wallet child: {e}"), - }); - } - - /// Key `p`: one probe of the running child — is its RPC answering, and is - /// the chain at the tip? The only thing that can report `ready`. - fn wallet_child_probe(&mut self) { - self.status_note = Some(self.wallet_child_note()); - } - - /// The child status line, or the copy that names what is missing. - fn wallet_child_note(&mut self) -> String { - let line = self.rt.block_on(self.node.wallet_child_refresh()).line(); - if line.is_empty() { - "no wallet child configured — set a chain source first".into() - } else { - line - } - } - fn wallet_toggle_qr(&mut self) { let Screen::Wallet { ref mut qr_modal, @@ -2109,9 +2053,6 @@ impl App { return Ok(()); }; let pk = friend.pubkey.clone(); - if !self.wallet_ready(false) { - return Ok(()); - } match self.rt.block_on(self.node.pay_invoice(&pk, atomic, memo)) { Ok(()) => self.status_note = Some("invoice sent".into()), Err(e) => self.status_note = Some(e), @@ -2125,9 +2066,6 @@ impl App { return Ok(()); }; let pk = friend.pubkey.clone(); - if !self.wallet_ready(true) { - return Ok(()); - } match self.rt.block_on(self.node.tip(&pk, atomic, memo)) { Ok(()) => self.status_note = Some("tip sent".into()), Err(e) => self.status_note = Some(e), @@ -2212,21 +2150,8 @@ impl App { draw_passphrase(f, *kind, entry.first().is_some(), entry.buf()) } Screen::Quit { prompt } => draw_quit(f, prompt.typed()), - Screen::Wallet { - receive_addr, - balance, - transfers, - qr_modal, - } => { - let child = self.node.wallet_child_line(); - draw_wallet( - f, - receive_addr, - balance, - transfers, - qr_modal.as_ref(), - &child, - ) + Screen::Wallet { receive_addr, balance, transfers, qr_modal } => { + draw_wallet(f, receive_addr, balance, transfers, qr_modal.as_ref()) } Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), } @@ -2547,7 +2472,7 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "c create i import r qr s/x child Esc back ? help", + Screen::Wallet { .. } => "c create i import r qr Esc back ? help", Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { "Enter submit Esc cancel ? help" @@ -2815,7 +2740,6 @@ fn draw_wallet( balance: &str, transfers: &[wallet::TransferRow], modal: Option<&QrModal>, - child: &str, ) { let area = f.area(); if let Some(m) = modal { @@ -2886,17 +2810,14 @@ fn draw_wallet( balance {balance} + +recent transfers " ); - let mut lines: Vec = body.lines().map(str::to_string).collect(); - // Only rendered when a chain source is configured or a child was started, so - // an unconfigured install shows the same screen it always did. - if !child.is_empty() { - lines.push(String::new()); - lines.push(format!(" {child}")); - } - lines.push(String::new()); - lines.push("recent transfers".into()); + let mut lines: Vec = body + .lines() + .map(str::to_string) + .collect(); if transfers.is_empty() { lines.push(" (none)".into()); } else { @@ -2905,7 +2826,7 @@ balance lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::(), xmr)); } } - let help = "s start child x stop child p probe c create i import r qr Esc back"; + let help = "c create i import r toggle qr Esc back"; lines.push("".into()); f.render_widget( Paragraph::new(lines.join("\n")) diff --git a/src/wallet.rs b/src/wallet.rs index 1c02368..61234cc 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -1,4 +1,3 @@ -use std::path::PathBuf; use std::time::Duration; use rand::RngCore; @@ -19,260 +18,6 @@ impl std::fmt::Display for Error { impl std::error::Error for Error {} -/// The user's choice of where the Monero daemon lives. No default remote node -/// is ever implied — every `Remote` is constructed from explicit user input. -/// -/// Wallet RPC is always loopback HTTP Digest. The chain source is what the -/// *wallet child* connects to, not what the messenger dials. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ChainSource { - /// Receive-only. No wallet child, no daemon, no spend. - None, - /// Spawn a local `monerod`. Chain traffic stays on the device. - Local { - /// Path to the `monerod` binary. - monerod_bin: PathBuf, - /// Data directory for the local daemon. - datadir: PathBuf, - }, - /// A daemon address the user supplied. Trust follows the address. - Remote { - /// Daemon host. May be loopback, `.onion`, or a clearnet host the user - /// typed explicitly. - host: String, - /// Daemon port. User-configurable; 18089 (restricted RPC) is common but - /// not a constant. - port: u16, - }, -} - -impl ChainSource { - /// Does this source name a Tor onion service? Only a `.onion` daemon needs - /// the SOCKS child; a loopback or clearnet host the user typed does not. - pub fn is_onion(&self) -> bool { - match self { - ChainSource::Remote { host, .. } => is_onion_host(host), - _ => false, - } - } - - /// Short label for a status line: what the wallet child is dialling. - pub fn label(&self) -> String { - match self { - ChainSource::None => "receive-only".to_string(), - ChainSource::Local { .. } => "local node".to_string(), - ChainSource::Remote { host, .. } if is_onion_host(host) => { - "remote onion daemon".to_string() - } - ChainSource::Remote { .. } => "remote daemon".to_string(), - } - } -} - -/// Does this host name a Tor onion service? Case-insensitive, and it needs the -/// suffix — `notonion.example` is not one. -pub fn is_onion_host(host: &str) -> bool { - host.trim().to_ascii_lowercase().ends_with(".onion") -} - -/// Remote-mode wallet config: the `monero-wallet-rpc` the user already runs -/// themselves (F7 sets it, the store keeps it, env is the migration path). -/// -/// `rpc_url` never carries `user:pass` — that is `rpc_login`, which stays in a -/// wiping buffer and is sealed at rest. This is the same three fields -/// `ONIONWIRE_WALLET_RPC` / `ONIONWIRE_WALLET_RPC_LOGIN` / -/// `ONIONWIRE_WALLET_NO_SPEND` describe. -#[derive(Clone)] -pub struct WalletConfig { - /// `http://host:port[/path]`. Loopback-only enforcement stays in - /// [`parse_http_url`]. - pub rpc_url: String, - /// `user:pass`. Never logged, never in a status line, never on disk in the - /// clear. - pub rpc_login: Zeroizing, - /// View-only deployment: `/tip` is refused locally, before any dial. - pub no_spend: bool, -} - -impl WalletConfig { - pub fn new(rpc_url: &str, rpc_login: &str, no_spend: bool) -> Self { - Self { - rpc_url: rpc_url.trim().to_string(), - rpc_login: Zeroizing::new(rpc_login.trim().to_string()), - no_spend, - } - } - - /// The password half of `user:pass` (the whole string when there is no - /// colon), for redaction. Never rendered anywhere. - pub fn secret(&self) -> &str { - match self.rpc_login.split_once(':') { - Some((_, pass)) => pass, - None => self.rpc_login.as_str(), - } - } -} - -/// Redacted on purpose: a `Debug` that prints the login turns any `{:?}` — -/// a log line, a panic message, an assert — into a credential leak. -impl std::fmt::Debug for WalletConfig { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WalletConfig") - .field("rpc_url", &self.rpc_url) - .field("rpc_login", &"") - .field("no_spend", &self.no_spend) - .finish() - } -} - -impl PartialEq for WalletConfig { - fn eq(&self, other: &Self) -> bool { - self.rpc_url == other.rpc_url - && self.rpc_login.as_str() == other.rpc_login.as_str() - && self.no_spend == other.no_spend - } -} - -impl Eq for WalletConfig {} - -impl Default for WalletConfig { - fn default() -> Self { - Self::new("", "", false) - } -} - -/// The snapshot the TUI draws (main-screen indicator + config-screen status -/// line). No dialing, no secrets: `last_error` is already sanitized and short. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct WalletStatus { - /// A stored or env config resolved to a usable `Wallet`. - pub configured: bool, - /// The last probe succeeded. **Never** set from config-existence: config is - /// not reachability. - pub connected: bool, - /// The most recent failure, sanitized for display. Cleared on success. - pub last_error: Option, - /// Human-readable balance, e.g. `123456 piconero`, or `—`. - pub balance_line: String, - /// The address `/pay` invoices would hand out, or `—`. - pub receive_address: String, -} - -/// The `—` the TUI shows for a readout that has no honest value yet. -pub const NOT_SET: &str = "—"; - -impl WalletStatus { - /// Configured, never probed: the state right after boot or a save. - pub fn idle(configured: bool) -> Self { - Self { - configured, - connected: false, - last_error: None, - balance_line: NOT_SET.to_string(), - receive_address: NOT_SET.to_string(), - } - } - - pub fn configured(&self) -> bool { - self.configured - } - - pub fn connected(&self) -> bool { - self.connected - } -} - -/// The config screen's Test-connection result. `status` is the success copy; -/// `error` is a short sanitized reason, and it never carries the login. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PingResult { - pub ok: bool, - /// Short human status, e.g. `connected`, or `not connected` on failure. - pub status: String, - /// Short sanitized reason on failure, or `None`. - pub error: Option, -} - -impl PingResult { - /// The TUI's status line: one string, never a secret. - pub fn line(&self) -> String { - match &self.error { - Some(e) => format!("{} · {e}", self.status), - None => self.status.clone(), - } - } -} - -/// Refusal copy for the pay/tip guard. Deterministic: the TUI asserts these -/// exact strings. -pub const NOT_CONFIGURED_MSG: &str = - "wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC"; -pub const NOT_CONNECTED_MSG: &str = "wallet not connected — check endpoint, login, daemon"; - -/// The pay/tip pre-check answer, in the order the guard evaluates it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Readiness { - /// Configured, reachable, and (for `/tip`) spend-capable. - Ready, - /// No stored and no env config. - NotConfigured, - /// Configured but the probe failed (or there was none). - NotConnected, - /// `/tip` on a view-only/no-spend wallet. Never a dial. - NoSpend, -} - -impl Readiness { - /// The refusal copy when the guard rejects, `None` when ready. - pub fn refusal(self) -> Option<&'static str> { - match self { - Readiness::Ready => None, - Readiness::NotConfigured => Some(NOT_CONFIGURED_MSG), - Readiness::NotConnected => Some(NOT_CONNECTED_MSG), - Readiness::NoSpend => Some(VIEW_ONLY_MSG), - } - } - - pub fn is_ready(self) -> bool { - matches!(self, Readiness::Ready) - } -} - -/// The guard's state table, and the only place its order is decided: -/// -/// 1. not configured — the copy names the fix (F7, or the env var); -/// 2. `/tip` on a no-spend wallet — it can never spend, so it is refused -/// before any dial, reachable or not (same rule as `transfer`); -/// 3. configured but not connected — check endpoint, login, daemon; -/// 4. otherwise ready. `/pay` is fine on a view-only wallet. -pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool) -> Readiness { - if !configured { - return Readiness::NotConfigured; - } - if is_tip && no_spend { - return Readiness::NoSpend; - } - if !connected { - return Readiness::NotConnected; - } - Readiness::Ready -} - -/// Display copy, not a log line: drop the secret if some lower layer put it in -/// the message, and keep it short enough for a status line. -pub(crate) fn redact(msg: &str, secret: &str) -> String { - let mut out = msg.trim().to_string(); - if !secret.is_empty() { - out = out.replace(secret, ""); - } - const MAX: usize = 120; - if out.chars().count() > MAX { - out = out.chars().take(MAX).collect(); - out.push('…'); - } - out -} - #[derive(Clone)] struct Endpoint { host: String, @@ -298,26 +43,12 @@ impl std::fmt::Debug for Endpoint { pub struct Wallet { endpoint: Option, no_spend: bool, - /// Budget for loopback management calls (`get_address`, `query_key`, - /// create/import). The wallet child is on the same box, so this stays short. - timeout_local: Duration, - /// Budget for calls that wait on the daemon (`get_info`, `get_transfers`, - /// `transfer`). A first sync or a remote daemon legitimately outlasts the - /// local budget, and treating that as "down" is what left receipts - /// permanently unverified. - timeout_chain: Duration, } /// 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. The TUI's -/// pay/tip guard returns this exact string (see [`Readiness::refusal`]). -pub const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work"; - -/// What a spend says while the wallet is not synced. Honest state, not a bug: -/// the caller retries once the daemon has caught up. -pub const NOT_SYNCED_MSG: &str = - "wallet is not synced — spend refused until the daemon reaches the chain tip"; +/// 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`. @@ -338,25 +69,12 @@ pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone wi const RPC_TIMEOUT: Duration = Duration::from_secs(5); -/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`, -/// `transfer`). A first sync or a remote daemon legitimately outlasts the -/// loopback budget; a 5s cap there leaves receipts permanently unverified. -pub const CHAIN_RPC_TIMEOUT: Duration = Duration::from_secs(60); - impl Wallet { - /// The one place the budgets are defaulted. Callers adjust them with - /// [`Wallet::with_timeouts`]. - fn new(endpoint: Option, no_spend: bool) -> Self { - Self { - endpoint, - no_spend, - timeout_local: RPC_TIMEOUT, - timeout_chain: CHAIN_RPC_TIMEOUT, - } - } - pub fn disabled() -> Self { - Self::new(None, false) + Self { + endpoint: None, + no_spend: false, + } } /// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is @@ -374,147 +92,31 @@ impl Wallet { .map(|v| Zeroizing::new(v.trim().to_string())) .filter(|v| !v.is_empty()); match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) { - Ok(endpoint) => Self::new(Some(endpoint), no_spend), + Ok(endpoint) => Self { + endpoint: Some(endpoint), + no_spend, + }, Err(e) => { eprintln!("ONIONWIRE_WALLET_RPC: {e}"); - Self::new(None, no_spend) + Self { + endpoint: None, + no_spend, + } } } } - _ => Self::new(None, no_spend), - } - } - - pub fn from_url(url: &str) -> Result { - Ok(Self::new(Some(parse_http_url(url, None)?), false)) - } - - /// Build the wallet from stored config. `rpc_url` must be a usable loopback - /// `http://` endpoint; the login is required and never echoed in an error. - pub fn from_config(cfg: &WalletConfig) -> Result { - if cfg.rpc_url.trim().is_empty() { - return Err(Error("wallet RPC endpoint required".into())); - } - let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str())) - .map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?; - Ok(Self::new(Some(ep), cfg.no_spend)) - } - - /// Boot path: stored config wins, env is the migration/fallback path, and - /// nothing at all means a disabled wallet (chat still works). - /// - /// A stored config that cannot be used does not silently dial anything: it - /// falls back to env/env-less, so a typo cannot point a spend at a host the - /// user did not mean. - pub fn for_boot(stored: Option<&WalletConfig>) -> Self { - if let Some(cfg) = stored { - match Self::from_config(cfg) { - Ok(w) => return w, - Err(e) => eprintln!("wallet config: {e}"), - } - } - Self::from_env() - } - - /// The config in use, for the F7 screen's prefill. `None` when the wallet - /// has no endpoint. The URL is rebuilt without userinfo; the login is the - /// secret half. - pub fn config(&self) -> Option { - let ep = self.endpoint.as_ref()?; - Some(WalletConfig { - rpc_url: format!("http://{}{}", host_header(&ep.host, ep.port), ep.path), - rpc_login: Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())), - no_spend: self.no_spend, - }) - } - - /// One probe, folded into the snapshot the TUI draws: `get_address` (the - /// cheapest call that also proves the RPC has a wallet open) then - /// `get_balance` for the readout. - /// - /// This is the freshness rule: `connected` is whatever the *last* probe - /// said, never "config exists". A successful probe clears `last_error`; a - /// failure sets `connected=false` and keeps `configured=true`. - pub async fn status(&self) -> WalletStatus { - if !self.configured() { - return WalletStatus::idle(false); - } - match self.get_address().await { - Ok(addr) => { - let balance = match self.get_balance().await { - Ok(b) if !b.trim().is_empty() => format!("{} piconero", b.trim()), - _ => NOT_SET.to_string(), - }; - WalletStatus { - configured: true, - connected: true, - last_error: None, - balance_line: balance, - receive_address: if addr.trim().is_empty() { - NOT_SET.to_string() - } else { - addr - }, - } - } - Err(e) => WalletStatus { - configured: true, - connected: false, - last_error: Some(self.sanitize(&e.to_string())), - balance_line: NOT_SET.to_string(), - receive_address: NOT_SET.to_string(), + _ => Self { + endpoint: None, + no_spend, }, } } - /// One-shot Test-connection probe against an endpoint the user is *typing* - /// (not necessarily the stored one). Same rules as every other call: - /// loopback only, digest required, no password in the result. - pub async fn ping(rpc_url: &str, rpc_login: &str) -> PingResult { - let cfg = WalletConfig::new(rpc_url, rpc_login, false); - let wallet = match Self::from_config(&cfg) { - Ok(w) => w, - Err(e) => { - return PingResult { - ok: false, - status: "not connected".into(), - error: Some(redact(&e.to_string(), cfg.secret())), - }; - } - }; - let st = wallet.status().await; - if st.connected { - PingResult { - ok: true, - status: "connected".into(), - error: None, - } - } else { - PingResult { - ok: false, - status: "not connected".into(), - error: st.last_error, - } - } - } - - /// Display-safe copy of an error: no RPC password, short enough for a line. - fn sanitize(&self, msg: &str) -> String { - let pass = self - .endpoint - .as_ref() - .map(|e| e.pass.as_str()) - .unwrap_or(""); - redact(msg, pass) - } - - /// Set both RPC budgets. The timeout is a property of the backend, not a - /// compile-time constant: a loopback wallet child answers fast, while a - /// remote daemon or a first sync needs a longer chain-side budget. - pub fn with_timeouts(mut self, local: Duration, chain: Duration) -> Self { - self.timeout_local = local; - self.timeout_chain = chain; - self + pub fn from_url(url: &str) -> Result { + Ok(Self { + endpoint: Some(parse_http_url(url, None)?), + no_spend: false, + }) } /// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`. @@ -549,14 +151,8 @@ impl Wallet { if self.no_spend { return Err(Error(VIEW_ONLY_MSG.into())); } - // Honest gate: a wallet that has not caught up to the chain tip cannot - // build a spend, so refuse instead of letting the RPC fail opaquely. - // Fail closed — if readiness cannot be proven, the spend is refused. - if !self.can_spend().await { - return Err(Error(NOT_SYNCED_MSG.into())); - } let sent = self - .chain_rpc( + .rpc( "transfer", serde_json::json!({ "destinations": [{"amount": amount, "address": address}], @@ -595,7 +191,7 @@ impl Wallet { pub async fn get_transfers(&self) -> Result> { let v = self - .chain_rpc( + .rpc( "get_transfers", serde_json::json!({"in": true, "pending": true}), ) @@ -625,53 +221,6 @@ impl Wallet { json_str(&v, "balance") } - /// Unlocked balance in piconero — the part a spend can actually use. - pub async fn unlocked_balance(&self) -> Result { - let v = self - .rpc("get_balance", serde_json::json!({"account_index": 0})) - .await?; - json_str(&v, "unlocked_balance")? - .trim() - .parse::() - .map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into())) - } - - /// The real readiness predicate: the daemon has reached the chain tip and - /// the wallet has scanned up to it. `synchronized` must be explicitly true — - /// a missing field is not-ready, never a silent pass. - pub async fn chain_ready(&self) -> Result { - let v = self.chain_rpc("get_info", serde_json::json!({})).await?; - let synced = v - .get("synchronized") - .and_then(|b| b.as_bool()) - .unwrap_or(false); - let height = v.get("height").and_then(|h| h.as_u64()).unwrap_or(0); - let target = v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0); - Ok(synced && height > 0 && (target == 0 || height >= target)) - } - - /// May this wallet attempt a spend? Fail closed: any readiness doubt is a - /// refusal, and a view-only/no-spend wallet never spends. - pub async fn can_spend(&self) -> bool { - !self.no_spend && self.configured() && self.chain_ready().await.unwrap_or(false) - } - - /// The stricter signal for the spend UI: chain-ready *and* holding unlocked - /// funds. Zero unlocked balance is not spend-ready. - pub async fn spend_ready(&self) -> Result { - if !self.chain_ready().await? { - return Ok(false); - } - Ok(self.unlocked_balance().await? > 0) - } - - /// Receipt verification is only honest on a synced wallet: `get_transfers` - /// on a wallet that has not scanned to the tip cannot see the tx, so a - /// "miss" would be a lie. Until ready, receipts stay `verified=0`. - pub async fn can_verify_receipts(&self) -> bool { - self.configured() && self.chain_ready().await.unwrap_or(false) - } - /// Create a new spend-capable wallet on the RPC (`create_wallet`). The /// user does not paste a key — the daemon generates the seed. Returns that /// seed once (from `query_key mnemonic`) so the UI can show a backup @@ -696,7 +245,11 @@ impl Wallet { let v = self .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) .await - .map_err(|e| Error(format!("wallet created but seed backup unavailable: {e}")))?; + .map_err(|e| { + Error(format!( + "wallet created but seed backup unavailable: {e}" + )) + })?; json_str(&v, "key") } @@ -727,28 +280,7 @@ impl Wallet { Ok(()) } - /// Loopback management call: the wallet child is on the same box, so it gets - /// the short budget. async fn rpc(&self, method: &str, params: serde_json::Value) -> Result { - self.rpc_with(method, params, self.timeout_local).await - } - - /// Chain-dependent call (`get_info`, `get_transfers`, `transfer`): it waits - /// on the daemon, so it gets the longer budget. - async fn chain_rpc( - &self, - method: &str, - params: serde_json::Value, - ) -> Result { - self.rpc_with(method, params, self.timeout_chain).await - } - - async fn rpc_with( - &self, - method: &str, - params: serde_json::Value, - budget: Duration, - ) -> Result { let ep = self .endpoint .as_ref() @@ -760,7 +292,7 @@ impl Wallet { "params": params, }) .to_string(); - let raw = post_timeout(ep, &build_req(ep, &body, None), budget).await?; + let raw = post_timeout(ep, &build_req(ep, &body, None)).await?; let status = http_status(&raw).unwrap_or(0); if status == 200 { return Err(Error( @@ -779,7 +311,7 @@ impl Wallet { )); } let auth = digest_authorization(ep, &challenge)?; - let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?; + let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth))).await?; parse_json_rpc(&raw) } } @@ -908,8 +440,8 @@ fn host_header(host: &str, port: u16) -> String { const MAX_RPC_BYTES: usize = 1024 * 1024; -async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result> { - tokio::time::timeout(budget, http_post(ep, req.as_bytes())) +async fn post_timeout(ep: &Endpoint, req: &str) -> Result> { + tokio::time::timeout(RPC_TIMEOUT, http_post(ep, req.as_bytes())) .await .map_err(|_| Error("wallet RPC timed out".into()))? } diff --git a/src/wallet_child.rs b/src/wallet_child.rs deleted file mode 100644 index 2ff650a..0000000 --- a/src/wallet_child.rs +++ /dev/null @@ -1,1606 +0,0 @@ -//! Wallet child lifecycle: the app owns `monero-wallet-rpc` — and, when the -//! user chose a local chain source, `monerod` — instead of asking the user to -//! start them and export an env var. -//! -//! Locked shape: -//! -//! * The wallet child speaks loopback HTTP Digest only -//! (`--rpc-bind-ip 127.0.0.1`, a random free port, generated `--rpc-login`). -//! * The RPC credentials are generated once, sealed with the store data key and -//! kept in the encrypted SQLCipher store. They are never a plaintext file. -//! * The chain source is the user's explicit choice ([`ChainSource`]) — never a -//! compiled-in public node. -//! * A `.onion` daemon is reached through a SOCKS child: the bundled `arti` -//! binary run as `arti proxy -p `, with **TCP loopback only** (arti -//! 2.6.0 / tor-config 0.46 have no AF_UNIX listener — `Listen` is IP-only and -//! arti's `port_info` says AF_UNIX is future work, arti#1965). The wallet -//! child is then pointed at it with `--proxy socks5://127.0.0.1:` -//! *and* `--daemon-address :`. The messenger's in-process -//! `arti-client` is never handed to the wallet child, and C-tor is never -//! used. -//! * The two Tor clients do not share state: the SOCKS child gets its own -//! `state_dir`/`cache_dir` under the wallet dir. -//! * `--trusted-daemon` is never passed: a remote daemon is untrusted. - -use std::fs; -use std::net::{Ipv4Addr, SocketAddr, TcpStream}; -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; -use std::process::{Child, Command}; -use std::sync::Mutex; -use std::time::{Duration, Instant}; - -use rand::RngCore; -use zeroize::Zeroizing; - -use crate::store::Store; -use crate::wallet::{self, ChainSource, Wallet}; - -/// `monerod` RPC port for a local chain source. Unrestricted RPC default; the -/// wallet child is the only thing that dials it. -pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081; - -/// Name of the `monero-wallet-rpc` binary when the caller does not point at one. -pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc"; - -/// Name of the `arti` binary the SOCKS child runs when the caller does not -/// point at one. `arti proxy -p `; there is no in-process SOCKS listener. -pub const DEFAULT_ARTI_BIN: &str = "arti"; - -/// How long the app waits for the SOCKS listener to accept a connection before -/// it gives up and reports the failure instead of spawning a wallet child that -/// can only hang. Arti binds its listener before it bootstraps (bootstrap is -/// on-demand), so this is a listener budget, not a Tor-bootstrap budget. -pub const SOCKS_READY_TIMEOUT: Duration = Duration::from_secs(20); - -/// Per-attempt connect budget for the SOCKS readiness probe. -pub const SOCKS_PROBE_TIMEOUT: Duration = Duration::from_millis(500); - -/// Gap between readiness-probe attempts. -pub const SOCKS_PROBE_INTERVAL: Duration = Duration::from_millis(100); - -/// The scheme Monero's `--proxy` needs for SOCKS5. A bare `host:port` means -/// SOCKS4a (docs/proxies.md), which is *not* what this app asks for. -pub const SOCKS5_SCHEME: &str = "socks5://"; - -/// Errors from wallet child setup and lifecycle. -#[derive(Debug)] -pub struct ChildError(String); - -impl std::fmt::Display for ChildError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} - -impl std::error::Error for ChildError {} - -type Result = std::result::Result; - -/// The app-owned wallet child set (`monerod` when local, `arti proxy` when the -/// daemon is a `.onion`, `monero-wallet-rpc` always unless `None`). -pub struct WalletChild { - source: ChainSource, - wallet_rpc_bin: PathBuf, - arti_bin: PathBuf, - wallet_dir: PathBuf, - wallet_filename: String, - /// Pinned SOCKS listen port. `None` (the default) means a random free - /// loopback port, exactly like the wallet RPC port. - socks_port: Option, - /// Readiness budget for the SOCKS listener. Tests shrink it; production - /// uses [`SOCKS_READY_TIMEOUT`]. - socks_ready_timeout: Duration, - monerod: Mutex>, - socks: Mutex>, - wallet_rpc: Mutex>, -} - -impl WalletChild { - /// Configure the children. Nothing is spawned until [`WalletChild::start`]. - /// - /// `wallet_dir` is created 0700 and holds the wallet file plus the daemon - /// state; the caller passes `$ONIONWIRE_HOME/wallet`. - pub fn new( - source: ChainSource, - wallet_dir: PathBuf, - wallet_filename: Option, - ) -> Result { - let wallet_filename = - wallet_filename.unwrap_or_else(|| wallet::DEFAULT_WALLET_FILENAME.to_string()); - if wallet_filename.trim().is_empty() { - return Err(ChildError("wallet filename required".into())); - } - create_dir_700(&wallet_dir).map_err(|e| ChildError(format!("wallet dir: {e}")))?; - Ok(Self { - source, - wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN), - arti_bin: PathBuf::from(DEFAULT_ARTI_BIN), - wallet_dir, - wallet_filename, - socks_port: None, - socks_ready_timeout: SOCKS_READY_TIMEOUT, - monerod: Mutex::new(None), - socks: Mutex::new(None), - wallet_rpc: Mutex::new(None), - }) - } - - /// Point at a specific `monero-wallet-rpc` binary (explicit config, tests). - pub fn with_wallet_rpc_bin(mut self, bin: PathBuf) -> Self { - self.wallet_rpc_bin = bin; - self - } - - /// Point at a specific `arti` binary (explicit config, tests). - pub fn with_arti_bin(mut self, bin: PathBuf) -> Self { - self.arti_bin = bin; - self - } - - /// Pin the SOCKS listen port instead of taking a random free loopback one. - /// Loopback only either way: `arti proxy -p ` binds `127.0.0.1` and - /// `::1` and nothing else. - pub fn with_socks_port(mut self, port: u16) -> Self { - self.socks_port = Some(port); - self - } - - /// Shrink the SOCKS readiness budget (tests). - pub fn with_socks_ready_timeout(mut self, budget: Duration) -> Self { - self.socks_ready_timeout = budget; - self - } - - /// The user's chain-source choice. `None` is receive-only: no child at all. - pub fn chain_source(&self) -> &ChainSource { - &self.source - } - - pub fn wallet_dir(&self) -> &Path { - &self.wallet_dir - } - - pub fn wallet_filename(&self) -> &str { - &self.wallet_filename - } - - /// This child's own settings, in the persisted shape. - pub fn config(&self) -> ChildConfig { - ChildConfig { - source: self.source.clone(), - wallet_rpc_bin: self.wallet_rpc_bin.clone(), - arti_bin: self.arti_bin.clone(), - wallet_filename: self.wallet_filename.clone(), - } - } - - /// Whether this configuration spawns any child. - pub fn is_enabled(&self) -> bool { - !matches!(self.source, ChainSource::None) - } - - /// Does this host name a Tor onion service? Only `.onion` daemons need the - /// SOCKS child; a loopback or clearnet host the user typed does not. - pub fn is_onion_host(host: &str) -> bool { - wallet::is_onion_host(host) - } - - /// Is the `monero-wallet-rpc` child itself alive? The wallet RPC is the - /// process every wallet call goes through, so this — not "some child is up" - /// — is what decides `ready` vs `exited`. - pub fn wallet_rpc_running(&self) -> bool { - let _ = self.reap_exited(); - self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false) - } - - /// Is a tracked child still alive? Polls the process table; an exited child - /// is reaped here so a later `stop` is a no-op. - pub fn running(&self) -> bool { - let _ = self.reap_exited(); - self.monerod.lock().map(|g| g.is_some()).unwrap_or(false) - || self.socks.lock().map(|g| g.is_some()).unwrap_or(false) - || self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false) - } - - /// True when a tracked child has exited since the last poll. Watching the - /// child is polling + `try_wait`: there is no pidfd plumbing in std, and the - /// honest thing is to report what `try_wait` actually says. - pub fn child_exited(&self) -> bool { - self.reap_exited() - } - - fn reap_exited(&self) -> bool { - let mut exited = false; - for slot in [&self.monerod, &self.socks, &self.wallet_rpc] { - let Ok(mut guard) = slot.lock() else { - continue; - }; - let gone = match guard.as_mut() { - Some(child) => matches!(child.try_wait(), Ok(Some(_))), - None => false, - }; - if gone { - *guard = None; - exited = true; - } - } - exited - } - - /// The exact argv used to spawn `arti` as the SOCKS child: `arti proxy -p - /// `, with its *own* state and cache dirs so the two Tor clients in - /// one app never share state silently. - /// - /// `-p` is the arti CLI's `socks-port` argument (arti 2.6.0 `src/lib.rs`); - /// it binds localhost only (`Listen::new_localhost`, tor-config 0.46 - /// `listen.rs`: "We interpret standalone ports to be localhost - /// addresses" — `[::1, 127.0.0.1]`). There is no Unix-socket listen target - /// to prefer: `Listen` is IP-only and arti's `port_info` says AF_UNIX is - /// future work (arti#1965). - pub fn arti_proxy_argv( - bin: &Path, - port: u16, - state_dir: &Path, - cache_dir: &Path, - ) -> Vec { - vec![ - bin.display().to_string(), - "proxy".into(), - "-p".into(), - port.to_string(), - "-o".into(), - format!("storage.state_dir=\"{}\"", state_dir.display()), - "-o".into(), - format!("storage.cache_dir=\"{}\"", cache_dir.display()), - ] - } - - /// The `--proxy` value the wallet child is given. `socks5://` is explicit - /// on purpose: Monero's `--proxy` defaults to SOCKS4a for a bare - /// `host:port` (`docs/proxies.md`). - pub fn socks_proxy_url(port: u16) -> String { - format!("{SOCKS5_SCHEME}127.0.0.1:{port}") - } - - /// Wait for the SOCKS listener to accept a connection, with an explicit - /// budget so a dead proxy fails visibly instead of hanging the wallet - /// screen. - /// - /// This proves the *listener* is up (arti binds before it bootstraps); - /// it does not prove the Tor circuit works. It also does not resolve the - /// `.onion` name locally — the name travels inside the SOCKS request. - pub fn socks_listener_ready(port: u16, budget: Duration) -> Result<()> { - let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); - let deadline = Instant::now() + budget; - let mut last = None; - while Instant::now() <= deadline { - match TcpStream::connect_timeout(&addr, SOCKS_PROBE_TIMEOUT) { - Ok(_) => return Ok(()), - Err(e) => last = Some(e), - } - std::thread::sleep(SOCKS_PROBE_INTERVAL); - } - Err(ChildError(format!( - "SOCKS proxy on 127.0.0.1:{port} did not accept a connection within {}s \ - ({}) — not spawning a wallet child against a dead proxy", - budget.as_secs_f32(), - last.map(|e| e.to_string()).unwrap_or_default() - ))) - } - - /// The honest one-liner a UI can show for the configured chain source. A - /// `.onion` daemon buys transport privacy, not host privacy: the daemon - /// operator still sees the wallet's addresses during sync. - pub fn chain_copy(source: &ChainSource) -> String { - match source { - ChainSource::None => "receive-only: no daemon, no chain traffic".into(), - ChainSource::Local { .. } => { - "local monerod on this box (loopback): no Tor, no remote operator".into() - } - ChainSource::Remote { host, port } if Self::is_onion_host(host) => format!( - "remote {host}:{port} over Tor (SOCKS5 on loopback, never clearnet) — Tor hides \ - the transport, not the host: the daemon operator still sees your addresses \ - during sync" - ), - ChainSource::Remote { host, port } => format!( - "remote {host}:{port} over clearnet, because you typed it — the daemon operator \ - and your ISP see the traffic" - ), - } - } - - /// The `--daemon-address` for each chain source. A local source is the - /// loopback daemon this struct owns; a remote one is exactly what the user - /// typed. - pub fn daemon_address(source: &ChainSource) -> Option { - match source { - ChainSource::None => None, - ChainSource::Local { .. } => Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")), - ChainSource::Remote { host, port } => Some(format!("{host}:{port}")), - } - } - - /// Bind a loopback port and hand it back. The listener is dropped - /// immediately; the port is only used to keep two instances from colliding. - pub fn pick_port() -> Result { - let listener = std::net::TcpListener::bind("127.0.0.1:0") - .map_err(|e| ChildError(format!("bind loopback port: {e}")))?; - let port = listener - .local_addr() - .map_err(|e| ChildError(format!("local_addr: {e}")))? - .port(); - drop(listener); - Ok(port) - } - - /// The exact argv used to spawn `monerod`. Single source of truth: `start` - /// spawns this and the tests assert on it. - pub fn monerod_argv(bin: &Path, datadir: &Path, rpc_port: u16) -> Vec { - vec![ - bin.display().to_string(), - "--non-interactive".into(), - "--data-dir".into(), - datadir.display().to_string(), - "--rpc-bind-ip".into(), - "127.0.0.1".into(), - "--rpc-bind-port".into(), - rpc_port.to_string(), - ] - } - - /// The exact argv used to spawn `monero-wallet-rpc`. Digest login is - /// mandatory and the bind is loopback; `--trusted-daemon` is deliberately - /// absent. - /// - /// `socks_proxy` is the wallet child's `--proxy` target. It is only passed - /// for a `.onion` daemon, and it is always a `socks5://127.0.0.1:` - /// string: the wallet child talks plain SOCKS5 to the app's own `arti proxy` - /// child. The messenger's in-process Arti client is never handed to it. - pub fn wallet_rpc_argv( - bin: &Path, - port: u16, - login: &str, - wallet_dir: &Path, - daemon_address: Option<&str>, - socks_proxy: Option<&str>, - ) -> Vec { - let mut argv = vec![ - bin.display().to_string(), - "--rpc-bind-ip".into(), - "127.0.0.1".into(), - "--rpc-bind-port".into(), - port.to_string(), - "--rpc-login".into(), - login.to_string(), - "--wallet-dir".into(), - wallet_dir.display().to_string(), - ]; - if let Some(addr) = daemon_address { - argv.push("--daemon-address".into()); - argv.push(addr.to_string()); - } - if let Some(proxy) = socks_proxy { - argv.push("--proxy".into()); - argv.push(proxy.to_string()); - } - argv - } - - /// Start the children (idempotent per source) and hand back the loopback - /// client the app should talk to. - /// - /// `None` -> `Ok(None)`: receive-only, nothing is spawned. The `Store` is - /// what gates every spawn: the SOCKS child, like the wallet child, is only - /// reachable through an unlocked store. - pub fn start(&self, store: &Store) -> Result> { - if !self.is_enabled() { - return Ok(None); - } - if self.running() { - return Err(ChildError("wallet child already running".into())); - } - match self.start_children(store) { - Ok(client) => Ok(client), - Err(e) => { - // A failure after the SOCKS child came up must not leave the - // listener (or monerod) orphaned behind the error. - let _ = self.stop(); - Err(e) - } - } - } - - fn start_children(&self, store: &Store) -> Result> { - // Local chain source: own monerod first, so the wallet child has a - // daemon to dial. - if let ChainSource::Local { - monerod_bin, - datadir, - } = &self.source - { - ensure_parent(datadir)?; - let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT); - let child = spawn(&argv, "monerod")?; - let mut guard = self - .monerod - .lock() - .map_err(|e| ChildError(format!("monerod lock: {e}")))?; - *guard = Some(child); - } - - // A `.onion` daemon is only reachable through SOCKS. The app bundles the - // `arti` binary as that proxy; it must be up before the wallet child - // starts, or the wallet child sits there failing to dial its daemon. - let socks_proxy = match &self.source { - ChainSource::Remote { host, .. } if Self::is_onion_host(host) => { - Some(self.start_socks_proxy()?) - } - _ => None, - }; - - let (user, pass) = self.creds(store)?; - let port = Self::pick_port()?; - let login = format!("{user}:{}", pass.as_str()); - let daemon = Self::daemon_address(&self.source); - let argv = Self::wallet_rpc_argv( - &self.wallet_rpc_bin, - port, - &login, - &self.wallet_dir, - daemon.as_deref(), - socks_proxy.as_deref(), - ); - let child = spawn(&argv, "monero-wallet-rpc")?; - { - let mut guard = self - .wallet_rpc - .lock() - .map_err(|e| ChildError(format!("wallet-rpc lock: {e}")))?; - if guard.is_some() { - return Err(ChildError("wallet child already running".into())); - } - *guard = Some(child); - } - // monero-wallet-rpc creates the wallet file 0600; make that true even if - // it already existed with looser bits. - harden_wallet_file(&self.wallet_dir.join(&self.wallet_filename)); - Ok(Some(WalletClient { - url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()), - no_spend: false, - })) - } - - /// Spawn `arti proxy -p ` and hand back its wallet-child-facing - /// `--proxy` value. - /// - /// Its state and cache live under the wallet dir, not in the messenger's - /// Arti state dir: the two Tor clients in this app do not share state. - fn start_socks_proxy(&self) -> Result { - let port = match self.socks_port { - Some(p) => p, - None => Self::pick_port()?, - }; - let state_dir = self.wallet_dir.join("arti-socks").join("state"); - let cache_dir = self.wallet_dir.join("arti-socks").join("cache"); - for dir in [state_dir.parent(), Some(&state_dir), Some(&cache_dir)] - .into_iter() - .flatten() - { - create_dir_700(dir).map_err(|e| ChildError(format!("arti dir: {e}")))?; - } - let argv = Self::arti_proxy_argv(&self.arti_bin, port, &state_dir, &cache_dir); - let child = spawn(&argv, "arti proxy")?; - { - let mut guard = self - .socks - .lock() - .map_err(|e| ChildError(format!("socks lock: {e}")))?; - *guard = Some(child); - } - Self::socks_listener_ready(port, self.socks_ready_timeout)?; - Ok(Self::socks_proxy_url(port)) - } - - /// Stop every child. Idempotent, and tolerant of a child that already - /// exited on its own. The wallet child goes first so no wallet RPC can be - /// mid-request against the chain, then the SOCKS listener, then `monerod`. - pub fn stop(&self) -> Result<()> { - kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?; - kill_slot(&self.socks, "arti proxy")?; - kill_slot(&self.monerod, "monerod")?; - Ok(()) - } - - /// Load the sealed creds, or generate them once and seal them in the store. - /// The store is the only place they live; `wallet_dir` never sees them. - /// - /// The record is a read-modify-write: the settings written by a config - /// screen are never clobbered by first-start credential generation. - fn creds(&self, store: &Store) -> Result<(String, Zeroizing)> { - let existing = store - .load_wallet_child() - .map_err(|e| ChildError(format!("read wallet-child creds: {e}")))?; - // Persist what this child is running with, before anything is spawned. - let record = merge_record(existing.as_deref(), self.config().record_fields()); - store - .save_wallet_child(&record) - .map_err(|e| ChildError(format!("seal wallet-child config: {e}")))?; - - if let Some(raw) = existing.as_deref() - && let Ok(parsed) = serde_json::from_str::(raw) - && let Some(user) = parsed - .get("user") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - && let Some(pass) = parsed - .get("pass") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - { - return Ok((user.to_string(), Zeroizing::new(pass.to_string()))); - } - let (user, pass) = generate_creds(); - let record = merge_record( - Some(&record), - serde_json::json!({"user": user, "pass": pass.as_str()}), - ); - store - .save_wallet_child(&record) - .map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?; - Ok((user, pass)) - } -} - -/// Everything the app needs to spawn the wallet child, minus the RPC creds: -/// which chain to dial, which binaries to run, which wallet file to open. -/// -/// Persisted as part of the sealed `wallet_child` record (the generated creds -/// live in the same record), so a configured child survives a restart without -/// env vars. This is the shape the SDK's `ChainConfig` record maps to. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ChildConfig { - /// The user's chain-source choice. `None` is receive-only: nothing spawns. - pub source: ChainSource, - /// `monero-wallet-rpc`. A bare name is resolved on `PATH`; Android passes an - /// absolute path out of the app's native library directory. - pub wallet_rpc_bin: PathBuf, - /// `arti`, run as the SOCKS child for a `.onion` daemon only. - pub arti_bin: PathBuf, - /// Wallet file name inside `$ONIONWIRE_HOME/wallet`. - pub wallet_filename: String, -} - -impl Default for ChildConfig { - fn default() -> Self { - Self { - source: ChainSource::None, - wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN), - arti_bin: PathBuf::from(DEFAULT_ARTI_BIN), - wallet_filename: wallet::DEFAULT_WALLET_FILENAME.to_string(), - } - } -} - -impl ChildConfig { - /// Nothing spawns: the wallet screen is receive-only. - pub fn receive_only() -> Self { - Self::default() - } - - /// Does this configuration spawn a child at all? - pub fn is_enabled(&self) -> bool { - !matches!(self.source, ChainSource::None) - } - - /// The chain-source label a status line shows. - pub fn source_label(&self) -> String { - self.source.label() - } - /// Reject a configuration that could only fail later (empty binary path, - /// empty host, port 0) *before* it is persisted or spawned. - pub fn validate(&self) -> Result<()> { - if self.wallet_filename.trim().is_empty() { - return Err(ChildError("wallet filename required".into())); - } - // Receive-only spawns nothing, so a binary path there is not a setting - // to reject — a Kotlin caller legitimately leaves both empty for it. - if matches!(self.source, ChainSource::None) { - return Ok(()); - } - if self.wallet_rpc_bin.as_os_str().is_empty() { - return Err(ChildError("monero-wallet-rpc path required".into())); - } - if self.arti_bin.as_os_str().is_empty() { - return Err(ChildError("arti path required".into())); - } - match &self.source { - ChainSource::None => {} - ChainSource::Local { - monerod_bin, - datadir, - } => { - if monerod_bin.as_os_str().is_empty() { - return Err(ChildError("monerod path required for a local node".into())); - } - if datadir.as_os_str().is_empty() { - return Err(ChildError( - "monerod data dir required for a local node".into(), - )); - } - } - ChainSource::Remote { host, port } => { - if host.trim().is_empty() { - return Err(ChildError( - "daemon host required for a remote daemon".into(), - )); - } - if *port == 0 { - return Err(ChildError( - "daemon port required for a remote daemon".into(), - )); - } - } - } - Ok(()) - } - - /// Build the child this configuration describes. `wallet_dir` is the - /// caller's `$ONIONWIRE_HOME/wallet`. - pub fn build(&self, wallet_dir: PathBuf) -> Result { - self.validate()?; - Ok(WalletChild::new( - self.source.clone(), - wallet_dir, - Some(self.wallet_filename.clone()), - )? - .with_wallet_rpc_bin(self.wallet_rpc_bin.clone()) - .with_arti_bin(self.arti_bin.clone())) - } - - /// The settings half of the sealed record, for - /// [`merge_record`] + `Store::save_wallet_child`. - pub fn record_fields(&self) -> serde_json::Value { - serde_json::json!({ - "source": source_to_json(&self.source), - "wallet_rpc_bin": self.wallet_rpc_bin.display().to_string(), - "arti_bin": self.arti_bin.display().to_string(), - "wallet_filename": self.wallet_filename, - }) - } - - /// Read the stored settings back. `Ok(None)` when the record holds creds but - /// no source block — a record written before the settings were persisted. - pub fn from_record(raw: &str) -> Result> { - let parsed: serde_json::Value = serde_json::from_str(raw) - .map_err(|e| ChildError(format!("parse wallet-child record: {e}")))?; - let Some(source) = parsed.get("source") else { - return Ok(None); - }; - let mut cfg = Self { - source: source_from_json(source)?, - ..Self::default() - }; - if let Some(v) = parsed.get("wallet_rpc_bin").and_then(|v| v.as_str()) { - cfg.wallet_rpc_bin = PathBuf::from(v); - } - if let Some(v) = parsed.get("arti_bin").and_then(|v| v.as_str()) { - cfg.arti_bin = PathBuf::from(v); - } - if let Some(v) = parsed.get("wallet_filename").and_then(|v| v.as_str()) { - cfg.wallet_filename = v.to_string(); - } - Ok(Some(cfg)) - } -} - -/// Merge `fields` into the sealed record JSON, keeping every other key — the -/// generated RPC creds in particular. A missing or non-object `existing` starts -/// a fresh record. -pub fn merge_record(existing: Option<&str>, fields: serde_json::Value) -> String { - let mut obj = existing - .and_then(|raw| serde_json::from_str::(raw).ok()) - .and_then(|v| v.as_object().cloned()) - .unwrap_or_default(); - if let serde_json::Value::Object(patch) = fields { - for (k, v) in patch { - obj.insert(k, v); - } - } - serde_json::Value::Object(obj).to_string() -} - -/// The observable state of the app-owned wallet child. Derived from the real -/// process + the last probe, never from env-var presence. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WalletChildState { - /// No child configured, or none started yet. - Off, - /// The child process is up but its wallet RPC has not answered. - Connecting, - /// The wallet answered, but the chain is not at the tip yet. - Syncing, - /// Wallet RPC answered and the chain is synced. - Ready, - /// A started child has exited (crashed or killed). Never reported ready. - Exited, -} - -impl WalletChildState { - /// The lowercase label the SDK and the TUI show. - pub fn as_str(self) -> &'static str { - match self { - WalletChildState::Off => "off", - WalletChildState::Connecting => "connecting", - WalletChildState::Syncing => "syncing", - WalletChildState::Ready => "ready", - WalletChildState::Exited => "exited", - } - } -} - -/// One snapshot of the child. Cheap to read: no dial, no lock held across work. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct WalletChildStatus { - pub state: WalletChildState, - /// A child process is alive right now. - pub running: bool, - /// A chain source is configured (not receive-only), whether or not it runs. - pub configured: bool, - /// The chain-source label: `receive-only` / `local node` / - /// `remote onion daemon` / `remote daemon`. - pub chain_source: String, - /// The last failure, display-ready. Never carries the generated login. - pub last_error: Option, -} - -impl WalletChildStatus { - /// The one-line form a TUI status row or a Kotlin toast can show. Empty when - /// nothing is configured, so an unconfigured install renders no row. - pub fn line(&self) -> String { - if !self.configured && self.state == WalletChildState::Off { - return String::new(); - } - let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source); - if let Some(err) = &self.last_error { - line.push_str(" · "); - line.push_str(err); - } - line - } -} - -/// The loopback client built from the generated URL — the production path when -/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but -/// numeric loopback. -#[derive(Debug, Clone)] -pub struct WalletClient { - url: String, - no_spend: bool, -} - -impl WalletClient { - /// Build the [`Wallet`] this child serves. The chain-side RPC budget is the - /// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync - /// or a remote daemon legitimately outlasts a loopback round trip. - pub fn into_wallet(self) -> Wallet { - Wallet::from_url(&self.url) - .expect("wallet child URL is always valid loopback with creds") - .with_no_spend(self.no_spend) - } - - /// The loopback URL. Carries the generated creds — do not log it. - pub fn url(&self) -> &str { - &self.url - } - - pub fn no_spend(&self) -> bool { - self.no_spend - } - - pub fn set_no_spend(&mut self, on: bool) { - self.no_spend = on; - } -} - -/// Random, shell- and HTTP-safe credentials: `[a-z0-9]` only. No `:`, no quotes, -/// no whitespace — the login goes through `--rpc-login` and an HTTP Digest -/// header. The user and the password are drawn from separate randomness. -fn generate_creds() -> (String, Zeroizing) { - let mut user_buf = [0u8; 16]; - let mut pass_buf = [0u8; 24]; - let mut rng = rand::thread_rng(); - rng.fill_bytes(&mut user_buf); - rng.fill_bytes(&mut pass_buf); - (rand_token(&user_buf), Zeroizing::new(rand_token(&pass_buf))) -} - -fn rand_token(buf: &[u8]) -> String { - const ALPH: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789"; - let mut out = String::with_capacity(buf.len()); - for b in buf { - out.push(ALPH[(*b as usize) % ALPH.len()] as char); - } - out -} - -/// Snapshot of the user's chain-source choice, stored beside the creds so the -/// UI can show what the child was started against. -fn source_to_json(source: &ChainSource) -> serde_json::Value { - match source { - ChainSource::None => serde_json::json!({"kind": "none"}), - ChainSource::Local { - monerod_bin, - datadir, - } => serde_json::json!({ - "kind": "local", - "monerod_bin": monerod_bin.display().to_string(), - "datadir": datadir.display().to_string(), - }), - ChainSource::Remote { host, port } => serde_json::json!({ - "kind": "remote", - "host": host, - "port": port, - }), - } -} - -fn source_from_json(value: &serde_json::Value) -> Result { - let kind = value - .get("kind") - .and_then(|k| k.as_str()) - .unwrap_or_default(); - match kind { - "none" => Ok(ChainSource::None), - "local" => { - let monerod_bin = value - .get("monerod_bin") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| { - ChildError("stored local chain source has no monerod path".into()) - })?; - let datadir = value - .get("datadir") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| ChildError("stored local chain source has no data dir".into()))?; - Ok(ChainSource::Local { - monerod_bin: PathBuf::from(monerod_bin), - datadir: PathBuf::from(datadir), - }) - } - "remote" => { - let host = value - .get("host") - .and_then(|v| v.as_str()) - .filter(|s| !s.trim().is_empty()) - .ok_or_else(|| ChildError("stored remote chain source has no host".into()))?; - let port = value - .get("port") - .and_then(|v| v.as_u64()) - .filter(|p| (1..=65535).contains(p)) - .ok_or_else(|| ChildError("stored remote chain source has no port".into()))?; - Ok(ChainSource::Remote { - host: host.to_string(), - port: port as u16, - }) - } - other => Err(ChildError(format!("unknown chain source kind {other:?}"))), - } -} - -fn spawn(argv: &[String], what: &str) -> Result { - let (bin, args) = argv - .split_first() - .ok_or_else(|| ChildError(format!("empty argv for {what}")))?; - Command::new(bin) - .args(args) - .spawn() - .map_err(|e| ChildError(format!("spawn {what}: {e}"))) -} - -fn kill_slot(slot: &Mutex>, what: &str) -> Result<()> { - let mut guard = slot - .lock() - .map_err(|e| ChildError(format!("{what} lock: {e}")))?; - if let Some(child) = guard.as_mut() { - // An already-exited child (reaped or not) makes kill() an error: check - // first so `stop` stays idempotent. - if !matches!(child.try_wait(), Ok(Some(_))) { - let _ = child.kill(); - let _ = child.wait(); - } - } - *guard = None; - Ok(()) -} - -fn create_dir_700(path: &Path) -> std::io::Result<()> { - fs::create_dir_all(path)?; - let mut perms = fs::metadata(path)?.permissions(); - perms.set_mode(0o700); - fs::set_permissions(path, perms) -} - -fn ensure_parent(path: &Path) -> Result<()> { - if let Some(parent) = path.parent() - && !parent.as_os_str().is_empty() - { - create_dir_700(parent).map_err(|e| ChildError(format!("datadir parent: {e}")))?; - } - Ok(()) -} - -/// The wallet file is a spend authority: keep it 0600. -fn harden_wallet_file(path: &Path) { - let Ok(meta) = fs::metadata(path) else { - return; - }; - let mut perms = meta.permissions(); - perms.set_mode(0o600); - let _ = fs::set_permissions(path, perms); -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - fn tmp_dir(tag: &str) -> PathBuf { - let dir = - std::env::temp_dir().join(format!("onionwire-child-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - dir - } - - /// Fake children live in their own dir: `Store::open_at*` already creates - /// `/arti` and `/cache` (the app's Arti state), so a fake `arti` - /// at the home root would collide with that directory. - fn fake_dir(dir: &Path) -> PathBuf { - let path = dir.join("fake-bins"); - fs::create_dir_all(&path).unwrap(); - path - } - - fn open_store(dir: &Path) -> Store { - Store::open_at_with_passphrase(dir, "child-test-pass").expect("open store") - } - - /// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks. - fn fake_bin(dir: &Path, name: &str, log: &Path) -> PathBuf { - let path = dir.join(name); - let mut f = fs::File::create(&path).unwrap(); - writeln!(f, "#!/bin/sh").unwrap(); - writeln!(f, ": > '{}'", log.display()).unwrap(); - writeln!( - f, - "for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done", - log.display() - ) - .unwrap(); - writeln!(f, "sleep 30").unwrap(); - drop(f); - let mut perms = fs::metadata(&path).unwrap().permissions(); - perms.set_mode(0o700); - fs::set_permissions(&path, perms).unwrap(); - path - } - - fn argv_from(log: &Path) -> Vec { - fs::read_to_string(log) - .unwrap_or_default() - .lines() - .map(str::to_string) - .collect() - } - - /// The fake child writes its argv after exec: poll instead of racing it. - fn wait_for_argv(log: &Path) -> Vec { - for _ in 0..60 { - let argv = argv_from(log); - if !argv.is_empty() { - return argv; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } - argv_from(log) - } - - fn local_source(dir: &Path, monerod: PathBuf) -> ChainSource { - ChainSource::Local { - monerod_bin: monerod, - datadir: dir.join("monerod-data"), - } - } - - #[test] - fn none_source_is_disabled_and_starts_nothing() { - let dir = tmp_dir("none"); - let store = open_store(&dir); - let arti_log = dir.join("arti.argv"); - let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None) - .unwrap() - .with_arti_bin(fake_bin(&fake_dir(&dir), "arti", &arti_log)); - assert!(!child.is_enabled()); - assert!(child.start(&store).unwrap().is_none()); - assert!(!child.running()); - assert!( - !arti_log.exists(), - "receive-only must not spawn the SOCKS child" - ); - } - - /// A live listener for the readiness gate to dial. `arti proxy -p ` - /// binds localhost only, so 127.0.0.1 is exactly what the gate probes. - fn held_loopback_port() -> (std::net::TcpListener, u16) { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - (listener, port) - } - - fn freed_loopback_port() -> u16 { - held_loopback_port().1 - } - - /// A fake child that also records its pid, so a test can prove the process - /// is gone after `stop` — an orphaned SOCKS listener is the failure mode. - fn fake_bin_with_pid(dir: &Path, name: &str, log: &Path, pid_file: &Path) -> PathBuf { - let path = dir.join(name); - let mut f = fs::File::create(&path).unwrap(); - writeln!(f, "#!/bin/sh").unwrap(); - writeln!(f, "echo $$ > '{}'", pid_file.display()).unwrap(); - writeln!(f, ": > '{}'", log.display()).unwrap(); - writeln!( - f, - "for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done", - log.display() - ) - .unwrap(); - writeln!(f, "sleep 30").unwrap(); - drop(f); - let mut perms = fs::metadata(&path).unwrap().permissions(); - perms.set_mode(0o700); - fs::set_permissions(&path, perms).unwrap(); - path - } - - /// Poll for the child's pid file: the script writes it after exec. - fn child_pid(pid_file: &Path) -> u32 { - for _ in 0..60 { - if let Ok(raw) = fs::read_to_string(pid_file) - && let Ok(pid) = raw.trim().parse::() - { - return pid; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } - panic!("child never wrote {}", pid_file.display()); - } - - /// The process must actually be gone, not merely dropped from a slot. - fn wait_for_process_exit(pid: u32) { - let proc_dir = PathBuf::from(format!("/proc/{pid}")); - for _ in 0..60 { - if !proc_dir.exists() { - return; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } - panic!("pid {pid} is still alive — orphaned child"); - } - - fn pairs(argv: &[String]) -> Vec<(String, String)> { - argv.windows(2) - .map(|w| (w[0].clone(), w[1].clone())) - .collect() - } - - #[test] - fn arti_proxy_argv_binds_a_loopback_port_and_isolates_state() { - let dir = tmp_dir("arti-argv"); - let bin = PathBuf::from("/opt/arti/arti"); - let state = dir.join("wallet").join("arti-socks").join("state"); - let cache = dir.join("wallet").join("arti-socks").join("cache"); - let argv = WalletChild::arti_proxy_argv(&bin, 45123, &state, &cache); - assert_eq!(argv[0], bin.display().to_string()); - assert_eq!(argv[1], "proxy"); - assert!( - pairs(&argv).contains(&("-p".into(), "45123".into())), - "{argv:?}" - ); - // `-p` binds localhost only (arti's `socks-port` arg); there is no - // Unix-socket listen target in arti 2.6.0 / tor-config 0.46. - assert!(!argv.iter().any(|a| a == "--port"), "{argv:?}"); - assert!( - argv.iter() - .any(|a| a.contains(&state.display().to_string())), - "the SOCKS child gets its own state dir: {argv:?}" - ); - assert!( - argv.iter() - .any(|a| a.contains(&cache.display().to_string())), - "the SOCKS child gets its own cache dir: {argv:?}" - ); - } - - #[test] - fn onion_remote_points_the_wallet_child_at_the_socks_proxy_and_the_onion() { - let dir = tmp_dir("onion-argv"); - let bin = PathBuf::from("/opt/monero/monero-wallet-rpc"); - let proxy = WalletChild::socks_proxy_url(45678); - let argv = WalletChild::wallet_rpc_argv( - &bin, - 39127, - "owuser:owpass", - &dir, - Some("abcdefghijklmnop.onion:18089"), - Some(&proxy), - ); - let pairs = pairs(&argv); - assert!( - pairs.contains(&("--proxy".into(), "socks5://127.0.0.1:45678".into())), - "{argv:?}" - ); - assert!( - argv.iter().any(|a| a.contains("127.0.0.1:45678")), - "the literal loopback:port the card asks for: {argv:?}" - ); - assert!( - pairs.contains(&( - "--daemon-address".into(), - "abcdefghijklmnop.onion:18089".into() - )), - "{argv:?}" - ); - // The wallet child speaks plain SOCKS5 to loopback. It never gets the - // messenger's in-process Arti client, and the daemon stays untrusted. - assert!(!argv.iter().any(|a| a == "--trusted-daemon"), "{argv:?}"); - } - - #[test] - fn onion_detection_is_case_insensitive_and_needs_the_suffix() { - assert!(WalletChild::is_onion_host("abcdefgh.onion")); - assert!(WalletChild::is_onion_host("ABCDEFGH.ONION")); - assert!(WalletChild::is_onion_host(" abcdefgh.onion ")); - assert!(!WalletChild::is_onion_host("onion.example.com")); - assert!(!WalletChild::is_onion_host("127.0.0.1")); - assert!(!WalletChild::is_onion_host("node.onion.example.com")); - } - - #[test] - fn chain_copy_says_tor_hides_the_transport_not_the_host() { - let onion = WalletChild::chain_copy(&ChainSource::Remote { - host: "abcdefghijklmnop.onion".into(), - port: 18089, - }); - assert!(onion.contains("Tor"), "{onion}"); - assert!( - onion.contains("hides the transport, not the host"), - "{onion}" - ); - assert!( - onion.contains("operator still sees your addresses"), - "{onion}" - ); - - let clearnet = WalletChild::chain_copy(&ChainSource::Remote { - host: "node.example.com".into(), - port: 18089, - }); - assert!(clearnet.contains("clearnet"), "{clearnet}"); - assert!(!clearnet.contains("Tor"), "{clearnet}"); - - let local = WalletChild::chain_copy(&local_source( - Path::new("/tmp"), - PathBuf::from("/usr/bin/monerod"), - )); - assert!(local.contains("local monerod"), "{local}"); - assert_eq!( - WalletChild::chain_copy(&ChainSource::None), - "receive-only: no daemon, no chain traffic" - ); - } - - /// The readiness gate is real code, not a stub: it accepts a listener that - /// is up and gives up with a typed error, inside its budget, when nothing - /// is listening. - #[test] - fn socks_listener_ready_accepts_a_live_listener_and_times_out_without_one() { - let (held, port) = held_loopback_port(); - assert!( - WalletChild::socks_listener_ready(port, Duration::from_millis(200)).is_ok(), - "a live listener must pass" - ); - drop(held); - - let started = std::time::Instant::now(); - let err = WalletChild::socks_listener_ready(port, Duration::from_millis(200)) - .unwrap_err() - .to_string(); - assert!(err.contains("SOCKS"), "{err}"); - assert!(err.contains(&port.to_string()), "{err}"); - assert!( - started.elapsed() < Duration::from_secs(5), - "the probe must honour its budget, took {:?}", - started.elapsed() - ); - } - - /// The spawn path: a `.onion` remote starts `arti proxy -p ` first, - /// the wallet child is pointed at it, and stopping the wallet child takes - /// the SOCKS listener with it. - #[test] - fn onion_remote_start_spawns_the_socks_child_then_stops_it_with_the_wallet() { - let dir = tmp_dir("onion-start"); - let store = open_store(&dir); - let arti_log = dir.join("arti.argv"); - let arti_pid = dir.join("arti.pid"); - let rpc_log = dir.join("wallet-rpc.argv"); - let rpc_pid = dir.join("wallet-rpc.pid"); - - // The gate dials 127.0.0.1:; the test holds that port open so the - // gate passes without a real arti binary. The gate itself is covered by - // `socks_listener_ready_*` above. - let (held, socks_port) = held_loopback_port(); - - let child = WalletChild::new( - ChainSource::Remote { - host: "abcdefghijklmnop.onion".into(), - port: 18089, - }, - dir.join("wallet"), - None, - ) - .unwrap() - .with_arti_bin(fake_bin_with_pid( - &fake_dir(&dir), - "arti", - &arti_log, - &arti_pid, - )) - .with_wallet_rpc_bin(fake_bin_with_pid( - &dir, - "monero-wallet-rpc", - &rpc_log, - &rpc_pid, - )) - .with_socks_port(socks_port); - - let client = child.start(&store).unwrap().expect("enabled child"); - assert!(child.running(), "both children must be tracked"); - assert!(client.url().contains("127.0.0.1"), "{}", client.url()); - - let arti_argv = wait_for_argv(&arti_log); - // The fake logs only the arguments (`$@`), not argv[0]. - assert_eq!(arti_argv[0], "proxy", "{arti_argv:?}"); - assert!( - pairs(&arti_argv).contains(&("-p".into(), socks_port.to_string())), - "{arti_argv:?}" - ); - - let rpc_argv = wait_for_argv(&rpc_log); - let rpc_pairs = pairs(&rpc_argv); - assert!( - rpc_pairs.contains(&("--proxy".into(), format!("socks5://127.0.0.1:{socks_port}"))), - "{rpc_argv:?}" - ); - assert!( - rpc_pairs.contains(&( - "--daemon-address".into(), - "abcdefghijklmnop.onion:18089".into() - )), - "{rpc_argv:?}" - ); - - let arti_proc = child_pid(&arti_pid); - let rpc_proc = child_pid(&rpc_pid); - drop(held); - - child.stop().unwrap(); - assert!(!child.running()); - wait_for_process_exit(arti_proc); - wait_for_process_exit(rpc_proc); - } - - /// A wallet child that cannot dial its daemon must not be spawned at all: - /// a dead SOCKS proxy is a visible error, not a hung wallet screen. - #[test] - fn onion_remote_start_fails_visibly_when_the_socks_proxy_never_listens() { - let dir = tmp_dir("onion-dead-proxy"); - let store = open_store(&dir); - let arti_pid = dir.join("arti.pid"); - let arti_log = dir.join("arti.argv"); - let rpc_log = dir.join("wallet-rpc.argv"); - let port = freed_loopback_port(); - - let child = WalletChild::new( - ChainSource::Remote { - host: "abcdefghijklmnop.onion".into(), - port: 18089, - }, - dir.join("wallet"), - None, - ) - .unwrap() - .with_arti_bin(fake_bin_with_pid( - &fake_dir(&dir), - "arti", - &arti_log, - &arti_pid, - )) - .with_wallet_rpc_bin(fake_bin(&fake_dir(&dir), "monero-wallet-rpc", &rpc_log)) - .with_socks_port(port) - .with_socks_ready_timeout(Duration::from_millis(300)); - - let err = child.start(&store).unwrap_err().to_string(); - assert!(err.contains("SOCKS"), "{err}"); - assert!(err.contains(&port.to_string()), "{err}"); - assert!( - !rpc_log.exists(), - "no wallet child may be spawned against a dead proxy" - ); - assert!(!child.running(), "a failed start leaves nothing running"); - wait_for_process_exit(child_pid(&arti_pid)); - } - - /// A loopback or clearnet daemon the user typed never gets a proxy, and - /// never starts the SOCKS child: `--proxy` is for `.onion` only. - #[test] - fn loopback_and_clearnet_remotes_carry_no_proxy_and_spawn_no_socks_child() { - for host in ["127.0.0.1", "node.example.com"] { - let dir = tmp_dir(&format!("nosocks-{}", host.replace('.', "-"))); - let store = open_store(&dir); - let arti_log = dir.join("arti.argv"); - let rpc_log = dir.join("wallet-rpc.argv"); - let child = WalletChild::new( - ChainSource::Remote { - host: host.into(), - port: 18089, - }, - dir.join("wallet"), - None, - ) - .unwrap() - .with_arti_bin(fake_bin(&fake_dir(&dir), "arti", &arti_log)) - .with_wallet_rpc_bin(fake_bin( - &fake_dir(&dir), - "monero-wallet-rpc", - &rpc_log, - )); - - child.start(&store).unwrap().expect("enabled child"); - let rpc_argv = wait_for_argv(&rpc_log); - assert!( - pairs(&rpc_argv).contains(&("--daemon-address".into(), format!("{host}:18089"))), - "{rpc_argv:?}" - ); - assert!( - !rpc_argv.iter().any(|a| a == "--proxy"), - "no SOCKS for {host}: {rpc_argv:?}" - ); - assert!(!arti_log.exists(), "no SOCKS child for {host}"); - child.stop().unwrap(); - } - } - - #[test] - fn daemon_address_matches_each_chain_source() { - assert_eq!(WalletChild::daemon_address(&ChainSource::None), None); - assert_eq!( - WalletChild::daemon_address(&local_source( - Path::new("/tmp"), - PathBuf::from("/usr/bin/monerod") - )), - Some("127.0.0.1:18081".into()) - ); - assert_eq!( - WalletChild::daemon_address(&ChainSource::Remote { - host: "node.example.com".into(), - port: 18089 - }), - Some("node.example.com:18089".into()) - ); - } - - #[test] - fn wallet_rpc_argv_carries_the_locked_flags() { - let dir = tmp_dir("argv"); - let bin = PathBuf::from("/opt/monero/monero-wallet-rpc"); - let argv = WalletChild::wallet_rpc_argv( - &bin, - 39127, - "owuser:owpass", - &dir, - Some("127.0.0.1:18081"), - None, - ); - let pairs: Vec<(&str, &str)> = argv - .windows(2) - .map(|w| (w[0].as_str(), w[1].as_str())) - .collect(); - assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}"); - assert!(pairs.contains(&("--rpc-bind-port", "39127")), "{argv:?}"); - assert!( - pairs.contains(&("--rpc-login", "owuser:owpass")), - "{argv:?}" - ); - assert!( - pairs.contains(&("--wallet-dir", dir.to_str().unwrap())), - "{argv:?}" - ); - assert!( - pairs.contains(&("--daemon-address", "127.0.0.1:18081")), - "{argv:?}" - ); - assert_eq!(argv[0], bin.display().to_string()); - assert!( - !argv.iter().any(|a| a == "--trusted-daemon"), - "a remote daemon is untrusted: {argv:?}" - ); - } - - #[test] - fn monerod_argv_binds_loopback_and_uses_the_datadir() { - let dir = tmp_dir("monerod-argv"); - let datadir = dir.join("chain"); - let argv = WalletChild::monerod_argv( - &PathBuf::from("/usr/bin/monerod"), - &datadir, - DEFAULT_MONEROD_RPC_PORT, - ); - let pairs: Vec<(&str, &str)> = argv - .windows(2) - .map(|w| (w[0].as_str(), w[1].as_str())) - .collect(); - assert!( - pairs.contains(&("--data-dir", datadir.to_str().unwrap())), - "{argv:?}" - ); - assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}"); - assert!(pairs.contains(&("--rpc-bind-port", "18081")), "{argv:?}"); - } - - /// The real spawn path: a local chain source starts monerod, then - /// monero-wallet-rpc, with exactly the argv the builders produce — and the - /// creds come out of the encrypted store, not a file in the wallet dir. - #[test] - fn start_spawns_both_children_with_the_built_argv() { - let dir = tmp_dir("start"); - let store = open_store(&dir); - let monerod_log = dir.join("monerod.argv"); - let rpc_log = dir.join("wallet-rpc.argv"); - let datadir = dir.join("monerod-data"); - - let child = WalletChild::new( - local_source(&dir, fake_bin(&dir, "monerod", &monerod_log)), - dir.join("wallet"), - None, - ) - .unwrap() - .with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log)); - - let client = child.start(&store).unwrap().expect("enabled child"); - assert!(child.running(), "children must be tracked"); - - let monerod_argv = wait_for_argv(&monerod_log); - assert!( - monerod_argv - .windows(2) - .any(|w| w[0] == "--data-dir" && w[1] == datadir.display().to_string()), - "{monerod_argv:?}" - ); - - let rpc_argv = wait_for_argv(&rpc_log); - assert!( - rpc_argv.iter().any(|a| a == "--rpc-bind-ip"), - "{rpc_argv:?}" - ); - assert!(rpc_argv.iter().any(|a| a == "127.0.0.1"), "{rpc_argv:?}"); - assert!(rpc_argv.iter().any(|a| a == "--rpc-login"), "{rpc_argv:?}"); - assert!(rpc_argv.iter().any(|a| a == "--wallet-dir"), "{rpc_argv:?}"); - assert!( - rpc_argv.windows(2).any(|w| w[0] == "--daemon-address"), - "{rpc_argv:?}" - ); - assert!( - !rpc_argv.iter().any(|a| a == "--trusted-daemon"), - "{rpc_argv:?}" - ); - - // The wallet client is the generated loopback URL, and it carries the - // same login the child was spawned with. - let url = client.url().to_string(); - assert!(url.starts_with("http://"), "{url}"); - assert!(url.contains("@127.0.0.1:"), "{url}"); - let login_arg = rpc_argv - .iter() - .position(|a| a == "--rpc-login") - .map(|i| rpc_argv[i + 1].clone()) - .expect("login"); - let (user, pass) = login_arg.split_once(':').expect("user:pass"); - assert_ne!(user, pass, "user and password must be independent"); - assert!( - url.contains(user) && url.contains(pass), - "{url} vs {login_arg}" - ); - - // Creds live sealed in the store, and nothing in the wallet dir holds - // them in the clear. - let sealed = store.load_wallet_child().unwrap().expect("sealed creds"); - assert!(sealed.contains(user)); - for entry in fs::read_dir(child.wallet_dir()).unwrap() { - let path = entry.unwrap().path(); - let body = fs::read(&path).unwrap_or_default(); - assert!( - !body.windows(pass.len()).any(|w| w == pass.as_bytes()), - "{} holds the RPC password in the clear", - path.display() - ); - } - - child.stop().unwrap(); - assert!(!child.running(), "stop must kill both children"); - child.stop().unwrap(); // idempotent - assert!(child.start(&store).is_ok(), "restart after stop"); - child.stop().unwrap(); - } - - #[test] - fn creds_are_stable_across_restarts_and_never_regenerated() { - let dir = tmp_dir("creds"); - let store = open_store(&dir); - let rpc_log = dir.join("wallet-rpc.argv"); - let child = WalletChild::new( - ChainSource::Remote { - host: "node.example.com".into(), - port: 18089, - }, - dir.join("wallet"), - None, - ) - .unwrap() - .with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log)); - - let first = child.start(&store).unwrap().unwrap().url().to_string(); - child.stop().unwrap(); - let second = child.start(&store).unwrap().unwrap().url().to_string(); - child.stop().unwrap(); - // Same login, different random port: the creds persist in the store - // instead of being regenerated per launch. - assert_eq!(login_of(&first), login_of(&second), "creds must persist"); - assert!(first.contains("127.0.0.1"), "{first}"); - } - - /// `http://user:pass@127.0.0.1:port/json_rpc` -> `user:pass`. - fn login_of(url: &str) -> String { - let rest = url.strip_prefix("http://").expect("http url"); - rest.split('@').next().expect("userinfo").to_string() - } - - #[test] - fn pick_port_is_free_loopback_and_bindable() { - let port = WalletChild::pick_port().unwrap(); - assert!(port > 0); - let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap(); - drop(listener); - } - - #[test] - fn stop_without_start_is_a_noop() { - let dir = tmp_dir("stop"); - let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap(); - child.stop().unwrap(); - assert!(!child.running()); - assert!(!child.child_exited()); - } - - #[test] - fn wallet_dir_is_created_0700() { - let dir = tmp_dir("perm"); - let wallet_dir = dir.join("wallet"); - let _ = WalletChild::new(ChainSource::None, wallet_dir.clone(), None).unwrap(); - let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o700, "wallet dir must be 0700"); - } -} diff --git a/tests/wallet.rs b/tests/wallet.rs index 6a57b87..10fb7a1 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -4,10 +4,7 @@ use std::sync::{Arc, Mutex}; use ed25519_dalek::SigningKey; use onionwire::pay; -use onionwire::wallet::{ - self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet, - WalletConfig, WalletStatus, readiness, -}; +use onionwire::wallet::{self, TransferRow, Wallet}; use onionwire::{PaymentWrite, Store}; use rand::rngs::OsRng; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -16,6 +13,7 @@ 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(), @@ -114,23 +112,24 @@ async fn mock_get_address_parses_string() { #[tokio::test] async fn mock_create_address_and_transfer() { - let addr_hex = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; 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(move |method| match method { - // A spend is only attempted on a synced wallet. - "get_info" => synced_info(), - _ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)), - }), - )); - let w = recording_wallet(port); + let addr = listener.local_addr().unwrap(); + let canned = json_rpc_ok( + r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB","tx_hash":"abc123"}"#, + ); + tokio::spawn(serve_digest_then(listener, canned.clone())); + let w = Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{}", addr.port())).unwrap(); let created = w.create_address().await.expect("create_address"); assert!(created.starts_with('8')); - let txid = w.transfer(addr_hex, 1).await.expect("transfer"); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(serve_digest_then(listener, canned)); + let w = Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{}", addr.port())).unwrap(); + let txid = w + .transfer("8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", 1) + .await + .expect("transfer"); assert_eq!(txid, "abc123"); } @@ -296,12 +295,6 @@ fn rpc_result(result: &str) -> String { format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#) } -/// What a fully synced wallet answers to `get_info`: the daemon has reached the -/// tip and the wallet has scanned it. This is the honest readiness signal. -fn synced_info() -> String { - rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#) -} - fn recording_wallet(port: u16) -> Wallet { Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("url") } @@ -328,7 +321,10 @@ async fn no_spend_mode_refuses_transfer_with_no_rpc_request() { .await .unwrap_err() .to_string(); - assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}"); + 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:?}"); @@ -387,7 +383,6 @@ async fn view_only_wallet_maps_transfer_failure_to_clear_message() { Arc::clone(&log), Arc::new(|method| match method { "query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), - "get_info" => synced_info(), _ => rpc_error(-18, "No transaction created"), }), )); @@ -419,7 +414,6 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() { Arc::new(Mutex::new(Vec::new())), Arc::new(|method| match method { "query_key" => rpc_result(r#"{"key":"00112233"}"#), - "get_info" => synced_info(), _ => rpc_error(-18, "No transaction created"), }), )); @@ -470,8 +464,8 @@ async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() { "filename missing: {create}" ); assert!( - seen.iter() - .any(|r| r.contains(r#""method":"query_key""#) && r.contains("mnemonic")), + seen.iter().any(|r| r.contains(r#""method":"query_key""#) + && r.contains("mnemonic")), "must read mnemonic after create: {seen:?}" ); } @@ -509,9 +503,7 @@ async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() { listener, Arc::clone(&log), Arc::new(|method| match method { - "restore_deterministic_wallet" => rpc_result( - r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#, - ), + "restore_deterministic_wallet" => rpc_result(r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#), _ => rpc_error(-1, "unexpected method"), }), )); @@ -624,624 +616,3 @@ async fn mock_digest_auth_accepted() { let got = w.get_address().await.expect("get_address"); assert!(got.starts_with('4'), "got {got}"); } - -/// Answers the Digest challenge, then holds the reply for `delay`. Lets a test -/// prove which call classes get which budget. -async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { - while let Ok((mut sock, _)) = listener.accept().await { - 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(); - if !req.contains("Authorization:") { - let _ = sock.write_all(digest_401().as_bytes()).await; - continue; - } - tokio::time::sleep(delay).await; - let body = match rpc_method(&req).as_str() { - "get_info" => synced_info(), - _ => rpc_result( - r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, - ), - }; - let _ = sock.write_all(http_200_body(&body).as_bytes()).await; - } -} - -const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; - -/// Readiness is a real predicate, not "sync made some progress": a wallet whose -/// daemon has not reached the tip is not ready, refuses to spend, and does not -/// even ask the RPC for a transfer. -#[tokio::test] -async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() { - 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 { - "get_info" => { - rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#) - } - _ => rpc_result(r#"{"tx_hash":"abc123"}"#), - }), - )); - let w = recording_wallet(port); - assert!( - !w.chain_ready().await.expect("get_info"), - "must not be ready" - ); - assert!( - !w.can_verify_receipts().await, - "an unsynced wallet cannot verify receipts" - ); - - let err = w.transfer(SPEND_ADDR, 1).await.unwrap_err().to_string(); - assert!(err.to_ascii_lowercase().contains("not synced"), "got {err}"); - let seen = log.lock().expect("log").clone(); - assert!( - !seen.iter().any(|r| r.contains("\"method\":\"transfer\"")), - "a not-ready wallet must not attempt a spend: {seen:?}" - ); -} - -/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready, -/// never a silent pass. Fail closed. -#[tokio::test] -async fn missing_or_behind_synchronized_is_not_ready() { - for info in [ - r#"{"height":10}"#, - r#"{"height":100,"target_height":200,"synchronized":true}"#, - r#"{"height":0,"target_height":0,"synchronized":true}"#, - r#"{"synchronized":"true"}"#, - ] { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let canned = rpc_result(info); - tokio::spawn(serve_recording( - listener, - Arc::new(Mutex::new(Vec::new())), - Arc::new(move |_| canned.clone()), - )); - let w = recording_wallet(port); - assert!( - !w.chain_ready().await.expect("get_info"), - "{info} must not read as ready" - ); - } -} - -#[tokio::test] -async fn synced_wallet_is_ready_and_spends() { - 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 { - "get_info" => synced_info(), - _ => rpc_result(r#"{"tx_hash":"abc123"}"#), - }), - )); - let w = recording_wallet(port); - assert!(w.chain_ready().await.expect("get_info")); - assert!(w.can_verify_receipts().await); - assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123"); -} - -/// `spend_ready` is the stricter signal for the spend UI: synced *and* holding -/// unlocked funds. Zero unlocked balance is not spend-ready. -#[tokio::test] -async fn spend_ready_needs_an_unlocked_balance() { - for (unlocked, ready) in [("0", false), ("5", true)] { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let balance = rpc_result(&format!( - r#"{{"balance":"{unlocked}","unlocked_balance":"{unlocked}"}}"# - )); - tokio::spawn(serve_recording( - listener, - Arc::new(Mutex::new(Vec::new())), - Arc::new(move |method| match method { - "get_info" => synced_info(), - "get_balance" => balance.clone(), - _ => rpc_result(r#"{}"#), - }), - )); - let w = recording_wallet(port); - assert_eq!(w.spend_ready().await.expect("spend_ready"), ready); - } -} - -/// The honest not-ready state: a receipt whose history *would* match stays -/// verified=0 while the wallet is unsynced. (node.rs gates on the same -/// predicate via `can_verify_receipts`.) -#[tokio::test] -async fn unsynced_wallet_leaves_a_matching_receipt_unverified() { - let dir = tempfile::tempdir().expect("tempdir"); - let store = Store::open_at_with_passphrase(dir.path(), "onionwire-test").expect("open"); - let sk = SigningKey::generate(&mut OsRng); - let pk = sk.verifying_key().to_bytes(); - store.upsert_friend(&pk, "peer.onion", None).unwrap(); - let addr = xmr_addr(); - let rcp = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "5", &addr, 1).unwrap(); - let id = store - .insert_payment( - &pk, - PaymentWrite { - dir: "in", - kind: "receipt", - amount_atomic: &rcp.amount_atomic, - address: &rcp.address, - memo: "", - txid: Some(&rcp.txid), - verified: false, - }, - ) - .unwrap(); - - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let addr_owned = addr.clone(); - tokio::spawn(serve_recording( - listener, - Arc::new(Mutex::new(Vec::new())), - Arc::new(move |method| match method { - "get_info" => { - rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#) - } - "get_transfers" => rpc_result(&format!( - r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"# - )), - _ => rpc_result(r#"{}"#), - }), - )); - let w = recording_wallet(port); - - // The same shape node.rs::ingest_receipt runs. - if w.can_verify_receipts().await - && let Ok(rows) = w.get_transfers().await - && wallet::transfers_match(&rows, &rcp.txid, &rcp.amount_atomic, &rcp.address) - { - store.mark_verified(id).unwrap(); - } - assert!( - !store.list_payments(&pk).unwrap()[0].verified, - "an unsynced wallet must leave the receipt unverified" - ); -} - -/// Chain-dependent calls get a longer budget than local wallet-management calls, -/// and the budget is the backend's to set — not a hard-coded 5s. -#[tokio::test] -async fn chain_calls_get_a_longer_budget_than_local_calls() { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - tokio::spawn(serve_delayed( - listener, - std::time::Duration::from_millis(400), - )); - let w = recording_wallet(port).with_timeouts( - std::time::Duration::from_millis(150), - std::time::Duration::from_millis(2000), - ); - let err = w.get_address().await.unwrap_err().to_string(); - assert!( - err.to_ascii_lowercase().contains("timed out"), - "the local call must hit the short budget: {err}" - ); - assert!( - w.chain_ready() - .await - .expect("get_info within the chain budget"), - "chain calls must outlast daemon latency" - ); -} - -// --------------------------------------------------------------------------- -// Stored wallet config (F7): read at boot, sealed at rest, never in an error. -// --------------------------------------------------------------------------- - -/// The exact refusal copy the TUI asserts. Pinned here as literals so a copy -/// change is a test failure, and cross-checked against the constants the guard -/// returns. -#[test] -fn readiness_guard_refuses_each_state_with_exact_copy() { - assert_eq!( - NOT_CONFIGURED_MSG, - "wallet not configured — open F7 to set it up, or set ONIONWIRE_WALLET_RPC" - ); - assert_eq!( - NOT_CONNECTED_MSG, - "wallet not connected — check endpoint, login, daemon" - ); - assert_eq!(Readiness::NotConfigured.refusal(), Some(NOT_CONFIGURED_MSG)); - assert_eq!(Readiness::NotConnected.refusal(), Some(NOT_CONNECTED_MSG)); - assert_eq!(Readiness::NoSpend.refusal(), Some(VIEW_ONLY_MSG)); - assert_eq!(Readiness::Ready.refusal(), None); - - // not configured beats everything else, whatever else is true. - assert_eq!( - readiness(false, false, false, true), - Readiness::NotConfigured - ); - assert_eq!(readiness(false, true, true, true), Readiness::NotConfigured); - // configured but not reachable. - assert_eq!(readiness(true, false, false, true), Readiness::NotConnected); - assert_eq!( - readiness(true, false, false, false), - Readiness::NotConnected - ); - // view-only: /tip is refused on its own terms, /pay keeps working. - assert_eq!(readiness(true, true, true, true), Readiness::NoSpend); - assert_eq!(readiness(true, false, true, true), Readiness::NoSpend); - assert_eq!(readiness(true, true, true, false), Readiness::Ready); - // allowed only when configured + connected + spend-capable. - assert_eq!(readiness(true, true, false, true), Readiness::Ready); - assert!(!readiness(true, false, false, true).is_ready()); -} - -#[test] -fn wallet_config_debug_never_prints_the_login() { - let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2XYZ", true); - let dbg = format!("{cfg:?}"); - assert!(!dbg.contains("hunter2XYZ"), "debug leaked the login: {dbg}"); - assert!(dbg.contains("127.0.0.1:18083"), "{dbg}"); -} - -/// Stored config is what boot reads; env is the migration/fallback path. -#[test] -fn boot_reads_stored_config_over_env_and_falls_back_to_env() { - let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - unsafe { - std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:envpass@127.0.0.1:18083"); - std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN"); - std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND"); - } - - let stored = WalletConfig::new("http://127.0.0.1:18084", "ow:storedpass", true); - let w = Wallet::for_boot(Some(&stored)); - assert!(w.configured(), "stored config must configure the wallet"); - assert!(w.no_spend(), "stored no_spend must win over env"); - let in_use = w.config().expect("configured wallet has a config"); - assert_eq!(in_use.rpc_url, "http://127.0.0.1:18084/json_rpc"); - assert_eq!(in_use.rpc_login.as_str(), "ow:storedpass"); - assert!(!in_use.rpc_url.contains("storedpass"), "{}", in_use.rpc_url); - - // No stored config: the env vars still boot headless / pre-F7 installs. - let w = Wallet::for_boot(None); - assert!(w.configured()); - let in_use = w.config().expect("env wallet has a config"); - assert_eq!(in_use.rpc_url, "http://127.0.0.1:18083/json_rpc"); - assert_eq!(in_use.rpc_login.as_str(), "ow:envpass"); - assert!(!w.no_spend()); - - // A stored config that cannot be used falls through to env, not to a dial. - let broken = WalletConfig::new("http://example.com:18083", "ow:x", false); - assert!(Wallet::for_boot(Some(&broken)).configured()); - - // Neither: disabled, and the refusal says so. - unsafe { - std::env::remove_var("ONIONWIRE_WALLET_RPC"); - } - let w = Wallet::for_boot(None); - assert!(!w.configured()); - assert!(w.config().is_none()); -} - -#[test] -fn malformed_config_errors_never_carry_the_password() { - let cfg = WalletConfig::new("http://example.com:18083", "ow:hunter2XYZ", false); - let err = Wallet::from_config(&cfg).unwrap_err().to_string(); - assert!(!err.contains("hunter2XYZ"), "password leaked: {err}"); - let cfg = WalletConfig::new("http://127.0.0.1:18083", "", false); - let err = Wallet::from_config(&cfg).unwrap_err().to_string(); - assert!(!err.is_empty()); - let cfg = WalletConfig::new("", "ow:hunter2XYZ", false); - assert!( - Wallet::from_config(&cfg).is_err(), - "empty url is not a config" - ); -} - -/// One row, sealed with the store data key on top of SQLCipher, and nothing in -/// the clear on disk. -#[test] -fn stored_wallet_config_round_trips_and_the_login_is_sealed_on_disk() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap(); - assert!( - store.load_wallet_config().unwrap().is_none(), - "a fresh store has no wallet config" - ); - - let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:cfg-secret-xyz", false); - store.save_wallet_config(&cfg).unwrap(); - let got = store.load_wallet_config().unwrap().expect("stored config"); - assert_eq!(got.rpc_url, "http://127.0.0.1:18083"); - assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz"); - assert!(!got.no_spend); - - // Saving again replaces the single row. - let cfg2 = WalletConfig::new("http://127.0.0.1:18085", "ow:second-secret-abc", true); - store.save_wallet_config(&cfg2).unwrap(); - let got = store.load_wallet_config().unwrap().expect("stored config"); - assert_eq!(got.rpc_url, "http://127.0.0.1:18085"); - assert_eq!(got.rpc_login.as_str(), "ow:second-secret-abc"); - assert!(got.no_spend); - - // An empty URL clears the stored config instead of storing a half-config. - store - .save_wallet_config(&WalletConfig::new("", "", false)) - .unwrap(); - assert!(store.load_wallet_config().unwrap().is_none()); - - store.save_wallet_config(&cfg).unwrap(); - store.checkpoint_wal().unwrap(); - drop(store); - for name in ["onionwire.db", "onionwire.db-wal", "onionwire.db-shm"] { - let Ok(bytes) = std::fs::read(dir.path().join(name)) else { - continue; - }; - assert!( - !contains_bytes(&bytes, b"cfg-secret-xyz"), - "{name} holds the RPC login in the clear" - ); - } - // The readers come back to a config that still decrypts. - let store = Store::open_at_with_passphrase(dir.path(), "cfg-pass").unwrap(); - let got = store - .load_wallet_config() - .unwrap() - .expect("reopened config"); - assert_eq!(got.rpc_login.as_str(), "ow:cfg-secret-xyz"); -} - -fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool { - haystack.windows(needle.len()).any(|w| w == needle) -} - -/// The one-shot probe the config screen's Test button fires. It is against the -/// *typed* endpoint, so it must not touch the live wallet. -#[tokio::test] -async fn ping_reports_success_and_sanitizes_failures() { - // A reachable endpoint: digest challenge, then get_address. - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let canned = json_rpc_ok( - r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, - ); - tokio::spawn(serve_digest_then(listener, canned)); - let ok = wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await; - assert!(ok.ok, "{ok:?}"); - assert_eq!(ok.status, "connected"); - assert_eq!(ok.error, None); - assert!(!format!("{ok:?}").contains("ping-secret-xyz")); - - // Nothing listening: refused, and the reason carries no password. - let dead = freed_loopback_port(); - let bad = wallet::Wallet::ping(&format!("http://127.0.0.1:{dead}"), "ow:ping-secret-xyz").await; - assert!(!bad.ok, "{bad:?}"); - assert!(bad.error.is_some(), "{bad:?}"); - assert!( - !bad.error.as_deref().unwrap().contains("ping-secret-xyz"), - "{bad:?}" - ); - - // A non-loopback host is refused locally, before any dial. - let off = wallet::Wallet::ping("http://node.example.com:18083", "ow:ping-secret-xyz").await; - assert!(!off.ok); - assert!( - !off.error - .as_deref() - .unwrap_or_default() - .contains("ping-secret-xyz"), - "{off:?}" - ); - - // An open RPC (no digest challenge) is refused with no password in it. - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let open = http_200_body(r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AA"}}"#); - 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(open.as_bytes()).await; - }); - let open = - wallet::Wallet::ping(&format!("http://127.0.0.1:{port}"), "ow:ping-secret-xyz").await; - assert!(!open.ok, "{open:?}"); - assert!( - open.error.as_deref().unwrap_or_default().contains("digest"), - "{open:?}" - ); -} - -/// `WalletStatus.connected` comes from a probe, never from config-existence — -/// and a lower layer that echoes the password into an RPC error cannot leak it -/// into the status line. -#[tokio::test] -async fn status_is_connected_only_after_a_successful_probe() { - // Configured but never probed: connected is false, config is not reachability. - let idle = WalletStatus::idle(true); - assert!(idle.configured()); - assert!(!idle.connected, "config exists is not reachability"); - assert_eq!(idle.balance_line, "—"); - assert_eq!(idle.receive_address, "—"); - - // A successful probe: connected, address + balance filled in. - 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: &str| match method { - "get_address" => rpc_result( - r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, - ), - "get_balance" => rpc_result(r#"{"balance":"123456"}"#), - _ => rpc_result("{}"), - }), - )); - let w = recording_wallet(port); - let ok = w.status().await; - assert!(ok.configured() && ok.connected, "{ok:?}"); - assert_eq!(ok.last_error, None); - assert_eq!(ok.balance_line, "123456 piconero"); - assert!(ok.receive_address.starts_with('4'), "{ok:?}"); - - // A probe that fails keeps configured=true and turns connected off. - let dead = freed_loopback_port(); - let down = Wallet::from_url(&format!("http://ow:ping-secret-xyz@127.0.0.1:{dead}")).unwrap(); - let bad = down.status().await; - assert!(bad.configured(), "{bad:?}"); - assert!(!bad.connected, "{bad:?}"); - assert!(bad.last_error.is_some(), "{bad:?}"); - assert_eq!(bad.balance_line, "—"); - assert_eq!(bad.receive_address, "—"); - - // An RPC error message that repeats the password is redacted before display. - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let leaky = http_200_body(&rpc_error(-1, "auth failed for ow:leak-secret-xyz")); - tokio::spawn(serve_digest_then(listener, leaky)); - let w = Wallet::from_url(&format!("http://ow:leak-secret-xyz@127.0.0.1:{port}")).unwrap(); - let leak = w.status().await; - assert!(!leak.connected, "{leak:?}"); - let err = leak.last_error.expect("failure reason"); - assert!(!err.contains("leak-secret-xyz"), "password leaked: {err}"); - assert!(err.contains(""), "{err}"); - assert!( - err.chars().count() <= 121, - "status copy must stay short: {err}" - ); - - // Nothing configured at all. - let none = Wallet::disabled().status().await; - assert!(!none.configured() && !none.connected, "{none:?}"); -} - -// Chain-source labels and the persisted wallet-child settings. The child itself -// spawns processes (see `src/node.rs`'s tests and `src/wallet_child.rs`), so -// these cover the public shapes a config screen and the SDK build on. - -#[test] -fn chain_source_labels_name_what_the_child_dials() { - use std::path::PathBuf; - - use onionwire::wallet::ChainSource; - - assert_eq!(ChainSource::None.label(), "receive-only"); - assert_eq!( - ChainSource::Local { - monerod_bin: PathBuf::from("/usr/bin/monerod"), - datadir: PathBuf::from("/var/lib/onionwire"), - } - .label(), - "local node" - ); - assert_eq!( - ChainSource::Remote { - host: "daemon.onion".into(), - port: 18089 - } - .label(), - "remote onion daemon" - ); - assert_eq!( - ChainSource::Remote { - host: "127.0.0.1".into(), - port: 18089 - } - .label(), - "remote daemon" - ); - // Onion detection needs the suffix, and is case-insensitive. - assert!( - ChainSource::Remote { - host: "ABCDEF.ONION".into(), - port: 1 - } - .is_onion() - ); - assert!( - !ChainSource::Remote { - host: "notonion.example".into(), - port: 1 - } - .is_onion() - ); - assert!(!ChainSource::None.is_onion()); -} - -#[test] -fn child_settings_round_trip_sealed_and_keep_the_creds() { - use std::path::PathBuf; - - use onionwire::wallet::ChainSource; - use onionwire::wallet_child::{ChildConfig, merge_record}; - - let cfg = ChildConfig { - source: ChainSource::Remote { - host: "daemon.onion".into(), - port: 18089, - }, - wallet_rpc_bin: PathBuf::from("/data/app/lib/libmonero-wallet-rpc.so"), - arti_bin: PathBuf::from("/data/app/lib/libarti.so"), - wallet_filename: "onionwire".into(), - }; - let record = merge_record(None, cfg.record_fields()); - // The creds a first start seals live in the same record and must survive a - // later settings save. - let with_creds = merge_record( - Some(&record), - serde_json::json!({"user": "owuser", "pass": "ow-secret"}), - ); - - let dir = std::env::temp_dir().join(format!("ow-child-cfg-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let store = Store::open_at_with_passphrase(&dir, "child-cfg-pass").unwrap(); - store.save_wallet_child(&with_creds).unwrap(); - let raw = store.load_wallet_child().unwrap().expect("record"); - assert_eq!( - ChildConfig::from_record(&raw).unwrap().expect("settings"), - cfg, - "the settings survive the sealed round trip" - ); - drop(store); - let _ = std::fs::remove_dir_all(&dir); - - // A record written before the settings existed is `None`, not a lie. - assert_eq!( - ChildConfig::from_record(r#"{"user":"u","pass":"p"}"#).unwrap(), - None - ); - - // Receive-only spawns nothing, so empty binaries are not an error there; - // they are for the kinds that spawn. - assert!(ChildConfig::receive_only().validate().is_ok()); - let mut local = ChildConfig::receive_only(); - local.source = ChainSource::Local { - monerod_bin: PathBuf::new(), - datadir: PathBuf::from("/var/lib/onionwire"), - }; - let err = local.validate().expect_err("a local node needs monerod"); - assert!(err.to_string().contains("monerod path required"), "{err}"); - let mut remote = ChildConfig::receive_only(); - remote.source = ChainSource::Remote { - host: "daemon.onion".into(), - port: 0, - }; - let err = remote.validate().expect_err("a remote daemon needs a port"); - assert!(err.to_string().contains("daemon port required"), "{err}"); -} - -/// A port nothing is listening on: bind it, read it, drop the listener. -fn freed_loopback_port() -> u16 { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - drop(listener); - port -}