diff --git a/docs/WALLET.md b/docs/WALLET.md index 99655a2..09cda7d 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -208,42 +208,18 @@ 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 wallet +### Readiness — receipt verification needs a synced daemon -`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. +`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. 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_transfers`, `transfer`) get 60s -(`CHAIN_RPC_TIMEOUT`). Readiness is not a chain wait: it is one local -`get_height` plus one bounded daemon probe. +Calls that wait on the chain (`get_info`, `get_transfers`, `transfer`) get 60s +(`CHAIN_RPC_TIMEOUT`). ## Env vars (migration path) @@ -280,9 +256,8 @@ 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 asks the configured daemon -for its tip (the wallet's `get_height` is the other half), so poll it on the -order of seconds). +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). 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 340ab7a..16efa37 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1065,12 +1065,7 @@ impl Node { return self.wallet_child_status(); } let cfg = self.wallet_child_config(); - // 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()); + let w = self.wallet_snapshot(); if !w.configured() { return self.wallet_child_status(); } @@ -1095,7 +1090,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.tip.unwrap_or(0)), + 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 @@ -1339,9 +1334,7 @@ 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() - .with_daemon_probe(self.wallet_child_config().daemon_probe_addr()); + let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } @@ -2160,9 +2153,7 @@ 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() - .with_daemon_probe(self.wallet_child_config().daemon_probe_addr()); + let w = self.wallet_snapshot(); let ready = w.configured() && w.can_verify_receipts().await; if ready { match w.get_transfers().await { @@ -3426,43 +3417,25 @@ pub(crate) mod tests { } /// A loopback wallet RPC that answers what the tip path actually asks for: - /// 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) { + /// 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 { 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_height") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string() + if req.contains("get_info") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# + .to_string() } else { r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string() } }); tokio::spawn(serve_mock_rpc(listener, reply)); - 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"); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } /// 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 @@ -3470,9 +3443,11 @@ pub(crate) mod tests { #[tokio::test] async fn outbound_tip_appends_the_senders_own_tip_chat_line() { let dir = tempfile::tempdir().unwrap(); - 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 node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(DialOk), + mock_wallet().await, + ); let peer = Keys::generate(); let addr = xmr_addr(); { @@ -3573,9 +3548,11 @@ pub(crate) mod tests { #[tokio::test] async fn outbound_tip_records_a_tip_payment_row() { let dir = tempfile::tempdir().unwrap(); - 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 node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(DialOk), + mock_wallet().await, + ); let peer = Keys::generate(); let addr = xmr_addr(); { @@ -3790,62 +3767,23 @@ 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_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) { + /// 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 { 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_height") { + if req.contains("get_info") { format!( - r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height}}}}}"# + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"# ) } else if req.contains("get_address") { format!( @@ -3857,10 +3795,7 @@ pub(crate) mod tests { } }); tokio::spawn(serve_mock_rpc(listener, reply)); - 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) + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") } /// Point `node`'s wallet client at a mock. The child process stays whatever @@ -3869,14 +3804,13 @@ pub(crate) mod tests { *node.wallet.lock().expect("wallet") = wallet; } - /// 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. + /// 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. pub(crate) async fn mock_wallet_at( height: std::sync::Arc, target: u64, - ) -> (Wallet, String) { + ) -> Wallet { use std::sync::atomic::Ordering; let listener = tokio::net::TcpListener::bind("127.0.0.1:0") @@ -3884,9 +3818,11 @@ 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_height") { + if req.contains("get_info") { let h = height.load(Ordering::Relaxed); - format!(r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h}}}}}"#) + format!( + r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"# + ) } else if req.contains("get_address") { r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string() } else { @@ -3894,10 +3830,7 @@ pub(crate) mod tests { } }); tokio::spawn(serve_mock_rpc(listener, reply)); - 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) + 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 @@ -3935,12 +3868,12 @@ pub(crate) mod tests { Some(()) } - /// 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. + /// 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 the_wallet_height_and_the_daemon_tip_fill_the_chain_progress() { + 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"); @@ -3957,16 +3890,14 @@ 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, 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); + // 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, 4549, "{status:?}"); - assert!(status.line().contains("sync 4549/4549"), "{}", status.line()); + 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"); @@ -5086,8 +5017,9 @@ pub(crate) mod tests { r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#, addr = xmr_addr() ) - } else if req.contains("get_height") { - r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string() + } else if req.contains("get_info") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# + .to_string() } else { r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"# .to_string() @@ -5346,9 +5278,7 @@ pub(crate) mod tests { ); // The read after the restart takes the success path: the same mock - // answers `get_address` / `get_balance` / `get_height`. - let daemon = mock_daemon(100, 100).await; - chain_source_at(&node, &daemon); + // answers `get_address`/`get_balance`/`get_info`. 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 89fc845..ecc3dee 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -7694,22 +7694,8 @@ mod wallet_setup_config_tests { app.node.start_wallet_child().expect("start"); let height = Arc::new(AtomicU64::new(1111)); - let (wallet, daemon) = rt.block_on(mock_wallet_at(Arc::clone(&height), 9000)); + let wallet = 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 966dd62..c5cf04f 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -488,53 +488,34 @@ 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_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_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 /// 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, } -/// 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". +/// 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 { - /// Blocks the wallet has scanned, from the wallet RPC's `get_height`. + /// 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, - /// The daemon's chain tip, or `None` when it could not be asked. - pub tip: Option, + /// Blocks that daemon is syncing towards; `0` when it reported none. + pub target_height: u64, } -/// 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, 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. + /// 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.height > 0 - && self.tip.is_some_and(|tip| { - tip == 0 || self.height.saturating_add(READY_SLACK_BLOCKS) >= tip - }) + self.synchronized + && self.height > 0 + && (self.target_height == 0 || self.height >= self.target_height) } } @@ -582,7 +563,6 @@ impl Wallet { no_spend, timeout_local: RPC_TIMEOUT, timeout_chain: CHAIN_RPC_TIMEOUT, - daemon_probe: None, } } @@ -765,13 +745,6 @@ 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 } @@ -885,34 +858,27 @@ impl Wallet { .map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into())) } - /// 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. + /// 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. pub async fn chain_ready(&self) -> Result { Ok(self.chain_info().await?.ready()) } - /// 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. + /// 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 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 }) + 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), + }) } /// 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 4ee0c98..e8a69d8 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -824,25 +824,17 @@ impl ChildConfig { self.source.label() } - /// 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. + /// 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 { + 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, } } @@ -2617,12 +2609,11 @@ mod tests { ); } - /// 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. + /// 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_reachable_daemon_gets_a_probe_address() { + 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 { @@ -2642,25 +2633,16 @@ 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 380d49f..92723b0 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -150,14 +150,12 @@ 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: the wallet's own - // scanned height plus the daemon tip. - "get_height" => wallet_height(3210000), + // A spend is only attempted on a synced wallet. + "get_info" => synced_info(), _ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)), }), )); - let daemon = mock_daemon(3210000, 3210000).await; - let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + let w = recording_wallet(port); let created = w.create_address().await.expect("create_address"); assert!(created.starts_with('8')); @@ -443,59 +441,10 @@ fn rpc_result(result: &str) -> String { format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#) } -/// 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 +/// 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}"#) } fn recording_wallet(port: u16) -> Wallet { @@ -583,12 +532,11 @@ 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_height" => wallet_height(3210000), + "get_info" => synced_info(), _ => rpc_error(-18, "No transaction created"), }), )); - let daemon = mock_daemon(3210000, 3210000).await; - let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + let w = recording_wallet(port); assert!(!w.no_spend()); let err = w .transfer( @@ -616,13 +564,11 @@ 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_height" => wallet_height(3210000), + "get_info" => synced_info(), _ => 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, @@ -1271,8 +1217,7 @@ async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { serve_rpc_conns( listener, Arc::new(|method: &str| match method { - "get_height" => wallet_height(3210000), - "get_transfers" => rpc_result(r#"{"in":[],"pending":[]}"#), + "get_info" => synced_info(), _ => rpc_result( r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, ), @@ -1297,14 +1242,15 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() { listener, Arc::clone(&log), Arc::new(|method| match method { - "get_height" => wallet_height(1200000), + "get_info" => { + rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#) + } _ => rpc_result(r#"{"tx_hash":"abc123"}"#), }), )); - let daemon = mock_daemon(3210000, 3210000).await; - let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + let w = recording_wallet(port); assert!( - !w.chain_ready().await.expect("get_height"), + !w.chain_ready().await.expect("get_info"), "must not be ready" ); assert!( @@ -1321,115 +1267,16 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() { ); } -/// `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. +/// A missing/absent `synchronized` (or a wallet behind the daemon) is not-ready, +/// never a silent pass. Fail closed. #[tokio::test] -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), +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"}"#, ] { - 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); @@ -1438,10 +1285,9 @@ async fn a_missing_or_zero_wallet_height_is_not_ready() { Arc::new(Mutex::new(Vec::new())), Arc::new(move |_| canned.clone()), )); - let daemon = mock_daemon(0, 0).await; - let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + let w = recording_wallet(port); assert!( - !w.chain_ready().await.expect("get_height"), + !w.chain_ready().await.expect("get_info"), "{info} must not read as ready" ); } @@ -1455,13 +1301,12 @@ async fn synced_wallet_is_ready_and_spends() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(|method| match method { - "get_height" => wallet_height(3210000), + "get_info" => synced_info(), _ => rpc_result(r#"{"tx_hash":"abc123"}"#), }), )); - 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")); + let w = recording_wallet(port); + assert!(w.chain_ready().await.expect("get_info")); assert!(w.can_verify_receipts().await); assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123"); } @@ -1480,13 +1325,12 @@ async fn spend_ready_needs_an_unlocked_balance() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(move |method| match method { - "get_height" => wallet_height(3210000), + "get_info" => synced_info(), "get_balance" => balance.clone(), - _ => rpc_result("{}"), + _ => rpc_result(r#"{}"#), }), )); - let daemon = mock_daemon(3210000, 3210000).await; - let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + let w = recording_wallet(port); assert_eq!(w.spend_ready().await.expect("spend_ready"), ready); } } @@ -1525,15 +1369,16 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() { listener, Arc::new(Mutex::new(Vec::new())), Arc::new(move |method| match method { - "get_height" => wallet_height(1200000), + "get_info" => { + rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#) + } "get_transfers" => rpc_result(&format!( r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"# )), - _ => rpc_result("{}"), + _ => rpc_result(r#"{}"#), }), )); - let daemon = mock_daemon(3210000, 3210000).await; - let w = recording_wallet(port).with_daemon_probe(Some(daemon)); + let w = recording_wallet(port); // The same shape node.rs::ingest_receipt runs. if w.can_verify_receipts().await @@ -1548,10 +1393,8 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() { ); } -/// 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. +/// 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. #[tokio::test] async fn chain_calls_get_a_longer_budget_than_local_calls() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -1569,11 +1412,12 @@ 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}" ); - let rows = w - .get_transfers() - .await - .expect("get_transfers within the chain budget"); - assert!(rows.is_empty(), "{rows:?}"); + assert!( + w.chain_ready() + .await + .expect("get_info within the chain budget"), + "chain calls must outlast daemon latency" + ); } // ---------------------------------------------------------------------------