onionwire/src/cuprate.rs
agent ffea4bf9df
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
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.
2026-09-18 13:45:59 -04:00

298 lines
12 KiB
Rust

//! In-process Monero chain daemon (Cuprate) as OnionWire's local chain source.
//!
//! This is the chain half of the wallet's "the app owns the daemon" story: the
//! daemon — P2P, consensus, RandomX — runs **in this process** instead of as a
//! spawned `monerod`. `monero-wallet-rpc` is still a child and is unchanged: it
//! dials the unrestricted loopback RPC that [`crate::wallet_child`] already
//! computes ([`DEFAULT_MONEROD_RPC_PORT`]), so no wallet-layer code moves.
//!
//! [`DEFAULT_MONEROD_RPC_PORT`]: crate::wallet_child::DEFAULT_MONEROD_RPC_PORT
//!
//! Locked facts this module encodes:
//!
//! * `cuprated` is a **git** dependency pinned to a revision, behind the
//! `cuprate-daemon` feature, off by default. Cuprate is pre-1.0 and is not
//! published to crates.io (every Cuprate crate there is a `0.0.0-placeholder`
//! name reservation), so a pinned revision is the only honest way to depend on
//! it.
//! * Cuprate's own `arti` feature stays **off**. Its Tor stack is arti 0.44,
//! which cannot unify with this crate's arti 0.46, and this daemon is
//! clearnet-only: OnionWire's Arti is the only Tor in the process.
//! * The **unrestricted** RPC listener binds `127.0.0.1:<port>` — the address
//! `WalletChild::daemon_address` returns for a local source. The restricted
//! listener is disabled: nothing here dials it, and its metrics are
//! placeholders (a 5 GiB `database_size`, an empty `version`, `free_space =
//! u64::MAX`).
//! * The network is **testnet**. Mainnet is not validated: Cuprate is
//! pre-production and its monerod RPC parity is incomplete
//! (`docs/cuprate-launch-spike.md` §Parity gaps). Pointing a mainnet wallet at
//! it is not something this build claims to do.
//! * The chain database is **fjall**, a separate embedded store from OnionWire's
//! SQLCipher file. Cuprate puts it under the datadir it is given
//! (`<datadir>/<network>/fjall`), so it never lands next to `onionwire.db`.
//!
//! # Building without the feature
//!
//! [`CuprateNode`] exists in every build with the same constructor, so the
//! chain-source type, its stored record and the picker do not fork on a cargo
//! feature. In a build without `cuprate-daemon`, [`CuprateNode::launch`] fails
//! with the feature name instead of silently doing nothing.
/// The one-line caveat every surface that offers the in-process daemon has to
/// carry, so the picker, the chain block and the docs cannot drift apart.
///
/// Unconditional — *not* feature-gated: a build without `cuprate-daemon` says
/// the same thing rather than describing a daemon it cannot start.
pub const TESTNET_ONLY: &str = "testnet only — mainnet is unvalidated";
/// Can this build actually start the daemon? `false` without the feature.
pub const fn available() -> bool {
cfg!(feature = "cuprate-daemon")
}
/// Why starting the daemon fails in a build without the feature. One string, so
/// the refusal cannot drift between this module and its callers.
pub const NO_FEATURE_MSG: &str =
"this build has no in-process chain daemon — rebuild with --features cuprate-daemon";
#[cfg(feature = "cuprate-daemon")]
mod imp {
use std::path::Path;
use std::sync::mpsc;
use cuprated::Node;
use cuprated::config::{Config, resolve_max_memory};
/// The network this daemon runs. Testnet, deliberately — see the module
/// docs. Cuprate spells this `Testnet`.
pub const NETWORK: &str = "Testnet";
/// What the daemon aims to stay under, in bytes. Cuprate would otherwise
/// read total system memory, which on a phone with a wallet on it is not a
/// number this app gets to choose.
const TARGET_MAX_MEMORY: u64 = 2_000_000_000;
/// Threads for the tx-pool + blockchain reader pool. Small on purpose: this
/// runs next to the messenger, not on its own box.
const READER_THREADS: usize = 4;
/// Worker threads for the runtime the daemon's tasks live on. The node's
/// services are spawned tasks; two workers is enough to drive them (and the
/// wallet child's RPC is the only client).
const RUNTIME_WORKERS: usize = 2;
/// A running in-process chain daemon.
///
/// Owning it *is* the lifecycle: `cuprated::Node` implements `Drop` and asks
/// its services to stop there, so dropping this value stops the daemon.
/// There is no pid to signal.
pub struct CuprateNode {
/// The runtime the node's services were launched on. Owned here so it
/// lives exactly as long as the daemon does — drop the runtime and the
/// services stop being polled.
runtime: Option<tokio::runtime::Runtime>,
/// `None` only inside `Drop`, where it is taken out to be dropped first.
node: Option<Node>,
}
impl CuprateNode {
/// Launch the daemon with its chain in `datadir`, unrestricted RPC on
/// loopback `port`.
///
/// Synchronous on purpose: [`crate::wallet_child::WalletChild::start`]
/// is sync (the TUI calls it off its own thread, UniFFI calls it from an
/// async context), and a runtime cannot be *started* from inside another
/// runtime. The launch therefore happens on a thread of its own with a
/// runtime this value owns, and the result is handed back over a channel.
/// Blocking this thread for the duration of the launch is the same thing
/// the app already does for a `.onion` chain source's SOCKS readiness
/// wait.
pub fn launch(datadir: &Path, port: u16) -> Result<Self, String> {
let text = config_toml(datadir, port);
let (tx, rx) = mpsc::channel();
std::thread::Builder::new()
.name("onionwire-cuprate".into())
.spawn(move || {
let _ = tx.send(launch_on_owned_runtime(&text));
})
.map_err(|e| format!("launch thread: {e}"))?;
let (runtime, node) = rx
.recv()
.map_err(|_| "the launch thread died before answering".to_string())??;
Ok(Self {
runtime: Some(runtime),
node: Some(node),
})
}
/// Ask the node's services to stop.
///
/// Cancels the node's shutdown token; the services then drain on the
/// runtime that launched them (dropping the value cuts that short, so
/// [`crate::wallet_child::WalletChild::stop`] calls this first). Safe in
/// any context — no blocking, no runtime handle needed.
pub fn shutdown(&self) {
if let Some(node) = &self.node {
node.shutdown();
}
}
/// Blocks the daemon has, from its own consensus context. The RPC
/// answer is the same number; this one needs no HTTP round trip.
pub fn chain_height(&mut self) -> u64 {
match self.node.as_mut() {
Some(node) => node.blockchain.context().chain_height as u64,
None => 0,
}
}
}
impl Drop for CuprateNode {
fn drop(&mut self) {
// Ask first, then take the value out and drop it *here* so its own
// `Drop` (the node's shutdown) runs while the runtime is still
// alive to poll the services that observe it.
if let Some(node) = &self.node {
node.shutdown();
}
drop(self.node.take());
// A runtime cannot be dropped from inside another runtime's context
// (tokio panics: "Cannot drop a runtime in a context where blocking
// is not allowed"), and this value can be dropped from the SDK's
// async context. `shutdown_background` is the exit that never blocks
// and never panics; the services are already shutting down above.
if let Some(runtime) = self.runtime.take() {
runtime.shutdown_background();
}
}
}
/// Build the daemon's runtime, launch the node on it, hand both back.
///
/// Runs on the launch thread — never on a thread that is already inside a
/// runtime, which is what makes `block_on` legal here.
fn launch_on_owned_runtime(text: &str) -> Result<(tokio::runtime::Runtime, Node), String> {
let mut config: Config = toml::from_str(text).map_err(|e| format!("config: {e}"))?;
resolve_max_memory(&mut config).map_err(|e| format!("config: {e}"))?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(RUNTIME_WORKERS)
.enable_all()
.build()
.map_err(|e| format!("runtime: {e}"))?;
let node = runtime
.block_on(Node::launch(config))
.map_err(|e| format!("launch: {e}"))?;
Ok((runtime, node))
}
/// The cuprated config this app launches with, as TOML.
///
/// A TOML document rather than a struct literal: cuprated's nested config
/// types move between revisions, and every one of them is `Deserialize` with
/// `deny_unknown_fields`, so a stale key is a parse error instead of a
/// default silently standing in for the setting that was meant.
///
/// No data directory is created here — the caller owns the 0700 wallet dir.
pub fn config_toml(datadir: &Path, port: u16) -> String {
let datadir = datadir.display();
format!(
r#"network = "{NETWORK}"
offline = false
fast_sync = true
target_max_memory = {TARGET_MAX_MEMORY}
[fs]
fast_data_directory = "{datadir}"
slow_data_directory = "{datadir}"
cache_directory = "{datadir}/cache"
[storage]
reader_threads = {READER_THREADS}
# The unrestricted listener: this is the one the wallet child dials, and the one
# with real numbers. The restricted listener is off — its metrics are
# placeholders, and nothing in this app reads them.
[rpc.unrestricted]
address = "127.0.0.1"
port = {port}
enable = true
[rpc.restricted]
address = "127.0.0.1"
port = 0
enable = false
# Inbound connections are off: this is a wallet's daemon, not a public node.
# Tor P2P stays off too — OnionWire already runs Arti for the messenger, and
# chain traffic on loopback-only clearnet does not need a second Tor stack.
[p2p.clear_net]
enable_inbound = false
enable_inbound_v6 = false
[p2p.tor_net]
enabled = false
[tor]
mode = "Auto"
"#
)
}
#[cfg(test)]
mod tests {
use super::*;
/// The config has to *parse* into this revision's `Config`: every
/// cuprated config struct is `deny_unknown_fields`, so a key that moved
/// between revisions is a hard error, not a silently ignored setting.
#[test]
fn the_config_parses_into_this_revision() {
let mut config: Config =
toml::from_str(&config_toml(Path::new("/tmp/onionwire-chain"), 18081))
.expect("the config must parse against the pinned cuprated revision");
resolve_max_memory(&mut config).expect("target_max_memory is set, so nothing to probe");
assert_eq!(format!("{:?}", config.network), NETWORK);
// The fjall store is Cuprate's, under the datadir it was given —
// never beside OnionWire's SQLCipher file.
assert_eq!(
config.fjall_directory(),
Path::new("/tmp/onionwire-chain/testnet/fjall"),
"the chain database is a separate store under the chain datadir"
);
}
}
}
#[cfg(not(feature = "cuprate-daemon"))]
mod imp {
use std::path::Path;
/// Placeholder for a build without `cuprate-daemon`.
///
/// It has no state because nothing can ever be launched: [`launch`] always
/// fails. It exists so the chain-source type, its persistence and the
/// status copy do not fork on a cargo feature.
///
/// [`launch`]: CuprateNode::launch
pub struct CuprateNode(());
impl CuprateNode {
/// Always fails: this build has no in-process daemon.
pub fn launch(_datadir: &Path, _port: u16) -> Result<Self, String> {
Err(super::NO_FEATURE_MSG.into())
}
/// Nothing to stop: no daemon was ever launched.
pub fn shutdown(&self) {}
/// No daemon, no chain: the same number a stopped node reports.
pub fn chain_height(&mut self) -> u64 {
0
}
}
}
pub use imp::CuprateNode;
#[cfg(feature = "cuprate-daemon")]
pub use imp::{NETWORK, config_toml};