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";

View file

@ -1132,6 +1132,10 @@ struct App {
who_open: bool,
chat_scroll: u16,
job_rx: Option<mpsc::Receiver<String>>,
/// The height the wallet screen saw last time it probed the daemon, so
/// connectivity can be read from movement instead of from `get_info`'s peer
/// counts (Cuprate reports zero peers while it is downloading blocks).
chain_last_height: std::cell::Cell<Option<u64>>,
}
enum Screen {
@ -1517,13 +1521,72 @@ pub fn wallet_view(
}
}
/// The sync line: what the daemon's own numbers say, and nothing else.
///
/// Connectivity is inferred from **block-height movement** between two probes.
/// It is never inferred from `get_info` peer counts (Cuprate answers
/// `outgoing_connections_count = 0` while it is downloading blocks) and never
/// from `database_size`/`free_space`/`version` (its restricted server answers a
/// 5 GiB placeholder, `u64::MAX` and an empty string).
///
/// `previous_height` is the height of the previous probe on this screen, or
/// `None` when there is no earlier sample to compare with.
pub fn sync_line(sync: &DaemonSync, previous_height: Option<u64>) -> String {
if !sync.reachable {
return format!(
"sync: unknown — {}",
sync.note.as_deref().unwrap_or("no daemon")
);
}
if sync.target_height == 0 {
// No target is not "caught up": Cuprate says `synchronized = true` with
// `target_height = 0` while it has no peers to sync from. Showing
// `1160/0` would dress that up as progress.
return format!(
"sync: unknown — daemon reports no chain target (height {})",
sync.height
);
}
if sync.height >= sync.target_height {
return format!("sync: synced — height {}", sync.height);
}
match previous_height {
Some(previous) if previous < sync.height => format!(
"sync: connected to P2P — syncing {}/{}",
sync.height, sync.target_height
),
Some(_) => format!(
"sync: no new blocks — {}/{} (daemon answering, no progress)",
sync.height, sync.target_height
),
None => format!("sync: syncing — {}/{}", sync.height, sync.target_height),
}
}
/// Pure builder for the chain block: every honest-status rule lives here.
///
/// The no-history form: callers that have no earlier probe to compare with (the
/// frame tests, the first draw) get the same lines they always did.
pub fn chain_view(
source: &ChainSource,
child: WalletChildState,
sync: &DaemonSync,
free_gb: Option<u64>,
readiness: WalletReadiness,
) -> ChainView {
chain_view_with_progress(source, child, sync, free_gb, readiness, None)
}
/// [`chain_view`] with the previous probe's height, which is what the live
/// screen passes: it is the only input that can tell "syncing" apart from
/// "connected but stalled".
pub fn chain_view_with_progress(
source: &ChainSource,
child: WalletChildState,
sync: &DaemonSync,
free_gb: Option<u64>,
readiness: WalletReadiness,
previous_height: Option<u64>,
) -> ChainView {
let source_line = match source {
ChainSource::None => "chain: receive-only — no daemon, no chain traffic".to_string(),
@ -1543,18 +1606,7 @@ pub fn chain_view(
WalletChildState::Running => "daemon: running (child owned by this app)",
}
.to_string();
let sync_line = if sync.reachable {
if sync.synced() {
format!("sync: synced — height {}", sync.height)
} else {
format!("sync: syncing — {}/{}", sync.height, sync.target_height)
}
} else {
format!(
"sync: unknown — {}",
sync.note.as_deref().unwrap_or("no daemon")
)
};
let sync_text = sync_line(sync, previous_height);
let storage_line = match (source, free_gb) {
(ChainSource::Local { .. }, Some(gb)) => format!(
"storage: {gb} GB free here — pruned mainnet wants ~50-60 GB, a full node ~200 GB"
@ -1568,7 +1620,7 @@ pub fn chain_view(
ChainView {
source_line: truncate_chars(&source_line, WALLET_LINE_MAX),
child_line: truncate_chars(&child_line, WALLET_LINE_MAX),
sync_line: truncate_chars(&sync_line, WALLET_LINE_MAX),
sync_line: truncate_chars(&sync_text, WALLET_LINE_MAX),
storage_line: truncate_chars(&storage_line, WALLET_LINE_MAX),
status_line: readiness.line().to_string(),
ready: readiness.ready(),
@ -1637,6 +1689,7 @@ impl App {
who_open: false,
chat_scroll: 0,
job_rx: None,
chain_last_height: std::cell::Cell::new(None),
})
}
@ -2199,12 +2252,21 @@ impl App {
let sync = self
.rt
.block_on(self.node.wallet_chain_sync(CHAIN_SYNC_BUDGET));
let chain = chain_view(
// The only thing that can distinguish "connected and syncing" from
// "answering but stalled" is whether the height moved since last draw.
let previous_height = self.chain_last_height.get();
self.chain_last_height.set(if sync.reachable {
Some(sync.height)
} else {
None
});
let chain = chain_view_with_progress(
&source,
child,
&sync,
self.node.wallet_chain_free_gb(),
readiness,
previous_height,
);
let receive_addr = self
.rt

View file

@ -1074,3 +1074,339 @@ fn json_amount(v: &serde_json::Value) -> String {
_ => String::new(),
}
}
// ---------------------------------------------------------------------------
// Chain daemon client (the chain side of the RPC layer)
// ---------------------------------------------------------------------------
//
// This is *not* the wallet child: that one is a loopback HTTP Digest RPC. This
// one dials the daemon the wallet child scans from, and that is the connection
// Cuprate changes shape on (`docs/cuprate-launch-spike.md` §Parity gaps, all
// three verified by running it):
//
// * a height above the tip is a **bare HTTP 500 with a zero-byte body**, where
// monerod answers a JSON-RPC error object (`TOO_BIG_HEIGHT`);
// * `get_info` reports zero peers even while blocks are arriving, and its
// restricted server answers a placeholder 5 GiB `database_size`, an empty
// `version`, and `free_space = u64::MAX`;
// * `get_height` is a URI endpoint — `{"method":"get_height"}` over `/json_rpc`
// is rejected with 422.
//
// Nothing in this client parses a peer count, a database size, a free-space
// figure or a version string. There is no field for them to land in, so a UI
// wired to this client cannot show a placeholder as a measurement.
/// `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` in monero's
/// `src/rpc/core_rpc_server_error_codes.h`. Cuprate answers the same request
/// with a bare HTTP 500 instead, which is why both spellings map to
/// [`WalletError::DaemonHeightOutOfRange`].
const TOO_BIG_HEIGHT_CODE: i64 = -2;
/// Typed failures of the chain-daemon calls. The wallet-child path above keeps
/// its plain string errors; this side distinguishes a *height* failure from
/// every other one because that is the answer Cuprate mangles.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WalletError {
/// The requested height is above the daemon's tip. Cuprate: bare HTTP 500,
/// empty body. monerod: HTTP 200, error code `-2`.
DaemonHeightOutOfRange,
/// A non-2xx status that is not the height case above.
DaemonHttpStatus(u16),
/// A JSON-RPC error object we do not special-case.
DaemonRpc {
/// The `error.code` the daemon sent.
code: i64,
/// The `error.message` the daemon sent.
message: String,
},
/// A 2xx answer with no usable body. Carries the address and the reason.
DaemonNoBody(String),
/// The daemon could not be reached, or the answer could not be read.
DaemonTransport(String),
}
impl WalletError {
/// Is this the "height above tip" failure? A caller that just asked for a
/// block at an unverified height may retry lower; every other error is a
/// different problem.
pub fn is_height_out_of_range(&self) -> bool {
matches!(self, Self::DaemonHeightOutOfRange)
}
}
impl std::fmt::Display for WalletError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DaemonHeightOutOfRange => {
f.write_str("daemon: height is above its chain tip (not synced that far yet)")
}
Self::DaemonHttpStatus(code) => write!(f, "daemon: HTTP {code}"),
Self::DaemonRpc { code, message } => write!(f, "daemon rpc error {code}: {message}"),
Self::DaemonNoBody(msg) | Self::DaemonTransport(msg) => f.write_str(msg),
}
}
}
impl std::error::Error for WalletError {}
/// What the chain view is allowed to know about a daemon: how far it is and how
/// far it is going. Deliberately nothing else — see the section comment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DaemonInfo {
/// Blocks the daemon has.
pub height: u64,
/// Blocks it is syncing towards. `0` means it reported none, which is not
/// the same as "caught up".
pub target_height: u64,
}
/// Cap on a daemon answer, in bytes. A `get_block` blob is the large case.
pub const DAEMON_MAX_BYTES: usize = 8 * 1024 * 1024;
/// `get_info` as the chain view needs it: height and target, nothing else.
pub async fn daemon_get_info(
addr: &str,
budget: Duration,
) -> std::result::Result<DaemonInfo, WalletError> {
let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#;
let request = json_rpc_request(addr, "/json_rpc", body);
let (status, raw) = daemon_http(addr, &request, budget).await?;
daemon_ok_status(status)?;
let json = daemon_json(&raw, addr)?;
let result = json
.get("result")
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_info has no result")))?;
let height = result
.get("height")
.and_then(serde_json::Value::as_u64)
.ok_or_else(|| {
WalletError::DaemonNoBody(format!("{addr}: get_info has no chain height"))
})?;
let target_height = result
.get("target_height")
.and_then(serde_json::Value::as_u64)
.unwrap_or(0);
Ok(DaemonInfo {
height,
target_height,
})
}
/// The daemon's tip, over the `get_height` URI endpoint.
///
/// Cuprate rejects `{"method":"get_height"}` over `/json_rpc` with 422, and the
/// URI endpoint is what monerod has always answered — one spelling works on
/// both, so this is the one to use.
pub async fn daemon_get_height(
addr: &str,
budget: Duration,
) -> std::result::Result<u64, WalletError> {
let request = uri_request(addr, "GET", "/get_height");
let (status, raw) = daemon_http(addr, &request, budget).await?;
if is_server_error(status) {
return Err(WalletError::DaemonHeightOutOfRange);
}
daemon_ok_status(status)?;
let json = daemon_json(&raw, addr)?;
// Both daemons answer a top-level `height` here; tolerate a jsonrpc
// envelope too rather than betting on the shape.
json.get("height")
.or_else(|| json.get("result").and_then(|r| r.get("height")))
.and_then(serde_json::Value::as_u64)
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_height has no height")))
}
/// One block by height, as raw bytes (the hex `blob` field, decoded).
///
/// Not called yet: this is the entry point the wallet's own refresh loop needs
/// once it scans blocks itself instead of leaving that to `monero-wallet-rpc`.
/// It exists now because the out-of-range answer is the Cuprate behaviour such
/// a loop has to survive, and the mapping belongs with the rest of the client.
pub async fn daemon_get_block(
addr: &str,
height: u64,
budget: Duration,
) -> std::result::Result<Vec<u8>, WalletError> {
let body = format!(
r#"{{"jsonrpc":"2.0","id":"0","method":"get_block","params":{{"height":{height}}}}}"#
);
let request = json_rpc_request(addr, "/json_rpc", &body);
let (status, raw) = daemon_http(addr, &request, budget).await?;
if is_server_error(status) {
return Err(WalletError::DaemonHeightOutOfRange);
}
daemon_ok_status(status)?;
let json = daemon_json(&raw, addr)?;
let blob = json
.get("result")
.and_then(|r| r.get("blob"))
.and_then(|b| b.as_str())
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block has no blob")))?;
hex_decode(blob)
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block blob is not hex")))
}
/// A bare 5xx is how Cuprate says "no such height" — it carries no body to
/// decode, so the *call* decides what it means: height-addressed calls (the two
/// above) read it as [`WalletError::DaemonHeightOutOfRange`], everything else
/// reads it as a status error.
fn is_server_error(status: u16) -> bool {
(500..600).contains(&status)
}
fn daemon_ok_status(status: u16) -> std::result::Result<(), WalletError> {
if (200..300).contains(&status) {
return Ok(());
}
Err(WalletError::DaemonHttpStatus(status))
}
fn json_rpc_request(addr: &str, path: &str, body: &str) -> String {
format!(
"POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn uri_request(addr: &str, method: &str, path: &str) -> String {
format!(
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)
}
/// One request, one answer: status code plus body. `Connection: close` and read
/// to EOF, so `Content-Length` never has to be trusted.
async fn daemon_http(
addr: &str,
request: &str,
budget: Duration,
) -> std::result::Result<(u16, Vec<u8>), WalletError> {
let mut stream = tokio::time::timeout(budget, TcpStream::connect(addr))
.await
.map_err(|_| WalletError::DaemonTransport(format!("{addr}: connect timed out")))?
.map_err(|e| WalletError::DaemonTransport(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_MAX_BYTES {
break;
}
}
Ok::<Vec<u8>, std::io::Error>(buf)
})
.await
.map_err(|_| WalletError::DaemonTransport(format!("{addr}: read timed out")))?
.map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?;
split_http(&raw)
.ok_or_else(|| WalletError::DaemonTransport(format!("{addr}: not an HTTP response")))
}
/// Status code and body from a raw HTTP/1.1 response.
///
/// Cuprate is axum/hyper: the body arrives `Transfer-Encoding: chunked`, so
/// scanning for the outermost braces is not a parse once a blob spans more than
/// one chunk. De-chunk here, once, for every call.
fn split_http(raw: &[u8]) -> Option<(u16, Vec<u8>)> {
let (head, body) = match find(raw, b"\r\n\r\n") {
Some(at) => (&raw[..at], &raw[at + 4..]),
None => {
let at = find(raw, b"\n\n")?;
(&raw[..at], &raw[at + 2..])
}
};
let head = std::str::from_utf8(head).ok()?;
let mut lines = head.lines();
let status = lines.next()?.split_whitespace().nth(1)?.parse().ok()?;
let chunked = lines.any(|line| {
line.split_once(':').is_some_and(|(k, v)| {
k.eq_ignore_ascii_case("transfer-encoding")
&& v.to_ascii_lowercase().contains("chunked")
})
});
let body = if chunked {
dechunk(body)?
} else {
body.to_vec()
};
Some((status, body))
}
fn dechunk(body: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::new();
let mut at = 0;
loop {
let line_end = find(&body[at..], b"\r\n")?;
let size_line = std::str::from_utf8(&body[at..at + line_end]).ok()?;
// `size[;chunk-extension]`
let size = usize::from_str_radix(size_line.split(';').next()?.trim(), 16).ok()?;
at += line_end + 2;
if size == 0 {
return Some(out);
}
if at + size > body.len() {
return None;
}
out.extend_from_slice(&body[at..at + size]);
at += size;
if body[at..].starts_with(b"\r\n") {
at += 2;
} else if body[at..].starts_with(b"\n") {
at += 1;
}
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
fn daemon_json(body: &[u8], addr: &str) -> std::result::Result<serde_json::Value, WalletError> {
let text = std::str::from_utf8(body)
.map_err(|_| WalletError::DaemonNoBody(format!("{addr}: body is not UTF-8")))?;
let json: serde_json::Value = serde_json::from_str(text.trim())
.map_err(|e| WalletError::DaemonNoBody(format!("{addr}: {e}")))?;
if let Some(err) = json.get("error") {
let code = err
.get("code")
.and_then(serde_json::Value::as_i64)
.unwrap_or(0);
if code == TOO_BIG_HEIGHT_CODE {
return Err(WalletError::DaemonHeightOutOfRange);
}
let message = err
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("rpc error")
.to_string();
return Err(WalletError::DaemonRpc { code, message });
}
Ok(json)
}
fn hex_decode(s: &str) -> Option<Vec<u8>> {
let bytes = s.as_bytes();
if !bytes.len().is_multiple_of(2) {
return None;
}
let mut out = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks(2) {
out.push((hex_val(pair[0])? << 4) | hex_val(pair[1])?);
}
Some(out)
}
fn hex_val(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
b'A'..=b'F' => Some(c - b'A' + 10),
_ => None,
}
}

View file

@ -25,10 +25,24 @@ use zeroize::Zeroizing;
use crate::store::Store;
use crate::wallet::{self, ChainSource, Wallet};
/// `monerod` RPC port for a local chain source. Unrestricted RPC default; the
/// wallet child is the only thing that dials it.
/// `monerod` RPC port for a local chain source. This is the *unrestricted*
/// server (`--rpc-bind-port`); the wallet child is the only thing that dials it.
pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081;
/// `monerod`'s *restricted* RPC port (`--rpc-restricted-bind-port`). Nothing in
/// this app ever dials it: a restricted daemon answers, so pointing the wallet
/// child there fails silently and dishonestly — Cuprate's restricted server
/// returns a placeholder `database_size` (exactly 5 GiB), an empty `version`,
/// and `free_space = u64::MAX` on both servers
/// (`docs/cuprate-launch-spike.md` §Parity gaps). The unrestricted listener is
/// the one with real numbers.
///
/// This is monerod's numbering. An in-process Cuprate chooses its own ports in
/// its config; whichever port that is, the rule is the same and the wallet
/// child must be pointed at the *unrestricted* listener, never the restricted
/// one (`docs/WALLET.md`, "Chain daemon").
pub const MONEROD_RESTRICTED_RPC_PORT: u16 = 18089;
/// Name of the `monero-wallet-rpc` binary when the caller does not point at one.
pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc";
@ -587,6 +601,48 @@ mod tests {
assert!(err.contains("SOCKS"), "got {err}");
}
/// The routing rule the Cuprate spike forced: the wallet child dials the
/// *unrestricted* daemon RPC. A restricted listener answers too, so getting
/// this wrong shows up as a wrong number rather than as an error.
#[test]
fn the_wallet_child_dials_the_unrestricted_daemon_rpc() {
let dir = Path::new("/tmp");
let monerod = PathBuf::from("/usr/bin/monerod");
let addr = WalletChild::daemon_address(&local_source(dir, monerod.clone()))
.expect("a local source has an address");
assert_eq!(addr, format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"));
assert_ne!(
DEFAULT_MONEROD_RPC_PORT, MONEROD_RESTRICTED_RPC_PORT,
"the two servers are different ports; confusing them is the bug"
);
// monerod is spawned on the full RPC port, and the restricted listener
// is never asked for.
let argv = WalletChild::monerod_argv(&monerod, &dir.join("data"), DEFAULT_MONEROD_RPC_PORT);
assert!(
argv.windows(2)
.any(|w| w[0] == "--rpc-bind-port" && w[1] == DEFAULT_MONEROD_RPC_PORT.to_string()),
"{argv:?}"
);
let restricted = MONEROD_RESTRICTED_RPC_PORT.to_string();
assert!(!argv.iter().any(|a| a.contains(&restricted)), "{argv:?}");
// ...and the wallet child is handed that same address.
let rpc = WalletChild::wallet_rpc_argv(
Path::new("/usr/bin/monero-wallet-rpc"),
18_083,
"user:pass",
&dir.join("wallet"),
Some(&addr),
);
assert!(
rpc.windows(2)
.any(|w| w[0] == "--daemon-address" && w[1] == addr),
"{rpc:?}"
);
assert!(!rpc.iter().any(|a| a.contains(&restricted)), "{rpc:?}");
}
#[test]
fn daemon_address_matches_each_chain_source() {
assert_eq!(WalletChild::daemon_address(&ChainSource::None), None);