wallet: wire the app-owned child into the node and TUI

The module was dead code: nothing started the child, so the payment spines
could only ever see an env-configured monero-wallet-rpc. Now:

- Node::start_wallet_child / stop_wallet_child / wallet_child_status /
  wallet_child_refresh / wallet_child_config / set_wallet_child_config. The
  start path honours the configured absolute binary path, points the node's
  wallet at the child, and shutdown() stops the child rather than orphaning
  a spend-capable RPC behind a loopback socket.
- The status is derived from the real process (try_wait) and the last probe:
  off / connecting / syncing / ready / exited, plus the chain-source label.
  A dead child is never reported ready.
- ChildConfig (source, wallet_rpc_bin, arti_bin, wallet_filename) persists in
  the sealed wallet_child record next to the generated creds; the record is a
  read-modify-write so first-start creds never clobber a saved config.
- TUI: F6 gains s (start) / x (stop) / p (probe) and a child status row, and
  the /pay and /tip key handlers now call the core readiness guard before
  sending.
This commit is contained in:
agent 2026-09-18 09:28:11 -04:00
commit 440a37caf0
No known key found for this signature in database
5 changed files with 1056 additions and 33 deletions

View file

@ -30,6 +30,7 @@ use crate::sanitize;
use crate::session::{self, Keys};
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
use crate::wallet::{self, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus};
pub struct RotateResult {
pub notified: usize,
@ -88,6 +89,15 @@ pub struct Node {
wallet: Mutex<Wallet>,
/// Last probe result, for the draw path. Cheap to read, never dials.
wallet_status: Mutex<WalletStatus>,
/// The app-owned wallet child, once one has been started. `None` until
/// `start_wallet_child`, and `None` again after `stop_wallet_child` — the
/// child is never started implicitly.
wallet_child: Mutex<Option<Arc<WalletChild>>>,
/// Did the running child's wallet report a synced chain at the last probe?
/// Only `wallet_child_refresh` writes it; the draw path only reads it.
child_synced: AtomicBool,
/// The last child failure, display-ready. Cleared on a successful start.
child_error: Mutex<Option<String>>,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
@ -155,6 +165,9 @@ impl Node {
keys: Mutex::new(keys),
wallet: Mutex::new(wallet),
wallet_status: Mutex::new(wallet_status),
wallet_child: Mutex::new(None),
child_synced: AtomicBool::new(false),
child_error: Mutex::new(None),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
@ -256,6 +269,19 @@ impl Node {
Ok(mut g) => drop(g.take()),
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
}
// The app owns these processes: an exit that left `monero-wallet-rpc`
// (a spend authority behind a loopback socket) or `monerod` behind would
// outlive the node that started them.
match self.wallet_child.lock().map(|mut g| g.take()) {
Ok(Some(child)) => {
self.child_synced.store(false, Ordering::Relaxed);
if let Err(e) = child.stop() {
eprintln!("shutdown: wallet child stop failed: {e}");
}
}
Ok(None) => {}
Err(_) => eprintln!("shutdown: wallet-child lock poisoned"),
}
self.checkpoint();
Ok(())
}
@ -522,6 +548,170 @@ impl Node {
wallet::readiness(status.configured, status.connected, w.no_spend(), is_tip)
}
// ----- the app-owned wallet child (`src/wallet_child.rs`) ----------------
/// The child settings this node would spawn with: the stored record, or the
/// defaults (receive-only, binaries by name) when nothing was ever set.
pub fn wallet_child_config(&self) -> ChildConfig {
self.store
.lock()
.ok()
.and_then(|store| store.load_wallet_child().ok().flatten())
.and_then(|raw| ChildConfig::from_record(&raw).ok().flatten())
.unwrap_or_default()
}
/// Persist the settings a config screen or the SDK set. Validated first, so
/// a rejected config is never written; the creds already in the record are
/// preserved. A running child is not restarted — the change applies on the
/// next `start_wallet_child`.
pub fn set_wallet_child_config(&self, cfg: &ChildConfig) -> Result<(), String> {
cfg.validate().map_err(|e| e.to_string())?;
let store = self.store.lock().map_err(|e| e.to_string())?;
let existing = store.load_wallet_child().map_err(|e| e.to_string())?;
let record = crate::wallet_child::merge_record(existing.as_deref(), cfg.record_fields());
store
.save_wallet_child(&record)
.map_err(|e| e.to_string())?;
Ok(())
}
/// Start the app-owned wallet child and point this node's wallet at it.
///
/// Idempotent: a live wallet child is reported, not respawned. Spawning is
/// synchronous — argv is built, the child is spawned, and a `.onion` chain
/// source waits up to `SOCKS_READY_TIMEOUT` for the SOCKS listener — which
/// is why callers block on it (`rt.block_on` in the TUI).
pub fn start_wallet_child(&self) -> Result<(), String> {
let cfg = self.wallet_child_config();
if !cfg.is_enabled() {
return Err("no chain source configured — the wallet child is receive-only".into());
}
let already_running = self
.wallet_child
.lock()
.map_err(|e| e.to_string())?
.as_ref()
.is_some_and(|child| child.wallet_rpc_running());
if already_running {
return Ok(());
}
let child = Arc::new(
cfg.build(self.home.join("wallet"))
.map_err(|e| e.to_string())?,
);
let client = {
let store = self.store.lock().map_err(|e| e.to_string())?;
child.start(&store).map_err(|e| e.to_string())?
};
let Some(client) = client else {
return Err("chain source is receive-only — nothing to start".into());
};
let wallet = client.into_wallet();
let configured = wallet.configured();
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
*self.child_error.lock().map_err(|e| e.to_string())? = None;
self.child_synced.store(false, Ordering::Relaxed);
*self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child);
Ok(())
}
/// Stop the app-owned wallet child (idempotent) and put the wallet back on
/// the stored/env config, if any. The next launch starts the child again —
/// nothing promises it stays up across a restart, and Android will not.
pub fn stop_wallet_child(&self) -> Result<(), String> {
let child = self.wallet_child.lock().map_err(|e| e.to_string())?.take();
if let Some(child) = child {
child.stop().map_err(|e| e.to_string())?;
}
self.child_synced.store(false, Ordering::Relaxed);
let stored = self
.store
.lock()
.map_err(|e| e.to_string())?
.load_wallet_config()
.map_err(|e| e.to_string())?;
let wallet = Wallet::for_boot(stored.as_ref());
let configured = wallet.configured();
*self.wallet.lock().map_err(|e| e.to_string())? = wallet;
*self.wallet_status.lock().map_err(|e| e.to_string())? = WalletStatus::idle(configured);
Ok(())
}
/// The child's observable state, derived from the real process plus the last
/// probe — never from env-var presence. Cheap: no dial, safe on a draw path.
pub fn wallet_child_status(&self) -> WalletChildStatus {
let cfg = self.wallet_child_config();
let child = self
.wallet_child
.lock()
.ok()
.and_then(|guard| guard.clone());
let running = child
.as_ref()
.is_some_and(|child| child.wallet_rpc_running());
let connected = self
.wallet_status
.lock()
.map(|s| s.connected)
.unwrap_or(false);
let state = match &child {
None => WalletChildState::Off,
Some(_) if !running => WalletChildState::Exited,
Some(_) if !connected => WalletChildState::Connecting,
Some(_) if self.child_synced.load(Ordering::Relaxed) => WalletChildState::Ready,
Some(_) => WalletChildState::Syncing,
};
WalletChildStatus {
state,
running,
configured: cfg.is_enabled(),
chain_source: cfg.source_label(),
last_error: self.child_error.lock().ok().and_then(|err| err.clone()),
}
}
/// The one-line child status a TUI row shows. Empty when nothing is
/// configured, so an unconfigured install renders no row at all.
pub fn wallet_child_line(&self) -> String {
self.wallet_child_status().line()
}
/// Probe the running child once: is its wallet RPC answering, and is the
/// chain at the tip? Only this (or a failed start) moves the state off
/// `connecting`, and it never invents `ready` for a dead child.
pub async fn wallet_child_refresh(&self) -> WalletChildStatus {
let running = self
.wallet_child
.lock()
.map(|guard| guard.is_some())
.unwrap_or(false);
if !running {
return self.wallet_child_status();
}
let w = self.wallet_snapshot();
if !w.configured() {
return self.wallet_child_status();
}
let status = w.status().await;
let connected = status.connected;
let error = status.last_error.clone();
if let Ok(mut slot) = self.wallet_status.lock() {
*slot = status;
}
let synced = if connected {
w.chain_ready().await.unwrap_or(false)
} else {
false
};
self.child_synced.store(synced, Ordering::Relaxed);
if let Ok(mut slot) = self.child_error.lock() {
*slot = if connected { None } else { error };
}
self.wallet_child_status()
}
/// The config screen's Test-connection button: one shot against the endpoint
/// the user is typing. It does not touch the live wallet or the snapshot —
/// a test of an untyped endpoint is not the wallet we are running.
@ -1591,6 +1781,8 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
mod tests {
use super::*;
use std::pin::Pin;
use crate::wallet::ChainSource;
use std::task::{Context, Poll};
use futures::io::{AsyncRead, AsyncWrite};
@ -1678,6 +1870,7 @@ mod tests {
.expect("unbootstrapped Tor client");
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(Arc::clone(&store), deliverer));
let wallet_status = WalletStatus::idle(wallet.configured());
Node {
home: home.to_path_buf(),
store,
@ -1685,7 +1878,11 @@ mod tests {
hs: Mutex::new(None),
onion: Mutex::new("test.onion".to_string()),
keys: Mutex::new(keys),
wallet,
wallet: Mutex::new(wallet),
wallet_status: Mutex::new(wallet_status),
wallet_child: Mutex::new(None),
child_synced: AtomicBool::new(false),
child_error: Mutex::new(None),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
outbox,
@ -1899,6 +2096,11 @@ mod tests {
/// A wallet child that clears the Digest challenge and answers one
/// `transfer` — the two-connection dance `tests/wallet.rs` mocks.
/// A loopback wallet RPC that answers what the tip path actually asks for:
/// a digest challenge, then a synced `get_info` for the readiness gate and
/// `tx_hash` for the transfer. The old single-answer mock stopped covering
/// the path when `Wallet::transfer` started probing the chain tip first —
/// it answered `tx_hash` to `get_info` and every tip was refused as unsynced.
async fn mock_wallet() -> Wallet {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@ -1907,13 +2109,18 @@ mod tests {
.expect("bind mock wallet");
let port = listener.local_addr().expect("mock wallet addr").port();
tokio::spawn(async move {
for attempt in 0..2 {
// Every call starts unauthenticated, so every call gets one
// challenge — the client retries each request with digest auth.
for _ in 0..8 {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let _ = sock.read(&mut buf).await;
if attempt == 0 {
let Ok(n) = sock.read(&mut buf).await else {
return;
};
let req = String::from_utf8_lossy(&buf[..n]).to_string();
if !req.contains("Authorization:") {
let _ = sock
.write_all(
b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
@ -1921,7 +2128,11 @@ mod tests {
.await;
continue;
}
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#;
let body = if req.contains("get_info") {
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#
};
let _ = sock
.write_all(
format!(
@ -2102,5 +2313,308 @@ mod tests {
assert_eq!(rows[0].dir, "in");
assert_eq!(rows[0].kind, "tip");
}
}
/// A stand-in for `monero-wallet-rpc`: it records its argv, then does what
/// the test needs. The wallet child spawns a real process, so this is the
/// only honest way to drive the start path offline.
fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf {
std::fs::create_dir_all(dir).expect("fake bin dir");
let path = dir.join(name);
let script = format!(
"#!/bin/sh\n: > '{}'\nprintf '%s\\n' \"$0\" >> '{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done\n{body}\n",
log.display(),
log.display(),
log.display()
);
std::fs::write(&path, script).expect("write fake bin");
let mut perms = std::fs::metadata(&path).expect("stat").permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700);
std::fs::set_permissions(&path, perms).expect("chmod");
path
}
/// A loopback daemon is the one source that spawns no SOCKS child, so the
/// test drives exactly one process.
fn loopback_child_config(bin: PathBuf, filename: &str) -> ChildConfig {
ChildConfig {
source: ChainSource::Remote {
host: "127.0.0.1".into(),
port: 18081,
},
wallet_rpc_bin: bin,
arti_bin: PathBuf::from("arti"),
wallet_filename: filename.to_string(),
}
}
fn sealed_creds(node: &Node) -> (String, String) {
let raw = node
.store
.lock()
.expect("store")
.load_wallet_child()
.expect("record")
.expect("a start seals the creds");
let parsed: serde_json::Value = serde_json::from_str(&raw).expect("json");
(
parsed["user"].as_str().expect("user").to_string(),
parsed["pass"].as_str().expect("pass").to_string(),
)
}
/// A receive-only node says `off` and starts nothing: the status comes from
/// the real configuration, never from a guess or an env var.
#[tokio::test]
async fn a_receive_only_node_reports_off_and_refuses_to_start_a_child() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
let status = node.wallet_child_status();
assert_eq!(status.state, WalletChildState::Off);
assert!(!status.running);
assert!(!status.configured);
assert_eq!(status.chain_source, "receive-only");
assert!(status.last_error.is_none());
assert_eq!(
node.wallet_child_line(),
"",
"an unconfigured install renders no status row"
);
let err = node
.start_wallet_child()
.expect_err("receive-only cannot start anything");
assert!(err.contains("no chain source configured"), "{err}");
}
/// The start path honours `with_wallet_rpc_bin` — the configured absolute
/// path is what gets spawned, not a name off `PATH` — and the status tracks
/// the real process.
#[tokio::test]
async fn start_wallet_child_honours_the_configured_binary() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("child");
let node = offline_node(&home, Arc::new(NoDial));
let log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&log,
"sleep 30",
);
node.set_wallet_child_config(&loopback_child_config(bin.clone(), "onionwire"))
.expect("set config");
node.start_wallet_child().expect("start");
let status = node.wallet_child_status();
assert!(status.running, "{status:?}");
assert_eq!(
status.state,
WalletChildState::Connecting,
"nothing has answered the wallet RPC yet"
);
assert!(status.configured);
assert_eq!(status.chain_source, "remote daemon");
let mut argv: Vec<String> = Vec::new();
for _ in 0..200 {
argv = std::fs::read_to_string(&log)
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect();
if !argv.is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(
argv.first().map(String::as_str),
bin.to_str(),
"the configured binary ($0) is what got spawned: {argv:?}"
);
assert!(argv.iter().any(|a| a == "--wallet-dir"), "{argv:?}");
assert!(
argv.iter()
.any(|a| a == &home.join("wallet").display().to_string()),
"{argv:?}"
);
assert!(argv.iter().any(|a| a == "--daemon-address"), "{argv:?}");
assert!(
!argv.iter().any(|a| a == "--trusted-daemon"),
"a remote daemon is never trusted: {argv:?}"
);
// Idempotent: a live child is reported, not respawned.
node.start_wallet_child().expect("second start");
assert!(node.wallet_child_status().running);
node.stop_wallet_child().expect("stop");
let after = node.wallet_child_status();
assert_eq!(after.state, WalletChildState::Off);
assert!(!after.running, "stop must not leave a process behind");
}
/// A child that dies on its own is `exited` — never `ready` — and stopping
/// after that is still a clean no-op.
#[tokio::test]
async fn a_died_child_reports_exited_and_never_ready() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
let log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&log,
"exit 0",
);
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
.expect("set config");
node.start_wallet_child().expect("start");
let mut status = node.wallet_child_status();
for _ in 0..300 {
status = node.wallet_child_status();
if status.state == WalletChildState::Exited {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(status.state, WalletChildState::Exited, "{status:?}");
assert!(!status.running);
assert_ne!(status.state.as_str(), "ready");
node.stop_wallet_child()
.expect("stop is a no-op after an exit");
assert_eq!(node.wallet_child_status().state, WalletChildState::Off);
}
/// The settings live in the sealed store, so they survive a restart, and
/// re-saving them does not clobber the RPC creds a start already sealed.
#[tokio::test]
async fn chain_source_persists_and_keeps_the_sealed_creds() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("child");
let log = dir.path().join("argv.log");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&log,
"sleep 30",
);
let saved = loopback_child_config(bin.clone(), "onionwire");
{
let node = offline_node(&home, Arc::new(NoDial));
node.set_wallet_child_config(&saved).expect("set config");
node.start_wallet_child().expect("start");
let before = sealed_creds(&node);
let mut other = saved.clone();
other.source = ChainSource::Remote {
host: "127.0.0.1".into(),
port: 18089,
};
node.set_wallet_child_config(&other).expect("re-save");
assert_eq!(sealed_creds(&node), before, "creds survived the rewrite");
node.stop_wallet_child().expect("stop");
}
let node = offline_node(&home, Arc::new(NoDial));
assert_eq!(
node.wallet_child_config(),
ChildConfig {
source: ChainSource::Remote {
host: "127.0.0.1".into(),
port: 18089,
},
..saved
},
"the saved source outlives the process"
);
}
/// A binary that cannot be spawned is an error and leaves no half-started
/// child behind.
#[tokio::test]
async fn a_missing_binary_fails_the_start_and_leaves_no_child() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
node.set_wallet_child_config(&loopback_child_config(
PathBuf::from("/nonexistent/onionwire-wallet-rpc"),
"onionwire",
))
.expect("set config");
let err = node
.start_wallet_child()
.expect_err("a missing binary fails");
assert!(err.contains("spawn"), "{err}");
let status = node.wallet_child_status();
assert_eq!(status.state, WalletChildState::Off);
assert!(!status.running);
}
/// A rejected setting is rejected before it is written: the stored config is
/// unchanged, so a bad form never points the child at nothing.
#[tokio::test]
async fn a_rejected_chain_source_is_not_persisted() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
let bin = dir.path().join("fake-bins").join("monero-wallet-rpc");
let saved = loopback_child_config(bin.clone(), "onionwire");
node.set_wallet_child_config(&saved).expect("set config");
let mut no_host = saved.clone();
no_host.source = ChainSource::Remote {
host: " ".into(),
port: 18081,
};
let err = node
.set_wallet_child_config(&no_host)
.expect_err("an empty host is rejected");
assert!(err.contains("daemon host required"), "{err}");
assert_eq!(
node.wallet_child_config(),
saved,
"the stored config is intact"
);
}
/// `shutdown` stops the processes the app owns: an exit must not orphan a
/// spend-capable wallet RPC behind a loopback socket.
#[tokio::test]
async fn shutdown_stops_the_wallet_child() {
let dir = tempfile::tempdir().unwrap();
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
let log = dir.path().join("argv.log");
let pid_file = dir.path().join("child.pid");
let bin = fake_child_bin(
&dir.path().join("fake-bins"),
"monero-wallet-rpc",
&log,
&format!("echo $$ > '{}'; exec sleep 30", pid_file.display()),
);
node.set_wallet_child_config(&loopback_child_config(bin, "onionwire"))
.expect("set config");
node.start_wallet_child().expect("start");
let mut pid = 0u32;
for _ in 0..200 {
if let Ok(raw) = std::fs::read_to_string(&pid_file)
&& let Ok(parsed) = raw.trim().parse::<u32>()
{
pid = parsed;
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(pid > 0, "the fake child recorded its pid");
node.shutdown().await.expect("shutdown");
let mut gone = false;
for _ in 0..300 {
if !Path::new(&format!("/proc/{pid}")).exists() {
gone = true;
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert!(gone, "shutdown must not leave the wallet child behind");
}
}