From 0a91744924cb69629d99b8f242cf69a730576992 Mon Sep 17 00:00:00 2001 From: onionwire Date: Sat, 19 Sep 2026 19:38:52 -0400 Subject: [PATCH] wallet: show the chain daemon's sync height and target on the child status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The user watching an in-process Cuprate node on Android saw only a phase word (connecting, with 'wallet connect: Connection refused (os error 111)') and asked to see height vs tip. - WalletChildStatus gains height / target_height, and line() appends 'sync h/t' when a probe read either number. No percentage is invented when the daemon reports no target (h/0 is honest), and an off/exited child reports 0/0. - Node::wallet_child_refresh fills them: one wallet-RPC get_info now answers both the readiness gate and the numbers (Wallet::chain_info, with chain_ready built on the same parse), and when the wallet RPC is down while the chain source is local/in-process, the loopback daemon is asked directly (ChildConfig::daemon_probe_addr). A refused daemon stays 0/0 — unknown, not caught up. Only refresh dials; the draw path reads two atomics. - UniFFI WalletChildStatus carries the same two u64 fields so Android can show them; SDK test covers the round trip. Tests: cargo test --locked --target x86_64-unknown-linux-gnu (all green), clippy -D warnings clean; crates/onionwire-sdk cargo test --locked + clippy clean (separate workspace). --- crates/onionwire-sdk/src/lib.rs | 37 +++++ docs/WALLET.md | 16 ++ src/node.rs | 261 ++++++++++++++++++++++++++++++-- src/wallet.rs | 47 +++++- src/wallet_child.rs | 124 +++++++++++++++ 5 files changed, 468 insertions(+), 17 deletions(-) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 247f284..c9b5b2b 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -872,6 +872,8 @@ fn child_status( } else { String::new() }, + height: status.height, + target_height: status.target_height, last_error: status.last_error, } } @@ -1077,6 +1079,14 @@ pub struct WalletChildStatus { /// node's side (the daemon's loopback RPC has not answered yet); it is /// never persisted, polled from a file, or inferred from a timeout. pub node_state: String, + /// Blocks the chain daemon had at the last probe, as the wallet RPC (or the + /// daemon itself, over loopback) reported them. `0` means unknown: never + /// probed, the child is off/exited, or the probe failed — it is not the + /// same as caught up, and it is never a wallet-scan height. + pub height: u64, + /// Blocks the daemon was syncing towards. `0` means the daemon reported + /// none (also not the same as caught up). + pub target_height: u64, /// The last failure, display-ready. Never carries the generated login. pub last_error: Option, } @@ -1889,6 +1899,8 @@ mod tests { running: true, configured: true, chain_source: "in-process node".to_string(), + height: 0, + target_height: 0, last_error: None, } } @@ -1960,4 +1972,29 @@ mod tests { let status = child_status(core_status(WalletChildState::Off), &ChainSource::None); assert_eq!(status.node_available, onionwire::cuprate::available()); } + + /// The chain's own progress reaches Kotlin: a snapshot that carries the + /// daemon's height and target copies both numbers onto the record, so an + /// Android status line can show `1160/3090939` without a second probe. + #[test] + fn the_daemons_height_and_target_reach_the_sdk_record() { + let mut core = core_status(WalletChildState::Connecting); + core.height = 1160; + core.target_height = 3_090_939; + let status = child_status(core, &ChainSource::None); + assert_eq!(status.height, 1160); + assert_eq!(status.target_height, 3_090_939); + // The core's own word still passes straight through: the numbers are an + // addition, not a second state machine. + assert_eq!(status.state, "connecting"); + } + + /// A snapshot with nothing to report keeps `0/0`: unknown is not caught up, + /// and no percentage is invented on the way out. + #[test] + fn an_unprobed_child_reports_an_unknown_chain_progress() { + let status = child_status(core_status(WalletChildState::Off), &ChainSource::None); + assert_eq!(status.height, 0); + assert_eq!(status.target_height, 0); + } } diff --git a/docs/WALLET.md b/docs/WALLET.md index 0adc25d..2a34f03 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -342,6 +342,22 @@ env-var presence, and `ready` is never reported for a child that has died. - **`exited`** — a started child has died. Stop and start again; the status is not stale, it is the process table. +The same one-liner carries the chain's own progress once a probe has read it: + +``` +child syncing · in-process node · sync 1160/3090939 +``` + +Those are the **daemon's** height and the tip it is syncing towards — from the +wallet RPC's `get_info` when it answers, and, when the wallet RPC is *not* +answering (the `connecting` case, e.g. `Connection refused (os error 111)`) while +the chain source is `local node` or `in-process node`, from that loopback daemon +directly. `sync 0/0`, or no `sync` segment at all, means **unknown**: the child +is off or exited, the probe failed, or the daemon reported no target — which is +not the same as caught up, and is never a wallet-scan height. No percentage is +ever derived from it. `WalletChildStatus` (and the UniFFI record) carries the two +numbers as `height` / `target_height`. + `start` is idempotent: a live child is reported, not respawned. A start that cannot spawn the binary is an error and leaves no child behind. diff --git a/src/node.rs b/src/node.rs index cbad028..15e7220 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,7 +1,7 @@ //! Two-node onion session: host HS, Noise IK, persist plaintext locally. use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -55,6 +55,10 @@ pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30); /// The drain inside `shutdown` gets a shorter budget: teardown must not hang /// the caller behind a Tor dial. Undelivered rows survive in sqlite. pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); +/// Budget for the direct loopback `get_info` a child refresh makes when the +/// wallet RPC is not answering. Local TCP only — a refused daemon returns +/// immediately, and a live one answers in milliseconds. +const DAEMON_PROBE_BUDGET: Duration = Duration::from_secs(3); struct HsHandle { svc: Arc, @@ -96,6 +100,13 @@ pub struct Node { /// 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, + /// Blocks the chain daemon had at the last probe. `0` means unknown: never + /// probed, the child is off/exited, or the probe failed. Only + /// `wallet_child_refresh` writes it; the draw path only reads it. + child_height: AtomicU64, + /// Blocks the daemon was syncing towards at the last probe. `0` means the + /// daemon reported none — not the same as caught up. + child_target: AtomicU64, /// The last child failure, display-ready. Cleared on a successful start. child_error: Mutex>, incoming_limit: Mutex, @@ -167,6 +178,8 @@ impl Node { wallet_status: Mutex::new(wallet_status), wallet_child: Mutex::new(None), child_synced: AtomicBool::new(false), + child_height: AtomicU64::new(0), + child_target: AtomicU64::new(0), child_error: Mutex::new(None), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), @@ -274,7 +287,7 @@ impl Node { // 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); + self.reset_child_probe(); if let Err(e) = child.stop() { eprintln!("shutdown: wallet child stop failed: {e}"); } @@ -659,7 +672,7 @@ impl Node { *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.reset_child_probe(); *self.wallet_child.lock().map_err(|e| e.to_string())? = Some(child); Ok(()) } @@ -672,7 +685,7 @@ impl Node { if let Some(child) = child { child.stop().map_err(|e| e.to_string())?; } - self.child_synced.store(false, Ordering::Relaxed); + self.reset_child_probe(); let stored = self .store .lock() @@ -686,6 +699,15 @@ impl Node { Ok(()) } + /// Clear the last child probe: no chain answers, nothing remembered. Called + /// wherever the child's lifecycle moves (start, stop, shutdown), so a stale + /// height from a previous run can never survive into the next one. + fn reset_child_probe(&self) { + self.child_synced.store(false, Ordering::Relaxed); + self.child_height.store(0, Ordering::Relaxed); + self.child_target.store(0, Ordering::Relaxed); + } + /// 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 { @@ -710,11 +732,22 @@ impl Node { Some(_) if self.child_synced.load(Ordering::Relaxed) => WalletChildState::Ready, Some(_) => WalletChildState::Syncing, }; + // Only a live child has anything to say about a chain. An off or exited + // child reports unknown (`0/0`), whatever the last probe left behind. + let heights = match state { + WalletChildState::Off | WalletChildState::Exited => (0, 0), + WalletChildState::Connecting | WalletChildState::Syncing | WalletChildState::Ready => ( + self.child_height.load(Ordering::Relaxed), + self.child_target.load(Ordering::Relaxed), + ), + }; WalletChildStatus { state, running, configured: cfg.is_enabled(), chain_source: cfg.source_label(), + height: heights.0, + target_height: heights.1, last_error: self.child_error.lock().ok().and_then(|err| err.clone()), } } @@ -725,9 +758,10 @@ impl Node { 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. + /// Probe the running child once: is its wallet RPC answering, is the chain + /// at the tip, and how far along is the chain daemon? 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 @@ -737,6 +771,7 @@ impl Node { if !running { return self.wallet_child_status(); } + let cfg = self.wallet_child_config(); let w = self.wallet_snapshot(); if !w.configured() { return self.wallet_child_status(); @@ -747,18 +782,44 @@ impl Node { if let Ok(mut slot) = self.wallet_status.lock() { *slot = status; } - let synced = if connected { - w.chain_ready().await.unwrap_or(false) + // One probe answers both questions: is it synced, and how far along. + let progress = if connected { + w.chain_info().await.ok() } else { - false + None + }; + let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready); + let (height, target_height) = match progress { + Some(info) => (info.height, info.target_height), + // The wallet RPC is the honest source when it answers. When it does + // not (a refused connection is the common one), the daemon this box + // owns can still say — and a daemon that does not answer leaves + // `0/0`, which is "unknown", not "caught up". + None => self.chain_daemon_progress(&cfg).await, }; self.child_synced.store(synced, Ordering::Relaxed); + self.child_height.store(height, Ordering::Relaxed); + self.child_target.store(target_height, Ordering::Relaxed); if let Ok(mut slot) = self.child_error.lock() { *slot = if connected { None } else { error }; } self.wallet_child_status() } + /// The chain daemon's own height/target, asked directly because the wallet + /// RPC did not answer. Only a daemon on this box is asked (see + /// [`ChildConfig::daemon_probe_addr`]) and any failure is `(0, 0)` — a + /// daemon still coming up is unknown, not an error to put on the status row. + async fn chain_daemon_progress(&self, cfg: &ChildConfig) -> (u64, u64) { + let Some(addr) = cfg.daemon_probe_addr() else { + return (0, 0); + }; + match wallet::daemon_get_info(&addr, DAEMON_PROBE_BUDGET).await { + Ok(info) => (info.height, info.target_height), + Err(_) => (0, 0), + } + } + /// 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. @@ -1827,6 +1888,7 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; use std::pin::Pin; use crate::wallet::ChainSource; @@ -1929,6 +1991,8 @@ mod tests { wallet_status: Mutex::new(wallet_status), wallet_child: Mutex::new(None), child_synced: AtomicBool::new(false), + child_height: AtomicU64::new(0), + child_target: AtomicU64::new(0), child_error: Mutex::new(None), incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(file::Inbox::new(home.join("inbox"))), @@ -2458,6 +2522,183 @@ mod tests { } } + /// A loopback wallet RPC that answers the *status* probe: a digest + /// challenge, then `get_address` / `get_balance` / `get_info`, with the + /// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the + /// *transfer* path; this one answers a refresh, which never transfers. + async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock wallet"); + let port = listener.local_addr().expect("mock wallet addr").port(); + tokio::spawn(async move { + // 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 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", + ) + .await; + continue; + } + let body = if req.contains("get_info") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# + ) + } else if req.contains("get_address") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, + addr = xmr_addr() + ) + } else { + r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string() + }; + let _ = sock + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ) + .await; + } + }); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + + /// A loopback daemon that answers `get_info` on the port the child probes + /// when its wallet RPC is down. `None` when that port is already held (a real + /// `monerod` on this box): that daemon is not ours to replace, and the test + /// must not claim to have served the answer. + async fn mock_daemon_on_default_port(height: u64, target: u64) -> Option<()> { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = + tokio::net::TcpListener::bind(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")) + .await + .ok()?; + tokio::spawn(async move { + for _ in 0..4 { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 4096]; + let _ = sock.read(&mut buf).await; + let body = format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"# + ); + let _ = sock + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ) + .await; + } + }); + Some(()) + } + + /// The status row carries the real chain numbers: a wallet RPC that answers + /// `get_info` fills height and target, and the one-liner shows them. A + /// daemon that reports no target is not a caught-up chain — `h/0` with no + /// invented percentage. + #[tokio::test] + async fn a_wallet_that_answers_get_info_fills_the_chain_progress() { + 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, + "sleep 30", + ); + node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) + .expect("set config"); + node.start_wallet_child().expect("start"); + // The child is a fake process; the wallet the node actually talks to is + // the mock RPC, which is where the numbers come from. + *node.wallet.lock().unwrap() = mock_syncing_wallet(4549, 0).await; + + let status = node.wallet_child_refresh().await; + assert_eq!(status.state, WalletChildState::Ready, "{status:?}"); + assert_eq!(status.height, 4549, "{status:?}"); + assert_eq!(status.target_height, 0, "{status:?}"); + assert!(status.line().contains("sync 4549/0"), "{}", status.line()); + assert!(!status.line().contains('%'), "{}", status.line()); + + node.stop_wallet_child().expect("stop"); + } + + /// The case the user hit: the wallet RPC is refused (`os error 111`) while + /// the chain source is this box's own daemon. The status still shows the + /// chain's height and target — asked of the daemon directly — and the state + /// stays `connecting`, because the *wallet* is what did not answer. + #[tokio::test] + async fn a_refused_wallet_rpc_falls_back_to_the_local_daemons_own_height() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("child"); + let Some(()) = mock_daemon_on_default_port(1160, 3_090_939).await else { + eprintln!( + "skipping: 127.0.0.1:{DEFAULT_MONEROD_RPC_PORT} is already held by something else" + ); + return; + }; + let node = offline_node(&home, Arc::new(NoDial)); + let monerod = fake_child_bin( + &dir.path().join("fake-bins"), + "monerod", + &dir.path().join("monerod.argv"), + "sleep 30", + ); + let rpc = fake_child_bin( + &dir.path().join("fake-bins"), + "monero-wallet-rpc", + &dir.path().join("rpc.argv"), + "sleep 30", + ); + node.set_wallet_child_config(&ChildConfig { + source: ChainSource::Local { + monerod_bin: monerod, + datadir: dir.path().join("chain"), + prune: true, + }, + wallet_rpc_bin: rpc, + arti_bin: PathBuf::from("arti"), + wallet_filename: "onionwire".to_string(), + }) + .expect("set config"); + node.start_wallet_child().expect("start"); + + let status = node.wallet_child_refresh().await; + assert_eq!(status.state, WalletChildState::Connecting, "{status:?}"); + assert_eq!(status.height, 1160, "{status:?}"); + assert_eq!(status.target_height, 3_090_939, "{status:?}"); + assert!( + status.line().contains("sync 1160/3090939"), + "{}", + status.line() + ); + + node.stop_wallet_child().expect("stop"); + } + fn sealed_creds(node: &Node) -> (String, String) { let raw = node .store diff --git a/src/wallet.rs b/src/wallet.rs index f404cea..226dab0 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -363,6 +363,30 @@ pub struct Wallet { timeout_chain: Duration, } +/// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and +/// the numbers a status line shows. `0` height/target means the wallet RPC +/// answered without a number — unknown, never "caught up", and never a percent. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ChainInfo { + /// The wallet RPC said `synchronized: true`. A missing field is `false`. + pub synchronized: bool, + /// Blocks the wallet's daemon has, as the wallet RPC reports them. + pub height: u64, + /// Blocks that daemon is syncing towards; `0` when it reported none. + pub target_height: u64, +} + +impl ChainInfo { + /// The readiness predicate: the daemon reached the tip and the wallet + /// scanned up to it. `synchronized` must be explicitly true, and a chain + /// with no height is not ready. + pub fn ready(&self) -> bool { + self.synchronized + && self.height > 0 + && (self.target_height == 0 || self.height >= self.target_height) + } +} + /// What /tip says when the wallet cannot spend. Same text for the explicit /// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over /// RPC, so the operator never has to guess which one it was. The TUI's @@ -695,14 +719,23 @@ impl Wallet { /// the wallet has scanned up to it. `synchronized` must be explicitly true — /// a missing field is not-ready, never a silent pass. pub async fn chain_ready(&self) -> Result { + Ok(self.chain_info().await?.ready()) + } + + /// One `get_info` round trip, carrying both the readiness fields and the + /// numbers a status line shows — the status line and the spend gate ask the + /// same question, so they ask it once. `0` height/target means the wallet + /// RPC answered without a number: unknown, never "caught up". + pub async fn chain_info(&self) -> Result { let v = self.chain_rpc("get_info", serde_json::json!({})).await?; - let synced = v - .get("synchronized") - .and_then(|b| b.as_bool()) - .unwrap_or(false); - let height = v.get("height").and_then(|h| h.as_u64()).unwrap_or(0); - let target = v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0); - Ok(synced && height > 0 && (target == 0 || height >= target)) + Ok(ChainInfo { + synchronized: v + .get("synchronized") + .and_then(|b| b.as_bool()) + .unwrap_or(false), + height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0), + target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0), + }) } /// May this wallet attempt a spend? Fail closed: any readiness doubt is a diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 8769ccb..e56ee0e 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -727,6 +727,21 @@ impl ChildConfig { pub fn source_label(&self) -> String { self.source.label() } + + /// Where a status refresh may ask the chain daemon itself for + /// height/target, when the wallet RPC is not answering. Only a daemon this + /// box owns: a `monerod`/Cuprate the child spawned binds loopback, and + /// asking it is a plain local socket. A remote daemon is the wallet child's + /// to dial (over SOCKS, if it is an onion) — a status refresh does not open + /// a second path to it. + pub fn daemon_probe_addr(&self) -> Option { + match self.source { + ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => { + Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")) + } + ChainSource::None | ChainSource::Remote { .. } => None, + } + } /// 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<()> { @@ -888,6 +903,12 @@ pub struct WalletChildStatus { /// The chain-source label: `receive-only` / `local node` / /// `remote onion daemon` / `remote daemon`. pub chain_source: String, + /// Blocks the chain daemon currently has. `0` means unknown (not started, or + /// the last probe failed). This is daemon height, never wallet-rpc scan height. + pub height: u64, + /// Blocks the daemon is syncing towards. `0` means the daemon reported none + /// (not the same as caught up — see `wallet::chain_ready`). + pub target_height: u64, /// The last failure, display-ready. Never carries the generated login. pub last_error: Option, } @@ -900,6 +921,13 @@ impl WalletChildStatus { return String::new(); } let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source); + // A probe that read nothing says nothing: the line is unchanged until a + // daemon (or the wallet's daemon) actually reported numbers. No + // percentage is derived — `target_height == 0` is "the daemon told us + // nothing", not "caught up". + if self.height > 0 || self.target_height > 0 { + line.push_str(&format!(" · sync {}/{}", self.height, self.target_height)); + } if let Some(err) = &self.last_error { line.push_str(" · "); line.push_str(err); @@ -1965,6 +1993,102 @@ mod tests { assert!(closed, "the daemon's RPC listener outlived stop()"); } + fn probe_status(state: WalletChildState, height: u64, target_height: u64) -> WalletChildStatus { + WalletChildStatus { + state, + running: true, + configured: true, + chain_source: "in-process node".to_string(), + height, + target_height, + last_error: None, + } + } + + /// No probe numbers, no `sync` segment: a snapshot that never read a height + /// renders exactly the line it rendered before this existed. + #[test] + fn a_status_line_without_probe_numbers_carries_no_sync_segment() { + let line = probe_status(WalletChildState::Connecting, 0, 0).line(); + assert_eq!(line, "child connecting · in-process node"); + assert!(!line.contains("sync"), "{line}"); + } + + /// The numbers the user asked for: the daemon's own height over the tip it + /// is syncing towards, on the same one-liner the wallet screen already shows. + #[test] + fn a_status_line_shows_the_daemons_height_and_target() { + let line = probe_status(WalletChildState::Connecting, 1160, 3_090_939).line(); + assert!(line.contains("sync 1160/3090939"), "{line}"); + assert!(!line.contains('%'), "{line}"); + } + + /// A daemon that reports no target is not a caught-up chain: the height is + /// still shown — over `0` — and no percentage is invented for it. + #[test] + fn a_missing_target_still_shows_the_height_and_no_percent() { + let line = probe_status(WalletChildState::Syncing, 4549, 0).line(); + assert!(line.contains("sync 4549/0"), "{line}"); + assert!(!line.contains('%'), "{line}"); + } + + /// The failure text stays last: a probe number never displaces the error a + /// reader is looking for. + #[test] + fn a_status_line_keeps_the_error_after_the_sync_segment() { + let mut status = probe_status(WalletChildState::Connecting, 1160, 3_090_939); + status.last_error = Some("wallet connect: Connection refused (os error 111)".into()); + let line = status.line(); + assert!(line.contains("sync 1160/3090939"), "{line}"); + assert!( + line.ends_with("· wallet connect: Connection refused (os error 111)"), + "{line}" + ); + } + + /// Only a daemon this box owns is asked directly. A remote daemon is the + /// wallet child's to dial — a status refresh must not open a second path to + /// it, and receive-only has nothing to ask at all. + #[test] + fn only_a_loopback_source_gets_a_daemon_probe_address() { + let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"); + for source in [ + ChainSource::Local { + monerod_bin: PathBuf::from("monerod"), + datadir: PathBuf::from("/chain"), + prune: false, + }, + ChainSource::InProcessCuprate { + datadir: PathBuf::from("/chain"), + network: ChainNetwork::Mainnet, + prune: true, + }, + ] { + let cfg = ChildConfig { + source: source.clone(), + ..ChildConfig::default() + }; + assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str())); + } + for source in [ + ChainSource::None, + ChainSource::Remote { + host: "peer.onion".to_string(), + port: 18081, + }, + ChainSource::Remote { + host: "203.0.113.7".to_string(), + port: 18081, + }, + ] { + let cfg = ChildConfig { + source, + ..ChildConfig::default() + }; + assert_eq!(cfg.daemon_probe_addr(), None); + } + } + /// Poll a loopback address until it accepts, inside a budget. #[cfg(feature = "cuprate-daemon")] fn waits_for_tcp(addr: &str, budget: Duration) -> bool { -- 2.52.0