TUI: node control, chain-source picker, honest wallet sync readiness #76

Merged
sirius merged 1 commit from wt/t_09f67bf8 into feat/wallet-create-import 2026-09-15 17:01:46 +00:00
6 changed files with 1364 additions and 82 deletions
Showing only changes of commit cfdfe38536 - Show all commits

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
agent 2026-09-15 12:29:16 -04:00
No known key found for this signature in database

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

View file

@ -11,12 +11,12 @@ use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragra
use ratatui::{DefaultTerminal, Frame};
use zeroize::{Zeroize, Zeroizing};
use crate::node::Node;
use crate::node::{DaemonSync, Node, WalletChildState};
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
use crate::wallet;
use crate::wallet::{self, ChainSource, Readiness};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -454,7 +454,9 @@ OnionWire keys\n\
F3 paste invite\n\
F4 rotate onion locator\n\
F5 selected friend's profile (/who)\n\
F6 wallet (receive QR, create/import)\n\
F6 wallet (receive address, chain source)\n\
F6 s chain source: receive-only / local / remote\n\
F6 n start or stop the app-owned daemon\n\
/profile edit name, bio, Monero address\n\
/pay <xmr> [memo] invoice to receive\n\
/tip <xmr> [memo] pay selected friend\n\
@ -1123,11 +1125,10 @@ enum Screen {
entry: PassphraseEntry,
},
Wallet {
receive_addr: String,
balance: String,
transfers: Vec<wallet::TransferRow>,
view: WalletView,
qr_modal: Option<QrModal>,
},
ChainSetup(ChainSetup),
WalletSetup(WalletSetup),
Quit {
prompt: QuitPrompt,
@ -1142,6 +1143,284 @@ enum WalletSetup {
ImportPass { seed: Zeroizing<String>, entry: PassphraseEntry },
}
/// How far the wallet screen dares go. Derived from the parent card's
/// `wallet::readiness` predicate, so the UI cannot invent a fourth answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalletReadiness {
/// Configured, answered, and spend-capable: balance is authoritative.
Ready,
/// No wallet file / no RPC endpoint at all. Receive-only still works.
NotConfigured,
/// Configured but the RPC has not answered (child stopped, bad login).
NotConnected,
/// Answers, but `ONIONWIRE_WALLET_NO_SPEND=1`: balance is real, spend is not.
ViewOnly,
}
/// `wallet::readiness` for the wallet screen: it asks "can this wallet spend?",
/// which is what a balance implies.
pub fn wallet_readiness(configured: bool, connected: bool, no_spend: bool) -> WalletReadiness {
match wallet::readiness(configured, connected, no_spend, true) {
Readiness::Ready => WalletReadiness::Ready,
Readiness::NotConfigured => WalletReadiness::NotConfigured,
Readiness::NotConnected => WalletReadiness::NotConnected,
Readiness::NoSpend => WalletReadiness::ViewOnly,
}
}
impl WalletReadiness {
/// Whether the balance may be shown as a fact.
pub fn ready(self) -> bool {
matches!(self, Self::Ready)
}
/// The line the wallet screen prints. While this is not the ready line, the
/// balance below it is not an offer.
pub fn line(self) -> &'static str {
match self {
Self::Ready => "ready: wallet synced — spend and receipt verification available",
Self::NotConfigured => "not ready: no wallet — receive-only until c create / i import",
Self::NotConnected => "not ready: wallet RPC not answering — balance is not authoritative",
Self::ViewOnly => "view-only wallet: spend is refused locally, before any dial",
}
}
}
/// Lines that must fit the wallet body at 80 columns (the body is inset by a
/// border: 78 usable, 76 with slack).
pub const WALLET_LINE_MAX: usize = 76;
/// The chain half of the wallet screen: what the user chose, whether the child
/// is up, how far the daemon is, and whether the wallet can be trusted to show
/// a balance yet.
pub struct ChainView {
pub source_line: String,
pub child_line: String,
pub sync_line: String,
pub storage_line: String,
pub status_line: String,
/// `WalletReadiness::Ready` — the balance is authoritative only then.
pub ready: bool,
}
impl ChainView {
/// Every line this block renders, in draw order. The render test asserts
/// these fit; the draw prints exactly them.
pub fn lines(&self) -> Vec<String> {
[
&self.source_line,
&self.child_line,
&self.sync_line,
&self.storage_line,
&self.status_line,
]
.iter()
.flat_map(|l| l.lines())
.map(str::to_string)
.collect()
}
}
/// A pruned node is a real trade-off and the screen says so instead of implying
/// an archive.
pub const PRUNED_NOTE: &str = "pruned nodes are not archives: a deep seed restore can degrade. once this wallet has scanned, its own cache is the history";
/// Why `.onion` chain traffic cannot start here yet, in plain words. The raw
/// child error names an argv; the user needs the missing piece.
pub const ONION_NO_SOCKS_MSG: &str =
"a remote .onion daemon needs a local SOCKS listener.\nthis build does not have one yet — pick a local monerod,\nor a clearnet/loopback daemon you run yourself.";
/// The three choices the picker offers, in order. A public node is never one of
/// them and a remote daemon is never preselected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainChoice {
ReceiveOnly,
LocalMonerod,
RemoteDaemon,
}
impl ChainChoice {
pub const ALL: [ChainChoice; 3] = [Self::ReceiveOnly, Self::LocalMonerod, Self::RemoteDaemon];
pub fn label(self) -> &'static str {
match self {
Self::ReceiveOnly => "receive-only (no daemon)",
Self::LocalMonerod => "spawn a local monerod",
Self::RemoteDaemon => "enter a daemon address",
}
}
/// One line under the label, so the choice is not a mystery.
pub fn detail(self) -> &'static str {
match self {
Self::ReceiveOnly => "chain traffic stays off this device entirely",
Self::LocalMonerod => "the app owns monerod; chain stays on this device",
Self::RemoteDaemon => "someone else's daemon: they see your addresses",
}
}
/// Which choice the stored source corresponds to. A stored source is shown
/// as the current pick, never as a preselected remote.
pub fn of(source: &ChainSource) -> Self {
match source {
ChainSource::None => Self::ReceiveOnly,
ChainSource::Local { .. } => Self::LocalMonerod,
ChainSource::Remote { .. } => Self::RemoteDaemon,
}
}
}
enum ChainSetup {
Choose {
index: usize,
},
RemoteAddr {
buf: String,
err: Option<String>,
},
/// The trust shift, shown before anything is saved.
RemoteWarn {
host: String,
port: u16,
onion: bool,
},
}
/// What the F6 wallet screen draws. Built through [`wallet_view`] so the
/// not-ready rules are testable without a live node.
pub struct WalletView {
pub receive_addr: String,
pub balance: String,
pub transfers: Vec<wallet::TransferRow>,
pub chain: ChainView,
}
/// Assemble the wallet screen, applying the one rule that matters: while the
/// wallet is not ready the balance is **not** rendered as a fact.
pub fn wallet_view(
receive_addr: String,
balance: String,
transfers: Vec<wallet::TransferRow>,
chain: ChainView,
) -> WalletView {
if chain.ready {
WalletView {
receive_addr,
balance,
transfers,
chain,
}
} else {
WalletView {
receive_addr,
balance: "not synced — unavailable".to_string(),
transfers: Vec::new(),
chain,
}
}
}
/// Pure builder for the chain block: every honest-status rule lives here.
pub fn chain_view(
source: &ChainSource,
child: WalletChildState,
sync: &DaemonSync,
free_gb: Option<u64>,
readiness: WalletReadiness,
) -> ChainView {
let source_line = match source {
ChainSource::None => "chain: receive-only — no daemon, no chain traffic".to_string(),
ChainSource::Local {
monerod_bin,
datadir,
} => format!(
"chain: local monerod ({}) — chain in {}",
monerod_bin.display(),
datadir.display()
),
ChainSource::Remote { host, port } => format!("chain: remote daemon {host}:{port}"),
};
let child_line = match child {
WalletChildState::Off => "daemon: not configured — press s to choose a chain source",
WalletChildState::Stopped => "daemon: stopped — press n to start it",
WalletChildState::Running => "daemon: running (child owned by this app)",
}
.to_string();
let sync_line = if sync.reachable {
if sync.synced() {
format!("sync: synced — height {}", sync.height)
} else {
format!("sync: syncing — {}/{}", sync.height, sync.target_height)
}
} else {
format!(
"sync: unknown — {}",
sync.note.as_deref().unwrap_or("no daemon")
)
};
let storage_line = match (source, free_gb) {
(ChainSource::Local { .. }, Some(gb)) => format!(
"storage: {gb} GB free here — pruned mainnet wants ~50-60 GB, a full node ~200 GB"
),
(ChainSource::Local { .. }, None) => "storage: could not read free space".to_string(),
(ChainSource::Remote { .. }, _) => {
"storage: on the daemon operator's disk, not yours".to_string()
}
(ChainSource::None, _) => "storage: nothing stored on this device".to_string(),
};
ChainView {
source_line: truncate_chars(&source_line, WALLET_LINE_MAX),
child_line: truncate_chars(&child_line, WALLET_LINE_MAX),
sync_line: truncate_chars(&sync_line, WALLET_LINE_MAX),
storage_line: truncate_chars(&storage_line, WALLET_LINE_MAX),
status_line: readiness.line().to_string(),
ready: readiness.ready(),
}
}
/// `.onion` chain traffic needs the SOCKS listener this build does not have
/// yet. Checked before anything is dialled or spawned.
pub fn is_onion_host(host: &str) -> bool {
host.trim().to_ascii_lowercase().ends_with(".onion")
}
/// `host:port` from the picker's address field.
///
/// A `.onion`, a loopback host, and a clearnet host are all accepted — clearnet
/// only because the user typed it here. There is no default port: picking one
/// would be us choosing a daemon for them.
pub fn parse_daemon_addr(raw: &str) -> Result<(String, u16), String> {
let s = raw.trim();
if s.is_empty() {
return Err("enter host:port".into());
}
if s.chars().any(char::is_whitespace) {
return Err("no spaces in host:port".into());
}
let (host, port) = s
.rsplit_once(':')
.ok_or_else(|| "missing :port — write host:port".to_string())?;
let host = host.trim();
if host.is_empty() {
return Err("missing host — write host:port".into());
}
if host.contains('/') {
return Err("no path — host:port only".into());
}
let port: u16 = port
.trim()
.parse()
.map_err(|_| "port must be 1-65535".to_string())?;
if port == 0 {
return Err("port must be 1-65535".into());
}
Ok((host.to_string(), port))
}
/// The budget for the daemon `get_info` probe behind the sync line. Short on
/// purpose: a dead daemon must show as unknown, not freeze the screen.
pub const CHAIN_SYNC_BUDGET: Duration = Duration::from_secs(2);
impl App {
fn new(node: Arc<Node>, rt: tokio::runtime::Handle) -> Result<Self, String> {
let friends = node.list_friends()?;
@ -1425,6 +1704,8 @@ 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.open_chain_setup(),
KeyCode::Char('n') => self.toggle_wallet_child(),
KeyCode::Char('c') => {
self.screen = Screen::WalletSetup(WalletSetup::CreateWarn {
typed: String::new(),
@ -1437,6 +1718,7 @@ impl App {
}
_ => {}
},
Screen::ChainSetup(_) => self.handle_chain_setup(key)?,
Screen::WalletSetup(_) => self.handle_wallet_setup(key)?,
Screen::Quit { prompt } => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
@ -1642,27 +1924,217 @@ impl App {
}
fn open_wallet(&mut self) -> Result<(), String> {
let addr = self.rt.block_on(self.node.wallet_receive_address())?;
let balance = self.rt.block_on(self.node.wallet_balance());
let transfers = self.rt.block_on(self.node.wallet_recent_transfers(8)).unwrap_or_default();
self.screen = Screen::Wallet {
receive_addr: addr,
balance,
transfers,
view: self.build_wallet_view(),
qr_modal: None,
};
Ok(())
}
/// Draw state for the wallet screen.
///
/// One probe per open/refresh, then everything the screen says comes from
/// that answer: a balance rendered while the RPC is silent is the lie this
/// screen must not tell. Not being configured is a state to *show* (F6 must
/// open either way), not an error to bail out of.
fn build_wallet_view(&self) -> WalletView {
let status = self.rt.block_on(self.node.wallet_refresh());
let no_spend = self
.node
.wallet_config()
.map(|c| c.no_spend)
.unwrap_or(false);
let readiness = wallet_readiness(status.configured, status.connected, no_spend);
let source = self.node.wallet_chain_source();
let child = self.node.wallet_child_state();
let sync = self
.rt
.block_on(self.node.wallet_chain_sync(CHAIN_SYNC_BUDGET));
let chain = chain_view(
&source,
child,
&sync,
self.node.wallet_chain_free_gb(),
readiness,
);
let receive_addr = self
.rt
.block_on(self.node.wallet_receive_address())
.unwrap_or_default();
let balance = self.rt.block_on(self.node.wallet_balance());
let transfers = self
.rt
.block_on(self.node.wallet_recent_transfers(8))
.unwrap_or_default();
wallet_view(receive_addr, balance, transfers, chain)
}
/// Re-read the wallet screen after something changed what it shows.
fn refresh_wallet(&mut self) {
let view = self.build_wallet_view();
if let Screen::Wallet { view: slot, .. } = &mut self.screen {
*slot = view;
}
}
/// `s`: pick the chain source, with the stored choice shown as current.
fn open_chain_setup(&mut self) {
let current = ChainChoice::of(&self.node.wallet_chain_source());
let index = ChainChoice::ALL
.iter()
.position(|c| *c == current)
.unwrap_or(0);
self.screen = Screen::ChainSetup(ChainSetup::Choose { index });
}
/// `n`: start or stop the app-owned child.
///
/// A failure here is a normal thing to learn ("monerod is not on PATH"), so
/// it lands on the screen as a note, never as a fatal error that closes the
/// app.
fn toggle_wallet_child(&mut self) {
if let ChainSource::Remote { host, .. } = self.node.wallet_chain_source()
&& is_onion_host(&host)
{
// Say the missing piece in plain words, before any spawn attempt
// turns into a raw argv error.
self.status_note = Some(ONION_NO_SOCKS_MSG.replace('\n', " "));
self.refresh_wallet();
return;
}
let result = match self.node.wallet_child_state() {
WalletChildState::Running => self.node.wallet_child_stop(),
_ => self.node.wallet_child_start(),
};
self.status_note = Some(match result {
Ok(()) => match self.node.wallet_child_state() {
WalletChildState::Running => "wallet child started".to_string(),
_ => "wallet child stopped".to_string(),
},
Err(e) => format!("wallet child: {e}"),
});
self.refresh_wallet();
}
/// Chain-source picker keys. Kept as one state machine so the picker cannot
/// leave the wallet screen in a half-open state.
fn handle_chain_setup(&mut self, key: KeyEvent) -> Result<(), String> {
let mut pick = None;
let mut warn = None;
let mut save = false;
let mut back = false;
{
let Screen::ChainSetup(setup) = &mut self.screen else {
return Ok(());
};
match setup {
ChainSetup::Choose { index } => match key.code {
KeyCode::Esc => back = true,
KeyCode::Up | KeyCode::Char('k') => *index = index.saturating_sub(1),
KeyCode::Down | KeyCode::Char('j') => {
*index = (*index + 1).min(ChainChoice::ALL.len() - 1)
}
KeyCode::Enter => pick = Some(ChainChoice::ALL[*index]),
_ => {}
},
ChainSetup::RemoteAddr { buf, err } => match key.code {
KeyCode::Esc => back = true,
KeyCode::Backspace => {
buf.pop();
*err = None;
}
KeyCode::Enter => match parse_daemon_addr(buf) {
Ok((host, port)) => {
warn = Some((host, port));
}
Err(e) => *err = Some(e),
},
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c);
*err = None;
}
_ => {}
},
ChainSetup::RemoteWarn { .. } => match key.code {
KeyCode::Esc => back = true,
KeyCode::Enter => save = true,
_ => {}
},
}
}
if let Some(choice) = pick {
match choice {
ChainChoice::RemoteDaemon => {
self.screen = Screen::ChainSetup(ChainSetup::RemoteAddr {
buf: String::new(),
err: None,
});
}
ChainChoice::ReceiveOnly => self.apply_chain_source(ChainSource::None, None),
ChainChoice::LocalMonerod => {
let source = self.node.default_local_chain_source();
self.apply_chain_source(source, None);
}
}
return Ok(());
}
if let Some((host, port)) = warn {
let onion = is_onion_host(&host);
self.screen = Screen::ChainSetup(ChainSetup::RemoteWarn {
host,
port,
onion,
});
return Ok(());
}
if save {
let Screen::ChainSetup(ChainSetup::RemoteWarn { host, port, .. }) = &self.screen else {
return Ok(());
};
let source = ChainSource::Remote {
host: host.clone(),
port: *port,
};
let note = if is_onion_host(host) {
Some("saved — starting it needs a local SOCKS listener (not wired yet)".to_string())
} else {
None
};
self.apply_chain_source(source, note);
return Ok(());
}
if back {
self.screen = Screen::Wallet {
view: self.build_wallet_view(),
qr_modal: None,
};
}
Ok(())
}
/// Persist a pick and return to the wallet screen, where the choice is
/// visible at rest (AC 4). A save that fails says so instead of pretending.
fn apply_chain_source(&mut self, source: ChainSource, note: Option<String>) {
self.status_note = Some(match self.node.wallet_set_chain_source(&source) {
Ok(()) => note.unwrap_or_else(|| "chain source saved".to_string()),
Err(e) => format!("chain source not saved: {e}"),
});
self.screen = Screen::Wallet {
view: self.build_wallet_view(),
qr_modal: None,
};
}
fn wallet_toggle_qr(&mut self) {
let Screen::Wallet {
ref mut qr_modal,
ref receive_addr,
ref view,
..
} = self.screen
else {
return;
};
let receive_addr = &view.receive_addr;
if let Some(modal) = qr_modal {
*qr_modal = if modal.closed {
qr_modal.take()
@ -2019,9 +2491,8 @@ 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 { view, qr_modal } => draw_wallet(f, view, qr_modal.as_ref()),
Screen::ChainSetup(setup) => draw_chain_setup(f, setup),
Screen::WalletSetup(setup) => draw_wallet_setup(f, setup),
}
if self.help_open {
@ -2340,7 +2811,8 @@ 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 { .. } => "s chain n node c create i import r qr Esc back ? help",
Screen::ChainSetup(_) => "Enter select/save Esc back ? help",
Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help",
Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => {
"Enter submit Esc cancel ? help"
@ -2583,21 +3055,21 @@ fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// The `monero:` QR popup over the wallet screen. `pub` (fields private) because
/// [`draw_wallet`] takes one: the render spec draws the real screen.
#[derive(Clone, Debug)]
struct QrModal {
pub struct QrModal {
closed: bool,
matrix_rows: Vec<String>,
#[allow(dead_code)]
uri: String,
}
fn draw_wallet(
f: &mut Frame,
receive_addr: &str,
balance: &str,
transfers: &[wallet::TransferRow],
modal: Option<&QrModal>,
) {
/// The F6 wallet screen.
///
/// `pub` on purpose: the not-ready render is a spec of this card, so the test
/// draws this for real at a fixed size rather than a stand-in.
pub fn draw_wallet(f: &mut Frame, view: &WalletView, modal: Option<&QrModal>) {
let area = f.area();
if let Some(m) = modal {
// Clear behind the popup so the body does not bleed through.
@ -2642,9 +3114,7 @@ fn draw_wallet(
let cols = Layout::vertical([
Constraint::Length(2),
Constraint::Min(4),
Constraint::Length(2),
Constraint::Length(3),
Constraint::Min(6),
Constraint::Length(1),
])
.split(area);
@ -2656,44 +3126,110 @@ fn draw_wallet(
cols[0],
);
let addr_line = if receive_addr.is_empty() {
"no address".into()
let addr_line = if view.receive_addr.is_empty() {
"no address yet — /profile xmr, or create a wallet".to_string()
} else {
receive_addr.to_string()
view.receive_addr.clone()
};
let body = format!(
"address
{addr_line}
balance
{balance}
recent transfers
"
);
let mut lines: Vec<String> = body
.lines()
.map(str::to_string)
.collect();
if transfers.is_empty() {
lines.push(" (none)".into());
let mut lines: Vec<String> = vec![
format!("address {addr_line}"),
format!("balance {}", view.balance),
String::new(),
"chain".to_string(),
];
lines.extend(view.chain.lines());
lines.push(PRUNED_NOTE.to_string());
lines.push(String::new());
lines.push("recent transfers".to_string());
if view.transfers.is_empty() {
lines.push(" (none shown)".to_string());
} else {
for t in transfers.iter().take(5) {
for t in view.transfers.iter().take(4) {
let xmr = crate::pay::atomic_to_xmr_str(&t.amount);
lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::<String>(), xmr));
lines.push(format!(
" {} {} XMR",
t.txid.chars().take(16).collect::<String>(),
xmr
));
}
}
let help = "c create i import r toggle qr Esc back";
lines.push("".into());
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.block(apply_chrome_borders(Block::default()).border_style(style_border())),
cols[2],
cols[1],
);
f.render_widget(Paragraph::new(help).style(style_dim()), cols[3]);
let help = "s chain n start/stop c create i import r qr";
f.render_widget(Paragraph::new(help).style(style_dim()), cols[2]);
}
/// The chain-source picker and the remote-daemon trust shift, before anything
/// is saved.
fn draw_chain_setup(f: &mut Frame, setup: &ChainSetup) {
let (title, body) = match setup {
ChainSetup::Choose { index } => {
let mut lines = vec![
"where should the chain come from?".to_string(),
String::new(),
];
for (i, choice) in ChainChoice::ALL.iter().enumerate() {
let mark = if i == *index { ">" } else { " " };
lines.push(format!("{mark} {}", choice.label()));
lines.push(format!(" {}", choice.detail()));
}
lines.push(String::new());
lines.push("receive-only needs no wallet file and no daemon.".into());
lines.push("spend always needs the create/import flow and".into());
lines.push("its SPEND warning — there is no shortcut key.".into());
lines.push(String::new());
lines.push("Up/Down choose Enter select Esc back".into());
("chain source", lines.join("\n"))
}
ChainSetup::RemoteAddr { buf, err } => {
let mut lines = vec![
"daemon address, as host:port".to_string(),
" e.g. 127.0.0.1:18081 or yournode.onion:18089".to_string(),
String::new(),
format!("> {buf}"),
String::new(),
];
if let Some(e) = err {
lines.push(e.clone());
} else {
lines.push("Enter continues Esc goes back".into());
}
("enter daemon address", lines.join("\n"))
}
ChainSetup::RemoteWarn {
host,
port,
onion,
} => {
let mut lines = vec![
format!("use {host}:{port} for chain traffic?"),
String::new(),
"the daemon operator sees your addresses during sync,".into(),
"and every spend. a remote daemon is untrusted: this".into(),
"app never passes --trusted-daemon.".into(),
String::new(),
];
if *onion {
lines.push("this is a .onion host, so Tor would hide the transport.".into());
lines.push("it still does not hide your addresses from the operator.".into());
lines.push(String::new());
lines.extend(ONION_NO_SOCKS_MSG.lines().map(str::to_string));
} else {
lines.push("this is a clearnet host: your ISP can also see that".into());
lines.push("this device talks to a Monero node, and which one.".into());
}
lines.push(String::new());
lines.push("Enter saves it Esc cancels".into());
("trust shift", lines.join("\n"))
}
};
draw_text_overlay(f, title, &body);
}
fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) {

View file

@ -285,32 +285,24 @@ 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 same record also carries the chain-source choice
/// ([`save_chain_source`]), so this merges into it rather than replacing it.
fn creds(&self, store: &Store) -> Result<(String, Zeroizing<String>)> {
if let Some(raw) = store
.load_wallet_child()
.map_err(|e| ChildError(format!("read wallet-child creds: {e}")))?
let mut record = read_record(store)?;
if let (Some(user), Some(pass)) = (
record.get("user").and_then(|v| v.as_str()),
record.get("pass").and_then(|v| v.as_str()),
) && !user.is_empty()
&& !pass.is_empty()
{
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,
});
record["user"] = serde_json::json!(user);
record["pass"] = serde_json::json!(pass.as_str());
record["source"] = source_to_json(&self.source);
record["wallet_filename"] = serde_json::json!(self.wallet_filename);
store
.save_wallet_child(&record.to_string())
.map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?;
@ -318,6 +310,48 @@ impl WalletChild {
}
}
/// The user's persisted chain-source choice, or `None` before one was ever
/// saved. A record with an unrecognised `kind` reads as `None` rather than an
/// error: a record written by another build must not make the wallet screen
/// unusable.
pub fn load_chain_source(store: &Store) -> Result<Option<ChainSource>> {
Ok(parse_source(read_record(store)?.get("source")))
}
/// Persist the chain-source choice *without starting anything*, so the wallet
/// screen can show what the user picked after a restart.
///
/// Creds are generated here when the record does not have them yet, so a later
/// [`WalletChild::start`] finds a complete record instead of failing on missing
/// creds. Existing creds are kept: the `--rpc-login` of a child that is already
/// configured must not change under it.
pub fn save_chain_source(store: &Store, source: &ChainSource) -> Result<()> {
let mut record = read_record(store)?;
record["source"] = source_to_json(source);
let has_creds = record.get("user").and_then(|v| v.as_str()).is_some()
&& record.get("pass").and_then(|v| v.as_str()).is_some();
if !has_creds {
let (user, pass) = generate_creds();
record["user"] = serde_json::json!(user);
record["pass"] = serde_json::json!(pass.as_str());
}
store
.save_wallet_child(&record.to_string())
.map_err(|e| ChildError(format!("seal chain source: {e}")))
}
/// The sealed record as JSON, or an empty object when nothing is sealed yet.
fn read_record(store: &Store) -> Result<serde_json::Value> {
match store
.load_wallet_child()
.map_err(|e| ChildError(format!("read wallet-child record: {e}")))?
{
Some(raw) => serde_json::from_str(&raw)
.map_err(|e| ChildError(format!("parse wallet-child record: {e}"))),
None => Ok(serde_json::json!({})),
}
}
/// 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.
@ -393,6 +427,24 @@ fn source_to_json(source: &ChainSource) -> serde_json::Value {
}
}
/// Reverse of [`source_to_json`]. A missing or unrecognised `kind` is `None`
/// (receive-only), never an error.
fn parse_source(v: Option<&serde_json::Value>) -> Option<ChainSource> {
let v = v?;
match v.get("kind")?.as_str()? {
"none" => Some(ChainSource::None),
"local" => Some(ChainSource::Local {
monerod_bin: PathBuf::from(v.get("monerod_bin")?.as_str()?),
datadir: PathBuf::from(v.get("datadir")?.as_str()?),
}),
"remote" => Some(ChainSource::Remote {
host: v.get("host")?.as_str()?.to_string(),
port: u16::try_from(v.get("port")?.as_u64()?).ok()?,
}),
_ => None,
}
}
fn spawn(argv: &[String], what: &str) -> Result<Child> {
let (bin, args) = argv
.split_first()
@ -753,4 +805,119 @@ mod tests {
let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o700, "wallet dir must be 0700");
}
/// A fresh install has no record: receive-only, not "unknown".
#[test]
fn chain_source_is_absent_until_it_is_saved() {
let dir = tmp_dir("source-empty");
let store = open_store(&dir);
assert_eq!(load_chain_source(&store).unwrap(), None);
}
/// The picker's choice has to survive a restart *without* a child ever
/// starting, so it lives in the sealed record next to the creds.
#[test]
fn chain_source_round_trips_through_the_sealed_record() {
let dir = tmp_dir("source-roundtrip");
let store = open_store(&dir);
let remote = ChainSource::Remote {
host: "daemon.example.com".into(),
port: 18089,
};
save_chain_source(&store, &remote).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(remote));
let local = ChainSource::Local {
monerod_bin: PathBuf::from("/usr/bin/monerod"),
datadir: dir.join("chain"),
};
save_chain_source(&store, &local).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(local.clone()));
// Going back to receive-only is a choice too, and it must stick.
save_chain_source(&store, &ChainSource::None).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(ChainSource::None));
// An onion daemon is saved verbatim: refusing it is the SOCKS card's
// job, not the picker's.
let onion = ChainSource::Remote {
host: "abc234def.onion".into(),
port: 18081,
};
save_chain_source(&store, &onion).unwrap();
assert_eq!(load_chain_source(&store).unwrap(), Some(onion));
}
/// Saving a source must not rotate the `--rpc-login` out from under a child
/// that is already configured.
#[test]
fn saving_a_source_keeps_the_existing_creds() {
let dir = tmp_dir("source-creds");
let store = open_store(&dir);
let source = |h: &str| ChainSource::Remote {
host: h.into(),
port: 18089,
};
save_chain_source(&store, &source("a.example.com")).unwrap();
let first = store.load_wallet_child().unwrap().unwrap();
save_chain_source(&store, &source("b.example.com")).unwrap();
let second = store.load_wallet_child().unwrap().unwrap();
let (a, b): (serde_json::Value, serde_json::Value) =
(serde_json::from_str(&first).unwrap(), serde_json::from_str(&second).unwrap());
assert_eq!(a["user"], b["user"], "user must persist");
assert_eq!(a["pass"], b["pass"], "pass must persist");
assert_eq!(b["source"]["host"], "b.example.com");
}
/// The record `save_chain_source` writes has to be a record `start` can
/// consume: the picker runs before any child has ever started.
#[test]
fn a_saved_source_record_is_enough_to_start_the_child() {
let dir = tmp_dir("source-start");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let source = ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
};
save_chain_source(&store, &source).unwrap();
let child = WalletChild::new(source, dir.join("wallet"), None)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let client = child.start(&store).expect("start after a saved source");
assert!(client.is_some());
let argv = wait_for_argv(&rpc_log);
child.stop().unwrap();
assert!(
argv.windows(2)
.any(|w| w[0] == "--daemon-address" && w[1] == "node.example.com:18089"),
"{argv:?}"
);
}
/// A record with an unknown `kind` is receive-only; a corrupt record is an
/// error (fail-closed — do not silently overwrite it).
#[test]
fn an_unrecognised_source_reads_as_receive_only() {
let dir = tmp_dir("source-unknown");
let store = open_store(&dir);
store
.save_wallet_child(r#"{"user":"u","pass":"p","source":{"kind":"wormhole"}}"#)
.unwrap();
assert_eq!(load_chain_source(&store).unwrap(), None);
store.save_wallet_child("not json at all").unwrap();
assert!(
load_chain_source(&store).is_err(),
"a corrupt record must fail loudly, not read as receive-only"
);
assert!(
save_chain_source(&store, &ChainSource::None).is_err(),
"saving over a corrupt record would lose the creds"
);
}
}

View file

@ -46,6 +46,8 @@ fn help_overlay_lists_core_bindings() {
"F4",
"F5",
"F6",
"F6 s",
"F6 n",
"send chat",
"/profile",
"/pay",

View file

@ -12,12 +12,15 @@
//! They are the known-wrong metric (see `chars_count_is_not_terminal_cells`).
use onionwire::qr;
use onionwire::node::{DaemonSync, WalletChildState};
use onionwire::tui::{
backup_screen_text, banner_for_width, compact_banner, draw_share, fingerprint_mismatch_banner,
help_overlay_text, main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text,
rotate_screen_text, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner,
ProfileEditor, WipeKind,
backup_screen_text, banner_for_width, chain_view, compact_banner, draw_share, draw_wallet,
fingerprint_mismatch_banner, help_overlay_text, main_footer_hints, onion_glyph,
quit_screen_text, restore_screen_text, rotate_screen_text, status_footer, wallet_readiness,
wallet_view, who_overlay_text, wipe_screen_text, wordmark_banner, ChainChoice, ProfileEditor,
WalletReadiness, WALLET_LINE_MAX, WipeKind,
};
use onionwire::wallet::ChainSource;
use onionwire::FriendProfile;
use ratatui::backend::TestBackend;
use ratatui::layout::{Constraint, Layout, Rect};
@ -553,3 +556,163 @@ fn chars_count_is_not_terminal_cells() {
let ellipsis = "…";
assert_eq!(ellipsis.chars().count(), 1);
}
/// The F6 screen's not-ready state is a spec of this card, so this draws the
/// **real** `draw_wallet` at a fixed size and reads the cells back.
fn wallet_screen_at(w: u16, h: u16, view: &onionwire::tui::WalletView) -> String {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| draw_wallet(f, view, None))
.expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..h {
for x in 0..w {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
screen
}
fn local_source() -> ChainSource {
ChainSource::Local {
monerod_bin: std::path::PathBuf::from("monerod"),
datadir: std::path::PathBuf::from("/home/user/.onionwire/chain"),
}
}
fn address() -> String {
"4AdYaG7wVQ3nHvWoXbN9dQkXj1uYcR2mS8pT5LzE6fK7gB3aD".to_string()
}
#[test]
fn wallet_screen_says_not_ready_and_never_a_balance_before_sync() {
let chain = chain_view(
&local_source(),
WalletChildState::Stopped,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("127.0.0.1:18081: Connection refused (os error 111)".into()),
},
Some(412),
wallet_readiness(true, false, false),
);
let view = wallet_view(address(), "12.5 XMR".to_string(), Vec::new(), chain);
assert_eq!(
view.balance, "not synced — unavailable",
"a balance must not be rendered as a fact while the wallet has not synced"
);
assert!(!view.chain.ready);
for line in view.chain.lines() {
assert!(
line.chars().count() <= WALLET_LINE_MAX,
"chain line exceeds {WALLET_LINE_MAX}: {line:?}"
);
}
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"not ready: wallet RPC not answering",
"daemon: stopped — press n to start it",
"chain: local monerod",
"sync: unknown — 127.0.0.1:18081: Connection refused",
"storage: 412 GB free here",
"not synced — unavailable",
"pruned nodes are not archives",
] {
assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}");
}
// Nothing is clipped: every chain line survives whole.
for line in view.chain.lines() {
assert!(screen.contains(&line), "clipped line {line:?}:\n{screen}");
}
}
#[test]
fn wallet_screen_says_receive_only_when_nothing_is_configured() {
let chain = chain_view(
&ChainSource::None,
WalletChildState::Off,
&DaemonSync {
reachable: false,
height: 0,
target_height: 0,
note: Some("receive-only: no daemon".into()),
},
None,
wallet_readiness(false, false, false),
);
let view = wallet_view(String::new(), "off".to_string(), Vec::new(), chain);
let screen = wallet_screen_at(80, 24, &view);
for needle in [
"chain: receive-only",
"daemon: not configured — press s to choose a chain source",
"not ready: no wallet — receive-only until c create / i import",
"no address yet",
] {
assert!(screen.contains(needle), "wallet screen missing {needle:?}:\n{screen}");
}
}
#[test]
fn wallet_screen_keeps_the_balance_when_the_wallet_is_ready() {
let chain = chain_view(
&local_source(),
WalletChildState::Running,
&DaemonSync {
reachable: true,
height: 3_210_000,
target_height: 3_210_000,
note: None,
},
Some(412),
wallet_readiness(true, true, false),
);
let view = wallet_view(
address(),
"12.5 XMR".to_string(),
Vec::new(),
chain,
);
assert!(view.chain.ready);
assert_eq!(view.balance, "12.5 XMR");
let screen = wallet_screen_at(80, 24, &view);
assert!(screen.contains("ready: wallet synced"), "{screen}");
assert!(screen.contains("sync: synced — height 3210000"), "{screen}");
assert!(screen.contains("12.5 XMR"), "{screen}");
}
#[test]
fn a_view_only_wallet_says_so_instead_of_offering_a_spend() {
let readiness = wallet_readiness(true, true, true);
assert_eq!(readiness, WalletReadiness::ViewOnly);
assert!(!readiness.ready());
assert!(readiness.line().contains("view-only"));
}
#[test]
fn chain_choice_never_preselects_a_remote_daemon() {
for (source, want) in [
(ChainSource::None, ChainChoice::ReceiveOnly),
(local_source(), ChainChoice::LocalMonerod),
(
ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
},
ChainChoice::RemoteDaemon,
),
] {
assert_eq!(ChainChoice::of(&source), want);
}
assert_eq!(ChainChoice::ALL.len(), 3, "three choices, never a public node");
for choice in ChainChoice::ALL {
assert!(!choice.label().is_empty());
assert!(!choice.detail().is_empty());
}
}

View file

@ -6,9 +6,9 @@ use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::tui::{
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
status_footer, wrap_invite,
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, is_onion_host,
main_footer_hints, main_header_line, parse_daemon_addr, paste_screen_text, retry_in_text,
roster_col_width, short_send_reason, status_footer, wrap_invite,
};
use ratatui::Frame;
use ratatui::Terminal;
@ -796,3 +796,51 @@ async fn renders_a_queued_row_from_a_real_outbox_send() {
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}
/// The chain-source picker's address field: whatever the user typed either
/// parses into exactly `host:port`, or it is refused with a reason. `.onion`,
/// loopback and clearnet are all accepted — clearnet only because the user
/// typed it here — and there is no default port.
#[test]
fn daemon_addresses_parse_or_are_refused() {
assert_eq!(
parse_daemon_addr(" 127.0.0.1:18081 ").unwrap(),
("127.0.0.1".to_string(), 18081)
);
assert_eq!(
parse_daemon_addr("abc234defghijklmnop.onion:18089").unwrap(),
("abc234defghijklmnop.onion".to_string(), 18089)
);
assert_eq!(
parse_daemon_addr("node.example.com:18089").unwrap(),
("node.example.com".to_string(), 18089)
);
assert_eq!(parse_daemon_addr("[::1]:18081").unwrap().1, 18081);
for bad in [
"",
" ",
"127.0.0.1",
"host:",
":18081",
"host:0",
"host:65536",
"host:abc",
"host:-1",
"http://host:18081",
"host/path:18081",
"ho st:18081",
] {
let err = parse_daemon_addr(bad).expect_err(&format!("{bad:?} must be refused"));
assert!(!err.is_empty(), "{bad:?} refused without a reason");
}
}
#[test]
fn onion_hosts_are_recognised_before_any_spawn() {
assert!(is_onion_host("abc234.onion"));
assert!(is_onion_host("ABC234.ONION "));
assert!(!is_onion_host("127.0.0.1"));
assert!(!is_onion_host("node.example.com"));
assert!(!is_onion_host("notonion"));
}