wallet: land the in-process Cuprate chain source on main
`ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P,
consensus and RandomX run inside the OnionWire process instead of as a spawned
`monerod`. The wallet layer does not move — the daemon binds the same loopback
unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already
returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment
frames and the receipt-verification path are untouched.
- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the
`cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is
disabled (`default-features = false`): its arti-client 0.44 cannot unify with
this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in
the process. `Cargo.lock` gains the graph; a default build's
`cargo tree --locked -e normal -i cuprated` still says "did not match any
packages", and only `arti-client v0.46.0` is in the lock.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
(testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
off), launches it on a runtime it owns, and owns the node. `launch` is
synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its
blocking thread, UniFFI calls it from an async context) and a runtime cannot be
started from inside a runtime, so the launch runs on a thread of its own and
the node + its runtime come back over a channel. Dropping the value asks the
node to shut down and `shutdown_background`s the runtime, which is the only
exit that cannot panic when the value is dropped inside another runtime.
The type exists in every build (feature off: `launch` fails with the feature
name), so the chain-source type, its stored record and its copy do not fork on
a cargo feature.
- src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon
client the wallet line carried (typed `WalletError`, de-chunked HTTP,
`get_height` over the URI endpoint, an above-the-tip height as one typed
error). Cuprate answers those three differently from monerod and the
in-process source is what makes them the *local* case.
- src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the
free-space/ownership question, the honest `chain_copy` line, `kind =
"cuprate"` in the sealed record, and `ChildConfig::validate` for it.
- src/tui.rs: the wallet screen's chain line carries the testnet caveat when the
configured source is the in-process one. It computes the line at draw time, so
`Screen::Wallet`'s shape (which tests construct) does not change.
- docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the
feature flag and how to enable it, where the (fjall) chain store lives, the
**measured** +11.8 MiB delta, the pre-production/testnet caveat, and the
in-repo aarch64-linux-android proof with exit codes.
Scope deviations, stated plainly:
- `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's
allowed list; the card's own deliverable describes the module's behaviour.
- `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a
`pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the
root CI `sdk` job runs on every PR. One variant plus two match arms land here
so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card
owns the rest — feature passthrough, the config field's semantics, the label
and its tests, and the Android check.
- `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched:
main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7
work, and `docs/WALLET.md` says so rather than describing a picker that does
not exist).
Proof (all on this tree):
- Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345
passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked
--all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0.
- Feature on: `cargo test --locked --features cuprate-daemon --target
x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with
`--features cuprate-daemon` exit 0. The two extra tests are the real thing:
`wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down`
and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client`
— the latter launches the node, drives `get_info` / `get_height` / `get_block`
through the typed client, checks the above-the-tip 500 maps to
`DaemonHeightOutOfRange`, checks the chain store is under the chain datadir,
and checks the listener dies with the node.
- aarch64: `cargo check --locked --release --target aarch64-linux-android
--features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0
(`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link
args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26,
built by NDK r28c`.
- Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and
37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure
`docs/WALLET.md` now quotes.
This commit is contained in:
parent
8ba1cf4c6c
commit
ffea4bf9df
12 changed files with 2804 additions and 50 deletions
352
src/wallet.rs
352
src/wallet.rs
|
|
@ -35,6 +35,17 @@ pub enum ChainSource {
|
|||
/// Data directory for the local daemon.
|
||||
datadir: PathBuf,
|
||||
},
|
||||
/// A chain daemon **inside this process** (Cuprate), with its chain in
|
||||
/// `datadir`. Nothing is spawned; the wallet child still dials loopback
|
||||
/// RPC, so this is a [`ChainSource::Local`] with a different owner.
|
||||
///
|
||||
/// Two consequences the UI has to state: the chain is on this device, and
|
||||
/// the in-process daemon is **testnet-only** in this build (Cuprate is
|
||||
/// pre-production and its mainnet RPC parity is unvalidated).
|
||||
InProcessCuprate {
|
||||
/// Data directory for the daemon's chain database.
|
||||
datadir: PathBuf,
|
||||
},
|
||||
/// A daemon address the user supplied. Trust follows the address.
|
||||
Remote {
|
||||
/// Daemon host. May be loopback, `.onion`, or a clearnet host the user
|
||||
|
|
@ -61,6 +72,7 @@ impl ChainSource {
|
|||
match self {
|
||||
ChainSource::None => "receive-only".to_string(),
|
||||
ChainSource::Local { .. } => "local node".to_string(),
|
||||
ChainSource::InProcessCuprate { .. } => "in-process node".to_string(),
|
||||
ChainSource::Remote { host, .. } if is_onion_host(host) => {
|
||||
"remote onion daemon".to_string()
|
||||
}
|
||||
|
|
@ -1103,3 +1115,343 @@ 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 measured 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` metrics are not measurements — a placeholder 5 GiB
|
||||
// `database_size`, an empty `version`, `free_space = u64::MAX`, and zero peers
|
||||
// even while blocks are arriving;
|
||||
// * `get_height` is a **URI endpoint**: `{"method":"get_height"}` over
|
||||
// `/json_rpc` is rejected with 422.
|
||||
//
|
||||
// Nothing here 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 caller cannot show
|
||||
// a placeholder as a measurement.
|
||||
//
|
||||
// The in-process chain source ([`ChainSource::InProcessCuprate`]) is what makes
|
||||
// these the *local* case rather than a remote corner: it is the daemon this app
|
||||
// starts itself.
|
||||
|
||||
/// `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 by the app yet: the wallet's block scan still lives in
|
||||
/// `monero-wallet-rpc`. It exists because the out-of-range answer above is the
|
||||
/// Cuprate behaviour such a scan 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,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue