Merge pull request 'wallet: land the in-process Cuprate chain source on main (ChainSource::InProcessCuprate, cuprate-daemon feature)' (#110) from onionwire/t_04975420-cuprate-land-the-in-process-chain-source into main
All checks were successful
ci / test (push) Successful in 5m6s
ci / sdk (push) Successful in 1m3s
android-ci / android (push) Successful in 8m20s
ci / fuzz (push) Successful in 4m43s

Reviewed-on: #110
This commit is contained in:
sirius 2026-09-18 18:05:46 +00:00
commit 25e029ed4e
12 changed files with 2804 additions and 50 deletions

1509
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -20,6 +20,18 @@ repository = "https://github.com/sirius0xdev/onionwire"
default = ["rustls"]
native-tls = ["arti-client/native-tls"]
rustls = ["arti-client/rustls"]
# In-process Monero chain daemon (Cuprate) as the local chain source, instead of
# spawning `monerod`. OFF by default: `cuprated` is pre-1.0 and is not published
# to crates.io (every Cuprate crate there is a `0.0.0-placeholder` name
# reservation), so this pins a git revision and pulls a large tree (RandomX,
# fjall, axum/hyper, rayon). See `docs/WALLET.md`, "The in-process chain daemon".
#
# Cuprate's own `arti` feature stays OFF (and is off in its default feature set,
# which is why `default-features = false` is load-bearing): it would link a
# second, older Tor stack (arti-client 0.44, which cannot unify with this
# crate's 0.46) next to OnionWire's. The in-process daemon runs clearnet-only;
# OnionWire's Arti is the only Tor in the process.
cuprate-daemon = ["dep:cuprated", "dep:toml"]
[dependencies]
arti-client = { version = "0.46", default-features = false, features = [
@ -57,6 +69,12 @@ md-5 = "0.10"
rpassword = "7"
zeroize = { version = "1", features = ["derive"] }
qrcode = { version = "0.14", default-features = false }
cuprated = { git = "https://github.com/Cuprate/cuprate", rev = "4f8fcd1bf468f566fcd89c460d50de4adb6825bf", default-features = false, optional = true }
# `cuprated::config::Config` is deserialized, not built field by field: the
# struct's nested types move with the pinned revision, a TOML document does not.
# Cuprate has `deny_unknown_fields` on every config struct, so a stale key is a
# parse error instead of a silently ignored setting.
toml = { version = "0.8", features = ["parse", "display"], optional = true }
[dev-dependencies]
tempfile = "3"

View file

@ -727,6 +727,9 @@ fn child_config(cfg: ChainConfig) -> ChildConfig {
monerod_bin: PathBuf::from(cfg.monerod_bin),
datadir: PathBuf::from(cfg.monerod_datadir),
},
ChainChoice::InProcessCuprate => ChainSource::InProcessCuprate {
datadir: PathBuf::from(cfg.monerod_datadir),
},
ChainChoice::Remote => ChainSource::Remote {
host: cfg.host,
port: cfg.port,
@ -760,6 +763,13 @@ fn chain_config(cfg: &ChildConfig) -> ChainConfig {
monerod_bin.display().to_string(),
datadir.display().to_string(),
),
ChainSource::InProcessCuprate { datadir } => (
ChainChoice::InProcessCuprate,
String::new(),
0,
String::new(),
datadir.display().to_string(),
),
ChainSource::Remote { host, port } => (
ChainChoice::Remote,
host.clone(),
@ -881,15 +891,21 @@ pub enum ChainChoice {
None,
/// The app spawns `monerod` on this device.
Local,
/// The chain daemon runs **inside this app** (Cuprate). No `monerod` binary.
/// Testnet only, and pre-production software — see the core's
/// `ChainSource::InProcessCuprate`. `monerod_datadir` is the chain data
/// directory for it, and no binary path is needed.
InProcessCuprate,
/// A daemon address the user supplied (loopback, `.onion`, or clearnet).
Remote,
}
/// The wallet-child settings, as the Kotlin side sets them.
///
/// One record for all three kinds: the fields a kind does not use are ignored
/// One record for all four kinds: the fields a kind does not use are ignored
/// by that kind (`None` needs no binaries, `Local` needs `monerod_bin` and
/// `monerod_datadir`, `Remote` needs `host` and `port`). Persisted in the
/// `monerod_datadir`, `InProcessCuprate` needs only `monerod_datadir` as its
/// chain directory, `Remote` needs `host` and `port`). Persisted in the
/// encrypted store, so it survives a restart without env vars.
#[derive(Debug, Clone, uniffi::Record)]
pub struct ChainConfig {
@ -898,6 +914,9 @@ pub struct ChainConfig {
/// resolves on `PATH` on desktop.
pub monerod_bin: String,
/// `Local` only. Data directory for the local daemon.
///
/// `InProcessCuprate` also uses this field, as the chain data directory the
/// in-process daemon stores its (fjall) chain in.
pub monerod_datadir: String,
/// `Remote` only. Daemon host.
pub host: String,
@ -916,7 +935,8 @@ pub struct ChainConfig {
/// Derived from the real child process plus the last probe, never from env-var
/// presence. `state` is one of `off`, `connecting`, `syncing`, `ready`,
/// `exited`. `chain_source` is the label of the configured source:
/// `receive-only`, `local node`, `remote onion daemon`, or `remote daemon`.
/// `receive-only`, `local node`, `in-process node`, `remote onion daemon`, or
/// `remote daemon`.
#[derive(Debug, Clone, uniffi::Record)]
pub struct WalletChildStatus {
/// `off` until the child is started and again after it is stopped; `exited`

View file

@ -193,7 +193,34 @@ the app does not pick a public remote node for them.
Unsynced or not running is an honest “not ready” / unverified state, not a
fake success.
2. **A daemon address they supply.** The wallet child points `--daemon-address`
2. **An in-process daemon** (Cuprate, behind the `cuprate-daemon` feature, off by
default). P2P, consensus and RandomX run in the OnionWire process; nothing is
spawned and nothing leaves the device except the chain P2P traffic itself.
What that changes: there is **no daemon operator** to trust — your own process
is the daemon, so the "operator sees your addresses" question does not exist.
The spend key, the chain, and the messenger are then all on one device.
What it does not change: the **device is now the trust root for chain data**.
Chain state is only as trustworthy as the binary running it, and a
compromised device corrupts the chain view along with everything else.
Honest limits, stated here rather than in a footnote:
- Cuprate is **pre-production**. Its own user book says *"do NOT use cuprated
for any serious purposes"*, and its `monerod` RPC parity is incomplete
(Cuprate issue #278). This is why the source is an opt-in build feature and
a stored user choice, never a default.
- The config pins **testnet**. Mainnet is not validated by this app.
- Cuprate's own `arti` feature is off (its Tor stack is `arti-client` 0.44,
which cannot unify with this crate's 0.46), so the in-process daemon's P2P
traffic is **clearnet**: your ISP sees that this device talks to Monero
peers. No Tor is on the chain path — Tor is the messenger's transport here,
not the chain's.
- Inbound P2P is off and the restricted RPC listener is disabled; the
unrestricted RPC binds loopback only, and it is the address the wallet
child dials. `--trusted-daemon` is still never passed.
- The chain database is a separate embedded store (fjall) under the chain
data directory, not the SQLCipher store the messenger writes — different
file, different exposure: it is not encrypted by that store's key.
3. **A daemon address they supply.** The wallet child points `--daemon-address`
at that host. Trust follows the address:
- **Loopback** — same privacy as (1); the user owns `monerod`.
- **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener

View file

@ -57,17 +57,23 @@ not something the app stores for you.
## Chain source
The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire
does not pick a public remote node for you. The three shapes are:
does not pick a public remote node for you. The four shapes are:
```
ChainSource::None receive-only; no child, no daemon
ChainSource::Local { monerod_bin, datadir } the app spawns monerod on this box
ChainSource::InProcessCuprate { datadir } the daemon is inside this app
ChainSource::Remote { host, port } a daemon address you typed
```
1. **Local `monerod`.** Chain traffic stays on the box. You accept disk, first
sync, and (on Android) the daemon not always running.
2. **A daemon address you supply** — becomes `--daemon-address` on the wallet
2. **An in-process daemon** ([Cuprate](https://github.com/Cuprate/cuprate)
running inside the OnionWire process). No `monerod` binary to install or
spawn, chain on this device, and the wallet child dials the same loopback
port. **Testnet only** in this build, and it needs the `cuprate-daemon`
feature — see *The in-process chain daemon* below.
3. **A daemon address you supply** — becomes `--daemon-address` on the wallet
child. Loopback if you already run `monerod`. `.onion` if you want chain
traffic over Tor (see *Chain traffic over Tor* below). Clearnet only if you
type it — your ISP sees Monero-node traffic; it is never a default.
@ -75,6 +81,70 @@ ChainSource::Remote { host, port } a daemon address you typed
The port is a convention, not a constant: restricted RPC on `18089` is common,
but you supply it.
### The in-process chain daemon (`cuprate-daemon`)
Cuprate's chain daemon — P2P, consensus, RandomX — can run **inside the
OnionWire process** instead of as a spawned `monerod`. The wallet layer does not
change: `monero-wallet-rpc` is still a child, and it still dials the unrestricted
loopback RPC, `127.0.0.1:18081`, the same address a spawned `monerod` gets.
```
cargo build --release --features cuprate-daemon
```
- **Off by default.** `cuprated` is pre-1.0 and is not published to crates.io
(every Cuprate crate there is a `0.0.0-placeholder` name reservation), so it is
a git dependency pinned to a revision, behind the `cuprate-daemon` feature. A
default build does not compile it: the graph is large (RandomX, fjall,
axum/hyper, rayon) and it is a *choice*, never compiled-in. Without the feature
a stored in-process chain source can still be read back — the chain-source type
and its record do not fork on a cargo feature — but starting it fails with
`this build has no in-process chain daemon — rebuild with --features
cuprate-daemon`.
- **+11.8 MiB (12,327,768 bytes)** on a stripped `aarch64-linux-android` release
binary, measured in this repo: 24,725,704 bytes without the feature and
37,053,472 with it (`cargo rustc --release --target aarch64-linux-android
[--features cuprate-daemon] --bin onionwire`, both linked with the NDK C++
runtime / compiler-rt link args, then `llvm-strip`). The `+5.6 MB` figure that
circulated with the spike was an estimate and understates it. A cold build
also compiles the Cuprate graph in addition to this crate's own, so first-build
time grows accordingly.
- **Testnet only.** Cuprate is **pre-production software**. Its own user book
says *"do NOT use cuprated for any serious purposes"*, and its `monerod` RPC
parity is incomplete (Cuprate issue #278; the four gaps measured in this repo
are in `docs/cuprate-launch-spike.md` §Parity gaps). The config pins
`network = "Testnet"`; pointing a mainnet wallet at it is not something this
build claims to do. The wallet screen's chain line says so next to the source
(`testnet only — mainnet is unvalidated`).
- **No Tor in the chain path.** Cuprate's own `arti` feature is *not* enabled:
its Tor stack is `arti-client` 0.44, which cannot unify with this crate's 0.46,
and running two Tor stacks in one process is not a trade this app makes.
OnionWire's Arti is the only Tor here, and it serves the messenger. The
in-process daemon's P2P traffic is therefore **clearnet**: your ISP can see
that this device talks to Monero testnet peers, exactly as a spawned `monerod`
would.
- **Inbound connections are off** and the restricted RPC listener is disabled:
this is a wallet's daemon, not a public node (the restricted listener only
answers placeholder metrics — see below).
- **It is not a child process.** There is no pid to watch or signal: the node is
a value the app owns, and dropping it shuts the daemon down. `stop` (TUI key
`x`, or the SDK's `stop_wallet_child`) asks it to shut down with the wallet
child, and it does not outlive the app.
- **The chain lives in `$ONIONWIRE_HOME/chain`** — the same per-identity
directory a spawned `monerod` would use, so the two local sources are
interchangeable on disk. It is created `0700`. The chain database itself is
**fjall**, a separate embedded store from OnionWire's SQLCipher file:
Cuprate puts it under the datadir it is given (`<datadir>/testnet/fjall`), so
it is never beside `onionwire.db`.
- **Selecting it.** The chain source is a stored setting (`ChildConfig`), and
this build has no on-screen chain-source picker on the desktop TUI — that is
true of the other three sources too; the picker is a separate, unmerged piece
of work. What selects this source today is a `ChainSource::InProcessCuprate`
record with a `datadir` written through `Node::set_wallet_child_config` (the
SDK's `ChainConfig` path), and the daemon then starts with the child when the
wallet is started. The SDK gains its own chain-choice variant in a follow-up
card; until then `kind = "cuprate"` is the record's spelling.
### Chain traffic over Tor (`.onion` daemons)
A `.onion` daemon cannot be dialled directly, and OnionWire does not fall back

View file

@ -142,10 +142,49 @@ The release demo binary is 51 MB unstripped.
- `RANDOMX_DIR` / `DARCH` in `randomx-rs`'s build script are not a cross-compile
hazard today only because `DARCH` is inert. If the fork ever honours it, a
`-march=native` Android build would be a silent host-arch miscompile.
- Dependency cost is worth restating for the Android AAR: the same Cargo graph builds
**two** `tor-*`/`arti-client` families (Cuprate's 0.44 and OnionWire's 0.46) plus
`axum`/`hyper`/`fjall` for `cuprated`. That is build time and binary size, not a
correctness problem, but it is real on a phone.
- Dependency cost is worth restating for the Android AAR: the `cuprated` graph adds
`axum`/`hyper`/`fjall`/RandomX on top of this crate's own. That is build time and
binary size, not a correctness problem, but it is real on a phone.
The **two `arti` families** the spike tree built were an artifact of the PoC
manifest enabling `cuprated`'s default `arti` feature: OnionWire pins
`default-features = false` for `cuprated`, so its arti-client 0.44 is **not** in
this crate's graph — one Tor stack per process (see `docs/WALLET.md`).
- Throwaway harness (not committed, per spike policy):
`/var/tmp/cuprate-android-poc/{check-acceptance.sh,check-cold.sh,build-android.sh,link-android.sh}`
and the logs next to them (`/var/tmp/cuprate-android-{checkcold,accept,ndk2,link6}.log`).
## Proven in-repo (2026-09-18, card `t_04975420`)
The spike above ran on a throwaway PoC tree. The same two commands were re-run in
this repository, against `cuprated` at the same pinned revision
(`4f8fcd1bf468f566fcd89c460d50de4adb6825bf`) and behind this crate's
`cuprate-daemon` feature, with the environment from *Recipe* above:
```
$ cargo check --locked --release --target aarch64-linux-android --features cuprate-daemon
Finished `release` profile [optimized] target(s) in 1m 50s
CHECK_EXIT=0
$ cargo rustc --locked --release --target aarch64-linux-android \
--features cuprate-daemon --bin onionwire -- <the link args above>
Finished `release` profile [optimized] target(s) in 2m 05s
LINK_EXIT=0
$ file <target>/aarch64-linux-android/release/onionwire
ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked,
interpreter /system/bin/linker64, for Android 26, built by NDK r28c (13676358),
not stripped
```
`cargo rustc` needs `--bin onionwire` (or `--lib`) because this crate has both
targets and rustc link args may only go to one of them — the PoC had a single bin,
so this is new to the real tree.
Sizes, same target and link args, `llvm-strip`ed:
| build | stripped |
|---|---|
| without the feature | 24,725,704 bytes |
| `--features cuprate-daemon` | 37,053,472 bytes |
That is a delta of **12,327,768 bytes (≈ +11.8 MiB)**, the number
`docs/WALLET.md` quotes.

298
src/cuprate.rs Normal file
View file

@ -0,0 +1,298 @@
//! 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};

View file

@ -1,4 +1,5 @@
pub mod backup;
pub mod cuprate;
pub mod dispatch;
pub mod file;
pub mod frame;

View file

@ -16,7 +16,7 @@ use crate::outbox::DEFAULT_MAX_ATTEMPTS;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
use crate::wallet;
use crate::wallet::{self, ChainSource};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -1805,6 +1805,27 @@ impl App {
}
}
/// The wallet screen's chain-source line: the child status, plus the
/// caveat the configured source carries.
///
/// The in-process daemon is **testnet only** in this build, and this line is
/// the only place the wallet screen names the configured chain source (the
/// source itself is a stored setting), so the caveat travels with it — a
/// user who reads it as a mainnet node would be misled.
fn wallet_child_screen_line(&self) -> String {
let mut line = self.node.wallet_child_line();
if matches!(
self.node.wallet_child_config().source,
ChainSource::InProcessCuprate { .. }
) {
if !line.is_empty() {
line.push_str(" · ");
}
line.push_str(crate::cuprate::TESTNET_ONLY);
}
line
}
/// Key `s` on the wallet screen: start the app-owned wallet child. The
/// balance/address readouts refresh on the next F6 — the child's RPC is not
/// answering in the same breath — so this reports the state it reached.
@ -2218,7 +2239,7 @@ impl App {
transfers,
qr_modal,
} => {
let child = self.node.wallet_child_line();
let child = self.wallet_child_screen_line();
draw_wallet(
f,
receive_addr,

View file

@ -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,
}
}

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
}
}

View file

@ -1245,3 +1245,112 @@ fn freed_loopback_port() -> u16 {
drop(listener);
port
}
// ---------------------------------------------------------------------------
// The in-process chain daemon (feature `cuprate-daemon`).
//
// The one test in the suite that runs a real chain daemon: it launches the
// `cuprated` node OnionWire embeds, asks it through the *same* typed daemon
// client a remote `monerod` is asked through, and then proves the listener dies
// with the node. A testnet node with no peers answers RPC and stays at genesis,
// so this needs no network.
// ---------------------------------------------------------------------------
#[cfg(feature = "cuprate-daemon")]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn an_in_process_cuprate_node_answers_the_typed_daemon_client() {
let dir = tempfile::tempdir().expect("tempdir");
let datadir = dir.path().join("chain");
let port = freed_loopback_port();
let addr = format!("127.0.0.1:{port}");
let budget = std::time::Duration::from_secs(5);
let mut node = onionwire::cuprate::CuprateNode::launch(&datadir, port)
.expect("launch the in-process testnet daemon");
// `launch` returns with the services started; the RPC listener can still be
// a moment behind, so poll with a deadline instead of racing it.
let mut info = None;
for _ in 0..40 {
if let Ok(got) = wallet::daemon_get_info(&addr, budget).await {
info = Some(got);
break;
}
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
let info = info.expect("the in-process daemon never answered get_info on /json_rpc");
// A fresh testnet chain: genesis is height 1 and there is nothing to sync
// towards. The daemon's own consensus context is the reference, and the RPC
// answer may trail it by a block or two while it is running.
assert!(info.height >= 1, "genesis is height 1: {info:?}");
let context_height = node.chain_height();
assert!(context_height >= 1, "in-process height: {context_height}");
assert!(
info.height.abs_diff(context_height) <= 2,
"get_info ({}) and the node's own context ({context_height}) disagree",
info.height
);
assert_eq!(
info.target_height, 0,
"a testnet node with no peers reports no target, not a caught-up chain"
);
// `get_height` is the URI endpoint (Cuprate rejects it over /json_rpc), and
// it has to agree with `get_info`.
let height = wallet::daemon_get_height(&addr, budget)
.await
.expect("get_height on the URI endpoint");
assert!(height >= 1, "{height}");
assert!(
height.abs_diff(info.height) <= 2,
"get_height ({height}) and get_info ({}) disagree",
info.height
);
// Genesis is always retrievable, and a height above the tip is the bare-500
// answer the typed client normalizes.
let genesis = wallet::daemon_get_block(&addr, 0, std::time::Duration::from_secs(30))
.await
.expect("get_block at genesis");
assert!(
genesis.len() > 70,
"a genesis block with a header and one tx is longer than this: {}",
genesis.len()
);
let far = wallet::daemon_get_block(
&addr,
info.height + 1_000_000,
std::time::Duration::from_secs(30),
)
.await;
assert!(
matches!(far, Err(wallet::WalletError::DaemonHeightOutOfRange)),
"an above-the-tip height must map to the typed height error: {far:?}"
);
// The chain database is Cuprate's own embedded store, under the datadir it
// was given — never beside OnionWire's SQLCipher file.
let fjall = datadir.join("testnet").join("fjall");
assert!(
fjall.is_dir(),
"the chain store must live under the chain datadir: {}",
fjall.display()
);
// Dropping the node *is* the shutdown. The listener has to go with it, or
// the app would leave a chain daemon behind after quitting.
drop(node);
let mut closed = false;
for _ in 0..40 {
if tokio::net::TcpStream::connect(&addr).await.is_err() {
closed = true;
break;
}
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
}
assert!(
closed,
"the unrestricted RPC was still accepting after shutdown"
);
}