wallet: typed chain-daemon client for the Cuprate parity gaps
Some checks failed
ci / test (pull_request) Failing after 1m30s
ci / sdk (pull_request) Successful in 1m16s

The chain probe was a hand-rolled brace-scanner in `src/node.rs`. Cuprate
breaks three of its assumptions, all measured in Spike A
(`docs/cuprate-launch-spike.md` §Parity gaps, evidence in that spike's
`rpc-evidence/`):

1. **A height above the tip is a bare HTTP 500 with an empty body.** monerod
   answers a JSON-RPC error object instead (`TOO_BIG_HEIGHT`, code -2). The
   client now parses the HTTP status once, de-chunks `Transfer-Encoding:
   chunked` bodies (axum/hyper; the old brace-scan is not a parse once a blob
   spans more than one chunk), and maps both spellings of the height failure to
   one typed `WalletError::DaemonHeightOutOfRange`. `get_height` and `get_block`
   are height-addressed: their 5xx is the height error. `get_info` is not: its
   5xx is `WalletError::DaemonHttpStatus`.

2. **`get_info` metrics are not measurements.** Cuprate reports zero peers while
   it downloads blocks, its restricted server answers a placeholder
   `database_size` (exactly 5 GiB) and an empty `version`, and `free_space` is
   `u64::MAX` on both servers. `DaemonInfo` carries height and target only, so
   there is no field for a placeholder to reach the UI. The wallet screen's sync
   line is now built from block-height movement between two probes: "connected
   to P2P" needs the height to have moved, "no new blocks" is what a stalled
   daemon gets, and Cuprate's at-rest `synchronized = true` with
   `target_height = 0` reads as unknown instead of `1160/0`.

3. **`get_height` is a URI endpoint**: `{"method":"get_height"}` over
   `/json_rpc` is rejected with 422, so the client uses `GET /get_height`, which
   both daemons answer. The wallet-child routing rule is pinned too: it dials
   the daemon's *unrestricted* listener (monerod's `--rpc-bind-port`, and
   whatever port an in-process Cuprate binds for `[rpc.unrestricted]`), never the
   restricted one — a restricted listener answers, so a mix-up shows up as a
   wrong number rather than as an error.

Scope deviations, stated plainly:

- the card names `src/wallet.rs` + the TUI bindings. The probe itself lived in
  `src/node.rs`; it now delegates (net -100 lines there), and the routing
  constant/test live in `src/wallet_child.rs`. Tests are in `tests/wallet.rs`,
  `tests/tui_spec.rs` and `src/wallet_child.rs`'s test module.
- `daemon_get_block()` is **not called by anything yet**: it is the entry point
  the wallet's own block scan (Phase 2) needs, and the out-of-range answer it has
  to survive is item 1, so the mapping lives with the client.
- the card's item 3 gives the unrestricted port as 18089 and the restricted one
  as 28089. In monerod's numbering 18089 *is* the restricted port; the app's
  local source already dials the unrestricted 18081. The rule is what is pinned,
  not those numbers.
- `docs/cuprate-launch-spike.md` merged to `main` after this branch's base
  commit, so it is not in this tree and its Recommendation bullets are not
  updated here.
- based on `feat/wallet-create-import` (the wallet line, unmerged): the daemon
  client has no home on `main`. Retarget to `main` when that line lands.

Proof: `cargo test --locked` 306 passed / 0 failed, `cargo clippy --locked
--all-targets -- -D warnings` clean, `rustfmt --edition 2024 --check` adds no
hunk to any file (the inherited hunks in `src/node.rs`/`src/tui.rs`/
`tests/tui_spec.rs` are unchanged in count or region).
This commit is contained in:
hermes-rust-dev 2026-09-17 00:24:09 -04:00 • committed by agent
commit e6b5024ad3
No known key found for this signature in database
7 changed files with 850 additions and 1334 deletions

View file

