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

@ -1,12 +1,13 @@
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
use std::sync::{Arc, Mutex};
use std::time::Duration;
use ed25519_dalek::SigningKey;
use onionwire::pay;
use onionwire::wallet::{
self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet,
WalletConfig, WalletStatus, readiness,
self, DaemonInfo, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG,
Wallet, WalletConfig, WalletError, WalletStatus, readiness,
};
use onionwire::{PaymentWrite, Store};
use rand::rngs::OsRng;
@ -1130,3 +1131,232 @@ fn freed_loopback_port() -> u16 {
drop(listener);
port
}
// ---------------------------------------------------------------------------
// Chain daemon client: the Cuprate parity workarounds.
//
// Every payload below is copied from the Spike A evidence
// (`rpc-evidence/` next to `docs/cuprate-launch-spike.md`), not invented:
// Cuprate answers an out-of-range `get_block` with a bare HTTP 500 and a
// zero-byte body, reports `outgoing_connections_count = 0` while it downloads
// blocks, answers `database_size = 5368709120` (exactly 5 GiB) and
// `version = ""` on its restricted server, and `free_space` is `u64::MAX` on
// both servers.
// ---------------------------------------------------------------------------
/// Serve exactly one HTTP response, then drop the listener. Returns the port.
async fn serve_raw(response: String) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 8192];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(response.as_bytes()).await;
});
port
}
/// Same, but records the request line so a test can assert which endpoint and
/// method the client used.
async fn serve_raw_logged(response: String, log: Arc<Mutex<Vec<String>>>) -> u16 {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
log.lock()
.expect("log")
.push(String::from_utf8_lossy(&buf[..n]).to_string());
let _ = sock.write_all(response.as_bytes()).await;
});
port
}
/// `HTTP/1.1 500 Internal Server Error` with an empty body — what Cuprate
/// answers for a height above its tip.
const CUPRATE_OUT_OF_RANGE: &str =
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
/// monerod's answer to the same request: HTTP 200 with an epee/JSON-RPC error
/// object, `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` = -2
/// (`src/rpc/core_rpc_server_error_codes.h`).
fn monerod_too_big_height() -> String {
http_200_body(&rpc_error(
-2,
"Requested block height: 3300000 greater than current top block height: 23758",
))
}
fn daemon_addr(port: u16) -> String {
format!("127.0.0.1:{port}")
}
#[tokio::test]
async fn out_of_range_get_block_is_a_typed_height_error() {
let port = serve_raw(CUPRATE_OUT_OF_RANGE.to_string()).await;
let err = wallet::daemon_get_block(&daemon_addr(port), 3_300_000, Duration::from_secs(5))
.await
.expect_err("an out-of-range height must not decode");
assert_eq!(
err,
WalletError::DaemonHeightOutOfRange,
"a bare 500 on a height-addressed call is the Cuprate spelling of TOO_BIG_HEIGHT"
);
}
#[tokio::test]
async fn out_of_range_get_height_is_the_same_typed_error() {
let port = serve_raw(CUPRATE_OUT_OF_RANGE.to_string()).await;
let err = wallet::daemon_get_height(&daemon_addr(port), Duration::from_secs(5))
.await
.expect_err("a 500 must not decode");
assert_eq!(err, WalletError::DaemonHeightOutOfRange);
}
#[tokio::test]
async fn monerod_too_big_height_object_is_the_same_typed_error() {
let port = serve_raw(monerod_too_big_height()).await;
let err = wallet::daemon_get_block(&daemon_addr(port), 3_300_000, Duration::from_secs(5))
.await
.expect_err("code -2 must map to the height error");
assert_eq!(
err,
WalletError::DaemonHeightOutOfRange,
"parity: monerod's -2 and Cuprate's bare 500 are the same failure"
);
}
#[tokio::test]
async fn a_5xx_that_is_not_height_addressed_is_a_status_error() {
let port = serve_raw(
"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.to_string(),
)
.await;
let err = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5))
.await
.expect_err("503 is not a chain answer");
assert_eq!(err, WalletError::DaemonHttpStatus(503));
}
#[tokio::test]
async fn get_height_uses_the_uri_endpoint_and_cuprates_top_level_shape() {
// Evidence `GET__get_height.json`: no jsonrpc envelope, no `result`.
let body = r#"{"status":"OK","untrusted":false,"hash":"7458280ccc2befbbb074f50b37195ed13039178a05fd8816fc8f8a64fb4df417","height":23758}"#;
let log = Arc::new(Mutex::new(Vec::new()));
let port = serve_raw_logged(http_200_body(body), Arc::clone(&log)).await;
let height = wallet::daemon_get_height(&daemon_addr(port), Duration::from_secs(5))
.await
.expect("the URI endpoint answers");
assert_eq!(height, 23_758);
let req = log
.lock()
.expect("log")
.first()
.cloned()
.unwrap_or_default();
assert!(
req.starts_with("GET /get_height "),
"Cuprate rejects get_height over /json_rpc (422); the URI endpoint is the one that works: {req}"
);
}
#[tokio::test]
async fn get_info_reads_height_and_target_only() {
// Evidence `get_info.endpoint.post_sync.json`, mid-sync: height below
// target, zero peers, `free_space` u64::MAX.
let body = r#"{"jsonrpc":"2.0","id":"0","result":{"status":"OK","height":23758,"target_height":3090939,"synchronized":false,"database_size":54852877,"free_space":18446744073709551615,"incoming_connections_count":0,"outgoing_connections_count":0,"version":"0.1.0-preview-release"}}"#;
let port = serve_raw(http_200_body(body)).await;
let info = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5))
.await
.expect("a syncing daemon answers");
assert_eq!(
info,
DaemonInfo {
height: 23_758,
target_height: 3_090_939
}
);
}
#[tokio::test]
async fn cuprate_placeholder_metrics_never_change_what_the_client_reports() {
// The same height from both servers: the restricted payload carries a 5 GiB
// `database_size`, an empty `version`, zero peers and u64::MAX `free_space`.
// None of it may reach the client, because none of it is a measurement.
let unrestricted = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"target_height":0,"synchronized":true,"database_size":1770926,"free_space":18446744073709551615,"outgoing_connections_count":0,"version":"0.1.0-preview-release"}}"#;
let restricted = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"height_without_bootstrap":0,"target_height":0,"synchronized":true,"restricted":true,"database_size":5368709120,"free_space":18446744073709551615,"outgoing_connections_count":0,"incoming_connections_count":0,"version":""}}"#;
let a = serve_raw(http_200_body(unrestricted)).await;
let b = serve_raw(http_200_body(restricted)).await;
let one = wallet::daemon_get_info(&daemon_addr(a), Duration::from_secs(5))
.await
.unwrap();
let two = wallet::daemon_get_info(&daemon_addr(b), Duration::from_secs(5))
.await
.unwrap();
assert_eq!(
one, two,
"placeholder metrics must not influence the report"
);
assert_eq!(
one,
DaemonInfo {
height: 1160,
target_height: 0
}
);
}
#[tokio::test]
async fn chunked_daemon_answers_are_dechunked() {
// axum/hyper (Cuprate) answers with `Transfer-Encoding: chunked`; the body
// arrives framing-wrapped, so brace-scanning alone is not a parse.
let json = r#"{"jsonrpc":"2.0","id":"0","result":{"height":1160,"target_height":0}}"#;
let (head, tail) = json.split_at(json.len() / 2);
let chunked = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n{head}\r\n{:x}\r\n{tail}\r\n0\r\n\r\n",
head.len(),
tail.len()
);
let port = serve_raw(chunked).await;
let info = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(5))
.await
.expect("a chunked answer must parse");
assert_eq!(info.height, 1160);
}
#[tokio::test]
async fn a_dead_daemon_is_a_transport_error_that_names_the_address() {
let port = freed_loopback_port();
let err = wallet::daemon_get_info(&daemon_addr(port), Duration::from_secs(2))
.await
.expect_err("a closed port must not answer");
assert!(
err.to_string().contains(&daemon_addr(port)),
"the reason must name the address: {err}"
);
}
#[tokio::test]
async fn a_transport_failure_is_not_a_height_error() {
let port = freed_loopback_port();
let err = wallet::daemon_get_block(&daemon_addr(port), 1, Duration::from_secs(2))
.await
.expect_err("a closed port must not answer");
assert!(!err.is_height_out_of_range(), "{err}");
}
#[test]
fn only_the_height_error_reports_itself_as_one() {
assert!(WalletError::DaemonHeightOutOfRange.is_height_out_of_range());
assert!(!WalletError::DaemonHttpStatus(500).is_height_out_of_range());
assert!(
!WalletError::DaemonRpc {
code: -1,
message: "Invalid parameter".into()
}
.is_height_out_of_range()
);
}