wallet: show the chain daemon's sync height and target on the child status
All checks were successful
ci / test (pull_request) Successful in 5m50s
ci / sdk (pull_request) Successful in 1m34s
ci / fuzz (pull_request) Successful in 4m54s
android-ci / android (pull_request) Successful in 12m39s

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).
This commit is contained in:
onionwire 2026-09-19 19:38:52 -04:00
commit 0a91744924
No known key found for this signature in database
5 changed files with 468 additions and 17 deletions

View file

@ -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<RunningOnionService>,
@ -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<Option<String>>,
incoming_limit: Mutex<TokenBucket>,
@ -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:[email protected]:{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