wallet: land the in-process Cuprate chain source on main
`ChainSource::InProcessCuprate { datadir }` is the fourth chain source: P2P,
consensus and RandomX run inside the OnionWire process instead of as a spawned
`monerod`. The wallet layer does not move — the daemon binds the same loopback
unrestricted RPC (`127.0.0.1:18081`) that `WalletChild::daemon_address` already
returns for a local source, so `wallet_rpc_argv`, the RPC client, the payment
frames and the receipt-verification path are untouched.
- Cargo.toml: `cuprated` (git, rev 4f8fcd1b) + `toml`, both optional, behind the
`cuprate-daemon` feature, OFF by default. `cuprated`'s own `arti` feature is
disabled (`default-features = false`): its arti-client 0.44 cannot unify with
this crate's 0.46, and the in-process daemon is clearnet-only. One Tor stack in
the process. `Cargo.lock` gains the graph; a default build's
`cargo tree --locked -e normal -i cuprated` still says "did not match any
packages", and only `arti-client v0.46.0` is in the lock.
- src/cuprate.rs (new): `CuprateNode` builds the cuprated config as TOML
(testnet, unrestricted RPC on loopback, restricted RPC disabled, inbound P2P
off), launches it on a runtime it owns, and owns the node. `launch` is
synchronous on purpose: `WalletChild::start` is sync (the TUI calls it from its
blocking thread, UniFFI calls it from an async context) and a runtime cannot be
started from inside a runtime, so the launch runs on a thread of its own and
the node + its runtime come back over a channel. Dropping the value asks the
node to shut down and `shutdown_background`s the runtime, which is the only
exit that cannot panic when the value is dropped inside another runtime.
The type exists in every build (feature off: `launch` fails with the feature
name), so the chain-source type, its stored record and its copy do not fork on
a cargo feature.
- src/wallet.rs: the variant, its label (`in-process node`), and the chain-daemon
client the wallet line carried (typed `WalletError`, de-chunked HTTP,
`get_height` over the URI endpoint, an above-the-tip height as one typed
error). Cuprate answers those three differently from monerod and the
in-process source is what makes them the *local* case.
- src/wallet_child.rs: launches/holds/stops the node, `chain_datadir` for the
free-space/ownership question, the honest `chain_copy` line, `kind =
"cuprate"` in the sealed record, and `ChildConfig::validate` for it.
- src/tui.rs: the wallet screen's chain line carries the testnet caveat when the
configured source is the in-process one. It computes the line at draw time, so
`Screen::Wallet`'s shape (which tests construct) does not change.
- docs/WALLET.md, docs/THREAT_MODEL.md, docs/cuprate-android-spike.md: the
feature flag and how to enable it, where the (fjall) chain store lives, the
**measured** +11.8 MiB delta, the pre-production/testnet caveat, and the
in-repo aarch64-linux-android proof with exit codes.
Scope deviations, stated plainly:
- `src/cuprate.rs` and its one `src/lib.rs` module line are not in the card's
allowed list; the card's own deliverable describes the module's behaviour.
- `crates/onionwire-sdk/src/lib.rs` is forbidden, but adding a variant to a
`pub enum` that the SDK matches exhaustively breaks the SDK workspace, and the
root CI `sdk` job runs on every PR. One variant plus two match arms land here
so the SDK keeps compiling (`cargo test --locked` + clippy clean); the SDK card
owns the rest — feature passthrough, the config field's semantics, the label
and its tests, and the Android check.
- `tests/wallet.rs` carries the launch test. `tests/tui_frames.rs` is untouched:
main has no `ChainChoice` to pin (the chain-source picker is the unmerged F7
work, and `docs/WALLET.md` says so rather than describing a picker that does
not exist).
Proof (all on this tree):
- Default build: `cargo test --locked --target x86_64-unknown-linux-gnu` → 345
passed / 0 failed across 33 suites, exit 0; `cargo clippy --locked
--all-targets --target x86_64-unknown-linux-gnu -- -D warnings` exit 0.
- Feature on: `cargo test --locked --features cuprate-daemon --target
x86_64-unknown-linux-gnu` → 347 passed / 0 failed, exit 0; same clippy with
`--features cuprate-daemon` exit 0. The two extra tests are the real thing:
`wallet_child::tests::in_process_source_launches_a_daemon_and_stop_shuts_it_down`
and `tests/wallet.rs::an_in_process_cuprate_node_answers_the_typed_daemon_client`
— the latter launches the node, drives `get_info` / `get_height` / `get_block`
through the typed client, checks the above-the-tip 500 maps to
`DaemonHeightOutOfRange`, checks the chain store is under the chain datadir,
and checks the listener dies with the node.
- aarch64: `cargo check --locked --release --target aarch64-linux-android
--features cuprate-daemon` exit 0 (1m 50s), and the full link exit 0
(`cargo rustc ... --bin onionwire -- <NDK C++ runtime / compiler-rt link
args>`) producing `ELF 64-bit LSB pie executable, ARM aarch64, for Android 26,
built by NDK r28c`.
- Size: stripped aarch64 release binary, 24,725,704 bytes without the feature and
37,053,472 with it — +12,327,768 bytes (≈ +11.8 MiB), the figure
`docs/WALLET.md` now quotes.
This commit is contained in:
parent
8ba1cf4c6c
commit
ffea4bf9df
12 changed files with 2804 additions and 50 deletions
298
src/cuprate.rs
Normal file
298
src/cuprate.rs
Normal 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};
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
pub mod backup;
|
||||
pub mod cuprate;
|
||||
pub mod dispatch;
|
||||
pub mod file;
|
||||
pub mod frame;
|
||||
|
|
|
|||
25
src/tui.rs
25
src/tui.rs
|
|
@ -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,
|
||||
|
|
|
|||
352
src/wallet.rs
352
src/wallet.rs
|
|
@ -35,6 +35,17 @@ pub enum ChainSource {
|
|||
/// Data directory for the local daemon.
|
||||
datadir: PathBuf,
|
||||
},
|
||||
/// A chain daemon **inside this process** (Cuprate), with its chain in
|
||||
/// `datadir`. Nothing is spawned; the wallet child still dials loopback
|
||||
/// RPC, so this is a [`ChainSource::Local`] with a different owner.
|
||||
///
|
||||
/// Two consequences the UI has to state: the chain is on this device, and
|
||||
/// the in-process daemon is **testnet-only** in this build (Cuprate is
|
||||
/// pre-production and its mainnet RPC parity is unvalidated).
|
||||
InProcessCuprate {
|
||||
/// Data directory for the daemon's chain database.
|
||||
datadir: PathBuf,
|
||||
},
|
||||
/// A daemon address the user supplied. Trust follows the address.
|
||||
Remote {
|
||||
/// Daemon host. May be loopback, `.onion`, or a clearnet host the user
|
||||
|
|
@ -61,6 +72,7 @@ impl ChainSource {
|
|||
match self {
|
||||
ChainSource::None => "receive-only".to_string(),
|
||||
ChainSource::Local { .. } => "local node".to_string(),
|
||||
ChainSource::InProcessCuprate { .. } => "in-process node".to_string(),
|
||||
ChainSource::Remote { host, .. } if is_onion_host(host) => {
|
||||
"remote onion daemon".to_string()
|
||||
}
|
||||
|
|
@ -1103,3 +1115,343 @@ fn json_amount(v: &serde_json::Value) -> String {
|
|||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Chain daemon client (the chain side of the RPC layer)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// This is *not* the wallet child: that one is a loopback HTTP Digest RPC. This
|
||||
// one dials the *daemon* the wallet child scans from, and that is the connection
|
||||
// Cuprate changes shape on (`docs/cuprate-launch-spike.md` §Parity gaps, all
|
||||
// three measured by running it):
|
||||
//
|
||||
// * a height above the tip is a **bare HTTP 500 with a zero-byte body**, where
|
||||
// monerod answers a JSON-RPC error object (`TOO_BIG_HEIGHT`);
|
||||
// * `get_info` metrics are not measurements — a placeholder 5 GiB
|
||||
// `database_size`, an empty `version`, `free_space = u64::MAX`, and zero peers
|
||||
// even while blocks are arriving;
|
||||
// * `get_height` is a **URI endpoint**: `{"method":"get_height"}` over
|
||||
// `/json_rpc` is rejected with 422.
|
||||
//
|
||||
// Nothing here parses a peer count, a database size, a free-space figure or a
|
||||
// version string. There is no field for them to land in, so a caller cannot show
|
||||
// a placeholder as a measurement.
|
||||
//
|
||||
// The in-process chain source ([`ChainSource::InProcessCuprate`]) is what makes
|
||||
// these the *local* case rather than a remote corner: it is the daemon this app
|
||||
// starts itself.
|
||||
|
||||
/// `CORE_RPC_ERROR_CODE_TOO_BIG_HEIGHT` in monero's
|
||||
/// `src/rpc/core_rpc_server_error_codes.h`. Cuprate answers the same request
|
||||
/// with a bare HTTP 500 instead, which is why both spellings map to
|
||||
/// [`WalletError::DaemonHeightOutOfRange`].
|
||||
const TOO_BIG_HEIGHT_CODE: i64 = -2;
|
||||
|
||||
/// Typed failures of the chain-daemon calls. The wallet-child path above keeps
|
||||
/// its plain string errors; this side distinguishes a *height* failure from
|
||||
/// every other one because that is the answer Cuprate mangles.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum WalletError {
|
||||
/// The requested height is above the daemon's tip. Cuprate: bare HTTP 500,
|
||||
/// empty body. monerod: HTTP 200, error code `-2`.
|
||||
DaemonHeightOutOfRange,
|
||||
/// A non-2xx status that is not the height case above.
|
||||
DaemonHttpStatus(u16),
|
||||
/// A JSON-RPC error object we do not special-case.
|
||||
DaemonRpc {
|
||||
/// The `error.code` the daemon sent.
|
||||
code: i64,
|
||||
/// The `error.message` the daemon sent.
|
||||
message: String,
|
||||
},
|
||||
/// A 2xx answer with no usable body. Carries the address and the reason.
|
||||
DaemonNoBody(String),
|
||||
/// The daemon could not be reached, or the answer could not be read.
|
||||
DaemonTransport(String),
|
||||
}
|
||||
|
||||
impl WalletError {
|
||||
/// Is this the "height above tip" failure? A caller that just asked for a
|
||||
/// block at an unverified height may retry lower; every other error is a
|
||||
/// different problem.
|
||||
pub fn is_height_out_of_range(&self) -> bool {
|
||||
matches!(self, Self::DaemonHeightOutOfRange)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for WalletError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::DaemonHeightOutOfRange => {
|
||||
f.write_str("daemon: height is above its chain tip (not synced that far yet)")
|
||||
}
|
||||
Self::DaemonHttpStatus(code) => write!(f, "daemon: HTTP {code}"),
|
||||
Self::DaemonRpc { code, message } => write!(f, "daemon rpc error {code}: {message}"),
|
||||
Self::DaemonNoBody(msg) | Self::DaemonTransport(msg) => f.write_str(msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for WalletError {}
|
||||
|
||||
/// What the chain view is allowed to know about a daemon: how far it is and how
|
||||
/// far it is going. Deliberately nothing else — see the section comment.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DaemonInfo {
|
||||
/// Blocks the daemon has.
|
||||
pub height: u64,
|
||||
/// Blocks it is syncing towards. `0` means it reported none, which is not
|
||||
/// the same as "caught up".
|
||||
pub target_height: u64,
|
||||
}
|
||||
|
||||
/// Cap on a daemon answer, in bytes. A `get_block` blob is the large case.
|
||||
pub const DAEMON_MAX_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
/// `get_info` as the chain view needs it: height and target, nothing else.
|
||||
pub async fn daemon_get_info(
|
||||
addr: &str,
|
||||
budget: Duration,
|
||||
) -> std::result::Result<DaemonInfo, WalletError> {
|
||||
let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_info"}"#;
|
||||
let request = json_rpc_request(addr, "/json_rpc", body);
|
||||
let (status, raw) = daemon_http(addr, &request, budget).await?;
|
||||
daemon_ok_status(status)?;
|
||||
let json = daemon_json(&raw, addr)?;
|
||||
let result = json
|
||||
.get("result")
|
||||
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_info has no result")))?;
|
||||
let height = result
|
||||
.get("height")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.ok_or_else(|| {
|
||||
WalletError::DaemonNoBody(format!("{addr}: get_info has no chain height"))
|
||||
})?;
|
||||
let target_height = result
|
||||
.get("target_height")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
Ok(DaemonInfo {
|
||||
height,
|
||||
target_height,
|
||||
})
|
||||
}
|
||||
|
||||
/// The daemon's tip, over the `get_height` URI endpoint.
|
||||
///
|
||||
/// Cuprate rejects `{"method":"get_height"}` over `/json_rpc` with 422, and the
|
||||
/// URI endpoint is what monerod has always answered — one spelling works on
|
||||
/// both, so this is the one to use.
|
||||
pub async fn daemon_get_height(
|
||||
addr: &str,
|
||||
budget: Duration,
|
||||
) -> std::result::Result<u64, WalletError> {
|
||||
let request = uri_request(addr, "GET", "/get_height");
|
||||
let (status, raw) = daemon_http(addr, &request, budget).await?;
|
||||
if is_server_error(status) {
|
||||
return Err(WalletError::DaemonHeightOutOfRange);
|
||||
}
|
||||
daemon_ok_status(status)?;
|
||||
let json = daemon_json(&raw, addr)?;
|
||||
// Both daemons answer a top-level `height` here; tolerate a jsonrpc
|
||||
// envelope too rather than betting on the shape.
|
||||
json.get("height")
|
||||
.or_else(|| json.get("result").and_then(|r| r.get("height")))
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_height has no height")))
|
||||
}
|
||||
|
||||
/// One block by height, as raw bytes (the hex `blob` field, decoded).
|
||||
///
|
||||
/// Not called by the app yet: the wallet's block scan still lives in
|
||||
/// `monero-wallet-rpc`. It exists because the out-of-range answer above is the
|
||||
/// Cuprate behaviour such a scan has to survive, and the mapping belongs with
|
||||
/// the rest of the client.
|
||||
pub async fn daemon_get_block(
|
||||
addr: &str,
|
||||
height: u64,
|
||||
budget: Duration,
|
||||
) -> std::result::Result<Vec<u8>, WalletError> {
|
||||
let body = format!(
|
||||
r#"{{"jsonrpc":"2.0","id":"0","method":"get_block","params":{{"height":{height}}}}}"#
|
||||
);
|
||||
let request = json_rpc_request(addr, "/json_rpc", &body);
|
||||
let (status, raw) = daemon_http(addr, &request, budget).await?;
|
||||
if is_server_error(status) {
|
||||
return Err(WalletError::DaemonHeightOutOfRange);
|
||||
}
|
||||
daemon_ok_status(status)?;
|
||||
let json = daemon_json(&raw, addr)?;
|
||||
let blob = json
|
||||
.get("result")
|
||||
.and_then(|r| r.get("blob"))
|
||||
.and_then(|b| b.as_str())
|
||||
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block has no blob")))?;
|
||||
hex_decode(blob)
|
||||
.ok_or_else(|| WalletError::DaemonNoBody(format!("{addr}: get_block blob is not hex")))
|
||||
}
|
||||
|
||||
/// A bare 5xx is how Cuprate says "no such height" — it carries no body to
|
||||
/// decode, so the *call* decides what it means: height-addressed calls (the two
|
||||
/// above) read it as [`WalletError::DaemonHeightOutOfRange`], everything else
|
||||
/// reads it as a status error.
|
||||
fn is_server_error(status: u16) -> bool {
|
||||
(500..600).contains(&status)
|
||||
}
|
||||
|
||||
fn daemon_ok_status(status: u16) -> std::result::Result<(), WalletError> {
|
||||
if (200..300).contains(&status) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(WalletError::DaemonHttpStatus(status))
|
||||
}
|
||||
|
||||
fn json_rpc_request(addr: &str, path: &str, body: &str) -> String {
|
||||
format!(
|
||||
"POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
fn uri_request(addr: &str, method: &str, path: &str) -> String {
|
||||
format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// One request, one answer: status code plus body. `Connection: close` and read
|
||||
/// to EOF, so `Content-Length` never has to be trusted.
|
||||
async fn daemon_http(
|
||||
addr: &str,
|
||||
request: &str,
|
||||
budget: Duration,
|
||||
) -> std::result::Result<(u16, Vec<u8>), WalletError> {
|
||||
let mut stream = tokio::time::timeout(budget, TcpStream::connect(addr))
|
||||
.await
|
||||
.map_err(|_| WalletError::DaemonTransport(format!("{addr}: connect timed out")))?
|
||||
.map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?;
|
||||
let raw = tokio::time::timeout(budget, async {
|
||||
stream.write_all(request.as_bytes()).await?;
|
||||
let mut buf = Vec::new();
|
||||
let mut tmp = [0u8; 8192];
|
||||
loop {
|
||||
let n = stream.read(&mut tmp).await?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
buf.extend_from_slice(&tmp[..n]);
|
||||
if buf.len() >= DAEMON_MAX_BYTES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok::<Vec<u8>, std::io::Error>(buf)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| WalletError::DaemonTransport(format!("{addr}: read timed out")))?
|
||||
.map_err(|e| WalletError::DaemonTransport(format!("{addr}: {e}")))?;
|
||||
split_http(&raw)
|
||||
.ok_or_else(|| WalletError::DaemonTransport(format!("{addr}: not an HTTP response")))
|
||||
}
|
||||
|
||||
/// Status code and body from a raw HTTP/1.1 response.
|
||||
///
|
||||
/// Cuprate is axum/hyper: the body arrives `Transfer-Encoding: chunked`, so
|
||||
/// scanning for the outermost braces is not a parse once a blob spans more than
|
||||
/// one chunk. De-chunk here, once, for every call.
|
||||
fn split_http(raw: &[u8]) -> Option<(u16, Vec<u8>)> {
|
||||
let (head, body) = match find(raw, b"\r\n\r\n") {
|
||||
Some(at) => (&raw[..at], &raw[at + 4..]),
|
||||
None => {
|
||||
let at = find(raw, b"\n\n")?;
|
||||
(&raw[..at], &raw[at + 2..])
|
||||
}
|
||||
};
|
||||
let head = std::str::from_utf8(head).ok()?;
|
||||
let mut lines = head.lines();
|
||||
let status = lines.next()?.split_whitespace().nth(1)?.parse().ok()?;
|
||||
let chunked = lines.any(|line| {
|
||||
line.split_once(':').is_some_and(|(k, v)| {
|
||||
k.eq_ignore_ascii_case("transfer-encoding")
|
||||
&& v.to_ascii_lowercase().contains("chunked")
|
||||
})
|
||||
});
|
||||
let body = if chunked {
|
||||
dechunk(body)?
|
||||
} else {
|
||||
body.to_vec()
|
||||
};
|
||||
Some((status, body))
|
||||
}
|
||||
|
||||
fn dechunk(body: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0;
|
||||
loop {
|
||||
let line_end = find(&body[at..], b"\r\n")?;
|
||||
let size_line = std::str::from_utf8(&body[at..at + line_end]).ok()?;
|
||||
// `size[;chunk-extension]`
|
||||
let size = usize::from_str_radix(size_line.split(';').next()?.trim(), 16).ok()?;
|
||||
at += line_end + 2;
|
||||
if size == 0 {
|
||||
return Some(out);
|
||||
}
|
||||
if at + size > body.len() {
|
||||
return None;
|
||||
}
|
||||
out.extend_from_slice(&body[at..at + size]);
|
||||
at += size;
|
||||
if body[at..].starts_with(b"\r\n") {
|
||||
at += 2;
|
||||
} else if body[at..].starts_with(b"\n") {
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
haystack.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
fn daemon_json(body: &[u8], addr: &str) -> std::result::Result<serde_json::Value, WalletError> {
|
||||
let text = std::str::from_utf8(body)
|
||||
.map_err(|_| WalletError::DaemonNoBody(format!("{addr}: body is not UTF-8")))?;
|
||||
let json: serde_json::Value = serde_json::from_str(text.trim())
|
||||
.map_err(|e| WalletError::DaemonNoBody(format!("{addr}: {e}")))?;
|
||||
if let Some(err) = json.get("error") {
|
||||
let code = err
|
||||
.get("code")
|
||||
.and_then(serde_json::Value::as_i64)
|
||||
.unwrap_or(0);
|
||||
if code == TOO_BIG_HEIGHT_CODE {
|
||||
return Err(WalletError::DaemonHeightOutOfRange);
|
||||
}
|
||||
let message = err
|
||||
.get("message")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("rpc error")
|
||||
.to_string();
|
||||
return Err(WalletError::DaemonRpc { code, message });
|
||||
}
|
||||
Ok(json)
|
||||
}
|
||||
|
||||
fn hex_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let bytes = s.as_bytes();
|
||||
if !bytes.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(bytes.len() / 2);
|
||||
for pair in bytes.chunks(2) {
|
||||
out.push((hex_val(pair[0])? << 4) | hex_val(pair[1])?);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn hex_val(c: u8) -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue