monerod: spawn a pruned local monerod as the chain source #91
4 changed files with 535 additions and 1 deletions
|
|
@ -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,34 @@ 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`. Point your wallet child at that RPC
|
||||
yourself — `--daemon-address 127.0.0.1:18089`, exactly like the daemon address in
|
||||
option 2 above. OnionWire does not configure the wallet child for you; the
|
||||
address is only *exposed* to callers as `Node::monerod_rpc_addr()`, so a wallet
|
||||
child left on its previous `--daemon-address` keeps using that one. 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 /
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
422
src/monerod.rs
Normal file
422
src/monerod.rs
Normal file
|
|
@ -0,0 +1,422 @@
|
|||
//! 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. Corollary: a port check cannot tell *whose* port it
|
||||
/// is — if something already listens on `addr` (an operator's own `monerod`),
|
||||
/// this returns `Ok` even though our child may have failed to bind. The
|
||||
/// effective state is still "a local chain on loopback `addr`".
|
||||
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::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");
|
||||
// The search path must be empty of `monerod`. `Some(OsStr::new(""))` is
|
||||
// NOT that: `split_paths("")` yields one empty element, which `Path::join`
|
||||
// resolves to `./monerod` in the test's cwd (so a `monerod` sitting in the
|
||||
// crate root would be found). Point at an empty directory instead.
|
||||
let empty = dir.path().as_os_str();
|
||||
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})");
|
||||
}
|
||||
}
|
||||
84
src/node.rs
84
src/node.rs
|
|
@ -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};
|
||||
|
|
@ -19,6 +20,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;
|
||||
|
|
@ -82,6 +84,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>,
|
||||
|
|
@ -128,6 +134,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),
|
||||
|
|
@ -144,6 +151,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),
|
||||
|
|
@ -217,7 +225,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
|
||||
|
|
@ -245,10 +253,41 @@ 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`). Exposed so a caller can point the wallet child
|
||||
/// here with `--daemon-address`; the node does not wire that up itself.
|
||||
/// `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
|
||||
|
|
@ -1336,6 +1375,47 @@ pub fn ingest_chat_frame(
|
|||
Ok(line.to_vec())
|
||||
}
|
||||
|
||||
/// `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,
|
||||
|
|
@ -1516,6 +1596,8 @@ mod tests {
|
|||
onion: Mutex::new("test.onion".to_string()),
|
||||
keys: Mutex::new(keys),
|
||||
wallet: Wallet::disabled(),
|
||||
// No local chain in tests: `Monerod::spawn` is never called here.
|
||||
monerod: Mutex::new(None),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(file::Inbox::new(home.join("inbox"))),
|
||||
outbox,
|
||||
|
|
|
|||
Loading…
Reference in a new issue