From 3aafaefae89a7fdb47a2c13c6bf8b501533290db Mon Sep 17 00:00:00 2001 From: rust-dev Date: Sat, 31 Oct 2026 01:35:13 -0400 Subject: [PATCH] wallet: derive readiness from the wallet's get_height, not a nonexistent get_info monero-wallet-rpc does not implement get_info (-32601 Method not found); it exists on the daemon only. Every wallet therefore sat in syncing forever: no balance, spends refused, receipts never verified. Readiness is now the pair: - the wallet RPC's own get_height (its scanned height), and - the chain tip from the existing daemon client (GET /get_height). ready = height > 0 && (tip == 0 || height + 2 >= tip). The 2-block slack is deliberate: the tip moves every ~2 min and the two reads are not a snapshot. A daemon that does not answer, a missing height and -13 No wallet file are all not-ready, never an error banner. ChildConfig::daemon_probe_addr resolves a tip source for clearnet remotes (the wallet child already dials them); a .onion daemon is not dialled without the SOCKS child and stays fail-closed. docs/WALLET.md now documents the real rule. Tests cover -32601 get_info, equal tip, slack boundary, dead daemon and the no-wallet-file answer. --- docs/WALLET.md | 41 ++++++-- src/node.rs | 182 ++++++++++++++++++++++---------- src/tui.rs | 16 ++- src/wallet.rs | 100 ++++++++++++------ src/wallet_child.rs | 48 ++++++--- tests/wallet.rs | 246 ++++++++++++++++++++++++++++++++++++-------- 6 files changed, 475 insertions(+), 158 deletions(-) diff --git a/docs/WALLET.md b/docs/WALLET.md index 09cda7d..99655a2 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -208,18 +208,42 @@ C++ binary, so it reaches Tor through a SOCKS proxy the app provides: **Tor hides the transport, not the host.** The daemon operator still sees the wallet's addresses during sync. -### Readiness — receipt verification needs a synced daemon +### Readiness — receipt verification needs a synced wallet -`chain_ready()` asks the wallet RPC `get_info` and requires -**`synchronized == true`** with `height > 0` and `height >= target_height`. A -missing field is *not ready* — fail closed. +`chain_ready()` compares the wallet's **own scanned height** with the **chain +tip**. Both halves must answer: + +1. the wallet RPC's `get_height` reports `height > 0`. That is + `monero-wallet-rpc`'s own method; `get_info` does **not** exist there — it + answers `-32601 Method not found`, so readiness never asks for it. +2. the chain daemon reports a tip, and the wallet is at it or within **2 + blocks**. The tip moves every ~2 minutes and the two numbers are two reads, + not one snapshot, so a strict equality flaps; two blocks of slack does not + hide a real lag. + +The tip comes from `daemon_get_height` (`GET /get_height` — one spelling that +works on monerod and Cuprate) against `ChildConfig::daemon_probe_addr()`: + +- local `monerod` / in-process Cuprate → `127.0.0.1:18081`; +- a **clearnet** remote daemon the user typed → that host. The wallet child + already dials it, so one `get_height` is the same exposure, not a new path; +- a **`.onion`** daemon → **not dialled** without the SOCKS child: a direct dial + would resolve the name on clearnet DNS and leak. Readiness stays false + (height-only); the status row reads syncing. A documented limit, not a bug; +- receive-only, or an externally run wallet RPC with no chain source → nothing + to ask, so not ready. + +Unknown is **not caught up**. A daemon that does not answer, a wallet with no +file open (`-13 No wallet file`), and a missing height all read *not ready*, +never a silent pass. "No wallet open" is a state, not an error banner. Until then, **receipt verification stays `verified=0`**. An unsynced wallet cannot see the chain. That is an honest limit, not a UI bug. Loopback management calls (`get_address`, `query_key`, create/import) get 5s. -Calls that wait on the chain (`get_info`, `get_transfers`, `transfer`) get 60s -(`CHAIN_RPC_TIMEOUT`). +Calls that wait on the chain (`get_transfers`, `transfer`) get 60s +(`CHAIN_RPC_TIMEOUT`). Readiness is not a chain wait: it is one local +`get_height` plus one bounded daemon probe. ## Env vars (migration path) @@ -256,8 +280,9 @@ re-points the wallet without a restart; a rejected form writes nothing. UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`, `start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read: no dial, for first paint) and `wallet_child_refresh()` (a live probe of the -same record — it dials the loopback wallet RPC, and the local daemon's -`get_info` when that RPC does not answer, so poll it on the order of seconds). +same record — it dials the loopback wallet RPC and asks the configured daemon +for its tip (the wallet's `get_height` is the other half), so poll it on the +order of seconds). Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the core never resolves a binary the caller named explicitly. diff --git a/src/node.rs b/src/node.rs index 86b6412..3ab985f 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1065,7 +1065,12 @@ impl Node { return self.wallet_child_status(); } let cfg = self.wallet_child_config(); - let w = self.wallet_snapshot(); + // Readiness needs both halves: the wallet's own `get_height` and the + // chain tip. The tip comes from the configured daemon (loopback for a + // local source, the clearnet host the user typed, never a `.onion`). + let w = self + .wallet_snapshot() + .with_daemon_probe(cfg.daemon_probe_addr()); if !w.configured() { return self.wallet_child_status(); } @@ -1090,7 +1095,7 @@ impl Node { } let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready); let (height, target_height) = match progress { - Some(info) => (info.height, info.target_height), + Some(info) => (info.height, info.tip.unwrap_or(0)), // 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 @@ -1334,7 +1339,9 @@ impl Node { /// Pay selected friend via wallet RPC, then signed receipt. pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> { - let w = self.wallet_snapshot(); + let w = self + .wallet_snapshot() + .with_daemon_probe(self.wallet_child_config().daemon_probe_addr()); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } @@ -2153,7 +2160,9 @@ impl Node { // Honest prerequisite: an unsynced wallet cannot see the tx, so a // get_transfers "miss" would be a lie. Until the chain is ready the // receipt stays verified=0 — that is the correct state, not an error. - let w = self.wallet_snapshot(); + let w = self + .wallet_snapshot() + .with_daemon_probe(self.wallet_child_config().daemon_probe_addr()); let ready = w.configured() && w.can_verify_receipts().await; if ready { match w.get_transfers().await { @@ -3417,25 +3426,43 @@ pub(crate) mod tests { } /// A loopback wallet RPC that answers what the tip path actually asks for: - /// a digest challenge, then a synced `get_info` for the readiness gate and - /// `tx_hash` for the transfer. The old single-answer mock stopped covering - /// the path when `Wallet::transfer` started probing the chain tip first — - /// it answered `tx_hash` to `get_info` and every tip was refused as unsynced. - async fn mock_wallet() -> Wallet { + /// a digest challenge, then the wallet's own scanned `get_height` for the + /// readiness gate and `tx_hash` for the transfer. `get_info` is a daemon + /// method, not a wallet one, so it is never asked. Returns the wallet and + /// the daemon stub's address (the tip the gate compares against). + async fn mock_wallet() -> (Wallet, String) { 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(); let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { - if req.contains("get_info") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# - .to_string() + if req.contains("get_height") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string() } else { r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string() } }); tokio::spawn(serve_mock_rpc(listener, reply)); - Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + let wallet = Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")) + .expect("wallet url"); + let daemon = mock_daemon(100, 100).await; + (wallet, daemon) + } + + /// Point a test node's chain source at a daemon stub, so readiness has a + /// tip to compare the wallet's scanned height against. + fn chain_source_at(node: &Node, addr: &str) { + let (host, port) = addr.rsplit_once(':').expect("host:port"); + node.set_wallet_child_config(&ChildConfig { + source: ChainSource::Remote { + host: host.to_string(), + port: port.parse().expect("port"), + }, + wallet_rpc_bin: PathBuf::from("monero-wallet-rpc"), + arti_bin: PathBuf::from("arti"), + wallet_filename: wallet::DEFAULT_WALLET_FILENAME.to_string(), + }) + .expect("set chain source"); } /// The payer of a tip must see it in their own chat: `receipt_chat_line` is /// the recipient's view of the frame that arrived, `tip_chat_line` is what @@ -3443,11 +3470,9 @@ pub(crate) mod tests { #[tokio::test] async fn outbound_tip_appends_the_senders_own_tip_chat_line() { let dir = tempfile::tempdir().unwrap(); - let node = offline_node_with_wallet( - &dir.path().join("bob"), - Arc::new(DialOk), - mock_wallet().await, - ); + let (wallet, daemon) = mock_wallet().await; + let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet); + chain_source_at(&node, &daemon); let peer = Keys::generate(); let addr = xmr_addr(); { @@ -3548,11 +3573,9 @@ pub(crate) mod tests { #[tokio::test] async fn outbound_tip_records_a_tip_payment_row() { let dir = tempfile::tempdir().unwrap(); - let node = offline_node_with_wallet( - &dir.path().join("bob"), - Arc::new(DialOk), - mock_wallet().await, - ); + let (wallet, daemon) = mock_wallet().await; + let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet); + chain_source_at(&node, &daemon); let peer = Keys::generate(); let addr = xmr_addr(); { @@ -3767,23 +3790,62 @@ pub(crate) mod tests { } } + /// A chain-daemon stub on an ephemeral loopback port: `GET /get_height` + /// answers the tip, `/json_rpc get_info` answers height/target. Returns + /// `host:port`. + async fn mock_daemon(height: u64, target: u64) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind mock daemon"); + let addr = listener.local_addr().expect("mock daemon addr").to_string(); + tokio::spawn(async move { + while let Ok((mut sock, _)) = listener.accept().await { + let mut buf = vec![0u8; 4096]; + let Ok(n) = sock.read(&mut buf).await else { + return; + }; + if n == 0 { + continue; + } + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let body = if req.starts_with("GET /get_height") { + format!(r#"{{"height":{height}}}"#) + } else { + 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; + } + }); + addr + } + /// 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. - /// 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 { + /// challenge, then `get_address` / `get_balance` / `get_height`, with the + /// wallet's own scanned height. Returns the wallet and the daemon stub's + /// address — the tip comes from the daemon, never from the wallet RPC. + /// [`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, String) { 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(); let reply: Arc String + Send + Sync> = Arc::new(move |req: &str| { - if req.contains("get_info") { + if req.contains("get_height") { format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height}}}}}"# ) } else if req.contains("get_address") { format!( @@ -3795,7 +3857,10 @@ pub(crate) mod tests { } }); tokio::spawn(serve_mock_rpc(listener, reply)); - Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + let wallet = + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url"); + let daemon = mock_daemon(height, target).await; + (wallet, daemon) } /// Point `node`'s wallet client at a mock. The child process stays whatever @@ -3804,13 +3869,14 @@ pub(crate) mod tests { *node.wallet.lock().expect("wallet") = wallet; } - /// Like [`mock_syncing_wallet`], but `height` is read on every `get_info`, - /// so a later store is a later answer. `synchronized` stays false: the - /// status line is a syncing chain, not a caught-up one. + /// Like [`mock_syncing_wallet`], but the wallet's scanned `height` is read on + /// every `get_height`, so a later store is a later answer. The daemon stub + /// reports `target` as its tip. Returns the wallet and the daemon address so + /// a caller can point a chain source at it. pub(crate) async fn mock_wallet_at( height: std::sync::Arc, target: u64, - ) -> Wallet { + ) -> (Wallet, String) { use std::sync::atomic::Ordering; let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -3818,11 +3884,9 @@ pub(crate) mod tests { .expect("bind mock wallet"); let port = listener.local_addr().expect("mock wallet addr").port(); let reply: Arc String + Send + Sync> = Arc::new(move |req: &str| { - if req.contains("get_info") { + if req.contains("get_height") { let h = height.load(Ordering::Relaxed); - format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"# - ) + format!(r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h}}}}}"#) } else if req.contains("get_address") { r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string() } else { @@ -3830,7 +3894,10 @@ pub(crate) mod tests { } }); tokio::spawn(serve_mock_rpc(listener, reply)); - Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + let wallet = + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url"); + let daemon = mock_daemon(target, target).await; + (wallet, daemon) } /// A loopback daemon that answers `get_info` on the port the child probes @@ -3868,12 +3935,12 @@ pub(crate) mod tests { 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. + /// The status row carries the real chain numbers: the wallet RPC's own + /// `get_height` is the wallet's scanned height, and the daemon's tip is the + /// target. A daemon that reports no separate target still gives a tip, so + /// `h/h` is the honest line — never an invented percentage. #[tokio::test] - async fn a_wallet_that_answers_get_info_fills_the_chain_progress() { + async fn the_wallet_height_and_the_daemon_tip_fill_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"); @@ -3890,14 +3957,16 @@ pub(crate) mod tests { let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); 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; + // the mock RPC, and the tip comes from the daemon stub. + let (wallet, daemon) = mock_syncing_wallet(4549, 0).await; + *node.wallet.lock().unwrap() = wallet; + chain_source_at(&node, &daemon); 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_eq!(status.target_height, 4549, "{status:?}"); + assert!(status.line().contains("sync 4549/4549"), "{}", status.line()); assert!(!status.line().contains('%'), "{}", status.line()); node.stop_wallet_child().expect("stop"); @@ -5014,9 +5083,8 @@ pub(crate) mod tests { r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, addr = xmr_addr() ) - } else if req.contains("get_info") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# - .to_string() + } else if req.contains("get_height") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string() } else { r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"# .to_string() @@ -5275,7 +5343,9 @@ pub(crate) mod tests { ); // The read after the restart takes the success path: the same mock - // answers `get_address`/`get_balance`/`get_info`. + // answers `get_address` / `get_balance` / `get_height`. + let daemon = mock_daemon(100, 100).await; + chain_source_at(&node, &daemon); let status = node.wallet_child_refresh().await; assert!(status.wallet_open, "{status:?}"); assert!(!status.needs_passphrase, "{status:?}"); diff --git a/src/tui.rs b/src/tui.rs index ecc3dee..89fc845 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -7694,8 +7694,22 @@ mod wallet_setup_config_tests { app.node.start_wallet_child().expect("start"); let height = Arc::new(AtomicU64::new(1111)); - let wallet = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000)); + let (wallet, daemon) = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000)); test_install_wallet(&app.node, wallet); + // Readiness compares the wallet's scanned height with a daemon tip, so + // point the chain source at the stub the wallet mock returned. + let (host, port) = daemon.rsplit_once(':').expect("host:port"); + app.node + .set_wallet_child_config(&ChildConfig { + source: ChainSource::Remote { + host: host.to_string(), + port: port.parse().expect("daemon port"), + }, + wallet_rpc_bin: std::path::PathBuf::from("monero-wallet-rpc"), + arti_bin: std::path::PathBuf::from("arti"), + wallet_filename: "onionwire".into(), + }) + .expect("point the chain source at the daemon stub"); app.handle_key(key(KeyCode::F(7))).expect("F7"); wait_for_sync_line(&mut app, &rt, "sync 1111/9000"); diff --git a/src/wallet.rs b/src/wallet.rs index c5cf04f..966dd62 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -488,34 +488,53 @@ pub struct Wallet { /// Budget for loopback management calls (`get_address`, `query_key`, /// create/import). The wallet child is on the same box, so this stays short. timeout_local: Duration, - /// Budget for calls that wait on the daemon (`get_info`, `get_transfers`, - /// `transfer`). A first sync or a remote daemon legitimately outlasts the - /// local budget, and treating that as "down" is what left receipts + /// Budget for calls that wait on the daemon (`get_transfers`, `transfer`). + /// A first sync or a remote daemon legitimately outlasts the local budget, + /// and treating that as "down" is what left receipts /// permanently unverified. timeout_chain: Duration, + /// Chain daemon to compare the wallet's scanned height against. `None` + /// means no comparable tip (receive-only, a `.onion` daemon that needs the + /// SOCKS child, an externally run wallet RPC): readiness stays false. Set + /// from [`crate::wallet_child::ChildConfig::daemon_probe_addr`] by the node. + daemon_probe: Option, } -/// 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. +/// What the readiness pair is: the wallet's own scanned height and the chain +/// tip the daemon reports. Neither number comes from the wallet RPC's +/// `get_info` — `monero-wallet-rpc` does not implement it (`-32601 Method not +/// found`); `get_info` exists on the daemon only. +/// +/// `0` height means the wallet RPC answered without a number. `tip == None` +/// means the daemon did not answer. Both are unknown — never "caught up". #[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. + /// Blocks the wallet has scanned, from the wallet RPC's `get_height`. pub height: u64, - /// Blocks that daemon is syncing towards; `0` when it reported none. - pub target_height: u64, + /// The daemon's chain tip, or `None` when it could not be asked. + pub tip: Option, } +/// How far behind the daemon tip a wallet may be and still count as caught up. +/// +/// The tip moves every ~2 minutes and the daemon answer and the wallet scan are +/// two reads, not one snapshot, so a strict `>=` gate flaps on a wallet that is +/// one block behind for a few seconds. Two blocks is a deliberate slack, small +/// enough that a real lag (a first sync, a stalled scan) still reads not-ready. +const READY_SLACK_BLOCKS: u64 = 2; + 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. + /// The readiness predicate, stated once: + /// + /// `height > 0 && (tip == 0 || height + READY_SLACK_BLOCKS >= tip)` + /// + /// A daemon that did not answer is not ready. A wallet with no scanned + /// height is not ready. Fail closed on every branch. pub fn ready(&self) -> bool { - self.synchronized - && self.height > 0 - && (self.target_height == 0 || self.height >= self.target_height) + self.height > 0 + && self.tip.is_some_and(|tip| { + tip == 0 || self.height.saturating_add(READY_SLACK_BLOCKS) >= tip + }) } } @@ -563,6 +582,7 @@ impl Wallet { no_spend, timeout_local: RPC_TIMEOUT, timeout_chain: CHAIN_RPC_TIMEOUT, + daemon_probe: None, } } @@ -745,6 +765,13 @@ impl Wallet { self } + /// Where to read the chain tip for the readiness comparison. `None` keeps + /// readiness fail-closed: a wallet with no comparable daemon is never ready. + pub fn with_daemon_probe(mut self, addr: Option) -> Self { + self.daemon_probe = addr; + self + } + pub fn no_spend(&self) -> bool { self.no_spend } @@ -858,27 +885,34 @@ impl Wallet { .map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into())) } - /// The real readiness predicate: the daemon has reached the chain tip and - /// the wallet has scanned up to it. `synchronized` must be explicitly true — - /// a missing field is not-ready, never a silent pass. + /// The real readiness predicate: the wallet's own scanned height is at the + /// chain tip (within the deliberate [`READY_SLACK_BLOCKS`]). The wallet RPC + /// is asked `get_height` — never `get_info`, which it does not implement — + /// and the tip comes from the daemon client. 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". + /// One readiness pair: the wallet's scanned height from the wallet RPC's + /// `get_height`, and the daemon's tip from the daemon client. The status + /// line and the spend gate ask the same question, so they ask it once. + /// + /// A wallet RPC that cannot answer (no wallet file open, restarting, + /// transport) is `height: 0` + no tip: unknown is not ready, and "no wallet + /// open" is a state, not an error to paint on a status row. A missing + /// daemon answer leaves `tip: None`, which is also not ready. pub async fn chain_info(&self) -> Result { - let v = self.chain_rpc("get_info", serde_json::json!({})).await?; - 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), - }) + let height = match self.chain_rpc("get_height", serde_json::json!({})).await { + Ok(v) => v.get("height").and_then(|h| h.as_u64()).unwrap_or(0), + Err(_) => 0, + }; + let tip = match self.daemon_probe.as_deref() { + // One small probe: a slow or dead daemon is "unknown", not a hung + // status poll. The management budget is the short one. + Some(addr) => daemon_get_height(addr, self.timeout_local).await.ok(), + None => None, + }; + Ok(ChainInfo { height, tip }) } /// 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 2e797ac..b22b2b0 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -816,17 +816,25 @@ impl ChildConfig { 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. + /// Where the readiness comparison may ask the chain daemon itself for its + /// tip. `monero-wallet-rpc` has no `get_info`, so the wallet's own + /// `get_height` is only half the answer. + /// + /// - A daemon this box owns (`monerod`/Cuprate it spawned) binds loopback: + /// asking it is a plain local socket. + /// - A clearnet remote daemon the user typed is already the wallet child's + /// dial target, so one `get_height` is the same exposure — not a new path. + /// - A `.onion` daemon must **not** be dialled directly: without the SOCKS + /// child that would resolve the name on clearnet DNS and leak. It stays + /// fail-closed (height-only, not ready) until the SOCKS path exists. pub fn daemon_probe_addr(&self) -> Option { - match self.source { + match &self.source { ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => { Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")) } + ChainSource::Remote { host, port } if !crate::wallet::is_onion_host(host) => { + Some(format!("{}:{port}", host.trim())) + } ChainSource::None | ChainSource::Remote { .. } => None, } } @@ -2420,11 +2428,12 @@ mod tests { ); } - /// 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. + /// A daemon this box owns, or a clearnet daemon the user typed, may be asked + /// for its tip: both are already dialled by the wallet child. A `.onion` + /// daemon must not be dialled without the SOCKS child, and receive-only has + /// nothing to ask at all. #[test] - fn only_a_loopback_source_gets_a_daemon_probe_address() { + fn only_a_reachable_daemon_gets_a_probe_address() { let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"); for source in [ ChainSource::Local { @@ -2444,16 +2453,25 @@ mod tests { }; assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str())); } + // A clearnet remote daemon is the user's explicit choice and the wallet + // child already dials it: one `get_height` is the same exposure. + let cfg = ChildConfig { + source: ChainSource::Remote { + host: "203.0.113.7".to_string(), + port: 18081, + }, + ..ChildConfig::default() + }; + assert_eq!( + cfg.daemon_probe_addr().as_deref(), + Some("203.0.113.7:18081") + ); 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, diff --git a/tests/wallet.rs b/tests/wallet.rs index 92723b0..380d49f 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -150,12 +150,14 @@ async fn mock_create_address_and_transfer() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(move |method| match method { - // A spend is only attempted on a synced wallet. - "get_info" => synced_info(), + // A spend is only attempted on a synced wallet: the wallet's own + // scanned height plus the daemon tip. + "get_height" => wallet_height(3210000), _ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)), }), )); - let w = recording_wallet(port); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); let created = w.create_address().await.expect("create_address"); assert!(created.starts_with('8')); @@ -441,10 +443,59 @@ fn rpc_result(result: &str) -> String { format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#) } -/// What a fully synced wallet answers to `get_info`: the daemon has reached the -/// tip and the wallet has scanned it. This is the honest readiness signal. -fn synced_info() -> String { - rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#) +/// What the wallet RPC answers to `get_height`: the wallet's own scanned height. +/// This is the honest wallet-side signal — `get_info` does not exist there. +fn wallet_height(height: u64) -> String { + rpc_result(&format!(r#"{{"height":{height}}}"#)) +} + +/// A chain-daemon stub. `GET /get_height` answers the tip; `/json_rpc get_info` +/// answers height and target. A daemon is unauthenticated, so no Digest flow. +async fn serve_daemon( + listener: TcpListener, + height: u64, + target: u64, + log: Option>>>, +) { + while let Ok((mut sock, _)) = listener.accept().await { + let mut buf = vec![0u8; 8192]; + let Ok(n) = sock.read(&mut buf).await else { + return; + }; + if n == 0 { + continue; + } + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + if let Some(log) = &log { + log.lock().expect("daemon log").push(req.clone()); + } + let body = if req.starts_with("GET /get_height") { + format!(r#"{{"height":{height}}}"#) + } else if req.contains("get_info") { + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target}}}}}"# + ) + } else { + "{}".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; + } +} + +/// Start a daemon stub on an ephemeral loopback port; returns `host:port`. +async fn mock_daemon(height: u64, target: u64) -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + tokio::spawn(serve_daemon(listener, height, target, None)); + addr } fn recording_wallet(port: u16) -> Wallet { @@ -532,11 +583,12 @@ async fn view_only_wallet_maps_transfer_failure_to_clear_message() { Arc::clone(&log), Arc::new(|method| match method { "query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), - "get_info" => synced_info(), + "get_height" => wallet_height(3210000), _ => rpc_error(-18, "No transaction created"), }), )); - let w = recording_wallet(port); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); assert!(!w.no_spend()); let err = w .transfer( @@ -564,11 +616,13 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() { Arc::new(Mutex::new(Vec::new())), Arc::new(|method| match method { "query_key" => rpc_result(r#"{"key":"00112233"}"#), - "get_info" => synced_info(), + "get_height" => wallet_height(3210000), _ => rpc_error(-18, "No transaction created"), }), )); + let daemon = mock_daemon(3210000, 3210000).await; let err = recording_wallet(port) + .with_daemon_probe(Some(daemon)) .transfer( "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", 1, @@ -1217,7 +1271,8 @@ async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { serve_rpc_conns( listener, Arc::new(|method: &str| match method { - "get_info" => synced_info(), + "get_height" => wallet_height(3210000), + "get_transfers" => rpc_result(r#"{"in":[],"pending":[]}"#), _ => rpc_result( r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, ), @@ -1242,15 +1297,14 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() { listener, Arc::clone(&log), Arc::new(|method| match method { - "get_info" => { - rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#) - } + "get_height" => wallet_height(1200000), _ => rpc_result(r#"{"tx_hash":"abc123"}"#), }), )); - let w = recording_wallet(port); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); assert!( - !w.chain_ready().await.expect("get_info"), + !w.chain_ready().await.expect("get_height"), "must not be ready" ); assert!( @@ -1267,16 +1321,115 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() { ); } -/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready, -/// never a silent pass. Fail closed. +/// `monero-wallet-rpc` has no `get_info` (it answers `-32601 Method not found`). +/// Readiness must never depend on that call: the wallet's own `get_height` is +/// compared with the daemon's tip. #[tokio::test] -async fn missing_or_behind_synchronized_is_not_ready() { - for info in [ - r#"{"height":10}"#, - r#"{"height":100,"target_height":200,"synchronized":true}"#, - r#"{"height":0,"target_height":0,"synchronized":true}"#, - r#"{"synchronized":"true"}"#, +async fn readiness_never_asks_the_wallet_rpc_for_get_info() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "get_height" => wallet_height(3210000), + "get_info" => rpc_error(-32601, "Method not found"), + _ => rpc_result("{}"), + }), + )); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + assert!( + w.chain_ready().await.expect("get_height"), + "a wallet at the daemon tip is ready without get_info" + ); + let seen = log.lock().expect("log").clone(); + assert!( + seen.iter().any(|r| r.contains("\"method\":\"get_height\"")), + "the wallet's own scanned height must be asked: {seen:?}" + ); + assert!( + !seen.iter().any(|r| r.contains("\"method\":\"get_info\"")), + "get_info is not a wallet-RPC method and must not be probed: {seen:?}" + ); +} + +/// Readiness against a daemon tip: equal is ready, the tip moves every ~2 min so +/// a two-block gap is ready, a real lag is not. +#[tokio::test] +async fn a_wallet_within_the_slack_of_the_daemon_tip_is_ready() { + for (wallet, tip, ready) in [ + (3210000u64, 3210000u64, true), + (3209998, 3210000, true), + (3209997, 3210000, false), ] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_recording( + listener, + Arc::new(Mutex::new(Vec::new())), + Arc::new(move |_| wallet_height(wallet)), + )); + let daemon = mock_daemon(tip, tip).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + assert_eq!( + w.chain_ready().await.expect("get_height"), + ready, + "wallet {wallet} / tip {tip}" + ); + } +} + +/// A daemon that does not answer leaves the tip unknown. Unknown is *not* +/// caught up — fail closed, never a silent pass. +#[tokio::test] +async fn an_unreachable_daemon_is_not_ready() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_recording( + listener, + Arc::new(Mutex::new(Vec::new())), + Arc::new(|_| wallet_height(3210000)), + )); + // Bind, read the port, drop: nothing is listening there. + let dead = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let dead_addr = dead.local_addr().unwrap().to_string(); + drop(dead); + let w = recording_wallet(port).with_daemon_probe(Some(dead_addr)); + assert!( + !w.chain_ready().await.expect("get_height"), + "an unanswered daemon must not read as ready" + ); +} + +/// A wallet RPC with no wallet file open answers `-13 No wallet file` to +/// `get_height`. That is a state, not an error banner: not ready, no Err. +#[tokio::test] +async fn an_rpc_with_no_wallet_open_is_not_ready_and_not_an_error() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_recording( + listener, + Arc::new(Mutex::new(Vec::new())), + Arc::new(|_| rpc_error(-13, "No wallet file")), + )); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + assert!( + !w.chain_ready() + .await + .expect("no wallet file is a state, not an error"), + "a wallet with no file open is not ready" + ); + assert!(!w.can_verify_receipts().await); +} + +/// An answered `get_height` with no height (or height 0) is unknown, and a +/// daemon tip of 0 is a daemon that has not indexed anything: not ready. +#[tokio::test] +async fn a_missing_or_zero_wallet_height_is_not_ready() { + for info in [r#"{}"#, r#"{"height":0}"#, r#"{"height":"10"}"#] { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); let canned = rpc_result(info); @@ -1285,9 +1438,10 @@ async fn missing_or_behind_synchronized_is_not_ready() { Arc::new(Mutex::new(Vec::new())), Arc::new(move |_| canned.clone()), )); - let w = recording_wallet(port); + let daemon = mock_daemon(0, 0).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); assert!( - !w.chain_ready().await.expect("get_info"), + !w.chain_ready().await.expect("get_height"), "{info} must not read as ready" ); } @@ -1301,12 +1455,13 @@ async fn synced_wallet_is_ready_and_spends() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(|method| match method { - "get_info" => synced_info(), + "get_height" => wallet_height(3210000), _ => rpc_result(r#"{"tx_hash":"abc123"}"#), }), )); - let w = recording_wallet(port); - assert!(w.chain_ready().await.expect("get_info")); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + assert!(w.chain_ready().await.expect("get_height")); assert!(w.can_verify_receipts().await); assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123"); } @@ -1325,12 +1480,13 @@ async fn spend_ready_needs_an_unlocked_balance() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(move |method| match method { - "get_info" => synced_info(), + "get_height" => wallet_height(3210000), "get_balance" => balance.clone(), - _ => rpc_result(r#"{}"#), + _ => rpc_result("{}"), }), )); - let w = recording_wallet(port); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); assert_eq!(w.spend_ready().await.expect("spend_ready"), ready); } } @@ -1369,16 +1525,15 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(move |method| match method { - "get_info" => { - rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#) - } + "get_height" => wallet_height(1200000), "get_transfers" => rpc_result(&format!( r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"# )), - _ => rpc_result(r#"{}"#), + _ => rpc_result("{}"), }), )); - let w = recording_wallet(port); + let daemon = mock_daemon(3210000, 3210000).await; + let w = recording_wallet(port).with_daemon_probe(Some(daemon)); // The same shape node.rs::ingest_receipt runs. if w.can_verify_receipts().await @@ -1393,8 +1548,10 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() { ); } -/// Chain-dependent calls get a longer budget than local wallet-management calls, -/// and the budget is the backend's to set — not a hard-coded 5s. +/// Chain-dependent calls (`get_transfers`, `transfer`) get a longer budget than +/// local wallet-management calls, and the budget is the backend's to set — not a +/// hard-coded 5s. Readiness is no longer a chain wait: it is one local +/// `get_height` plus one bounded daemon probe. #[tokio::test] async fn chain_calls_get_a_longer_budget_than_local_calls() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -1412,12 +1569,11 @@ async fn chain_calls_get_a_longer_budget_than_local_calls() { err.to_ascii_lowercase().contains("timed out"), "the local call must hit the short budget: {err}" ); - assert!( - w.chain_ready() - .await - .expect("get_info within the chain budget"), - "chain calls must outlast daemon latency" - ); + let rows = w + .get_transfers() + .await + .expect("get_transfers within the chain budget"); + assert!(rows.is_empty(), "{rows:?}"); } // ---------------------------------------------------------------------------