wallet: in-process Cuprate chain daemon behind the cuprate-daemon feature #95
12 changed files with 3785 additions and 53 deletions
1509
Cargo.lock
generated
1509
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
15
Cargo.toml
15
Cargo.toml
|
|
@ -20,6 +20,17 @@ repository = "https://github.com/sirius0xdev/onionwire"
|
|||
default = ["native-tls"]
|
||||
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 a pre-1.0 project that is not
|
||||
# published to crates.io, so this pins a git revision and pulls a large tree
|
||||
# (randomx, fjall, axum/hyper, rayon). See `docs/WALLET.md`, "In-process chain
|
||||
# daemon".
|
||||
#
|
||||
# Cuprate's own `arti` feature stays OFF: 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 = [
|
||||
|
|
@ -49,6 +60,10 @@ 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.
|
||||
toml = { version = "0.8", features = ["parse", "display"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -55,17 +55,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 — that needs a SOCKS proxy for the wallet child and is **not
|
||||
implemented here**: configuring a `.onion` host today fails with a clear error
|
||||
|
|
@ -75,15 +81,61 @@ 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, so
|
||||
it is a git dependency pinned to a revision. Without the feature the picker
|
||||
still shows the row — the chain-source type and its stored 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`.
|
||||
- **+12.3 MB** on a stripped release binary, measured here: 26,942,168 bytes
|
||||
without the feature and 39,193,032 with it (`cargo build --release` with and
|
||||
without `--features cuprate-daemon`, then `strip` both). The +5.6 MB figure
|
||||
that circulated with the spike was an estimate and understates it. It also
|
||||
pulls a large build tree (RandomX, fjall, axum/hyper, rayon) — a cold build
|
||||
compiles ~586 crates in release — so a build from cold is noticeably longer
|
||||
than a plain TUI build.
|
||||
- **Testnet only.** Cuprate is pre-production and its `monerod` RPC parity is
|
||||
incomplete (`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 picker row and the chain block both say so.
|
||||
- **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. That means
|
||||
the in-process daemon's P2P traffic is **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, and the restricted server 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. `n` in the wallet
|
||||
screen stops it 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. Storage gate: the wallet screen reports free space
|
||||
there either way.
|
||||
|
||||
### The daemon you point at has to be its *unrestricted* RPC
|
||||
|
||||
Both the app-owned child and the chain probe behind the wallet screen dial the
|
||||
daemon's unrestricted listener: `--rpc-bind-port` for the `monerod` this app
|
||||
spawns (`127.0.0.1:18081`), and whatever port an in-process Cuprate binds for
|
||||
`[rpc.unrestricted]`. Never the restricted listener — it answers, so getting
|
||||
this wrong shows up as a *wrong number* rather than as an error. On Cuprate its
|
||||
restricted server reports a placeholder `database_size` (exactly 5 GiB), an
|
||||
empty `version`, and `free_space = u64::MAX` on both servers.
|
||||
spawns, and `[rpc.unrestricted]` for the in-process Cuprate — `127.0.0.1:18081`
|
||||
either way, which is why the chain source does not change the wallet child's
|
||||
argv. Never the restricted listener — it answers, so getting this wrong shows up
|
||||
as a *wrong number* rather than as an error. On Cuprate its restricted server
|
||||
reports a placeholder `database_size` (exactly 5 GiB), an empty `version`, and
|
||||
`free_space = u64::MAX` on both servers; the in-process daemon's restricted
|
||||
listener is disabled outright (`enable = false`).
|
||||
|
||||
What the wallet client reads from the daemon is chain height, and nothing else:
|
||||
`daemon_get_info` / `daemon_get_height` in `src/wallet.rs`. No peer count, no
|
||||
|
|
|
|||
200
src/cuprate.rs
Normal file
200
src/cuprate.rs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
//! In-process Monero chain daemon (Cuprate) as OnionWire's local chain source.
|
||||
//!
|
||||
//! This is Phase 1 of the Cuprate strategy (`docs/payment-integration-plan.md`
|
||||
//! §7a): the chain daemon — P2P, consensus, RandomX — runs **in this process**
|
||||
//! instead of a spawned `monerod`. The app then ships one fewer native binary
|
||||
//! (~52 MB) and `monero-wallet-rpc` keeps dialling loopback RPC exactly as it
|
||||
//! does today, so no wallet-layer code changes.
|
||||
//!
|
||||
//! Locked facts this module encodes:
|
||||
//!
|
||||
//! * `cuprated` is a **git** dependency pinned to a revision and gated behind
|
||||
//! the `cuprate-daemon` feature, off by default. Cuprate is pre-1.0 and not
|
||||
//! published to crates.io; 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 the in-process 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` already returns. 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.
|
||||
//! * `Node::launch` is async and the node's tasks run on the calling runtime, so
|
||||
//! the caller supplies the app's Tokio handle.
|
||||
//!
|
||||
//! # Building without the feature
|
||||
//!
|
||||
//! [`CuprateNode`] exists in every build with the same `launch` signature, so
|
||||
//! the chain-source type and its persistence do not fork on a cargo feature. In
|
||||
//! a build without `cuprate-daemon`, `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 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;
|
||||
|
||||
/// A running in-process chain daemon.
|
||||
///
|
||||
/// Owning it *is* the lifecycle: `cuprated::Node` implements `Drop` and
|
||||
/// shuts its services down there, so dropping this value stops the daemon.
|
||||
/// There is no `shutdown` method to forget to call, and no pid to signal.
|
||||
pub struct CuprateNode {
|
||||
node: Node,
|
||||
}
|
||||
|
||||
impl CuprateNode {
|
||||
/// Launch the daemon with its chain in `datadir`, unrestricted RPC on
|
||||
/// loopback `port`.
|
||||
///
|
||||
/// Must be awaited on a Tokio runtime: the node spawns its services onto
|
||||
/// the current one.
|
||||
pub async fn launch(datadir: &Path, port: u16) -> Result<Self, String> {
|
||||
let text = config_toml(datadir, port);
|
||||
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 node = Node::launch(config)
|
||||
.await
|
||||
.map_err(|e| format!("launch: {e}"))?;
|
||||
Ok(Self { node })
|
||||
}
|
||||
|
||||
/// Ask the node's services to stop.
|
||||
///
|
||||
/// `&self` and non-blocking: this cancels the node's shutdown token, and
|
||||
/// the services then drain on the runtime that launched them. Dropping
|
||||
/// the value afterwards closes the rest. Calling it before the drop is
|
||||
/// what gives them the chance.
|
||||
pub fn shutdown(&self) {
|
||||
self.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.
|
||||
///
|
||||
/// `&mut self` because cuprated's blockchain handle reads its context
|
||||
/// mutably; through [`crate::wallet_child`] that borrow happens under
|
||||
/// the node's own lock.
|
||||
pub fn chain_height(&mut self) -> u64 {
|
||||
self.node.blockchain.context().chain_height as u64
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 `Config` is `Deserialize` with
|
||||
/// `deny_unknown_fields`, so a typo 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(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 TUI
|
||||
/// picker 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 async 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) {}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
|
|
|||
31
src/node.rs
31
src/node.rs
|
|
@ -655,6 +655,16 @@ impl Node {
|
|||
}
|
||||
}
|
||||
|
||||
/// What "run an in-process daemon" means for this identity: Cuprate inside
|
||||
/// this process, with its chain in the same per-identity directory a local
|
||||
/// `monerod` would use. Requires the `cuprate-daemon` feature to actually
|
||||
/// start; without it, the child reports the feature name.
|
||||
pub fn default_in_process_chain_source(&self) -> ChainSource {
|
||||
ChainSource::InProcessCuprate {
|
||||
datadir: self.home.join("chain"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The state the wallet screen draws. Cheap: no dial, no spawn.
|
||||
pub fn wallet_child_state(&self) -> WalletChildState {
|
||||
// Read the (store-backed) choice first: never hold the child lock while
|
||||
|
|
@ -677,7 +687,11 @@ impl Node {
|
|||
/// Owning the child is the whole point: balance, receive address, `/tip` and
|
||||
/// receipt verification then all go through it, so a "start node" button
|
||||
/// cannot describe a daemon the wallet does not use.
|
||||
pub fn wallet_child_start(&self) -> Result<(), String> {
|
||||
///
|
||||
/// `runtime` is the app's Tokio handle, needed only by
|
||||
/// [`ChainSource::InProcessCuprate`]: that daemon's tasks run on the app's
|
||||
/// runtime, and this call happens on the TUI's blocking thread.
|
||||
pub fn wallet_child_start(&self, runtime: &tokio::runtime::Handle) -> Result<(), String> {
|
||||
self.ensure_running()?;
|
||||
let source = self.wallet_chain_source();
|
||||
if matches!(source, ChainSource::None) {
|
||||
|
|
@ -687,7 +701,8 @@ impl Node {
|
|||
return Err("wallet child already running".into());
|
||||
}
|
||||
let child = WalletChild::new(source, self.home.join("wallet"), None)
|
||||
.map_err(|e| e.to_string())?;
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_runtime(runtime.clone());
|
||||
let client = {
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
match child.start(&store) {
|
||||
|
|
@ -748,13 +763,13 @@ impl Node {
|
|||
}
|
||||
}
|
||||
|
||||
/// Free space on the filesystem a *local* daemon would store the chain on,
|
||||
/// in whole GiB. `None` for a remote source (their disk, not ours) and when
|
||||
/// the answer cannot be read — never a guessed number.
|
||||
/// Free space on the filesystem a *local* daemon would store the chain on
|
||||
/// — the spawned `monerod`'s or the in-process Cuprate node's, same
|
||||
/// directory — in whole GiB. `None` for a remote source (their disk, not
|
||||
/// ours) and when the answer cannot be read — never a guessed number.
|
||||
pub fn wallet_chain_free_gb(&self) -> Option<u64> {
|
||||
let ChainSource::Local { datadir, .. } = &self.wallet_chain_source() else {
|
||||
return None;
|
||||
};
|
||||
let source = self.wallet_chain_source();
|
||||
let datadir = WalletChild::chain_datadir(&source)?;
|
||||
// monerod creates the datadir on first run; before that, the volume that
|
||||
// will hold it is the one `home` is on.
|
||||
let path = if datadir.exists() { datadir } else { &self.home };
|
||||
|
|
|
|||
51
src/tui.rs
51
src/tui.rs
|
|
@ -1425,31 +1425,41 @@ pub const PRUNED_NOTE: &str = "pruned nodes are not archives: a deep seed restor
|
|||
pub const ONION_NO_SOCKS_MSG: &str =
|
||||
"a remote .onion daemon needs a local SOCKS listener.\nthis build does not have one yet — pick a local monerod,\nor a clearnet/loopback daemon you run yourself.";
|
||||
|
||||
/// The three choices the picker offers, in order. A public node is never one of
|
||||
/// The four choices the picker offers, in order. A public node is never one of
|
||||
/// them and a remote daemon is never preselected.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ChainChoice {
|
||||
ReceiveOnly,
|
||||
LocalMonerod,
|
||||
InProcessCuprate,
|
||||
RemoteDaemon,
|
||||
}
|
||||
|
||||
impl ChainChoice {
|
||||
pub const ALL: [ChainChoice; 3] = [Self::ReceiveOnly, Self::LocalMonerod, Self::RemoteDaemon];
|
||||
pub const ALL: [ChainChoice; 4] = [
|
||||
Self::ReceiveOnly,
|
||||
Self::LocalMonerod,
|
||||
Self::InProcessCuprate,
|
||||
Self::RemoteDaemon,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::ReceiveOnly => "receive-only (no daemon)",
|
||||
Self::LocalMonerod => "spawn a local monerod",
|
||||
Self::InProcessCuprate => "run an in-process daemon",
|
||||
Self::RemoteDaemon => "enter a daemon address",
|
||||
}
|
||||
}
|
||||
|
||||
/// One line under the label, so the choice is not a mystery.
|
||||
/// One line under the label, so the choice is not a mystery. The in-process
|
||||
/// row carries [`crate::cuprate::TESTNET_ONLY`]'s fact: it is not a daemon
|
||||
/// the user can treat as a mainnet node yet.
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Self::ReceiveOnly => "chain traffic stays off this device entirely",
|
||||
Self::LocalMonerod => "the app owns monerod; chain stays on this device",
|
||||
Self::InProcessCuprate => "Cuprate in this app: testnet only, no binary",
|
||||
Self::RemoteDaemon => "someone else's daemon: they see your addresses",
|
||||
}
|
||||
}
|
||||
|
|
@ -1460,6 +1470,7 @@ impl ChainChoice {
|
|||
match source {
|
||||
ChainSource::None => Self::ReceiveOnly,
|
||||
ChainSource::Local { .. } => Self::LocalMonerod,
|
||||
ChainSource::InProcessCuprate { .. } => Self::InProcessCuprate,
|
||||
ChainSource::Remote { .. } => Self::RemoteDaemon,
|
||||
}
|
||||
}
|
||||
|
|
@ -1598,6 +1609,13 @@ pub fn chain_view_with_progress(
|
|||
monerod_bin.display(),
|
||||
datadir.display()
|
||||
),
|
||||
ChainSource::InProcessCuprate { datadir } => format!(
|
||||
// The caveat is not decoration: this daemon runs testnet, and a
|
||||
// user who reads it as a mainnet node would be misled.
|
||||
"chain: in-process daemon — {}; chain in {}",
|
||||
crate::cuprate::TESTNET_ONLY,
|
||||
datadir.display()
|
||||
),
|
||||
ChainSource::Remote { host, port } => format!("chain: remote daemon {host}:{port}"),
|
||||
};
|
||||
let child_line = match child {
|
||||
|
|
@ -1608,10 +1626,14 @@ pub fn chain_view_with_progress(
|
|||
.to_string();
|
||||
let sync_text = sync_line(sync, previous_height);
|
||||
let storage_line = match (source, free_gb) {
|
||||
(ChainSource::Local { .. }, Some(gb)) => format!(
|
||||
// Both local sources put the chain on this device's disk; only the
|
||||
// *owner* of the daemon differs.
|
||||
(ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. }, Some(gb)) => format!(
|
||||
"storage: {gb} GB free here — pruned mainnet wants ~50-60 GB, a full node ~200 GB"
|
||||
),
|
||||
(ChainSource::Local { .. }, None) => "storage: could not read free space".to_string(),
|
||||
(ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. }, None) => {
|
||||
"storage: could not read free space".to_string()
|
||||
}
|
||||
(ChainSource::Remote { .. }, _) => {
|
||||
"storage: on the daemon operator's disk, not yours".to_string()
|
||||
}
|
||||
|
|
@ -1715,6 +1737,13 @@ impl App {
|
|||
continue;
|
||||
}
|
||||
if let Some(exit) = self.handle_key(key)? {
|
||||
// The children this app owns are not detached. Without this,
|
||||
// `monero-wallet-rpc` (and a spawned `monerod`) would outlive the
|
||||
// app as orphans, and an in-process Cuprate node would never get
|
||||
// its shutdown asked for.
|
||||
if let Err(e) = self.node.wallet_child_stop() {
|
||||
eprintln!("wallet child on exit: {e}");
|
||||
}
|
||||
return Ok(exit);
|
||||
}
|
||||
}
|
||||
|
|
@ -2315,7 +2344,7 @@ impl App {
|
|||
}
|
||||
let result = match self.node.wallet_child_state() {
|
||||
WalletChildState::Running => self.node.wallet_child_stop(),
|
||||
_ => self.node.wallet_child_start(),
|
||||
_ => self.node.wallet_child_start(&self.rt),
|
||||
};
|
||||
self.status_note = Some(match result {
|
||||
Ok(()) => match self.node.wallet_child_state() {
|
||||
|
|
@ -2386,6 +2415,16 @@ impl App {
|
|||
let source = self.node.default_local_chain_source();
|
||||
self.apply_chain_source(source, None);
|
||||
}
|
||||
ChainChoice::InProcessCuprate => {
|
||||
let source = self.node.default_in_process_chain_source();
|
||||
// The saved note says the caveat again: the picker's row is
|
||||
// gone once this screen closes.
|
||||
let note = format!(
|
||||
"chain source saved — in-process daemon, {}",
|
||||
crate::cuprate::TESTNET_ONLY
|
||||
);
|
||||
self.apply_chain_source(source, Some(note));
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,17 @@ pub enum ChainSource {
|
|||
/// not a constant.
|
||||
port: u16,
|
||||
},
|
||||
/// 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-1.0 and its mainnet RPC parity is unvalidated).
|
||||
InProcessCuprate {
|
||||
/// Data directory for the daemon's chain database.
|
||||
datadir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
/// Remote-mode wallet config: the `monero-wallet-rpc` the user already runs
|
||||
|
|
|
|||
|
|
@ -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, either `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:
|
||||
//!
|
||||
|
|
@ -12,6 +13,9 @@
|
|||
//! compiled-in public node. A `.onion` daemon needs a SOCKS proxy, which is a
|
||||
//! separate card: here it is refused with a clear error.
|
||||
//! * `--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 serves the same loopback RPC
|
||||
//! port, so everything downstream of `--daemon-address` is unchanged.
|
||||
|
||||
use std::fs;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
|
@ -22,11 +26,15 @@ use std::sync::Mutex;
|
|||
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. This is the *unrestricted*
|
||||
/// server (`--rpc-bind-port`); 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;
|
||||
|
||||
/// `monerod`'s *restricted* RPC port (`--rpc-restricted-bind-port`). Nothing in
|
||||
|
|
@ -60,7 +68,8 @@ impl std::error::Error for ChildError {}
|
|||
|
||||
type Result<T> = std::result::Result<T, ChildError>;
|
||||
|
||||
/// The app-owned wallet child pair (`monerod` when local, `monero-wallet-rpc`).
|
||||
/// The app-owned wallet child pair (`monerod` when local, `monero-wallet-rpc`),
|
||||
/// plus the in-process chain daemon when that is the chosen source.
|
||||
pub struct WalletChild {
|
||||
source: ChainSource,
|
||||
wallet_rpc_bin: PathBuf,
|
||||
|
|
@ -68,6 +77,14 @@ pub struct WalletChild {
|
|||
wallet_filename: String,
|
||||
monerod: 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>>,
|
||||
/// The app's Tokio handle. Required only to launch the in-process daemon:
|
||||
/// its tasks run on the app's runtime, and [`WalletChild::start`] is called
|
||||
/// from the TUI's blocking thread, which has no runtime context of its own.
|
||||
runtime: Option<tokio::runtime::Handle>,
|
||||
}
|
||||
|
||||
impl WalletChild {
|
||||
|
|
@ -93,9 +110,18 @@ impl WalletChild {
|
|||
wallet_filename,
|
||||
monerod: Mutex::new(None),
|
||||
wallet_rpc: Mutex::new(None),
|
||||
cuprate: Mutex::new(None),
|
||||
runtime: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The app's runtime, needed by [`ChainSource::InProcessCuprate`]. Without
|
||||
/// it, starting that source fails with a reason rather than blocking.
|
||||
pub fn with_runtime(mut self, runtime: tokio::runtime::Handle) -> Self {
|
||||
self.runtime = Some(runtime);
|
||||
self
|
||||
}
|
||||
|
||||
/// Point at a specific `monero-wallet-rpc` binary (explicit config, tests).
|
||||
pub fn with_wallet_rpc_bin(mut self, bin: PathBuf) -> Self {
|
||||
self.wallet_rpc_bin = bin;
|
||||
|
|
@ -122,8 +148,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)
|
||||
}
|
||||
|
||||
/// True when a tracked *child* (monerod / monero-wallet-rpc) is 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.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
|
||||
}
|
||||
|
|
@ -154,16 +189,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, 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> {
|
||||
|
|
@ -258,6 +307,12 @@ impl WalletChild {
|
|||
*guard = Some(child);
|
||||
}
|
||||
|
||||
// In-process chain source: start the daemon in this process, before the
|
||||
// wallet child is pointed at its loopback RPC.
|
||||
if let ChainSource::InProcessCuprate { datadir } = &self.source {
|
||||
self.start_in_process_daemon(datadir)?;
|
||||
}
|
||||
|
||||
let (user, pass) = self.creds(store)?;
|
||||
let port = Self::pick_port()?;
|
||||
let login = format!("{user}:{}", pass.as_str());
|
||||
|
|
@ -289,9 +344,52 @@ impl WalletChild {
|
|||
}))
|
||||
}
|
||||
|
||||
/// Launch the in-process Cuprate daemon and hold it.
|
||||
///
|
||||
/// Blocking on the app's runtime from this thread is deliberate: `start` runs
|
||||
/// on the TUI's blocking thread (no runtime context of its own), and the
|
||||
/// app's runtime is alive for the whole session, so its worker threads drive
|
||||
/// the node's services while this call waits for `launch` to return.
|
||||
fn start_in_process_daemon(&self, datadir: &Path) -> Result<()> {
|
||||
// Feature first: in a build without it, "no runtime handle" would be a
|
||||
// misleading answer to "why is there no daemon".
|
||||
if !crate::cuprate::available() {
|
||||
return Err(ChildError(crate::cuprate::NO_FEATURE_MSG.into()));
|
||||
}
|
||||
// Resolve the runtime before touching the disk: a refusal must leave
|
||||
// nothing behind.
|
||||
let runtime = self.runtime.as_ref().ok_or_else(|| {
|
||||
ChildError("in-process daemon needs the app's Tokio runtime handle".into())
|
||||
})?;
|
||||
create_dir_700(datadir).map_err(|e| ChildError(format!("chain datadir: {e}")))?;
|
||||
let node = runtime
|
||||
.block_on(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 both children. Idempotent, and tolerant of a child that already
|
||||
/// exited on its own.
|
||||
/// exited on its own. The in-process daemon goes first: it is not a process,
|
||||
/// and dropping it is its shutdown.
|
||||
pub fn stop(&self) -> Result<()> {
|
||||
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, and dropping alone would cut them off. (Bind and let it
|
||||
// drop rather than `drop(node)`: without the feature this type has
|
||||
// no `Drop` impl at all, and `clippy::drop_non_drop` is right to say
|
||||
// so.)
|
||||
node.shutdown();
|
||||
}
|
||||
kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?;
|
||||
kill_slot(&self.monerod, "monerod")?;
|
||||
Ok(())
|
||||
|
|
@ -438,6 +536,10 @@ fn source_to_json(source: &ChainSource) -> serde_json::Value {
|
|||
"host": host,
|
||||
"port": port,
|
||||
}),
|
||||
ChainSource::InProcessCuprate { datadir } => serde_json::json!({
|
||||
"kind": "cuprate",
|
||||
"datadir": datadir.display().to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -455,6 +557,9 @@ fn parse_source(v: Option<&serde_json::Value>) -> Option<ChainSource> {
|
|||
host: v.get("host")?.as_str()?.to_string(),
|
||||
port: u16::try_from(v.get("port")?.as_u64()?).ok()?,
|
||||
}),
|
||||
"cuprate" => Some(ChainSource::InProcessCuprate {
|
||||
datadir: PathBuf::from(v.get("datadir")?.as_str()?),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
|
@ -956,6 +1061,131 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn the_in_process_source_is_a_local_daemon_on_the_same_port() {
|
||||
let datadir = PathBuf::from("/tmp/onionwire-chain");
|
||||
let source = ChainSource::InProcessCuprate {
|
||||
datadir: datadir.clone(),
|
||||
};
|
||||
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_source(Path::new("/tmp"), PathBuf::from("monerod"))),
|
||||
"spawned and in-process local sources are the same address"
|
||||
);
|
||||
assert_eq!(
|
||||
WalletChild::chain_datadir(&source),
|
||||
Some(datadir.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"
|
||||
);
|
||||
let dir = tmp_dir("cuprate-enabled");
|
||||
assert!(
|
||||
WalletChild::new(source, dir.join("wallet"), None)
|
||||
.unwrap()
|
||||
.is_enabled(),
|
||||
"an in-process source is a chain source: `n` must have something to start"
|
||||
);
|
||||
}
|
||||
|
||||
/// The picker's choice has to survive a restart without a child ever
|
||||
/// starting, exactly like the other two.
|
||||
#[test]
|
||||
fn the_in_process_choice_round_trips_through_the_sealed_record() {
|
||||
let dir = tmp_dir("source-cuprate");
|
||||
let store = open_store(&dir);
|
||||
let source = ChainSource::InProcessCuprate {
|
||||
datadir: dir.join("chain"),
|
||||
};
|
||||
save_chain_source(&store, &source).unwrap();
|
||||
assert_eq!(load_chain_source(&store).unwrap(), Some(source.clone()));
|
||||
// ...and it is read back as itself, never as receive-only.
|
||||
assert_ne!(load_chain_source(&store).unwrap(), Some(ChainSource::None));
|
||||
|
||||
// The stored record names the source for the next reader, too.
|
||||
let raw = store.load_wallet_child().unwrap().expect("sealed record");
|
||||
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(),
|
||||
source_datadir(&source)
|
||||
);
|
||||
}
|
||||
|
||||
fn source_datadir(source: &ChainSource) -> &str {
|
||||
match source {
|
||||
ChainSource::InProcessCuprate { datadir } => datadir.to_str().unwrap(),
|
||||
other => panic!("not an in-process source: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starting the in-process source without the daemon compiled in fails with
|
||||
/// the feature name — 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 child = WalletChild::new(
|
||||
ChainSource::InProcessCuprate {
|
||||
datadir: dir.join("chain"),
|
||||
},
|
||||
dir.join("wallet"),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &dir.join("rpc.argv")));
|
||||
let err = child.start(&store).unwrap_err().to_string();
|
||||
assert!(err.contains("cuprate-daemon"), "got {err}");
|
||||
assert!(!child.running(), "nothing may be left running: {err}");
|
||||
assert_eq!(
|
||||
fs::read_to_string(dir.join("rpc.argv")).unwrap_or_default(),
|
||||
"",
|
||||
"the wallet RPC child must not be spawned against a daemon that never started"
|
||||
);
|
||||
child.stop().unwrap();
|
||||
}
|
||||
|
||||
/// With the daemon compiled in, the missing piece is the app's runtime
|
||||
/// handle, and the refusal says which one it is.
|
||||
#[cfg(feature = "cuprate-daemon")]
|
||||
#[test]
|
||||
fn in_process_source_without_a_runtime_handle_says_so() {
|
||||
let dir = tmp_dir("cuprate-no-rt");
|
||||
let store = open_store(&dir);
|
||||
let child = WalletChild::new(
|
||||
ChainSource::InProcessCuprate {
|
||||
datadir: dir.join("chain"),
|
||||
},
|
||||
dir.join("wallet"),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let err = child.start(&store).unwrap_err().to_string();
|
||||
assert!(err.contains("runtime"), "got {err}");
|
||||
assert!(!child.running(), "nothing may be left running: {err}");
|
||||
// No daemon, no datadir either: the refusal happens before any of it.
|
||||
assert!(
|
||||
!dir.join("chain").exists(),
|
||||
"an unstarted source writes nothing"
|
||||
);
|
||||
}
|
||||
|
||||
/// A record with an unknown `kind` is receive-only; a corrupt record is an
|
||||
/// error (fail-closed — do not silently overwrite it).
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -819,10 +819,22 @@ fn chain_choice_never_preselects_a_remote_daemon() {
|
|||
},
|
||||
ChainChoice::RemoteDaemon,
|
||||
),
|
||||
// The in-process daemon is its own row: it is local (this device's
|
||||
// chain, this app's process) but it is not a `monerod` spawn.
|
||||
(
|
||||
ChainSource::InProcessCuprate {
|
||||
datadir: std::path::PathBuf::from("/tmp/chain"),
|
||||
},
|
||||
ChainChoice::InProcessCuprate,
|
||||
),
|
||||
] {
|
||||
assert_eq!(ChainChoice::of(&source), want);
|
||||
}
|
||||
assert_eq!(ChainChoice::ALL.len(), 3, "three choices, never a public node");
|
||||
assert_eq!(
|
||||
ChainChoice::ALL.len(),
|
||||
4,
|
||||
"four choices, never a public node"
|
||||
);
|
||||
for choice in ChainChoice::ALL {
|
||||
assert!(!choice.label().is_empty());
|
||||
assert!(!choice.detail().is_empty());
|
||||
|
|
|
|||
1563
tests/tui_spec.rs
1563
tests/tui_spec.rs
File diff suppressed because it is too large
Load diff
103
tests/wallet.rs
103
tests/wallet.rs
|
|
@ -1348,6 +1348,109 @@ async fn a_transport_failure_is_not_a_height_error() {
|
|||
assert!(!err.is_height_out_of_range(), "{err}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The in-process chain daemon (feature `cuprate-daemon`).
|
||||
//
|
||||
// The only 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. It needs no network — a testnet node with no peers answers RPC and
|
||||
// stays at genesis.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `WalletChild::pick_port` is the app's own "give me a free loopback port".
|
||||
#[cfg(feature = "cuprate-daemon")]
|
||||
fn freed_port() -> u16 {
|
||||
onionwire::wallet_child::WalletChild::pick_port().expect("free loopback port")
|
||||
}
|
||||
|
||||
#[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_port();
|
||||
let addr = format!("127.0.0.1:{port}");
|
||||
|
||||
let mut node = onionwire::cuprate::CuprateNode::launch(&datadir, port)
|
||||
.await
|
||||
.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 budget = Duration::from_secs(5);
|
||||
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(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, 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, Duration::from_secs(30)).await;
|
||||
assert!(
|
||||
matches!(far, Err(WalletError::DaemonHeightOutOfRange)),
|
||||
"an above-the-tip height must map to the typed height error: {far:?}"
|
||||
);
|
||||
|
||||
// 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(Duration::from_millis(250)).await;
|
||||
}
|
||||
assert!(
|
||||
closed,
|
||||
"the unrestricted RPC was still accepting after shutdown"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_height_error_reports_itself_as_one() {
|
||||
assert!(WalletError::DaemonHeightOutOfRange.is_height_out_of_range());
|
||||
|
|
|
|||
Loading…
Reference in a new issue