monerod: spawn a pruned local monerod as the chain source
All checks were successful
ci / test (pull_request) Successful in 4m29s
ci / sdk (pull_request) Successful in 1m18s
android-ci / android (pull_request) Successful in 10m6s

docs/WALLET.md §Chain source offered "spawn a local monerod (pruned
on-device)" but nothing implemented it. Add src/monerod.rs: find monerod
on PATH, mkdir $ONIONWIRE_HOME/monero at 0700, spawn it with
--prune-blockchain --non-interactive and its RPC bound to 127.0.0.1:18089,
poll the port for readiness, and stop it with SIGTERM (SIGKILL after 10s).

Locks held: loopback-only RPC, no --trusted-daemon, no SOCKS, no C-tor,
no clearnet default, no UDP, no new dependency (std only — SIGTERM goes
through kill(1) because the crate takes no libc). A missing binary or a
port that never answers is an Err the node logs and shrugs off: no local
chain is the honest state, not a crash.

Node wires it opt-in via ONIONWIRE_MONEROD=1: start_monerod spawns on a
blocking task during start_with_passphrase, shutdown() takes the daemon
and stops it off the reactor, and monerod_rpc_addr() reports where the
wallet child should point --daemon-address.

Tests (7, in-module): argv is pruned/loopback and carries no forbidden
flag; PATH lookup needs an executable; empty PATH and a missing binary
both Err with a clear message (and the data dir is 0700); default addr is
127.0.0.1:18089; wait_for_ready times out against a dead port; a fake
daemon spawns, reports its addr, and stops via SIGTERM (its pid is gone).
This commit is contained in:
agent 2026-09-16 20:54:54 -04:00
commit cdaf403e94
No known key found for this signature in database
4 changed files with 523 additions and 1 deletions

View file

