diff --git a/docs/WALLET.md b/docs/WALLET.md index 90d382b..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,91 +20,11 @@ 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`. -- `--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 — that needs a SOCKS proxy for the wallet child and is **not - implemented here**: configuring a `.onion` host today fails with a clear error - instead of silently dialling clearnet. 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. - -### 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. | @@ -141,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 4a4e517..9d9eb7d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,7 +15,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 8754c6a..5ca5bbe 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1056,11 +1056,7 @@ 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 ready = self.wallet.configured() && self.wallet.can_verify_receipts().await; - if ready { + if self.wallet.configured() { match self.wallet.get_transfers().await { Ok(rows) if wallet::transfers_match( diff --git a/src/store.rs b/src/store.rs index e32b5b0..c93b037 100644 --- a/src/store.rs +++ b/src/store.rs @@ -251,14 +251,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 - ); CREATE TABLE IF NOT EXISTS payments ( id INTEGER PRIMARY KEY, friend_id INTEGER NOT NULL REFERENCES friends(id), @@ -306,43 +298,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())) - } - pub fn replace_identity_keys( &self, identity_sk: &[u8], @@ -1440,10 +1395,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"; - fn fingerprint(pubkey: &[u8]) -> String { pubkey.iter().map(|b| format!("{b:02x}")).collect() } @@ -1880,66 +1831,4 @@ mod at_rest { ); } } - - /// 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/wallet.rs b/src/wallet.rs index 62f254f..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,33 +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, - }, -} - #[derive(Clone)] struct Endpoint { host: String, @@ -71,14 +43,6 @@ 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 @@ -86,10 +50,6 @@ pub struct Wallet { /// 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"; -/// 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"; - /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's /// `src/wallet/wallet_rpc_server_error_codes.h`. const WATCH_ONLY_CODE: i64 = -29; @@ -109,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 @@ -145,28 +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), + _ => Self { + endpoint: None, + no_spend, + }, } } pub fn from_url(url: &str) -> Result { - Ok(Self::new(Some(parse_http_url(url, None)?), false)) - } - - /// 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 + Ok(Self { + endpoint: Some(parse_http_url(url, None)?), + no_spend: false, + }) } /// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`. @@ -201,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}], @@ -247,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}), ) @@ -277,56 +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 @@ -386,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() @@ -419,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( @@ -438,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) } } @@ -567,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 12f96df..0000000 --- a/src/wallet_child.rs +++ /dev/null @@ -1,756 +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 needs a SOCKS proxy, which is a -//! separate card: here it is refused with a clear error. -//! * `--trusted-daemon` is never passed: a remote daemon is untrusted. - -use std::fs; -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; -use std::process::{Child, Command}; -use std::sync::Mutex; - -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"; - -/// 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 pair (`monerod` when local, `monero-wallet-rpc`). -pub struct WalletChild { - source: ChainSource, - wallet_rpc_bin: PathBuf, - wallet_dir: PathBuf, - wallet_filename: String, - monerod: 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), - wallet_dir, - wallet_filename, - monerod: 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 - } - - /// 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 - } - - /// Whether this configuration spawns any child. - pub fn is_enabled(&self) -> bool { - !matches!(self.source, ChainSource::None) - } - - /// 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.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.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 `--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. - pub fn wallet_rpc_argv( - bin: &Path, - port: u16, - login: &str, - wallet_dir: &Path, - daemon_address: 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()); - } - 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. - pub fn start(&self, store: &Store) -> Result> { - if !self.is_enabled() { - return Ok(None); - } - if let ChainSource::Remote { host, .. } = &self.source - && host.trim().to_ascii_lowercase().ends_with(".onion") - { - return Err(ChildError( - "remote .onion daemon needs a SOCKS proxy — configure the local/remote \ - chain source instead (separate card)" - .into(), - )); - } - if self.running() { - return Err(ChildError("wallet child already running".into())); - } - - // 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); - } - - 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(), - ); - 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, - })) - } - - /// Stop both children. Idempotent, and tolerant of a child that already - /// exited on its own. - pub fn stop(&self) -> Result<()> { - kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?; - 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. - fn creds(&self, store: &Store) -> Result<(String, Zeroizing)> { - if let Some(raw) = store - .load_wallet_child() - .map_err(|e| ChildError(format!("read wallet-child creds: {e}")))? - { - let parsed: serde_json::Value = serde_json::from_str(&raw) - .map_err(|e| ChildError(format!("parse wallet-child creds: {e}")))?; - let user = parsed - .get("user") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| ChildError("wallet-child creds missing user".into()))?; - let pass = parsed - .get("pass") - .and_then(|v| v.as_str()) - .filter(|s| !s.is_empty()) - .ok_or_else(|| ChildError("wallet-child creds missing pass".into()))?; - return Ok((user.to_string(), Zeroizing::new(pass.to_string()))); - } - let (user, pass) = generate_creds(); - let record = serde_json::json!({ - "user": user, - "pass": pass.as_str(), - "source": source_to_json(&self.source), - "wallet_filename": self.wallet_filename, - }); - store - .save_wallet_child(&record.to_string()) - .map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?; - Ok((user, pass)) - } -} - -/// 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 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 - } - - 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 child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap(); - assert!(!child.is_enabled()); - assert!(child.start(&store).unwrap().is_none()); - assert!(!child.running()); - } - - #[test] - fn onion_remote_daemon_is_refused_without_a_socks_proxy() { - let dir = tmp_dir("onion"); - let store = open_store(&dir); - let child = WalletChild::new( - ChainSource::Remote { - host: "abcdefghijklmnop.onion".into(), - port: 18081, - }, - dir.join("wallet"), - None, - ) - .unwrap(); - let err = child.start(&store).unwrap_err().to_string(); - assert!(err.contains("SOCKS"), "got {err}"); - } - - #[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"), - ); - 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 41cdfb0..10fb7a1 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -112,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"); } @@ -294,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") } @@ -388,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"), }), )); @@ -420,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"), }), )); @@ -623,215 +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" - ); -}