Arti publishes these in lockstep. Bumped together: - arti-client 0.46 -> 0.49 (root + crates/onionwire-sdk, both lockfiles) - tor-cell, tor-hsservice, tor-rtcompat 0.46 -> 0.49 - safelog 0.9 -> 0.10 (same repo; 0.49's HsId implements safelog 0.10's DisplayRedacted, so the old direct pin broke display_redacted) Arti 0.49 (Arti 2.9.0, 2026-12-01) carries a medium-severity security fix (TROVE-2026-078, custom build flags) and two low-severity fixes. MSRV unchanged: Arti 0.49 needs rustc 1.92, the repo floor stays 1.98 (cuprate-daemon / tapes). Only docs/comments moved; src/hs.rs workarounds rechecked against 0.49: tor-hsservice OVERALL_UPLOAD_TIMEOUT is still 5 min (PUBLISH_WAIT 360s stands) and tor-config's Listen is still IP-only. Verified: cargo test --locked (173 lib + all integration suites), clippy --locked --all-targets -D warnings, SDK cargo test/clippy, live ignored tor_hs + two_node tests, and scripts/build-android-local.sh (APK + AAR).
448 lines
18 KiB
Rust
448 lines
18 KiB
Rust
//! In-process Monero chain daemon (Cuprate) as OnionWire's local chain source.
|
|
//!
|
|
//! This is the chain half of the wallet's "the app owns the daemon" story: the
|
|
//! daemon — P2P, consensus, RandomX — runs **in this process** instead of as a
|
|
//! spawned `monerod`. `monero-wallet-rpc` is still a child and is unchanged: it
|
|
//! dials the unrestricted loopback RPC that [`crate::wallet_child`] already
|
|
//! computes ([`DEFAULT_MONEROD_RPC_PORT`]), so no wallet-layer code moves.
|
|
//!
|
|
//! [`DEFAULT_MONEROD_RPC_PORT`]: crate::wallet_child::DEFAULT_MONEROD_RPC_PORT
|
|
//!
|
|
//! Locked facts this module encodes:
|
|
//!
|
|
//! * `cuprated` is a **git** dependency pinned to a revision, behind the
|
|
//! `cuprate-daemon` feature, which the Linux TUI default includes. A
|
|
//! `--no-default-features` build does not. 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.49, 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;
|
|
|
|
/// Android's default pthread stack is ~1 MiB; Cuprate + RandomX overflow it
|
|
/// and the launch thread dies before `tx.send`, which the UI reports as
|
|
/// "the launch thread died before answering". Same size on the tokio
|
|
/// workers that actually run consensus.
|
|
const LAUNCH_STACK: usize = 8 * 1024 * 1024;
|
|
|
|
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
|
|
if let Some(s) = payload.downcast_ref::<&str>() {
|
|
(*s).to_string()
|
|
} else if let Some(s) = payload.downcast_ref::<String>() {
|
|
s.clone()
|
|
} else {
|
|
"unknown panic".into()
|
|
}
|
|
}
|
|
|
|
/// Cuprate's `#[serde(default)]` fills missing nested structs via `Default`.
|
|
/// `ArtiConfig::default` (and `FileSystemConfig::default`) dereference
|
|
/// `CUPRATE_DATA_DIR` / `CUPRATE_CACHE_DIR`, which `unwrap()` `dirs::*`.
|
|
/// On Android `dirs-sys` has no getpwuid fallback and `HOME` is unset, so
|
|
/// those return `None`, the unwrap panics, and a second Start then hits
|
|
/// "LazyLock instance has previously been poisoned".
|
|
///
|
|
/// Point XDG at the chain datadir *before* parsing so those LazyLocks
|
|
/// initialize to a real path. Process-wide: OnionWire's own store is
|
|
/// `$ONIONWIRE_HOME`, not XDG.
|
|
fn seed_cuprate_xdg(datadir: &Path) {
|
|
let datadir = std::path::absolute(datadir).unwrap_or_else(|_| datadir.to_path_buf());
|
|
let home_needs_fix = match std::env::var_os("HOME") {
|
|
None => true,
|
|
Some(h) => Path::new(&h).parent().is_none(),
|
|
};
|
|
// SAFETY: called once on the dedicated cuprate launch thread before
|
|
// any other thread in this process reads these keys for Cuprate.
|
|
// OnionWire's store is `$ONIONWIRE_HOME`, not XDG.
|
|
unsafe {
|
|
// `dirs` ignores non-absolute XDG_* and falls through to HOME.
|
|
std::env::set_var("XDG_DATA_HOME", datadir.join("xdg-data"));
|
|
std::env::set_var("XDG_CACHE_HOME", datadir.join("xdg-cache"));
|
|
std::env::set_var("XDG_CONFIG_HOME", datadir.join("xdg-config"));
|
|
// HOME=/ (seen on some Androids) fails cuprate_helper::fs's
|
|
// "parent is some" assert even when XDG is set, if anything still
|
|
// reads HOME. Replace only a missing or root HOME.
|
|
if home_needs_fix {
|
|
std::env::set_var("HOME", &datadir);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn run_on_launch_thread<F, T>(f: F) -> Result<T, String>
|
|
where
|
|
F: FnOnce() -> Result<T, String> + Send + 'static,
|
|
T: Send + 'static,
|
|
{
|
|
let (tx, rx) = mpsc::channel();
|
|
std::thread::Builder::new()
|
|
.name("onionwire-cuprate".into())
|
|
.stack_size(LAUNCH_STACK)
|
|
.spawn(move || {
|
|
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
|
|
.unwrap_or_else(|p| {
|
|
let msg = panic_message(&*p);
|
|
if msg.contains("previously been poisoned") {
|
|
Err(format!(
|
|
"cuprate panicked: {msg} — force-stop the app; a previous panic poisoned process-wide init and cannot recover in-process"
|
|
))
|
|
} else {
|
|
Err(format!("cuprate panicked: {msg}"))
|
|
}
|
|
});
|
|
let _ = tx.send(result);
|
|
})
|
|
.map_err(|e| format!("launch thread: {e}"))?;
|
|
rx.recv()
|
|
.map_err(|_| "the launch thread died before answering".to_string())?
|
|
}
|
|
|
|
/// 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,
|
|
network: &str,
|
|
prune: bool,
|
|
) -> Result<Self, String> {
|
|
let text = config_toml(datadir, port, network, prune);
|
|
let datadir = datadir.to_path_buf();
|
|
let (runtime, node) =
|
|
run_on_launch_thread(move || launch_on_owned_runtime(&text, &datadir))?;
|
|
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,
|
|
datadir: &Path,
|
|
) -> Result<(tokio::runtime::Runtime, Node), String> {
|
|
seed_cuprate_xdg(datadir);
|
|
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)
|
|
.thread_stack_size(LAUNCH_STACK)
|
|
.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, network: &str, prune: bool) -> 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}
|
|
|
|
[storage.blockchain]
|
|
prune = {prune}
|
|
|
|
# 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"
|
|
|
|
# Explicit so serde does not call ArtiConfig::default(), which unwraps
|
|
# dirs::data_dir() (None on Android: no HOME, no getpwuid fallback).
|
|
[tor.arti]
|
|
directory_path = "{datadir}/arti"
|
|
"#,
|
|
)
|
|
}
|
|
|
|
#[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,
|
|
"Testnet",
|
|
false,
|
|
))
|
|
.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"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_panic_on_the_launch_thread_is_returned_as_an_error() {
|
|
let err = run_on_launch_thread(|| -> Result<(), String> { panic!("boom") })
|
|
.expect_err("a panic is an error, not a dead channel");
|
|
assert!(
|
|
err.contains("boom"),
|
|
"the panic payload has to reach the caller, got {err:?}"
|
|
);
|
|
assert!(
|
|
!err.contains("died before answering"),
|
|
"that string is only for a thread that never sent"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_toml_sets_arti_directory_so_default_does_not_touch_xdg() {
|
|
let text = config_toml(Path::new("/tmp/onionwire-chain"), 18081, "Mainnet", true);
|
|
assert!(
|
|
text.contains("[tor.arti]"),
|
|
"ArtiConfig::default unwraps dirs::data_dir(); on Android that is None"
|
|
);
|
|
assert!(
|
|
text.contains("/tmp/onionwire-chain/arti"),
|
|
"directory_path must be the chain datadir, got {text}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn seeding_xdg_lets_the_config_parse() {
|
|
let datadir = Path::new("/tmp/onionwire-chain");
|
|
seed_cuprate_xdg(datadir);
|
|
let mut config: Config = toml::from_str(&config_toml(datadir, 18081, "Testnet", false))
|
|
.expect("parse after xdg seed");
|
|
resolve_max_memory(&mut config).expect("target_max_memory is set");
|
|
assert_eq!(
|
|
config.fjall_directory(),
|
|
Path::new("/tmp/onionwire-chain/testnet/fjall")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_poisoned_lazylock_panic_tells_the_user_to_force_stop() {
|
|
let err = run_on_launch_thread(|| -> Result<(), String> {
|
|
panic!("LazyLock instance has previously been poisoned")
|
|
})
|
|
.expect_err("a panic is an error");
|
|
assert!(
|
|
err.contains("force-stop the app"),
|
|
"poison is unrecoverable in-process, got {err:?}"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[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,
|
|
_network: &str,
|
|
_prune: bool,
|
|
) -> 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};
|