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.
This commit is contained in:
parent
dddf74f274
commit
3aafaefae8
6 changed files with 476 additions and 159 deletions
|
|
@ -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
|
**Tor hides the transport, not the host.** The daemon operator still sees the
|
||||||
wallet's addresses during sync.
|
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
|
`chain_ready()` compares the wallet's **own scanned height** with the **chain
|
||||||
**`synchronized == true`** with `height > 0` and `height >= target_height`. A
|
tip**. Both halves must answer:
|
||||||
missing field is *not ready* — fail closed.
|
|
||||||
|
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
|
Until then, **receipt verification stays `verified=0`**. An unsynced wallet
|
||||||
cannot see the chain. That is an honest limit, not a UI bug.
|
cannot see the chain. That is an honest limit, not a UI bug.
|
||||||
|
|
||||||
Loopback management calls (`get_address`, `query_key`, create/import) get 5s.
|
Loopback management calls (`get_address`, `query_key`, create/import) get 5s.
|
||||||
Calls that wait on the chain (`get_info`, `get_transfers`, `transfer`) get 60s
|
Calls that wait on the chain (`get_transfers`, `transfer`) get 60s
|
||||||
(`CHAIN_RPC_TIMEOUT`).
|
(`CHAIN_RPC_TIMEOUT`). Readiness is not a chain wait: it is one local
|
||||||
|
`get_height` plus one bounded daemon probe.
|
||||||
|
|
||||||
## Env vars (migration path)
|
## 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()`,
|
UniFFI: `set_chain_source(ChainConfig)` / `chain_source()`,
|
||||||
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read:
|
`start_wallet_child()`, `stop_wallet_child()`, `wallet_status()` (cached read:
|
||||||
no dial, for first paint) and `wallet_child_refresh()` (a live probe of the
|
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
|
same record — it dials the loopback wallet RPC and asks the configured daemon
|
||||||
`get_info` when that RPC does not answer, so poll it on the order of seconds).
|
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
|
Pass absolute paths for `wallet_rpc_bin` / `arti_bin` (`nativeLibraryDir`); the
|
||||||
core never resolves a binary the caller named explicitly.
|
core never resolves a binary the caller named explicitly.
|
||||||
|
|
||||||
|
|
|
||||||
182
src/node.rs
182
src/node.rs
|
|
@ -1065,7 +1065,12 @@ impl Node {
|
||||||
return self.wallet_child_status();
|
return self.wallet_child_status();
|
||||||
}
|
}
|
||||||
let cfg = self.wallet_child_config();
|
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() {
|
if !w.configured() {
|
||||||
return self.wallet_child_status();
|
return self.wallet_child_status();
|
||||||
}
|
}
|
||||||
|
|
@ -1090,7 +1095,7 @@ impl Node {
|
||||||
}
|
}
|
||||||
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
let synced = progress.as_ref().is_some_and(wallet::ChainInfo::ready);
|
||||||
let (height, target_height) = match progress {
|
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
|
// 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
|
// not (a refused connection is the common one), the daemon this box
|
||||||
// owns can still say — and a daemon that does not answer leaves
|
// 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.
|
/// Pay selected friend via wallet RPC, then signed receipt.
|
||||||
pub async fn tip(&self, friend_pk: &[u8], atomic: &str, memo: &str) -> Result<(), String> {
|
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() {
|
if !w.configured() {
|
||||||
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
return Err(wallet::NOT_CONFIGURED_MSG.into());
|
||||||
}
|
}
|
||||||
|
|
@ -2153,7 +2160,9 @@ impl Node {
|
||||||
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
// Honest prerequisite: an unsynced wallet cannot see the tx, so a
|
||||||
// get_transfers "miss" would be a lie. Until the chain is ready the
|
// 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.
|
// 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;
|
let ready = w.configured() && w.can_verify_receipts().await;
|
||||||
if ready {
|
if ready {
|
||||||
match w.get_transfers().await {
|
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 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
|
/// a digest challenge, then the wallet's own scanned `get_height` for the
|
||||||
/// `tx_hash` for the transfer. The old single-answer mock stopped covering
|
/// readiness gate and `tx_hash` for the transfer. `get_info` is a daemon
|
||||||
/// the path when `Wallet::transfer` started probing the chain tip first —
|
/// method, not a wallet one, so it is never asked. Returns the wallet and
|
||||||
/// it answered `tx_hash` to `get_info` and every tip was refused as unsynced.
|
/// the daemon stub's address (the tip the gate compares against).
|
||||||
async fn mock_wallet() -> Wallet {
|
async fn mock_wallet() -> (Wallet, String) {
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
.await
|
.await
|
||||||
.expect("bind mock wallet");
|
.expect("bind mock wallet");
|
||||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
|
||||||
if req.contains("get_info") {
|
if req.contains("get_height") {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string()
|
||||||
.to_string()
|
|
||||||
} else {
|
} else {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
|
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
let wallet = Wallet::from_url(&format!("http://ow:[email protected]:{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 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
|
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
|
||||||
|
|
@ -3443,11 +3470,9 @@ pub(crate) mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
async fn outbound_tip_appends_the_senders_own_tip_chat_line() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let node = offline_node_with_wallet(
|
let (wallet, daemon) = mock_wallet().await;
|
||||||
&dir.path().join("bob"),
|
let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet);
|
||||||
Arc::new(DialOk),
|
chain_source_at(&node, &daemon);
|
||||||
mock_wallet().await,
|
|
||||||
);
|
|
||||||
let peer = Keys::generate();
|
let peer = Keys::generate();
|
||||||
let addr = xmr_addr();
|
let addr = xmr_addr();
|
||||||
{
|
{
|
||||||
|
|
@ -3548,11 +3573,9 @@ pub(crate) mod tests {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn outbound_tip_records_a_tip_payment_row() {
|
async fn outbound_tip_records_a_tip_payment_row() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
let node = offline_node_with_wallet(
|
let (wallet, daemon) = mock_wallet().await;
|
||||||
&dir.path().join("bob"),
|
let node = offline_node_with_wallet(&dir.path().join("bob"), Arc::new(DialOk), wallet);
|
||||||
Arc::new(DialOk),
|
chain_source_at(&node, &daemon);
|
||||||
mock_wallet().await,
|
|
||||||
);
|
|
||||||
let peer = Keys::generate();
|
let peer = Keys::generate();
|
||||||
let addr = xmr_addr();
|
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
|
/// A loopback wallet RPC that answers the *status* probe: a digest
|
||||||
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
/// challenge, then `get_address` / `get_balance` / `get_height`, with the
|
||||||
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
/// wallet's own scanned height. Returns the wallet and the daemon stub's
|
||||||
/// *transfer* path; this one answers a refresh, which never transfers.
|
/// address — the tip comes from the daemon, never from the wallet RPC.
|
||||||
/// A loopback wallet RPC that answers the *status* probe: a digest
|
/// [`mock_wallet`] above answers the *transfer* path; this one answers a
|
||||||
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
|
/// refresh, which never transfers.
|
||||||
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
|
async fn mock_syncing_wallet(height: u64, target: u64) -> (Wallet, String) {
|
||||||
/// *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")
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
.await
|
.await
|
||||||
.expect("bind mock wallet");
|
.expect("bind mock wallet");
|
||||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||||||
if req.contains("get_info") {
|
if req.contains("get_height") {
|
||||||
format!(
|
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") {
|
} else if req.contains("get_address") {
|
||||||
format!(
|
format!(
|
||||||
|
|
@ -3795,7 +3857,10 @@ pub(crate) mod tests {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
let wallet =
|
||||||
|
Wallet::from_url(&format!("http://ow:[email protected]:{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
|
/// 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;
|
*node.wallet.lock().expect("wallet") = wallet;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [`mock_syncing_wallet`], but `height` is read on every `get_info`,
|
/// Like [`mock_syncing_wallet`], but the wallet's scanned `height` is read on
|
||||||
/// so a later store is a later answer. `synchronized` stays false: the
|
/// every `get_height`, so a later store is a later answer. The daemon stub
|
||||||
/// status line is a syncing chain, not a caught-up one.
|
/// 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(
|
pub(crate) async fn mock_wallet_at(
|
||||||
height: std::sync::Arc<std::sync::atomic::AtomicU64>,
|
height: std::sync::Arc<std::sync::atomic::AtomicU64>,
|
||||||
target: u64,
|
target: u64,
|
||||||
) -> Wallet {
|
) -> (Wallet, String) {
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||||
|
|
@ -3818,11 +3884,9 @@ pub(crate) mod tests {
|
||||||
.expect("bind mock wallet");
|
.expect("bind mock wallet");
|
||||||
let port = listener.local_addr().expect("mock wallet addr").port();
|
let port = listener.local_addr().expect("mock wallet addr").port();
|
||||||
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
|
||||||
if req.contains("get_info") {
|
if req.contains("get_height") {
|
||||||
let h = height.load(Ordering::Relaxed);
|
let h = height.load(Ordering::Relaxed);
|
||||||
format!(
|
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h}}}}}"#)
|
||||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{h},"target_height":{target},"synchronized":false}}}}"#
|
|
||||||
)
|
|
||||||
} else if req.contains("get_address") {
|
} else if req.contains("get_address") {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string()
|
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4test"}}"#.to_string()
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -3830,7 +3894,10 @@ pub(crate) mod tests {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
tokio::spawn(serve_mock_rpc(listener, reply));
|
tokio::spawn(serve_mock_rpc(listener, reply));
|
||||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
|
let wallet =
|
||||||
|
Wallet::from_url(&format!("http://ow:[email protected]:{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
|
/// A loopback daemon that answers `get_info` on the port the child probes
|
||||||
|
|
@ -3868,12 +3935,12 @@ pub(crate) mod tests {
|
||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The status row carries the real chain numbers: a wallet RPC that answers
|
/// The status row carries the real chain numbers: the wallet RPC's own
|
||||||
/// `get_info` fills height and target, and the one-liner shows them. A
|
/// `get_height` is the wallet's scanned height, and the daemon's tip is the
|
||||||
/// daemon that reports no target is not a caught-up chain — `h/0` with no
|
/// target. A daemon that reports no separate target still gives a tip, so
|
||||||
/// invented percentage.
|
/// `h/h` is the honest line — never an invented percentage.
|
||||||
#[tokio::test]
|
#[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 dir = tempfile::tempdir().unwrap();
|
||||||
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
let node = offline_node(&dir.path().join("child"), Arc::new(NoDial));
|
||||||
let log = dir.path().join("argv.log");
|
let log = dir.path().join("argv.log");
|
||||||
|
|
@ -3890,14 +3957,16 @@ pub(crate) mod tests {
|
||||||
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&log));
|
||||||
node.start_wallet_child().expect("start");
|
node.start_wallet_child().expect("start");
|
||||||
// The child is a fake process; the wallet the node actually talks to is
|
// The child is a fake process; the wallet the node actually talks to is
|
||||||
// the mock RPC, which is where the numbers come from.
|
// the mock RPC, and the tip comes from the daemon stub.
|
||||||
*node.wallet.lock().unwrap() = mock_syncing_wallet(4549, 0).await;
|
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;
|
let status = node.wallet_child_refresh().await;
|
||||||
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
assert_eq!(status.state, WalletChildState::Ready, "{status:?}");
|
||||||
assert_eq!(status.height, 4549, "{status:?}");
|
assert_eq!(status.height, 4549, "{status:?}");
|
||||||
assert_eq!(status.target_height, 0, "{status:?}");
|
assert_eq!(status.target_height, 4549, "{status:?}");
|
||||||
assert!(status.line().contains("sync 4549/0"), "{}", status.line());
|
assert!(status.line().contains("sync 4549/4549"), "{}", status.line());
|
||||||
assert!(!status.line().contains('%'), "{}", status.line());
|
assert!(!status.line().contains('%'), "{}", status.line());
|
||||||
|
|
||||||
node.stop_wallet_child().expect("stop");
|
node.stop_wallet_child().expect("stop");
|
||||||
|
|
@ -5014,9 +5083,8 @@ pub(crate) mod tests {
|
||||||
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
|
||||||
addr = xmr_addr()
|
addr = xmr_addr()
|
||||||
)
|
)
|
||||||
} else if req.contains("get_info") {
|
} else if req.contains("get_height") {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
|
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100}}"#.to_string()
|
||||||
.to_string()
|
|
||||||
} else {
|
} else {
|
||||||
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0","unlocked_balance":"0"}}"#
|
||||||
.to_string()
|
.to_string()
|
||||||
|
|
@ -5275,7 +5343,9 @@ pub(crate) mod tests {
|
||||||
);
|
);
|
||||||
|
|
||||||
// The read after the restart takes the success path: the same mock
|
// 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;
|
let status = node.wallet_child_refresh().await;
|
||||||
assert!(status.wallet_open, "{status:?}");
|
assert!(status.wallet_open, "{status:?}");
|
||||||
assert!(!status.needs_passphrase, "{status:?}");
|
assert!(!status.needs_passphrase, "{status:?}");
|
||||||
|
|
|
||||||
16
src/tui.rs
16
src/tui.rs
|
|
@ -7694,8 +7694,22 @@ mod wallet_setup_config_tests {
|
||||||
app.node.start_wallet_child().expect("start");
|
app.node.start_wallet_child().expect("start");
|
||||||
|
|
||||||
let height = Arc::new(AtomicU64::new(1111));
|
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);
|
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");
|
app.handle_key(key(KeyCode::F(7))).expect("F7");
|
||||||
|
|
||||||
wait_for_sync_line(&mut app, &rt, "sync 1111/9000");
|
wait_for_sync_line(&mut app, &rt, "sync 1111/9000");
|
||||||
|
|
|
||||||
100
src/wallet.rs
100
src/wallet.rs
|
|
@ -488,34 +488,53 @@ pub struct Wallet {
|
||||||
/// Budget for loopback management calls (`get_address`, `query_key`,
|
/// Budget for loopback management calls (`get_address`, `query_key`,
|
||||||
/// create/import). The wallet child is on the same box, so this stays short.
|
/// create/import). The wallet child is on the same box, so this stays short.
|
||||||
timeout_local: Duration,
|
timeout_local: Duration,
|
||||||
/// Budget for calls that wait on the daemon (`get_info`, `get_transfers`,
|
/// Budget for calls that wait on the daemon (`get_transfers`, `transfer`).
|
||||||
/// `transfer`). A first sync or a remote daemon legitimately outlasts the
|
/// A first sync or a remote daemon legitimately outlasts the local budget,
|
||||||
/// local budget, and treating that as "down" is what left receipts
|
/// and treating that as "down" is what left receipts
|
||||||
/// permanently unverified.
|
/// permanently unverified.
|
||||||
timeout_chain: Duration,
|
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<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `get_info` fields one wallet-RPC probe carries: the readiness verdict and
|
/// What the readiness pair is: the wallet's own scanned height and the chain
|
||||||
/// the numbers a status line shows. `0` height/target means the wallet RPC
|
/// tip the daemon reports. Neither number comes from the wallet RPC's
|
||||||
/// answered without a number — unknown, never "caught up", and never a percent.
|
/// `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)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct ChainInfo {
|
pub struct ChainInfo {
|
||||||
/// The wallet RPC said `synchronized: true`. A missing field is `false`.
|
/// Blocks the wallet has scanned, from the wallet RPC's `get_height`.
|
||||||
pub synchronized: bool,
|
|
||||||
/// Blocks the wallet's daemon has, as the wallet RPC reports them.
|
|
||||||
pub height: u64,
|
pub height: u64,
|
||||||
/// Blocks that daemon is syncing towards; `0` when it reported none.
|
/// The daemon's chain tip, or `None` when it could not be asked.
|
||||||
pub target_height: u64,
|
pub tip: Option<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 {
|
impl ChainInfo {
|
||||||
/// The readiness predicate: the daemon reached the tip and the wallet
|
/// The readiness predicate, stated once:
|
||||||
/// scanned up to it. `synchronized` must be explicitly true, and a chain
|
///
|
||||||
/// with no height is not ready.
|
/// `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 {
|
pub fn ready(&self) -> bool {
|
||||||
self.synchronized
|
self.height > 0
|
||||||
&& self.height > 0
|
&& self.tip.is_some_and(|tip| {
|
||||||
&& (self.target_height == 0 || self.height >= self.target_height)
|
tip == 0 || self.height.saturating_add(READY_SLACK_BLOCKS) >= tip
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -563,6 +582,7 @@ impl Wallet {
|
||||||
no_spend,
|
no_spend,
|
||||||
timeout_local: RPC_TIMEOUT,
|
timeout_local: RPC_TIMEOUT,
|
||||||
timeout_chain: CHAIN_RPC_TIMEOUT,
|
timeout_chain: CHAIN_RPC_TIMEOUT,
|
||||||
|
daemon_probe: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -745,6 +765,13 @@ impl Wallet {
|
||||||
self
|
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<String>) -> Self {
|
||||||
|
self.daemon_probe = addr;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub fn no_spend(&self) -> bool {
|
pub fn no_spend(&self) -> bool {
|
||||||
self.no_spend
|
self.no_spend
|
||||||
}
|
}
|
||||||
|
|
@ -858,27 +885,34 @@ impl Wallet {
|
||||||
.map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into()))
|
.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 real readiness predicate: the wallet's own scanned height is at the
|
||||||
/// the wallet has scanned up to it. `synchronized` must be explicitly true —
|
/// chain tip (within the deliberate [`READY_SLACK_BLOCKS`]). The wallet RPC
|
||||||
/// a missing field is not-ready, never a silent pass.
|
/// 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<bool> {
|
pub async fn chain_ready(&self) -> Result<bool> {
|
||||||
Ok(self.chain_info().await?.ready())
|
Ok(self.chain_info().await?.ready())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One `get_info` round trip, carrying both the readiness fields and the
|
/// One readiness pair: the wallet's scanned height from the wallet RPC's
|
||||||
/// numbers a status line shows — the status line and the spend gate ask the
|
/// `get_height`, and the daemon's tip from the daemon client. The status
|
||||||
/// same question, so they ask it once. `0` height/target means the wallet
|
/// line and the spend gate ask the same question, so they ask it once.
|
||||||
/// RPC answered without a number: unknown, never "caught up".
|
///
|
||||||
|
/// 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<ChainInfo> {
|
pub async fn chain_info(&self) -> Result<ChainInfo> {
|
||||||
let v = self.chain_rpc("get_info", serde_json::json!({})).await?;
|
let height = match self.chain_rpc("get_height", serde_json::json!({})).await {
|
||||||
Ok(ChainInfo {
|
Ok(v) => v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
|
||||||
synchronized: v
|
Err(_) => 0,
|
||||||
.get("synchronized")
|
};
|
||||||
.and_then(|b| b.as_bool())
|
let tip = match self.daemon_probe.as_deref() {
|
||||||
.unwrap_or(false),
|
// One small probe: a slow or dead daemon is "unknown", not a hung
|
||||||
height: v.get("height").and_then(|h| h.as_u64()).unwrap_or(0),
|
// status poll. The management budget is the short one.
|
||||||
target_height: v.get("target_height").and_then(|h| h.as_u64()).unwrap_or(0),
|
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
|
/// May this wallet attempt a spend? Fail closed: any readiness doubt is a
|
||||||
|
|
|
||||||
|
|
@ -816,17 +816,25 @@ impl ChildConfig {
|
||||||
self.source.label()
|
self.source.label()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where a status refresh may ask the chain daemon itself for
|
/// Where the readiness comparison may ask the chain daemon itself for its
|
||||||
/// height/target, when the wallet RPC is not answering. Only a daemon this
|
/// tip. `monero-wallet-rpc` has no `get_info`, so the wallet's own
|
||||||
/// box owns: a `monerod`/Cuprate the child spawned binds loopback, and
|
/// `get_height` is only half the answer.
|
||||||
/// 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 daemon this box owns (`monerod`/Cuprate it spawned) binds loopback:
|
||||||
/// a second path to it.
|
/// 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<String> {
|
pub fn daemon_probe_addr(&self) -> Option<String> {
|
||||||
match self.source {
|
match &self.source {
|
||||||
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
|
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
|
||||||
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
|
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,
|
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
|
/// A daemon this box owns, or a clearnet daemon the user typed, may be asked
|
||||||
/// wallet child's to dial — a status refresh must not open a second path to
|
/// for its tip: both are already dialled by the wallet child. A `.onion`
|
||||||
/// it, and receive-only has nothing to ask at all.
|
/// daemon must not be dialled without the SOCKS child, and receive-only has
|
||||||
|
/// nothing to ask at all.
|
||||||
#[test]
|
#[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}");
|
let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
||||||
for source in [
|
for source in [
|
||||||
ChainSource::Local {
|
ChainSource::Local {
|
||||||
|
|
@ -2444,16 +2453,25 @@ mod tests {
|
||||||
};
|
};
|
||||||
assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str()));
|
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 [
|
for source in [
|
||||||
ChainSource::None,
|
ChainSource::None,
|
||||||
ChainSource::Remote {
|
ChainSource::Remote {
|
||||||
host: "peer.onion".to_string(),
|
host: "peer.onion".to_string(),
|
||||||
port: 18081,
|
port: 18081,
|
||||||
},
|
},
|
||||||
ChainSource::Remote {
|
|
||||||
host: "203.0.113.7".to_string(),
|
|
||||||
port: 18081,
|
|
||||||
},
|
|
||||||
] {
|
] {
|
||||||
let cfg = ChildConfig {
|
let cfg = ChildConfig {
|
||||||
source,
|
source,
|
||||||
|
|
|
||||||
246
tests/wallet.rs
246
tests/wallet.rs
|
|
@ -150,12 +150,14 @@ async fn mock_create_address_and_transfer() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |method| match method {
|
Arc::new(move |method| match method {
|
||||||
// A spend is only attempted on a synced wallet.
|
// A spend is only attempted on a synced wallet: the wallet's own
|
||||||
"get_info" => synced_info(),
|
// scanned height plus the daemon tip.
|
||||||
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_result(&format!(r#"{{"address":"{addr_hex}","tx_hash":"abc123"}}"#)),
|
_ => 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");
|
let created = w.create_address().await.expect("create_address");
|
||||||
assert!(created.starts_with('8'));
|
assert!(created.starts_with('8'));
|
||||||
|
|
||||||
|
|
@ -441,10 +443,59 @@ fn rpc_result(result: &str) -> String {
|
||||||
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a fully synced wallet answers to `get_info`: the daemon has reached the
|
/// What the wallet RPC answers to `get_height`: the wallet's own scanned height.
|
||||||
/// tip and the wallet has scanned it. This is the honest readiness signal.
|
/// This is the honest wallet-side signal — `get_info` does not exist there.
|
||||||
fn synced_info() -> String {
|
fn wallet_height(height: u64) -> String {
|
||||||
rpc_result(r#"{"height":3210000,"target_height":3210000,"synchronized":true}"#)
|
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<Arc<Mutex<Vec<String>>>>,
|
||||||
|
) {
|
||||||
|
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 {
|
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::clone(&log),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
"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"),
|
_ => 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());
|
assert!(!w.no_spend());
|
||||||
let err = w
|
let err = w
|
||||||
.transfer(
|
.transfer(
|
||||||
|
|
@ -564,11 +616,13 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_error(-18, "No transaction created"),
|
_ => rpc_error(-18, "No transaction created"),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
let err = recording_wallet(port)
|
let err = recording_wallet(port)
|
||||||
|
.with_daemon_probe(Some(daemon))
|
||||||
.transfer(
|
.transfer(
|
||||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||||
1,
|
1,
|
||||||
|
|
@ -1217,7 +1271,8 @@ async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {
|
||||||
serve_rpc_conns(
|
serve_rpc_conns(
|
||||||
listener,
|
listener,
|
||||||
Arc::new(|method: &str| match method {
|
Arc::new(|method: &str| match method {
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
|
"get_transfers" => rpc_result(r#"{"in":[],"pending":[]}"#),
|
||||||
_ => rpc_result(
|
_ => rpc_result(
|
||||||
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#,
|
||||||
),
|
),
|
||||||
|
|
@ -1242,15 +1297,14 @@ async fn unsynced_wallet_is_not_ready_and_refuses_to_spend() {
|
||||||
listener,
|
listener,
|
||||||
Arc::clone(&log),
|
Arc::clone(&log),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"get_info" => {
|
"get_height" => wallet_height(1200000),
|
||||||
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
|
||||||
}
|
|
||||||
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
_ => 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!(
|
assert!(
|
||||||
!w.chain_ready().await.expect("get_info"),
|
!w.chain_ready().await.expect("get_height"),
|
||||||
"must not be ready"
|
"must not be ready"
|
||||||
);
|
);
|
||||||
assert!(
|
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,
|
/// `monero-wallet-rpc` has no `get_info` (it answers `-32601 Method not found`).
|
||||||
/// never a silent pass. Fail closed.
|
/// Readiness must never depend on that call: the wallet's own `get_height` is
|
||||||
|
/// compared with the daemon's tip.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn missing_or_behind_synchronized_is_not_ready() {
|
async fn readiness_never_asks_the_wallet_rpc_for_get_info() {
|
||||||
for info in [
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
r#"{"height":10}"#,
|
let port = listener.local_addr().unwrap().port();
|
||||||
r#"{"height":100,"target_height":200,"synchronized":true}"#,
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||||||
r#"{"height":0,"target_height":0,"synchronized":true}"#,
|
tokio::spawn(serve_recording(
|
||||||
r#"{"synchronized":"true"}"#,
|
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 listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
let port = listener.local_addr().unwrap().port();
|
let port = listener.local_addr().unwrap().port();
|
||||||
let canned = rpc_result(info);
|
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(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |_| canned.clone()),
|
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!(
|
assert!(
|
||||||
!w.chain_ready().await.expect("get_info"),
|
!w.chain_ready().await.expect("get_height"),
|
||||||
"{info} must not read as ready"
|
"{info} must not read as ready"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -1301,12 +1455,13 @@ async fn synced_wallet_is_ready_and_spends() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(|method| match method {
|
Arc::new(|method| match method {
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
_ => rpc_result(r#"{"tx_hash":"abc123"}"#),
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
let w = recording_wallet(port);
|
let daemon = mock_daemon(3210000, 3210000).await;
|
||||||
assert!(w.chain_ready().await.expect("get_info"));
|
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!(w.can_verify_receipts().await);
|
||||||
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
|
assert_eq!(w.transfer(SPEND_ADDR, 1).await.expect("transfer"), "abc123");
|
||||||
}
|
}
|
||||||
|
|
@ -1325,12 +1480,13 @@ async fn spend_ready_needs_an_unlocked_balance() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |method| match method {
|
Arc::new(move |method| match method {
|
||||||
"get_info" => synced_info(),
|
"get_height" => wallet_height(3210000),
|
||||||
"get_balance" => balance.clone(),
|
"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);
|
assert_eq!(w.spend_ready().await.expect("spend_ready"), ready);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1369,16 +1525,15 @@ async fn unsynced_wallet_leaves_a_matching_receipt_unverified() {
|
||||||
listener,
|
listener,
|
||||||
Arc::new(Mutex::new(Vec::new())),
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
Arc::new(move |method| match method {
|
Arc::new(move |method| match method {
|
||||||
"get_info" => {
|
"get_height" => wallet_height(1200000),
|
||||||
rpc_result(r#"{"height":1200000,"target_height":3210000,"synchronized":false}"#)
|
|
||||||
}
|
|
||||||
"get_transfers" => rpc_result(&format!(
|
"get_transfers" => rpc_result(&format!(
|
||||||
r#"{{"in":[{{"txid":"deadbeef","amount":5,"address":"{addr_owned}"}}],"pending":[]}}"#
|
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.
|
// The same shape node.rs::ingest_receipt runs.
|
||||||
if w.can_verify_receipts().await
|
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,
|
/// Chain-dependent calls (`get_transfers`, `transfer`) get a longer budget than
|
||||||
/// and the budget is the backend's to set — not a hard-coded 5s.
|
/// 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]
|
#[tokio::test]
|
||||||
async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
async fn chain_calls_get_a_longer_budget_than_local_calls() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
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"),
|
err.to_ascii_lowercase().contains("timed out"),
|
||||||
"the local call must hit the short budget: {err}"
|
"the local call must hit the short budget: {err}"
|
||||||
);
|
);
|
||||||
assert!(
|
let rows = w
|
||||||
w.chain_ready()
|
.get_transfers()
|
||||||
.await
|
.await
|
||||||
.expect("get_info within the chain budget"),
|
.expect("get_transfers within the chain budget");
|
||||||
"chain calls must outlast daemon latency"
|
assert!(rows.is_empty(), "{rows:?}");
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue