TUI: node control, chain-source picker, honest wallet sync readiness
All checks were successful
ci / test (pull_request) Successful in 4m28s
ci / sdk (pull_request) Successful in 1m19s

Add the TUI control plane for the wallet child and chain source,
stacked on the wallet-child-lifecycle card:

- Chain-source picker (s): receive-only / local monerod / remote daemon
  with daemon-address entry + trust-shift warning for clearnet hosts
- Node control (n): start/stop the app-owned monero-wallet-rpc child,
  with fail-closed onion+SOCKS guard in the status line
- Wallet screen refreshes after picker/child changes, shows sync progress
  from the daemon and the chain-source/free-space/storage status line
- Honest spend guard: wallet view reflects real WalletStatus + Readiness
  so balance/transfer rendering only claims authority when the daemon is
  reachable, never while the child is silent
- Help overlay + footer hints updated for the new 's'/'n' keys
- Tests: chain-source round-trip through sealed record, saved-source
  starts the child, parse_source handles the 'none' kind
This commit is contained in:
agent 2026-09-15 12:29:16 -04:00
commit cfdfe38536
No known key found for this signature in database
6 changed files with 1364 additions and 82 deletions

View file

@ -1,12 +1,14 @@
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use futures::StreamExt;
use futures::io::{AsyncRead, AsyncWrite};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tor_cell::relaycell::msg::Connected;
use tor_hsservice::{RunningOnionService, handle_rend_requests};
use zeroize::Zeroizing;
@ -24,7 +26,8 @@ use crate::ratelimit::TokenBucket;
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::{self, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus};
use crate::wallet_child::{self, WalletChild};
pub struct RotateResult {
pub notified: usize,
@ -70,6 +73,50 @@ impl Drop for WorkerHandle {
}
}
/// Whether the app-owned wallet child pair is running.
///
/// The *choice* of chain source is separate: it lives in the sealed store
/// record and survives a restart even if no child was ever started.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalletChildState {
/// Receive-only, or nothing chosen yet: no daemon, nothing to start.
Off,
/// A chain source is configured, but no child of ours is alive.
Stopped,
/// A child this app spawned is still up.
Running,
}
/// How far along the chain the configured daemon says it is.
///
/// `reachable == false` means **unknown**, never "synced": a daemon we cannot
/// ask must not let the wallet screen claim the chain is current.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DaemonSync {
pub reachable: bool,
pub height: u64,
pub target_height: u64,
/// Why there is no answer (receive-only, no SOCKS listener, a failed dial).
pub note: Option<String>,
}
impl DaemonSync {
/// Synced means the daemon answered and reported a target it had reached.
/// Unreachable is *not* synced.
pub fn synced(&self) -> bool {
self.reachable && self.target_height > 0 && self.height >= self.target_height
}
fn unknown(note: impl Into<String>) -> Self {
Self {
reachable: false,
height: 0,
target_height: 0,
note: Some(note.into()),
}
}
}
pub struct Node {
home: PathBuf,
store: Arc<Mutex<Store>>,
@ -83,6 +130,10 @@ 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 child pair (`monerod` when the source is local,
/// `monero-wallet-rpc` always). `None` until `wallet_child_start`: the
/// chain-source *choice* lives in the sealed store record, not here.
child: Mutex<Option<WalletChild>>,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
@ -150,6 +201,7 @@ impl Node {
keys: Mutex::new(keys),
wallet: Mutex::new(wallet),
wallet_status: Mutex::new(wallet_status),
child: Mutex::new(None),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
@ -251,6 +303,10 @@ impl Node {
Ok(mut g) => drop(g.take()),
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
}
// The app owns the chain children; nothing else will reap them.
if let Err(e) = self.wallet_child_stop() {
eprintln!("shutdown: wallet child: {e}");
}
self.checkpoint();
Ok(())
}
@ -552,6 +608,148 @@ impl Node {
Ok(())
}
/// The chain source the user chose, read from the sealed store record.
///
/// A store that cannot be read reports receive-only rather than an error:
/// nothing has been started in that case either, so the screen must not
/// claim a daemon the app does not have.
pub fn wallet_chain_source(&self) -> ChainSource {
self.store
.lock()
.ok()
.and_then(|s| wallet_child::load_chain_source(&s).ok().flatten())
.unwrap_or(ChainSource::None)
}
/// Persist the picker's choice. Nothing is spawned: the user may pick a
/// source and start it later — or never, which is the receive-only path.
///
/// Refused while a child is running: re-pointing a live wallet child's
/// chain would leave the argv it was spawned with describing something
/// else, so stop it first.
pub fn wallet_set_chain_source(&self, source: &ChainSource) -> Result<(), String> {
if self.wallet_child_state() == WalletChildState::Running {
return Err("stop the wallet child before changing its chain source".into());
}
let store = self.store.lock().map_err(|e| e.to_string())?;
wallet_child::save_chain_source(&store, source).map_err(|e| e.to_string())
}
/// What "spawn a local monerod" means for this identity: the daemon binary
/// resolved from `PATH` (this app does not install one), with the chain in
/// this identity's own directory rather than a shared `/var/lib`.
pub fn default_local_chain_source(&self) -> ChainSource {
ChainSource::Local {
monerod_bin: PathBuf::from("monerod"),
datadir: self.home.join("chain"),
}
}
/// The state the wallet screen draws. Cheap: no dial, no spawn.
pub fn wallet_child_state(&self) -> WalletChildState {
// Read the (store-backed) choice first: never hold the child lock while
// taking the store lock.
let configured = !matches!(self.wallet_chain_source(), ChainSource::None);
let Ok(guard) = self.child.lock() else {
return WalletChildState::Stopped;
};
match guard.as_ref() {
Some(child) if child.running() => WalletChildState::Running,
_ if configured => WalletChildState::Stopped,
_ => WalletChildState::Off,
}
}
/// Spawn the configured children — `monerod` for a local source,
/// `monero-wallet-rpc` always — and re-point the app's wallet at the child
/// this app owns.
///
/// Owning the child is the whole point: balance, receive address, `/tip` and
/// receipt verification then all go through it, so a "start node" button
/// cannot describe a daemon the wallet does not use.
pub fn wallet_child_start(&self) -> Result<(), String> {
self.ensure_running()?;
let source = self.wallet_chain_source();
if matches!(source, ChainSource::None) {
return Err("receive-only: there is no daemon to start".into());
}
if self.wallet_child_state() == WalletChildState::Running {
return Err("wallet child already running".into());
}
let child = WalletChild::new(source, self.home.join("wallet"), None)
.map_err(|e| e.to_string())?;
let client = {
let store = self.store.lock().map_err(|e| e.to_string())?;
match child.start(&store) {
Ok(client) => client,
Err(e) => {
// A half-spawned pair (monerod up, wallet rpc refused) must
// not outlive the error.
let _ = child.stop();
return Err(e.to_string());
}
}
};
if let Some(client) = client {
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.lock().map_err(|e| e.to_string())? = Some(child);
Ok(())
}
/// Stop the children this app spawned. Idempotent.
pub fn wallet_child_stop(&self) -> Result<(), String> {
let child = self.child.lock().map_err(|e| e.to_string())?.take();
match child {
Some(child) => child.stop().map_err(|e| e.to_string()),
None => Ok(()),
}
}
/// Ask the configured daemon how far along the chain is, bounded by
/// `budget`. Never fabricates a height: a daemon we cannot ask — or must not
/// dial — comes back unreachable with the reason.
pub async fn wallet_chain_sync(&self, budget: Duration) -> DaemonSync {
let Some(addr) = WalletChild::daemon_address(&self.wallet_chain_source()) else {
return DaemonSync::unknown("receive-only: no daemon");
};
if is_onion_daemon(&addr) {
return DaemonSync::unknown(
"remote .onion daemon needs a local SOCKS listener (not wired yet)",
);
}
match daemon_get_info(&addr, budget).await {
Ok((height, target_height)) => DaemonSync {
reachable: true,
height,
target_height,
note: None,
},
Err(e) => DaemonSync::unknown(e),
}
}
/// Free space on the filesystem a *local* daemon would store the chain on,
/// in whole GiB. `None` for a remote source (their disk, not ours) and when
/// the answer cannot be read — never a guessed number.
pub fn wallet_chain_free_gb(&self) -> Option<u64> {
let ChainSource::Local { datadir, .. } = &self.wallet_chain_source() else {
return None;
};
// monerod creates the datadir on first run; before that, the volume that
// will hold it is the one `home` is on.
let path = if datadir.exists() { datadir } else { &self.home };
let out = Command::new("df").arg("-Pk").arg(path).output().ok()?;
if !out.status.success() {
return None;
}
parse_df_avail_kb(&String::from_utf8_lossy(&out.stdout)).map(|kb| kb / (1024 * 1024))
}
/// Current wallet balance as a human-readable XMR string, or `off` when the
/// wallet is not configured.
pub async fn wallet_balance(&self) -> String {
@ -1337,3 +1535,171 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
}
false
}
/// `.onion` daemon addresses must never be resolved locally: the SOCKS listener
/// is what dials them, and it does not exist yet. So this is a refusal, not a
/// dial — and it is checked before any socket is opened.
fn is_onion_daemon(addr: &str) -> bool {
addr.rsplit_once(':')
.map(|(host, _)| host)
.unwrap_or(addr)
.trim()
.to_ascii_lowercase()
.ends_with(".onion")
}
/// `get_info` from the daemon, over plain HTTP/1.1. Hand-rolled for the same
/// reason the wallet client is: no HTTP crate in this tree, and this request
/// carries nothing secret (the wallet RPC stays a separate, authenticated
/// loopback connection). This dials the *chain* address only.
const DAEMON_PROBE_MAX_BYTES: usize = 64 * 1024;
async fn daemon_get_info(addr: &str, budget: Duration) -> Result<(u64, u64), String> {
let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#;
let request = format!(
"POST /json_rpc HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let mut stream = tokio::time::timeout(budget, tokio::net::TcpStream::connect(addr))
.await
.map_err(|_| format!("{addr}: connect timed out"))?
.map_err(|e| format!("{addr}: {e}"))?;
let raw = tokio::time::timeout(budget, async {
stream.write_all(request.as_bytes()).await?;
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
loop {
let n = stream.read(&mut tmp).await?;
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
if buf.len() >= DAEMON_PROBE_MAX_BYTES {
break;
}
}
Ok::<Vec<u8>, std::io::Error>(buf)
})
.await
.map_err(|_| format!("{addr}: read timed out"))?
.map_err(|e| format!("{addr}: {e}"))?;
let text = String::from_utf8_lossy(&raw);
let json = text
.find('{')
.and_then(|start| text.rfind('}').map(|end| &text[start..=end]))
.ok_or_else(|| format!("{addr}: no JSON body"))?;
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| format!("{addr}: {e}"))?;
let result = value
.get("result")
.ok_or_else(|| format!("{addr}: no get_info result"))?;
match (
result.get("height").and_then(|h| h.as_u64()),
result.get("target_height").and_then(|h| h.as_u64()),
) {
(Some(height), Some(target_height)) => Ok((height, target_height)),
_ => Err(format!("{addr}: get_info has no chain height")),
}
}
/// Available 1K blocks from `df -Pk` output. Separate from the process call so
/// the parse is testable without a filesystem.
fn parse_df_avail_kb(stdout: &str) -> Option<u64> {
stdout.lines().rev().find_map(|line| {
let mut fields = line.split_whitespace();
fields.next()?; // filesystem
fields.next()?; // 1K blocks
fields.next()?; // used
fields.next()?.parse().ok() // available
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn onion_daemons_are_refused_before_any_dial() {
assert!(is_onion_daemon("abc234def.onion:18081"));
assert!(is_onion_daemon("ABC234DEF.ONION:18081"));
assert!(!is_onion_daemon("127.0.0.1:18081"));
assert!(!is_onion_daemon("node.example.com:18089"));
assert!(!is_onion_daemon("notonion:18081"));
}
#[test]
fn unavailable_daemon_is_not_synced() {
let synced = DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
};
assert!(synced.synced());
let behind = DaemonSync {
reachable: true,
height: 3_209_999,
target_height: 3_210_000,
note: None,
};
assert!(!behind.synced());
// A daemon that reports no target is not "synced", it is unknown.
let no_target = DaemonSync {
reachable: true,
height: 0,
target_height: 0,
note: None,
};
assert!(!no_target.synced());
assert!(!DaemonSync::unknown("no daemon").synced());
}
#[test]
fn parse_df_avail_reads_the_available_column() {
let out = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/sda1 100000000 50000000 48000000 52% /\n";
assert_eq!(parse_df_avail_kb(out), Some(48_000_000));
// Header only, or a relocated filesystem name: no number, no answer.
assert_eq!(
parse_df_avail_kb(
"Filesystem 1024-blocks Used Available Capacity Mounted on\n"
),
None
);
assert_eq!(parse_df_avail_kb("garbage"), None);
}
/// A real socket, a real HTTP response, a real parse: the sync line is only
/// as honest as this.
#[tokio::test]
async fn daemon_get_info_reads_height_and_target() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 2048];
let _ = sock.read(&mut buf).await;
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"height":3210000,"target_height":3210000}}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let _ = sock.write_all(resp.as_bytes()).await;
});
let (height, target) = daemon_get_info(&addr, Duration::from_secs(5)).await.unwrap();
assert_eq!((height, target), (3_210_000, 3_210_000));
server.await.unwrap();
}
/// A dead daemon is an error, never a fabricated height.
#[tokio::test]
async fn daemon_get_info_reports_a_dead_daemon() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
drop(listener);
let err = daemon_get_info(&addr, Duration::from_secs(5))
.await
.expect_err("a closed port must not answer");
assert!(err.contains(&addr), "{err}");
}
}