@ -27,6 +27,7 @@ document explains why, and what breaks when you do.
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
| `ONIONWIRE_MONEROD` | `1` / `true` / `yes` / `on` → OnionWire spawns a pruned local `monerod` as the chain source (option 1 below). Unset → no local chain; the wallet child uses whatever daemon you gave it. |
`README.md` carries the operator summary; this file is the long form.
@ -78,6 +79,31 @@ does not pick a public remote node for you.
Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable
→ receipts stay unverified and spend is refused. That is the honest state.
### Option 1 in practice: the in-app spawn
Set `ONIONWIRE_MONEROD=1` and the app starts the daemon itself — you do not run
`monerod` by hand. It looks for `monerod` on `PATH`, keeps its chain data in
`$ONIONWIRE_HOME/monero/` (mode 0700, never `/tmp` and never a shared location),
and starts it with `--prune-blockchain --non-interactive`, its RPC bound to
loopback only (`--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18089`), logging to
`$ONIONWIRE_HOME/monero/monerod.log`. The wallet child is pointed at that RPC
with `--daemon-address 127.0.0.1:18089`; which process runs the wallet RPC (and
how it is started) is separate from this and unchanged.
Zero trust is not optional here either: the spawn never passes
`--trusted-daemon`, and the daemon's RPC is loopback so only this machine can
talk to it. p2p is untouched (`monerod`'s own defaults, port 18081): a pruned
node still dials peers on the Monero network to sync, so "local daemon" means
you are not handing your addresses to someone else's node — it does not mean the
sync is offline.
On start the app waits up to 5s for the RPC port to answer. A missing binary or
a port that never comes up is **not** fatal: it is logged, no local chain is
assumed, and the wallet reports the unsynced state above. On shutdown the daemon
is SIGTERMed (SIGKILL after 10s). If you stop the app with SIGKILL, `monerod`
keeps running and keeps syncing; kill it yourself or leave it — the next start
reuses the same data dir.
## Create a view-only wallet
Either path produces a wallet file with the view key only. Keep the seed /

View file

@ -4,6 +4,7 @@ pub mod file;
pub mod frame;
pub mod hs;
pub mod loc;
pub mod monerod;
pub mod node;
pub mod outbox;
pub mod pay;

416
src/monerod.rs Normal file
View file

@ -0,0 +1,416 @@
//! Optional local `monerod` as the chain source (spawn + lifecycle).
//!
//! OnionWire never picks a public remote daemon: the chain source is either a
//! daemon the operator already runs, or this module's pruned `monerod` child on
//! loopback. The wallet child (`monero-wallet-rpc`) is a *separate* process —
//! this module only manages the daemon it is told to point `--daemon-address`
//! at (`Monerod::rpc_addr`).
//!
//! Locks, all pinned by tests:
//! - RPC binds `127.0.0.1:18089` only. No `--trusted-daemon`, no SOCKS, no
//! clearnet default, no UDP.
//! - `--prune-blockchain`: the on-device target is a pruned node, never an
//! archive. The operator accepts disk and first-sync time.
//! - `--data-dir` is `$ONIONWIRE_HOME/monero/`, created 0700 — never `/tmp`.
//! - A missing binary is an `Err`, and the caller is expected to fall back to
//! "no local chain" (the wallet then reports an honest unsynced state)
//! rather than aborting the app.
use std::ffi::OsStr;
use std::fs;
use std::net::{Ipv4Addr, SocketAddr, TcpStream};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
/// `monerod`'s default RPC port. We bind it, loopback-only.
pub const RPC_PORT: u16 = 18089;
/// `monerod`'s default p2p port, for the operator's reference. Peer dials keep
/// monerod's own defaults; this module does not touch p2p.
pub const P2P_PORT: u16 = 18081;
const BINARY: &str = "monerod";
/// Numeric loopback literal — never `localhost`, which would `getaddrinfo`.
const RPC_BIND_IP: &str = "127.0.0.1";
/// How long [`Monerod::spawn`] waits for the RPC port before giving up.
pub const READY_TIMEOUT: Duration = Duration::from_secs(5);
const READY_POLL: Duration = Duration::from_millis(200);
const CONNECT_TIMEOUT: Duration = Duration::from_millis(250);
/// SIGTERM gets this long before SIGKILL.
const TERM_GRACE: Duration = Duration::from_secs(10);
const STOP_POLL: Duration = Duration::from_millis(100);
/// A local, pruned `monerod` child. Dropping it does not kill the process —
/// call [`Monerod::stop`] (the node does this on shutdown).
pub struct Monerod {
child: Child,
data_dir: PathBuf,
rpc_addr: SocketAddr,
}
/// Loopback RPC address for a port. The wallet child is pointed here with
/// `--daemon-address`.
pub fn rpc_addr(port: u16) -> SocketAddr {
SocketAddr::from((Ipv4Addr::LOCALHOST, port))
}
/// Poll `addr` until something listens, or `timeout` elapses.
///
/// A listening port is "ready enough": `monerod` binds RPC before it serves
/// blocks, and the wallet child reports its own sync progress from there. We do
/// not speak HTTP ourselves.
pub fn wait_for_ready(addr: SocketAddr, timeout: Duration) -> Result<(), String> {
let started = Instant::now();
loop {
if TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_ok() {
return Ok(());
}
if started.elapsed() >= timeout {
return Err(format!("no listener on {addr} after {timeout:?}"));
}
std::thread::sleep(READY_POLL);
}
}
/// Whether `path` is a file we could exec.
fn is_executable(path: &Path) -> bool {
fs::metadata(path)
.map(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
/// Resolve `name` in a `PATH`-style search path. `None` as the path, or no
/// executable match, is `None` — a directory entry that is not executable
/// (e.g. a `monerod` data dir) is not a binary.
fn find_in(name: &str, path: Option<&OsStr>) -> Option<PathBuf> {
let path = path?;
std::env::split_paths(path)
.map(|dir| dir.join(name))
.find(|candidate| is_executable(candidate))
}
/// Find `monerod` on `PATH`.
pub fn find_binary() -> Result<PathBuf, String> {
find_in(BINARY, std::env::var_os("PATH").as_deref()).ok_or_else(not_on_path)
}
fn not_on_path() -> String {
"monerod not found on PATH — install monero, or point the wallet child at a \
daemon address you supply"
.to_string()
}
/// The argv for the daemon. Pure, so the locks are testable.
fn args(data_dir: &Path) -> Vec<String> {
let data_dir = data_dir.display().to_string();
vec![
"--data-dir".into(),
data_dir.clone(),
"--non-interactive".into(),
"--prune-blockchain".into(),
"--rpc-bind-ip".into(),
RPC_BIND_IP.into(),
"--rpc-bind-port".into(),
RPC_PORT.to_string(),
"--log-file".into(),
Path::new(&data_dir)
.join("monerod.log")
.display()
.to_string(),
]
}
/// `mkdir -p` + `chmod 0700`, the `store::mkdir_700` idiom.
fn mkdir_700(path: &Path) -> Result<(), String> {
fs::create_dir_all(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut perms = fs::metadata(path)
.map_err(|e| format!("{}: {e}", path.display()))?
.permissions();
perms.set_mode(0o700);
fs::set_permissions(path, perms).map_err(|e| format!("{}: {e}", path.display()))?;
Ok(())
}
impl Monerod {
/// Spawn a pruned local `monerod` under `home` and wait for its RPC port.
///
/// `Err` means "no local chain": a missing binary, a data dir we cannot
/// create, or an RPC port that never came up (the child is stopped before
/// returning). The caller falls back; the wallet then reports unsynced.
pub fn spawn(home: &Path) -> Result<Self, String> {
Self::spawn_with_path(home, std::env::var_os("PATH").as_deref())
}
fn spawn_with_path(home: &Path, path: Option<&OsStr>) -> Result<Self, String> {
let binary = find_in(BINARY, path).ok_or_else(not_on_path)?;
Self::spawn_binary(&binary, home)
}
fn spawn_binary(binary: &Path, home: &Path) -> Result<Self, String> {
let me = Self::spawn_process(binary, home)?;
let addr = me.rpc_addr();
if let Err(e) = wait_for_ready(addr, READY_TIMEOUT) {
let _ = me.stop();
return Err(format!("monerod never answered on {addr}: {e}"));
}
Ok(me)
}
/// Create the chain data dir (0700) and start the child, without waiting.
fn spawn_process(binary: &Path, home: &Path) -> Result<Self, String> {
let data_dir = home.join("monero");
mkdir_700(&data_dir)?;
let child = Command::new(binary)
.args(args(&data_dir))
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("spawn {}: {e}", binary.display()))?;
Ok(Self {
child,
data_dir,
rpc_addr: rpc_addr(RPC_PORT),
})
}
/// Where the wallet child should be pointed (`--daemon-address`).
pub fn rpc_addr(&self) -> SocketAddr {
self.rpc_addr
}
/// `$ONIONWIRE_HOME/monero/` — the chain data this process owns.
pub fn data_dir(&self) -> &Path {
&self.data_dir
}
/// SIGTERM, then SIGKILL after [`TERM_GRACE`]; reap the child.
///
/// `Err` means we could not signal or reap it — the chain is then in an
/// unknown state and must not be reported as cleanly stopped.
pub fn stop(mut self) -> Result<(), String> {
if matches!(self.child.try_wait(), Ok(Some(_))) {
return Ok(());
}
// std has no signal API and this crate takes no libc dependency, so
// SIGTERM goes through `kill(1)`. If that is unavailable, SIGKILL.
if !sigterm(self.child.id()) {
self.child
.kill()
.map_err(|e| format!("kill monerod: {e}"))?;
}
let started = Instant::now();
loop {
match self.child.try_wait() {
Ok(Some(_)) => return Ok(()),
Ok(None) => {}
Err(e) => return Err(format!("wait monerod: {e}")),
}
if started.elapsed() >= TERM_GRACE {
self.child
.kill()
.map_err(|e| format!("kill monerod: {e}"))?;
self.child
.wait()
.map_err(|e| format!("wait monerod: {e}"))?;
return Ok(());
}
std::thread::sleep(STOP_POLL);
}
}
}
fn sigterm(pid: u32) -> bool {
Command::new("kill")
.arg("-TERM")
.arg(pid.to_string())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use std::ffi::OsStr;
use std::net::TcpListener;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use super::*;
fn write_script(dir: &Path, name: &str, body: &str) -> PathBuf {
let path = dir.join(name);
std::fs::write(&path, body).expect("write script");
let mut perms = std::fs::metadata(&path).expect("metadata").permissions();
perms.set_mode(0o700);
std::fs::set_permissions(&path, perms).expect("chmod 0700");
path
}
fn alive(pid: u32) -> bool {
Command::new("kill")
.arg("-0")
.arg(pid.to_string())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[test]
fn args_are_pruned_loopback_rpc() {
let dir = Path::new("/home/op/.onionwire/monero");
let args = args(dir);
let joined = args.join(" ");
assert!(
joined.contains("--prune-blockchain"),
"pruned is the on-device target: {joined}"
);
assert!(
joined.contains("--rpc-bind-ip 127.0.0.1") && joined.contains("--rpc-bind-port 18089"),
"daemon RPC is loopback 18089 only: {joined}"
);
assert!(
joined.contains(&format!("--data-dir {}", dir.display())),
"data dir comes from the home we were handed: {joined}"
);
// Zero trust, and no transport the threat model forbids.
for forbidden in [
"trusted-daemon",
"socks",
"proxy",
"udp",
"--bind-ip 0.0.0.0",
] {
assert!(
!joined.contains(forbidden),
"{forbidden} must never be a monerod arg: {joined}"
);
}
}
#[test]
fn find_in_requires_an_executable() {
let dir = tempfile::tempdir().expect("tempdir");
write_script(dir.path(), "monerod-not-exec", "#!/bin/sh\nexit 0\n");
let mut perms = std::fs::metadata(dir.path().join("monerod-not-exec"))
.expect("metadata")
.permissions();
perms.set_mode(0o600);
std::fs::set_permissions(dir.path().join("monerod-not-exec"), perms).expect("chmod");
let path = dir.path().as_os_str();
assert!(
find_in("monerod-not-exec", Some(path)).is_none(),
"a non-executable name match is not a binary"
);
assert!(
find_in("monerod-absent", Some(path)).is_none(),
"no file, no binary"
);
write_script(dir.path(), "monerod-exec", "#!/bin/sh\nexit 0\n");
assert_eq!(
find_in("monerod-exec", Some(path)),
Some(dir.path().join("monerod-exec")),
"an executable on PATH resolves"
);
}
#[test]
fn spawn_without_monerod_on_path_is_a_clear_error() {
let dir = tempfile::tempdir().expect("tempdir");
let empty = OsStr::new("");
let err = match Monerod::spawn_with_path(dir.path(), Some(empty)) {
Ok(_) => panic!("no monerod on PATH"),
Err(e) => e,
};
assert!(
err.contains("monerod") && err.contains("PATH"),
"the error names the missing binary and where we looked: {err}"
);
}
#[test]
fn spawn_process_missing_binary_errors_and_leaves_a_0700_data_dir() {
let dir = tempfile::tempdir().expect("tempdir");
let err = match Monerod::spawn_process(Path::new("/nonexistent/ow/monerod"), dir.path()) {
Ok(_) => panic!("no such binary"),
Err(e) => e,
};
assert!(err.contains("monerod"), "the error names the binary: {err}");
let data_dir = dir.path().join("monero");
let mode = std::fs::metadata(&data_dir)
.expect("data dir is created before the spawn is attempted")
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o700, "chain data dir is private");
}
#[test]
fn default_rpc_addr_is_loopback_18089() {
assert_eq!(RPC_PORT, 18089);
assert_eq!(P2P_PORT, 18081);
assert_eq!(READY_TIMEOUT, Duration::from_secs(5));
assert_eq!(
rpc_addr(RPC_PORT),
"127.0.0.1:18089".parse().expect("literal addr")
);
}
#[test]
fn wait_for_ready_times_out_without_a_listener() {
// A bound-then-dropped port: no listener, no risk of racing a real
// monerod on the default port.
let addr = {
let l = TcpListener::bind(("127.0.0.1", 0)).expect("bind");
let addr = l.local_addr().expect("local_addr");
drop(l);
addr
};
let start = Instant::now();
let err = wait_for_ready(addr, Duration::from_secs(1)).expect_err("nothing is listening");
let elapsed = start.elapsed();
assert!(err.contains("no listener"), "honest error: {err}");
assert!(
elapsed >= Duration::from_secs(1) && elapsed < Duration::from_secs(5),
"polls until its budget, then gives up: {elapsed:?}"
);
}
#[test]
fn a_spawned_daemon_reports_its_addr_and_stops() {
let dir = tempfile::tempdir().expect("tempdir");
let pidfile = dir.path().join("pid");
let script = write_script(
dir.path(),
"monerod",
&format!(
"#!/bin/sh\necho $$ > {}\nexec sleep 60\n",
pidfile.display()
),
);
let daemon = Monerod::spawn_process(&script, dir.path()).expect("spawn fake daemon");
assert_eq!(daemon.rpc_addr(), "127.0.0.1:18089".parse().expect("addr"));
assert_eq!(daemon.data_dir(), dir.path().join("monero"));
let pid = loop {
match std::fs::read_to_string(&pidfile) {
Ok(s) => break s.trim().parse::<u32>().expect("pid"),
Err(_) => {
std::thread::sleep(Duration::from_millis(50));
}
}
};
assert!(alive(pid), "fake daemon is running");
daemon.stop().expect("stop");
assert!(!alive(pid), "SIGTERM took the child down (pid {pid})");
}
}

View file

@ -1,5 +1,6 @@
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
@ -16,6 +17,7 @@ use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT, TorState};
use crate::loc;
use crate::monerod::Monerod;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
use crate::profile;
@ -78,6 +80,10 @@ pub struct Node {
onion: Mutex<String>,
keys: Mutex<Keys>,
wallet: Wallet,
/// Opt-in local chain source (`ONIONWIRE_MONEROD=1`). `None` is the honest
/// "no local chain": the wallet child then has whatever `--daemon-address`
/// the operator gave it, or none, and reports unsynced.
monerod: Mutex<Option<Monerod>>,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
@ -124,6 +130,7 @@ impl Node {
let (svc, rend) = launched;
let onion = hs::onion_string(&svc)?;
let inbox = file::Inbox::new(home.join("inbox"));
let monerod = start_monerod(&home).await;
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(
Arc::clone(&store),
@ -140,6 +147,7 @@ impl Node {
onion: Mutex::new(onion.clone()),
keys: Mutex::new(keys),
wallet: Wallet::from_env(),
monerod: Mutex::new(monerod),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
@ -213,7 +221,7 @@ impl Node {
/// Order matters: drain the outbox while the Tor client is still alive,
/// then drop the onion service (its rendezvous task is aborted and the v3
/// service goes down), then abort the retry worker so nothing dials after
/// this, then checkpoint the WAL.
/// this, then stop a spawned local chain source, then checkpoint the WAL.
///
/// Idempotent: the flag is swapped first, so a second call — or a call
/// racing another teardown — returns `Ok(())` without touching anything
@ -241,10 +249,40 @@ impl Node {
Ok(mut g) => drop(g.take()),
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
}
// Take the daemon out of the lock before awaiting: the guard must not
// live across `spawn_blocking`.
let daemon = match self.monerod.lock() {
Ok(mut g) => g.take(),
Err(_) => {
eprintln!("shutdown: monerod lock poisoned");
None
}
};
if let Some(daemon) = daemon {
let addr = daemon.rpc_addr();
// `stop` SIGTERMs and waits up to 10s for it: keep that off the
// reactor. A daemon we cannot stop is reported, not silently
// reported as clean.
match tokio::task::spawn_blocking(move || daemon.stop()).await {
Ok(Ok(())) => eprintln!("monerod: stopped {addr}"),
Ok(Err(e)) => eprintln!("monerod: {e}"),
Err(e) => eprintln!("monerod: stop task failed: {e}"),
}
}
self.checkpoint();
Ok(())
}
/// Where the spawned local chain source listens, if this node started one
/// (`ONIONWIRE_MONEROD=1`). This is what the wallet child is pointed at
/// with `--daemon-address`; `None` means no local chain.
pub fn monerod_rpc_addr(&self) -> Option<SocketAddr> {
self.monerod
.lock()
.ok()
.and_then(|g| g.as_ref().map(Monerod::rpc_addr))
}
/// One bounded pass over every outstanding outbox row.
///
/// A timeout cancels the pass mid-flight, which can leave a row in
@ -1175,6 +1213,47 @@ impl Node {
}
}
/// `ONIONWIRE_MONEROD=1` opts into a spawned, pruned local `monerod` as the
/// chain source. Failure is never fatal: the node starts, and the wallet child
/// reports the honest unsynced state.
async fn start_monerod(home: &Path) -> Option<Monerod> {
if !env_flag("ONIONWIRE_MONEROD") {
return None;
}
let home = home.to_path_buf();
// Spawning waits up to `monerod::READY_TIMEOUT` for the RPC port: not on
// the reactor.
match tokio::task::spawn_blocking(move || Monerod::spawn(&home)).await {
Ok(Ok(daemon)) => {
eprintln!(
"monerod: pruned chain source, rpc {} (data {})",
daemon.rpc_addr(),
daemon.data_dir().display()
);
Some(daemon)
}
Ok(Err(e)) => {
eprintln!("monerod: no local chain: {e}");
None
}
Err(e) => {
eprintln!("monerod: spawn task failed: {e}");
None
}
}
}
fn env_flag(name: &str) -> bool {
std::env::var(name)
.map(|v| {
matches!(
v.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
})
.unwrap_or(false)
}
fn spawn_rend(
node: Arc<Node>,
rend: impl futures::Stream<Item = tor_hsservice::RendRequest> + Send + 'static,