wallet: land the in-process Cuprate chain source on main
All checks were successful
ci / test (pull_request) Successful in 5m39s
ci / sdk (pull_request) Successful in 1m22s
android-ci / android (pull_request) Successful in 8m58s
ci / fuzz (pull_request) Successful in 4m45s

`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:
agent 2026-09-18 13:45:59 -04:00
commit ffea4bf9df
No known key found for this signature in database
12 changed files with 2804 additions and 50 deletions

View file

@ -1,6 +1,7 @@
//! Wallet child lifecycle: the app owns `monero-wallet-rpc` — and, when the
//! user chose a local chain source, `monerod` — instead of asking the user to
//! start them and export an env var.
//! user chose a local chain source, `monerod` or an **in-process Cuprate node**
//! ([`crate::cuprate`], behind the `cuprate-daemon` feature) — instead of asking
//! the user to start them and export an env var.
//!
//! Locked shape:
//!
@ -21,6 +22,9 @@
//! * The two Tor clients do not share state: the SOCKS child gets its own
//! `state_dir`/`cache_dir` under the wallet dir.
//! * `--trusted-daemon` is never passed: a remote daemon is untrusted.
//! * The in-process daemon is *not* a child: it is a value owned by this struct,
//! and dropping it shuts the node down. It still binds the same loopback RPC
//! port, so everything downstream of `--daemon-address` is unchanged.
use std::fs;
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
@ -33,11 +37,15 @@ use std::time::{Duration, Instant};
use rand::RngCore;
use zeroize::Zeroizing;
use crate::cuprate::CuprateNode;
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.
///
/// An in-process Cuprate node binds the same port in its config, so the wallet
/// child's `--daemon-address` does not change with the chain source.
pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081;
/// Name of the `monero-wallet-rpc` binary when the caller does not point at one.
@ -94,6 +102,10 @@ pub struct WalletChild {
monerod: Mutex<Option<Child>>,
socks: Mutex<Option<Child>>,
wallet_rpc: Mutex<Option<Child>>,
/// The in-process Cuprate node, when [`ChainSource::InProcessCuprate`] is
/// the source. Owning it is the lifecycle: dropping it shuts the daemon
/// down. Never a child process, so there is no pid to watch or signal.
cuprate: Mutex<Option<CuprateNode>>,
}
impl WalletChild {
@ -123,6 +135,7 @@ impl WalletChild {
monerod: Mutex::new(None),
socks: Mutex::new(None),
wallet_rpc: Mutex::new(None),
cuprate: Mutex::new(None),
})
}
@ -196,8 +209,17 @@ impl WalletChild {
/// Is a tracked child still alive? Polls the process table; an exited child
/// is reaped here so a later `stop` is a no-op.
///
/// The in-process daemon has no process to poll: it counts as running for as
/// long as this struct holds it.
pub fn running(&self) -> bool {
let _ = self.reap_exited();
self.launched_processes() || self.cuprate.lock().map(|g| g.is_some()).unwrap_or(false)
}
/// Is a tracked *child process* alive? The in-process daemon is not one, so
/// it is never reported here.
fn launched_processes(&self) -> bool {
self.monerod.lock().map(|g| g.is_some()).unwrap_or(false)
|| self.socks.lock().map(|g| g.is_some()).unwrap_or(false)
|| self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
@ -298,6 +320,11 @@ impl WalletChild {
ChainSource::Local { .. } => {
"local monerod on this box (loopback): no Tor, no remote operator".into()
}
ChainSource::InProcessCuprate { .. } => format!(
"in-process daemon: chain and consensus run in this app, on this device \
(loopback, no Tor) — {}",
crate::cuprate::TESTNET_ONLY
),
ChainSource::Remote { host, port } if Self::is_onion_host(host) => format!(
"remote {host}:{port} over Tor (SOCKS5 on loopback, never clearnet) — Tor hides \
the transport, not the host: the daemon operator still sees your addresses \
@ -311,16 +338,30 @@ impl WalletChild {
}
/// The `--daemon-address` for each chain source. A local source is the
/// loopback daemon this struct owns; a remote one is exactly what the user
/// typed.
/// loopback daemon this struct owns — spawned `monerod` or in-process
/// Cuprate, the same port; a remote one is exactly what the user typed.
pub fn daemon_address(source: &ChainSource) -> Option<String> {
match source {
ChainSource::None => None,
ChainSource::Local { .. } => Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")),
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
}
ChainSource::Remote { host, port } => Some(format!("{host}:{port}")),
}
}
/// The directory a local chain source stores its chain in: the spawned
/// daemon's and the in-process daemon's are the same idea on disk. `None`
/// for a remote source (their disk, not ours) and for receive-only.
pub fn chain_datadir(source: &ChainSource) -> Option<&Path> {
match source {
ChainSource::Local { datadir, .. } | ChainSource::InProcessCuprate { datadir } => {
Some(datadir)
}
ChainSource::None | ChainSource::Remote { .. } => None,
}
}
/// Bind a loopback port and hand it back. The listener is dropped
/// immediately; the port is only used to keep two instances from colliding.
pub fn pick_port() -> Result<u16> {
@ -412,21 +453,26 @@ impl WalletChild {
}
fn start_children(&self, store: &Store) -> Result<Option<WalletClient>> {
// Local chain source: own monerod first, so the wallet child has a
// daemon to dial.
if let ChainSource::Local {
monerod_bin,
datadir,
} = &self.source
{
ensure_parent(datadir)?;
let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT);
let child = spawn(&argv, "monerod")?;
let mut guard = self
.monerod
.lock()
.map_err(|e| ChildError(format!("monerod lock: {e}")))?;
*guard = Some(child);
// Local chain source: own the daemon first, so the wallet child has
// something to dial. Either a spawned `monerod` or the in-process
// Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so
// `wallet_rpc_argv` below is identical either way.
match &self.source {
ChainSource::Local {
monerod_bin,
datadir,
} => {
ensure_parent(datadir)?;
let argv = Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT);
let child = spawn(&argv, "monerod")?;
let mut guard = self
.monerod
.lock()
.map_err(|e| ChildError(format!("monerod lock: {e}")))?;
*guard = Some(child);
}
ChainSource::InProcessCuprate { datadir } => self.start_in_process_daemon(datadir)?,
ChainSource::None | ChainSource::Remote { .. } => {}
}
// A `.onion` daemon is only reachable through SOCKS. The app bundles the
@ -502,13 +548,48 @@ impl WalletChild {
Ok(Self::socks_proxy_url(port))
}
/// Launch the in-process Cuprate daemon and hold it.
///
/// Blocking is deliberate: [`CuprateNode::launch`] is synchronous (it runs
/// the async launch on a runtime it owns and blocks this thread until the
/// node answers), so this works from the TUI's blocking thread *and* from an
/// SDK async context. It is the same shape as the SOCKS readiness wait
/// above: no daemon, no wallet child.
fn start_in_process_daemon(&self, datadir: &Path) -> Result<()> {
// Feature first: in a build without it, a datadir complaint would be a
// misleading answer to "why is there no daemon".
if !crate::cuprate::available() {
return Err(ChildError(crate::cuprate::NO_FEATURE_MSG.into()));
}
create_dir_700(datadir).map_err(|e| ChildError(format!("chain datadir: {e}")))?;
let node = CuprateNode::launch(datadir, DEFAULT_MONEROD_RPC_PORT)
.map_err(|e| ChildError(format!("in-process daemon: {e}")))?;
let mut guard = self
.cuprate
.lock()
.map_err(|e| ChildError(format!("cuprate lock: {e}")))?;
*guard = Some(node);
Ok(())
}
/// Stop every child. Idempotent, and tolerant of a child that already
/// exited on its own. The wallet child goes first so no wallet RPC can be
/// mid-request against the chain, then the SOCKS listener, then `monerod`.
/// mid-request against the chain, then the SOCKS listener, then the chain
/// daemon — the in-process one is asked to shut down rather than signalled.
pub fn stop(&self) -> Result<()> {
kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?;
kill_slot(&self.socks, "arti proxy")?;
kill_slot(&self.monerod, "monerod")?;
let node = self
.cuprate
.lock()
.map_err(|e| ChildError(format!("cuprate lock: {e}")))?
.take();
if let Some(node) = node {
// Ask before the value goes out of scope: the services drain on the
// runtime this node owns, and dropping alone would cut them off.
node.shutdown();
}
Ok(())
}
@ -629,6 +710,13 @@ impl ChildConfig {
));
}
}
ChainSource::InProcessCuprate { datadir } => {
if datadir.as_os_str().is_empty() {
return Err(ChildError(
"chain data dir required for an in-process daemon".into(),
));
}
}
ChainSource::Remote { host, port } => {
if host.trim().is_empty() {
return Err(ChildError(
@ -837,6 +925,10 @@ fn source_to_json(source: &ChainSource) -> serde_json::Value {
"monerod_bin": monerod_bin.display().to_string(),
"datadir": datadir.display().to_string(),
}),
ChainSource::InProcessCuprate { datadir } => serde_json::json!({
"kind": "cuprate",
"datadir": datadir.display().to_string(),
}),
ChainSource::Remote { host, port } => serde_json::json!({
"kind": "remote",
"host": host,
@ -870,6 +962,18 @@ fn source_from_json(value: &serde_json::Value) -> Result<ChainSource> {
datadir: PathBuf::from(datadir),
})
}
"cuprate" => {
let datadir = value
.get("datadir")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
ChildError("stored in-process chain source has no data dir".into())
})?;
Ok(ChainSource::InProcessCuprate {
datadir: PathBuf::from(datadir),
})
}
"remote" => {
let host = value
.get("host")
@ -1603,4 +1707,194 @@ mod tests {
let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o700, "wallet dir must be 0700");
}
fn in_process_source(dir: &Path) -> ChainSource {
ChainSource::InProcessCuprate {
datadir: dir.join("chain"),
}
}
/// The in-process source is a local daemon in every sense the caller cares
/// about: same loopback port, same datadir idea, nothing remote about it.
/// That is the whole reason `wallet_rpc_argv` does not change.
#[test]
fn the_in_process_source_is_a_local_daemon_on_the_same_port() {
let dir = tmp_dir("cuprate-local");
let source = in_process_source(&dir);
let local = local_source(&dir, PathBuf::from("monerod"));
assert_eq!(
WalletChild::daemon_address(&source),
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")),
"the wallet child dials the same port either way"
);
assert_eq!(
WalletChild::daemon_address(&source),
WalletChild::daemon_address(&local),
"a spawned and an in-process local source are the same address"
);
assert_eq!(
WalletChild::chain_datadir(&source),
Some(dir.join("chain").as_path()),
"the chain is on this device's disk"
);
assert_eq!(WalletChild::chain_datadir(&ChainSource::None), None);
assert_eq!(
WalletChild::chain_datadir(&ChainSource::Remote {
host: "node.example.com".into(),
port: 18089,
}),
None,
"a remote daemon's chain is not ours"
);
// The wallet-child argv is byte-for-byte the tested local-node shape:
// same `--daemon-address`, and never `--trusted-daemon`.
let argv = WalletChild::wallet_rpc_argv(
Path::new("monero-wallet-rpc"),
39127,
"u:p",
&dir.join("wallet"),
WalletChild::daemon_address(&source).as_deref(),
None,
);
assert!(
argv.windows(2).any(|w| w[0] == "--daemon-address"
&& w[1] == format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")),
"{argv:?}"
);
assert!(!argv.iter().any(|a| a == "--trusted-daemon"), "{argv:?}");
assert!(
WalletChild::new(source, dir.join("wallet"), None)
.unwrap()
.is_enabled(),
"an in-process source is a chain source: there is something to start"
);
}
/// The copy names what is on this device and the one thing that must not be
/// buried: this daemon is testnet-only.
#[test]
fn in_process_copy_says_local_and_testnet_only() {
let dir = tmp_dir("cuprate-copy");
let copy = WalletChild::chain_copy(&in_process_source(&dir));
assert!(copy.contains("in this app"), "{copy}");
assert!(copy.contains("no Tor"), "{copy}");
assert!(copy.contains(crate::cuprate::TESTNET_ONLY), "{copy}");
assert_eq!(
crate::cuprate::TESTNET_ONLY,
"testnet only — mainnet is unvalidated"
);
}
/// The picker's choice has to survive a restart without a child ever
/// starting, exactly like the other sources — and read back as itself,
/// never as receive-only.
#[test]
fn the_in_process_choice_round_trips_through_the_sealed_record() {
let dir = tmp_dir("cuprate-record");
let store = open_store(&dir);
let source = in_process_source(&dir);
let cfg = ChildConfig {
source: source.clone(),
..ChildConfig::default()
};
cfg.validate().unwrap();
let record = merge_record(None, cfg.record_fields());
store.save_wallet_child(&record).unwrap();
let raw = store.load_wallet_child().unwrap().expect("sealed record");
assert_eq!(ChildConfig::from_record(&raw).unwrap().unwrap(), cfg);
let json: serde_json::Value = serde_json::from_str(&raw).unwrap();
assert_eq!(json["source"]["kind"], "cuprate");
assert_eq!(
json["source"]["datadir"].as_str().unwrap(),
dir.join("chain").display().to_string()
);
// An empty datadir is rejected before it is stored, never persisted and
// then failed over.
let empty = ChildConfig {
source: ChainSource::InProcessCuprate {
datadir: PathBuf::new(),
},
..ChildConfig::default()
};
let err = empty.validate().unwrap_err().to_string();
assert!(err.contains("chain data dir"), "{err}");
}
/// Without the feature, starting the in-process source names the feature —
/// never a silent no-op, and never a spawned `monero-wallet-rpc` pointed at
/// a daemon that does not exist.
#[cfg(not(feature = "cuprate-daemon"))]
#[test]
fn in_process_source_without_the_feature_names_the_feature() {
let dir = tmp_dir("cuprate-off");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
let err = child.start(&store).unwrap_err().to_string();
assert!(err.contains("cuprate-daemon"), "{err}");
assert!(!child.running(), "nothing may be left running: {err}");
assert!(
!rpc_log.exists(),
"the wallet RPC child must not be spawned against a daemon that never started"
);
child.stop().unwrap();
}
/// With the feature compiled in, the launch is real: the daemon answers on
/// the port the wallet child is pointed at, `stop` shuts it down, and the
/// app-owned child list reports it honestly (as a daemon, never as a
/// process — there is no pid).
#[cfg(feature = "cuprate-daemon")]
#[test]
fn in_process_source_launches_a_daemon_and_stop_shuts_it_down() {
let dir = tmp_dir("cuprate-on");
let store = open_store(&dir);
let rpc_log = dir.join("wallet-rpc.argv");
let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None)
.unwrap()
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
// The wallet RPC child is fake, so `start` reaches only the daemon: the
// whole point of the in-process source is that the daemon *is* us.
let _ = child.start(&store);
let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
assert!(
waits_for_tcp(&addr, Duration::from_secs(20)),
"the in-process daemon never answered on {addr}"
);
assert!(child.running(), "an owned daemon counts as running");
assert!(dir.join("chain").exists(), "the chain dir is created 0700");
child.stop().unwrap();
assert!(!child.running(), "stop must drop the daemon");
let mut closed = false;
for _ in 0..60 {
if std::net::TcpStream::connect(&addr).is_err() {
closed = true;
break;
}
std::thread::sleep(Duration::from_millis(250));
}
assert!(closed, "the daemon's RPC listener outlived stop()");
}
/// Poll a loopback address until it accepts, inside a budget.
#[cfg(feature = "cuprate-daemon")]
fn waits_for_tcp(addr: &str, budget: Duration) -> bool {
let deadline = Instant::now() + budget;
while Instant::now() <= deadline {
if std::net::TcpStream::connect(addr).is_ok() {
return true;
}
std::thread::sleep(Duration::from_millis(100));
}
false
}
}