//! 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:` — 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 //! (`//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::() { s.clone() } else { "unknown panic".into() } } fn run_on_launch_thread(f: F) -> Result where F: FnOnce() -> Result + 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| Err(format!("cuprate panicked: {}", panic_message(&*p)))); 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, /// `None` only inside `Drop`, where it is taken out to be dropped first. node: Option, } 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 { let text = config_toml(datadir, port, network, prune); let (runtime, node) = run_on_launch_thread(move || launch_on_owned_runtime(&text))?; 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) .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" "# ) } #[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" ); } } } #[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 { 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};