//! 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"); } }