@ -8,7 +8,6 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use futures::StreamExt;
use futures::io::{AsyncRead, AsyncWrite};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tor_cell::relaycell::msg::Connected;
use tor_hsservice::{RunningOnionService, handle_rend_requests};
use zeroize::Zeroizing;
@ -724,6 +723,11 @@ impl Node {
/// Ask the configured daemon how far along the chain is, bounded by
/// `budget`. Never fabricates a height: a daemon we cannot ask — or must not
/// dial — comes back unreachable with the reason.
///
/// The call itself lives in [`crate::wallet::daemon_get_info`], where the
/// Cuprate parity gaps are handled (a bare HTTP 500 on a height-addressed
/// call, `get_height` as a URI endpoint, and the placeholder `get_info`
/// metrics this struct has no field for).
pub async fn wallet_chain_sync(&self, budget: Duration) -> DaemonSync {
let Some(addr) = WalletChild::daemon_address(&self.wallet_chain_source()) else {
return DaemonSync::unknown("receive-only: no daemon");
@ -733,14 +737,14 @@ impl Node {
"remote .onion daemon needs a local SOCKS listener (not wired yet)",
);
}
match daemon_get_info(&addr, budget).await {
Ok((height, target_height)) => DaemonSync {
match wallet::daemon_get_info(&addr, budget).await {
Ok(info) => DaemonSync {
reachable: true,
height,
target_height,
height: info.height,
target_height: info.target_height,
note: None,
},
Err(e) => DaemonSync::unknown(e),
Err(e) => DaemonSync::unknown(e.to_string()),
}
}
@ -1559,61 +1563,6 @@ fn is_onion_daemon(addr: &str) -> bool {
.ends_with(".onion")
}
/// `get_info` from the daemon, over plain HTTP/1.1. Hand-rolled for the same
/// reason the wallet client is: no HTTP crate in this tree, and this request
/// carries nothing secret (the wallet RPC stays a separate, authenticated
/// loopback connection). This dials the *chain* address only.
const DAEMON_PROBE_MAX_BYTES: usize = 64 * 1024;
async fn daemon_get_info(addr: &str, budget: Duration) -> Result<(u64, u64), String> {
let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#;
let request = format!(
"POST /json_rpc HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let mut stream = tokio::time::timeout(budget, tokio::net::TcpStream::connect(addr))
.await
.map_err(|_| format!("{addr}: connect timed out"))?
.map_err(|e| format!("{addr}: {e}"))?;
let raw = tokio::time::timeout(budget, async {
stream.write_all(request.as_bytes()).await?;
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
loop {
let n = stream.read(&mut tmp).await?;
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
if buf.len() >= DAEMON_PROBE_MAX_BYTES {
break;
}
}
Ok::<Vec<u8>, std::io::Error>(buf)
})
.await
.map_err(|_| format!("{addr}: read timed out"))?
.map_err(|e| format!("{addr}: {e}"))?;
let text = String::from_utf8_lossy(&raw);
let json = text
.find('{')
.and_then(|start| text.rfind('}').map(|end| &text[start..=end]))
.ok_or_else(|| format!("{addr}: no JSON body"))?;
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| format!("{addr}: {e}"))?;
let result = value
.get("result")
.ok_or_else(|| format!("{addr}: no get_info result"))?;
match (
result.get("height").and_then(|h| h.as_u64()),
result.get("target_height").and_then(|h| h.as_u64()),
) {
(Some(height), Some(target_height)) => Ok((height, target_height)),
_ => Err(format!("{addr}: get_info has no chain height")),
}
}
/// Available 1K blocks from `df -Pk` output. Separate from the process call so
/// the parse is testable without a filesystem.
fn parse_df_avail_kb(stdout: &str) -> Option<u64> {
@ -1680,40 +1629,6 @@ mod tests {
assert_eq!(parse_df_avail_kb("garbage"), None);
}
/// A real socket, a real HTTP response, a real parse: the sync line is only
/// as honest as this.
#[tokio::test]
async fn daemon_get_info_reads_height_and_target() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 2048];
let _ = sock.read(&mut buf).await;
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"height":3210000,"target_height":3210000}}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let _ = sock.write_all(resp.as_bytes()).await;
});
let (height, target) = daemon_get_info(&addr, Duration::from_secs(5)).await.unwrap();
assert_eq!((height, target), (3_210_000, 3_210_000));
server.await.unwrap();
}
/// A dead daemon is an error, never a fabricated height.
#[tokio::test]
async fn daemon_get_info_reports_a_dead_daemon() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
drop(listener);
let err = daemon_get_info(&addr, Duration::from_secs(5))
.await
.expect_err("a closed port must not answer");
assert!(err.contains(&addr), "{err}");
}
// Official mainnet standard address (Monero docs), the same constant the
// integration tests use. `insert_payment` checks the checksum.
const ADDR: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";