//! 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 } /// 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 { host.trim().to_ascii_lowercase().ends_with(".onion") } /// 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. 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 } /// 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"); } }