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

View file

@ -1537,6 +1537,9 @@ impl App {
Screen::Wallet { .. } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(),
KeyCode::Char('s') => self.wallet_child_start(),
KeyCode::Char('x') => self.wallet_child_stop(),
KeyCode::Char('p') => self.wallet_child_probe(),
KeyCode::Char('c') => {
self.screen = Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
@ -1784,6 +1787,59 @@ impl App {
Ok(())
}
/// The core's pay/tip readiness guard, refused before any dial when the
/// wallet is unconfigured, view-only (for a tip), or not answering. `true`
/// when the send may proceed; the reason is already in the status note when
/// it is not.
fn wallet_ready(&mut self, is_tip: bool) -> bool {
match self
.rt
.block_on(self.node.wallet_readiness(is_tip))
.refusal()
{
Some(refusal) => {
self.status_note = Some(refusal.to_string());
false
}
None => true,
}
}
/// Key `s` on the wallet screen: start the app-owned wallet child. The
/// balance/address readouts refresh on the next F6 — the child's RPC is not
/// answering in the same breath — so this reports the state it reached.
fn wallet_child_start(&mut self) {
self.status_note = Some(match self.node.start_wallet_child() {
Ok(()) => self.wallet_child_note(),
Err(e) => format!("wallet child: {e}"),
});
}
/// Key `x`: stop the child (idempotent) and drop back to the stored/env
/// wallet config.
fn wallet_child_stop(&mut self) {
self.status_note = Some(match self.node.stop_wallet_child() {
Ok(()) => "wallet child stopped".into(),
Err(e) => format!("wallet child: {e}"),
});
}
/// Key `p`: one probe of the running child — is its RPC answering, and is
/// the chain at the tip? The only thing that can report `ready`.
fn wallet_child_probe(&mut self) {
self.status_note = Some(self.wallet_child_note());
}
/// The child status line, or the copy that names what is missing.
fn wallet_child_note(&mut self) -> String {
let line = self.rt.block_on(self.node.wallet_child_refresh()).line();
if line.is_empty() {
"no wallet child configured — set a chain source first".into()
} else {
line
}
}
fn wallet_toggle_qr(&mut self) {
let Screen::Wallet {
ref mut qr_modal,
@ -2053,6 +2109,9 @@ impl App {
return Ok(());
};
let pk = friend.pubkey.clone();
if !self.wallet_ready(false) {
return Ok(());
}
match self.rt.block_on(self.node.pay_invoice(&pk, atomic, memo)) {
Ok(()) => self.status_note = Some("invoice sent".into()),
Err(e) => self.status_note = Some(e),
@ -2066,6 +2125,9 @@ impl App {
return Ok(());
};
let pk = friend.pubkey.clone();
if !self.wallet_ready(true) {
return Ok(());
}
match self.rt.block_on(self.node.tip(&pk, atomic, memo)) {
Ok(()) => self.status_note = Some("tip sent".into()),
Err(e) => self.status_note = Some(e),
@ -2150,8 +2212,21 @@ impl App {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
Screen::Wallet { receive_addr, balance, transfers, qr_modal } => {
draw_wallet(f, receive_addr, balance, transfers, qr_modal.as_ref())
Screen::Wallet {
receive_addr,
balance,
transfers,
qr_modal,
} => {
let child = self.node.wallet_child_line();
draw_wallet(
f,
receive_addr,
balance,
transfers,
qr_modal.as_ref(),
&child,
)
}
Screen::WalletSetup(setup) => draw_wallet_setup(f, setup),
}
@ -2472,7 +2547,7 @@ match screen {
BackupKind::Restore => "type RESTORE Esc cancel ? help",
},
Screen::Passphrase { .. } => "Enter submit Esc cancel ? help",
Screen::Wallet { .. } => "c create i import r qr Esc back ? help",
Screen::Wallet { .. } => "c create i import r qr s/x child Esc back ? help",
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => {
"Enter submit Esc cancel ? help"
@ -2740,6 +2815,7 @@ fn draw_wallet(
balance: &str,
transfers: &[wallet::TransferRow],
modal: Option<&QrModal>,
child: &str,
) {
let area = f.area();
if let Some(m) = modal {
@ -2810,14 +2886,17 @@ fn draw_wallet(
balance
{balance}
recent transfers
"
);
let mut lines: Vec<String> = body
.lines()
.map(str::to_string)
.collect();
let mut lines: Vec<String> = body.lines().map(str::to_string).collect();
// Only rendered when a chain source is configured or a child was started, so
// an unconfigured install shows the same screen it always did.
if !child.is_empty() {
lines.push(String::new());
lines.push(format!(" {child}"));
}
lines.push(String::new());
lines.push("recent transfers".into());
if transfers.is_empty() {
lines.push(" (none)".into());
} else {
@ -2826,7 +2905,7 @@ recent transfers
lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::<String>(), xmr));
}
}
let help = "c create i import r toggle qr Esc back";
let help = "s start child x stop child p probe c create i import r qr Esc back";
lines.push("".into());
f.render_widget(
Paragraph::new(lines.join("\n"))

View file

@ -46,6 +46,35 @@ pub enum ChainSource {
},
}
impl ChainSource {
/// Does this source name a Tor onion service? Only a `.onion` daemon needs
/// the SOCKS child; a loopback or clearnet host the user typed does not.
pub fn is_onion(&self) -> bool {
match self {
ChainSource::Remote { host, .. } => is_onion_host(host),
_ => false,
}
}
/// Short label for a status line: what the wallet child is dialling.
pub fn label(&self) -> String {
match self {
ChainSource::None => "receive-only".to_string(),
ChainSource::Local { .. } => "local node".to_string(),
ChainSource::Remote { host, .. } if is_onion_host(host) => {
"remote onion daemon".to_string()
}
ChainSource::Remote { .. } => "remote daemon".to_string(),
}
}
}
/// Does this host name a Tor onion service? Case-insensitive, and it needs the
/// suffix — `notonion.example` is not one.
pub fn is_onion_host(host: &str) -> bool {
host.trim().to_ascii_lowercase().ends_with(".onion")
}
/// Remote-mode wallet config: the `monero-wallet-rpc` the user already runs
/// themselves (F7 sets it, the store keeps it, env is the migration path).
///

View file

@ -165,6 +165,16 @@ impl WalletChild {
&self.wallet_filename
}
/// This child's own settings, in the persisted shape.
pub fn config(&self) -> ChildConfig {
ChildConfig {
source: self.source.clone(),
wallet_rpc_bin: self.wallet_rpc_bin.clone(),
arti_bin: self.arti_bin.clone(),
wallet_filename: self.wallet_filename.clone(),
}
}
/// Whether this configuration spawns any child.
pub fn is_enabled(&self) -> bool {
!matches!(self.source, ChainSource::None)
@ -173,7 +183,15 @@ impl WalletChild {
/// 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")
wallet::is_onion_host(host)
}
/// Is the `monero-wallet-rpc` child itself alive? The wallet RPC is the
/// process every wallet call goes through, so this — not "some child is up"
/// — is what decides `ready` vs `exited`.
pub fn wallet_rpc_running(&self) -> bool {
let _ = self.reap_exited();
self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
}
/// Is a tracked child still alive? Polls the process table; an exited child
@ -496,39 +514,262 @@ impl WalletChild {
/// Load the sealed creds, or generate them once and seal them in the store.
/// The store is the only place they live; `wallet_dir` never sees them.
///
/// The record is a read-modify-write: the settings written by a config
/// screen are never clobbered by first-start credential generation.
fn creds(&self, store: &Store) -> Result<(String, Zeroizing<String>)> {
if let Some(raw) = store
let existing = 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
.map_err(|e| ChildError(format!("read wallet-child creds: {e}")))?;
// Persist what this child is running with, before anything is spawned.
let record = merge_record(existing.as_deref(), self.config().record_fields());
store
.save_wallet_child(&record)
.map_err(|e| ChildError(format!("seal wallet-child config: {e}")))?;
if let Some(raw) = existing.as_deref()
&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(raw)
&& let Some(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
&& let Some(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,
});
let record = merge_record(
Some(&record),
serde_json::json!({"user": user, "pass": pass.as_str()}),
);
store
.save_wallet_child(&record.to_string())
.save_wallet_child(&record)
.map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?;
Ok((user, pass))
}
}
/// Everything the app needs to spawn the wallet child, minus the RPC creds:
/// which chain to dial, which binaries to run, which wallet file to open.
///
/// Persisted as part of the sealed `wallet_child` record (the generated creds
/// live in the same record), so a configured child survives a restart without
/// env vars. This is the shape the SDK's `ChainConfig` record maps to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChildConfig {
/// The user's chain-source choice. `None` is receive-only: nothing spawns.
pub source: ChainSource,
/// `monero-wallet-rpc`. A bare name is resolved on `PATH`; Android passes an
/// absolute path out of the app's native library directory.
pub wallet_rpc_bin: PathBuf,
/// `arti`, run as the SOCKS child for a `.onion` daemon only.
pub arti_bin: PathBuf,
/// Wallet file name inside `$ONIONWIRE_HOME/wallet`.
pub wallet_filename: String,
}
impl Default for ChildConfig {
fn default() -> Self {
Self {
source: ChainSource::None,
wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN),
arti_bin: PathBuf::from(DEFAULT_ARTI_BIN),
wallet_filename: wallet::DEFAULT_WALLET_FILENAME.to_string(),
}
}
}
impl ChildConfig {
/// Nothing spawns: the wallet screen is receive-only.
pub fn receive_only() -> Self {
Self::default()
}
/// Does this configuration spawn a child at all?
pub fn is_enabled(&self) -> bool {
!matches!(self.source, ChainSource::None)
}
/// The chain-source label a status line shows.
pub fn source_label(&self) -> String {
self.source.label()
}
/// Reject a configuration that could only fail later (empty binary path,
/// empty host, port 0) *before* it is persisted or spawned.
pub fn validate(&self) -> Result<()> {
if self.wallet_filename.trim().is_empty() {
return Err(ChildError("wallet filename required".into()));
}
// Receive-only spawns nothing, so a binary path there is not a setting
// to reject — a Kotlin caller legitimately leaves both empty for it.
if matches!(self.source, ChainSource::None) {
return Ok(());
}
if self.wallet_rpc_bin.as_os_str().is_empty() {
return Err(ChildError("monero-wallet-rpc path required".into()));
}
if self.arti_bin.as_os_str().is_empty() {
return Err(ChildError("arti path required".into()));
}
match &self.source {
ChainSource::None => {}
ChainSource::Local {
monerod_bin,
datadir,
} => {
if monerod_bin.as_os_str().is_empty() {
return Err(ChildError("monerod path required for a local node".into()));
}
if datadir.as_os_str().is_empty() {
return Err(ChildError(
"monerod data dir required for a local node".into(),
));
}
}
ChainSource::Remote { host, port } => {
if host.trim().is_empty() {
return Err(ChildError(
"daemon host required for a remote daemon".into(),
));
}
if *port == 0 {
return Err(ChildError(
"daemon port required for a remote daemon".into(),
));
}
}
}
Ok(())
}
/// Build the child this configuration describes. `wallet_dir` is the
/// caller's `$ONIONWIRE_HOME/wallet`.
pub fn build(&self, wallet_dir: PathBuf) -> Result<WalletChild> {
self.validate()?;
Ok(WalletChild::new(
self.source.clone(),
wallet_dir,
Some(self.wallet_filename.clone()),
)?
.with_wallet_rpc_bin(self.wallet_rpc_bin.clone())
.with_arti_bin(self.arti_bin.clone()))
}
/// The settings half of the sealed record, for
/// [`merge_record`] + `Store::save_wallet_child`.
pub fn record_fields(&self) -> serde_json::Value {
serde_json::json!({
"source": source_to_json(&self.source),
"wallet_rpc_bin": self.wallet_rpc_bin.display().to_string(),
"arti_bin": self.arti_bin.display().to_string(),
"wallet_filename": self.wallet_filename,
})
}
/// Read the stored settings back. `Ok(None)` when the record holds creds but
/// no source block — a record written before the settings were persisted.
pub fn from_record(raw: &str) -> Result<Option<Self>> {
let parsed: serde_json::Value = serde_json::from_str(raw)
.map_err(|e| ChildError(format!("parse wallet-child record: {e}")))?;
let Some(source) = parsed.get("source") else {
return Ok(None);
};
let mut cfg = Self {
source: source_from_json(source)?,
..Self::default()
};
if let Some(v) = parsed.get("wallet_rpc_bin").and_then(|v| v.as_str()) {
cfg.wallet_rpc_bin = PathBuf::from(v);
}
if let Some(v) = parsed.get("arti_bin").and_then(|v| v.as_str()) {
cfg.arti_bin = PathBuf::from(v);
}
if let Some(v) = parsed.get("wallet_filename").and_then(|v| v.as_str()) {
cfg.wallet_filename = v.to_string();
}
Ok(Some(cfg))
}
}
/// Merge `fields` into the sealed record JSON, keeping every other key — the
/// generated RPC creds in particular. A missing or non-object `existing` starts
/// a fresh record.
pub fn merge_record(existing: Option<&str>, fields: serde_json::Value) -> String {
let mut obj = existing
.and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
.and_then(|v| v.as_object().cloned())
.unwrap_or_default();
if let serde_json::Value::Object(patch) = fields {
for (k, v) in patch {
obj.insert(k, v);
}
}
serde_json::Value::Object(obj).to_string()
}
/// The observable state of the app-owned wallet child. Derived from the real
/// process + the last probe, never from env-var presence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalletChildState {
/// No child configured, or none started yet.
Off,
/// The child process is up but its wallet RPC has not answered.
Connecting,
/// The wallet answered, but the chain is not at the tip yet.
Syncing,
/// Wallet RPC answered and the chain is synced.
Ready,
/// A started child has exited (crashed or killed). Never reported ready.
Exited,
}
impl WalletChildState {
/// The lowercase label the SDK and the TUI show.
pub fn as_str(self) -> &'static str {
match self {
WalletChildState::Off => "off",
WalletChildState::Connecting => "connecting",
WalletChildState::Syncing => "syncing",
WalletChildState::Ready => "ready",
WalletChildState::Exited => "exited",
}
}
}
/// One snapshot of the child. Cheap to read: no dial, no lock held across work.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletChildStatus {
pub state: WalletChildState,
/// A child process is alive right now.
pub running: bool,
/// A chain source is configured (not receive-only), whether or not it runs.
pub configured: bool,
/// The chain-source label: `receive-only` / `local node` /
/// `remote onion daemon` / `remote daemon`.
pub chain_source: String,
/// The last failure, display-ready. Never carries the generated login.
pub last_error: Option<String>,
}
impl WalletChildStatus {
/// The one-line form a TUI status row or a Kotlin toast can show. Empty when
/// nothing is configured, so an unconfigured install renders no row.
pub fn line(&self) -> String {
if !self.configured && self.state == WalletChildState::Off {
return String::new();
}
let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source);
if let Some(err) = &self.last_error {
line.push_str(" · ");
line.push_str(err);
}
line
}
}
/// The loopback client built from the generated URL — the production path when
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
/// numeric loopback.
@ -604,6 +845,51 @@ fn source_to_json(source: &ChainSource) -> serde_json::Value {
}
}
fn source_from_json(value: &serde_json::Value) -> Result<ChainSource> {
let kind = value
.get("kind")
.and_then(|k| k.as_str())
.unwrap_or_default();
match kind {
"none" => Ok(ChainSource::None),
"local" => {
let monerod_bin = value
.get("monerod_bin")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
ChildError("stored local chain source has no monerod path".into())
})?;
let datadir = value
.get("datadir")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| ChildError("stored local chain source has no data dir".into()))?;
Ok(ChainSource::Local {
monerod_bin: PathBuf::from(monerod_bin),
datadir: PathBuf::from(datadir),
})
}
"remote" => {
let host = value
.get("host")
.and_then(|v| v.as_str())
.filter(|s| !s.trim().is_empty())
.ok_or_else(|| ChildError("stored remote chain source has no host".into()))?;
let port = value
.get("port")
.and_then(|v| v.as_u64())
.filter(|p| (1..=65535).contains(p))
.ok_or_else(|| ChildError("stored remote chain source has no port".into()))?;
Ok(ChainSource::Remote {
host: host.to_string(),
port: port as u16,
})
}
other => Err(ChildError(format!("unknown chain source kind {other:?}"))),
}
}
fn spawn(argv: &[String], what: &str) -> Result<Child> {
let (bin, args) = argv
.split_first()

View file

@ -1123,6 +1123,121 @@ async fn status_is_connected_only_after_a_successful_probe() {
assert!(!none.configured() && !none.connected, "{none:?}");
}
// Chain-source labels and the persisted wallet-child settings. The child itself
// spawns processes (see `src/node.rs`'s tests and `src/wallet_child.rs`), so
// these cover the public shapes a config screen and the SDK build on.
#[test]
fn chain_source_labels_name_what_the_child_dials() {
use std::path::PathBuf;
use onionwire::wallet::ChainSource;
assert_eq!(ChainSource::None.label(), "receive-only");
assert_eq!(
ChainSource::Local {
monerod_bin: PathBuf::from("/usr/bin/monerod"),
datadir: PathBuf::from("/var/lib/onionwire"),
}
.label(),
"local node"
);
assert_eq!(
ChainSource::Remote {
host: "daemon.onion".into(),
port: 18089
}
.label(),
"remote onion daemon"
);
assert_eq!(
ChainSource::Remote {
host: "127.0.0.1".into(),
port: 18089
}
.label(),
"remote daemon"
);
// Onion detection needs the suffix, and is case-insensitive.
assert!(
ChainSource::Remote {
host: "ABCDEF.ONION".into(),
port: 1
}
.is_onion()
);
assert!(
!ChainSource::Remote {
host: "notonion.example".into(),
port: 1
}
.is_onion()
);
assert!(!ChainSource::None.is_onion());
}
#[test]
fn child_settings_round_trip_sealed_and_keep_the_creds() {
use std::path::PathBuf;
use onionwire::wallet::ChainSource;
use onionwire::wallet_child::{ChildConfig, merge_record};
let cfg = ChildConfig {
source: ChainSource::Remote {
host: "daemon.onion".into(),
port: 18089,
},
wallet_rpc_bin: PathBuf::from("/data/app/lib/libmonero-wallet-rpc.so"),
arti_bin: PathBuf::from("/data/app/lib/libarti.so"),
wallet_filename: "onionwire".into(),
};
let record = merge_record(None, cfg.record_fields());
// The creds a first start seals live in the same record and must survive a
// later settings save.
let with_creds = merge_record(
Some(&record),
serde_json::json!({"user": "owuser", "pass": "ow-secret"}),
);
let dir = std::env::temp_dir().join(format!("ow-child-cfg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = Store::open_at_with_passphrase(&dir, "child-cfg-pass").unwrap();
store.save_wallet_child(&with_creds).unwrap();
let raw = store.load_wallet_child().unwrap().expect("record");
assert_eq!(
ChildConfig::from_record(&raw).unwrap().expect("settings"),
cfg,
"the settings survive the sealed round trip"
);
drop(store);
let _ = std::fs::remove_dir_all(&dir);
// A record written before the settings existed is `None`, not a lie.
assert_eq!(
ChildConfig::from_record(r#"{"user":"u","pass":"p"}"#).unwrap(),
None
);
// Receive-only spawns nothing, so empty binaries are not an error there;
// they are for the kinds that spawn.
assert!(ChildConfig::receive_only().validate().is_ok());
let mut local = ChildConfig::receive_only();
local.source = ChainSource::Local {
monerod_bin: PathBuf::new(),
datadir: PathBuf::from("/var/lib/onionwire"),
};
let err = local.validate().expect_err("a local node needs monerod");
assert!(err.to_string().contains("monerod path required"), "{err}");
let mut remote = ChildConfig::receive_only();
remote.source = ChainSource::Remote {
host: "daemon.onion".into(),
port: 0,
};
let err = remote.validate().expect_err("a remote daemon needs a port");
assert!(err.to_string().contains("daemon port required"), "{err}");
}
/// A port nothing is listening on: bind it, read it, drop the listener.
fn freed_loopback_port() -> u16 {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();