2415 lines
94 KiB
Rust
2415 lines
94 KiB
Rust
|
|
//! Wallet child lifecycle: the app owns `monero-wallet-rpc` — and, when the
|
||
|
|
//! user chose a local chain source, `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:
|
||
|
|
//!
|
||
|
|
//! * The wallet child speaks loopback HTTP Digest only
|
||
|
|
//! (`--rpc-bind-ip 127.0.0.1`, a random free port, generated `--rpc-login`).
|
||
|
|
//! * The RPC credentials are generated once, sealed with the store data key and
|
||
|
|
//! kept in the encrypted SQLCipher store. They are never a plaintext file.
|
||
|
|
//! * The chain source is the user's explicit choice ([`ChainSource`]) — never a
|
||
|
|
//! compiled-in public node.
|
||
|
|
//! * A `.onion` daemon is reached through a SOCKS child: the bundled `arti`
|
||
|
|
//! binary run as `arti proxy -p <port>`, with **TCP loopback only** (arti
|
||
|
|
//! 2.6.0 / tor-config 0.46 have no AF_UNIX listener — `Listen` is IP-only and
|
||
|
|
//! arti's `port_info` says AF_UNIX is future work, arti#1965). The wallet
|
||
|
|
//! child is then pointed at it with `--proxy socks5://127.0.0.1:<port>`
|
||
|
|
//! *and* `--daemon-address <onion>:<port>`. The messenger's in-process
|
||
|
|
//! `arti-client` is never handed to the wallet child, and C-tor is never
|
||
|
|
//! used.
|
||
|
|
//! * The two Tor clients do not share state: the SOCKS child gets its own
|
||
|
|
//! `state_dir`/`cache_dir` under the wallet dir.
|
||
|
|
//! * `--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 binds the same loopback RPC
|
||
|
|
//! port, so everything downstream of `--daemon-address` is unchanged.
|
||
|
|
|
||
|
|
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};
|
||
|
|
use std::sync::Mutex;
|
||
|
|
use std::time::{Duration, Instant};
|
||
|
|
|
||
|
|
use rand::RngCore;
|
||
|
|
use zeroize::Zeroizing;
|
||
|
|
|
||
|
|
use crate::cuprate::CuprateNode;
|
||
|
|
use crate::store::Store;
|
||
|
|
use crate::wallet::{self, ChainNetwork, ChainSource, Wallet};
|
||
|
|
|
||
|
|
/// `monerod` RPC port for a local chain source. Unrestricted RPC default; 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;
|
||
|
|
|
||
|
|
/// Name of the `monero-wallet-rpc` binary when the caller does not point at one.
|
||
|
|
pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc";
|
||
|
|
|
||
|
|
/// Name of the `arti` binary the SOCKS child runs when the caller does not
|
||
|
|
/// point at one. `arti proxy -p <port>`; there is no in-process SOCKS listener.
|
||
|
|
pub const DEFAULT_ARTI_BIN: &str = "arti";
|
||
|
|
|
||
|
|
/// How long the app waits for the SOCKS listener to accept a connection before
|
||
|
|
/// it gives up and reports the failure instead of spawning a wallet child that
|
||
|
|
/// can only hang. Arti binds its listener before it bootstraps (bootstrap is
|
||
|
|
/// on-demand), so this is a listener budget, not a Tor-bootstrap budget.
|
||
|
|
pub const SOCKS_READY_TIMEOUT: Duration = Duration::from_secs(20);
|
||
|
|
|
||
|
|
/// Per-attempt connect budget for the SOCKS readiness probe.
|
||
|
|
pub const SOCKS_PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||
|
|
|
||
|
|
/// Gap between readiness-probe attempts.
|
||
|
|
pub const SOCKS_PROBE_INTERVAL: Duration = Duration::from_millis(100);
|
||
|
|
|
||
|
|
/// How long `start_children` waits for the app-owned chain daemon to accept a
|
||
|
|
/// TCP connection after `Node::launch` (or the `monerod` spawn) returned.
|
||
|
|
///
|
||
|
|
/// This is a `connect()`-accepted budget, not a Tor-bootstrap or chain-sync
|
||
|
|
/// budget: the spike saw Cuprate's unrestricted listener accept within ~0.2s of
|
||
|
|
/// `launch` returning. A longer wait only makes Start look dead again.
|
||
|
|
pub const DAEMON_LISTENER_TIMEOUT: Duration = Duration::from_secs(5);
|
||
|
|
|
||
|
|
/// How long `start_children` waits for its own `monero-wallet-rpc` to accept a
|
||
|
|
/// TCP connection before handing the client back. Same reasoning as
|
||
|
|
/// [`DAEMON_LISTENER_TIMEOUT`]: the child binds its port a moment after
|
||
|
|
/// `spawn` returns.
|
||
|
|
pub const WALLET_RPC_LISTENER_TIMEOUT: Duration = Duration::from_secs(5);
|
||
|
|
|
||
|
|
/// The scheme Monero's `--proxy` needs for SOCKS5. A bare `host:port` means
|
||
|
|
/// SOCKS4a (docs/proxies.md), which is *not* what this app asks for.
|
||
|
|
pub const SOCKS5_SCHEME: &str = "socks5://";
|
||
|
|
|
||
|
|
/// Errors from wallet child setup and lifecycle.
|
||
|
|
#[derive(Debug)]
|
||
|
|
pub struct ChildError(String);
|
||
|
|
|
||
|
|
impl std::fmt::Display for ChildError {
|
||
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
|
|
self.0.fmt(f)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl std::error::Error for ChildError {}
|
||
|
|
|
||
|
|
type Result<T> = std::result::Result<T, ChildError>;
|
||
|
|
|
||
|
|
/// The app-owned wallet child set (`monerod` when local, `arti proxy` when the
|
||
|
|
/// daemon is a `.onion`, `monero-wallet-rpc` always unless `None`).
|
||
|
|
pub struct WalletChild {
|
||
|
|
source: ChainSource,
|
||
|
|
wallet_rpc_bin: PathBuf,
|
||
|
|
arti_bin: PathBuf,
|
||
|
|
wallet_dir: PathBuf,
|
||
|
|
wallet_filename: String,
|
||
|
|
/// Pinned SOCKS listen port. `None` (the default) means a random free
|
||
|
|
/// loopback port, exactly like the wallet RPC port.
|
||
|
|
socks_port: Option<u16>,
|
||
|
|
/// Readiness budget for the SOCKS listener. Tests shrink it; production
|
||
|
|
/// uses [`SOCKS_READY_TIMEOUT`].
|
||
|
|
socks_ready_timeout: Duration,
|
||
|
|
monerod: Mutex<Option<Child>>,
|
||
|
|
socks: 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>>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl WalletChild {
|
||
|
|
/// Configure the children. Nothing is spawned until [`WalletChild::start`].
|
||
|
|
///
|
||
|
|
/// `wallet_dir` is created 0700 and holds the wallet file plus the daemon
|
||
|
|
/// state; the caller passes `$ONIONWIRE_HOME/wallet`.
|
||
|
|
pub fn new(
|
||
|
|
source: ChainSource,
|
||
|
|
wallet_dir: PathBuf,
|
||
|
|
wallet_filename: Option<String>,
|
||
|
|
) -> Result<Self> {
|
||
|
|
let wallet_filename =
|
||
|
|
wallet_filename.unwrap_or_else(|| wallet::DEFAULT_WALLET_FILENAME.to_string());
|
||
|
|
if wallet_filename.trim().is_empty() {
|
||
|
|
return Err(ChildError("wallet filename required".into()));
|
||
|
|
}
|
||
|
|
create_dir_700(&wallet_dir).map_err(|e| ChildError(format!("wallet dir: {e}")))?;
|
||
|
|
Ok(Self {
|
||
|
|
source,
|
||
|
|
wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN),
|
||
|
|
arti_bin: PathBuf::from(DEFAULT_ARTI_BIN),
|
||
|
|
wallet_dir,
|
||
|
|
wallet_filename,
|
||
|
|
socks_port: None,
|
||
|
|
socks_ready_timeout: SOCKS_READY_TIMEOUT,
|
||
|
|
monerod: Mutex::new(None),
|
||
|
|
socks: Mutex::new(None),
|
||
|
|
wallet_rpc: Mutex::new(None),
|
||
|
|
cuprate: Mutex::new(None),
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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;
|
||
|
|
self
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Point at a specific `arti` binary (explicit config, tests).
|
||
|
|
pub fn with_arti_bin(mut self, bin: PathBuf) -> Self {
|
||
|
|
self.arti_bin = bin;
|
||
|
|
self
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Pin the SOCKS listen port instead of taking a random free loopback one.
|
||
|
|
/// Loopback only either way: `arti proxy -p <port>` binds `127.0.0.1` and
|
||
|
|
/// `::1` and nothing else.
|
||
|
|
pub fn with_socks_port(mut self, port: u16) -> Self {
|
||
|
|
self.socks_port = Some(port);
|
||
|
|
self
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Shrink the SOCKS readiness budget (tests).
|
||
|
|
pub fn with_socks_ready_timeout(mut self, budget: Duration) -> Self {
|
||
|
|
self.socks_ready_timeout = budget;
|
||
|
|
self
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The user's chain-source choice. `None` is receive-only: no child at all.
|
||
|
|
pub fn chain_source(&self) -> &ChainSource {
|
||
|
|
&self.source
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn wallet_dir(&self) -> &Path {
|
||
|
|
&self.wallet_dir
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn wallet_filename(&self) -> &str {
|
||
|
|
&self.wallet_filename
|
||
|
|
}
|
||
|
|
|
||
|
|
/// This child's own settings, in the persisted shape.
|
||
|
|
pub fn config(&self) -> ChildConfig {
|
||
|
|
ChildConfig {
|
||
|
|
source: self.source.clone(),
|
||
|
|
wallet_rpc_bin: self.wallet_rpc_bin.clone(),
|
||
|
|
arti_bin: self.arti_bin.clone(),
|
||
|
|
wallet_filename: self.wallet_filename.clone(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Whether this configuration spawns any child.
|
||
|
|
pub fn is_enabled(&self) -> bool {
|
||
|
|
!matches!(self.source, ChainSource::None)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Does this host name a Tor onion service? Only `.onion` daemons need the
|
||
|
|
/// SOCKS child; a loopback or clearnet host the user typed does not.
|
||
|
|
pub fn is_onion_host(host: &str) -> bool {
|
||
|
|
wallet::is_onion_host(host)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Is the `monero-wallet-rpc` child itself alive? The wallet RPC is the
|
||
|
|
/// process every wallet call goes through, so this — not "some child is up"
|
||
|
|
/// — is what decides `ready` vs `exited`.
|
||
|
|
pub fn wallet_rpc_running(&self) -> bool {
|
||
|
|
let _ = self.reap_exited();
|
||
|
|
self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The pid of the running `monero-wallet-rpc` child, when there is one.
|
||
|
|
///
|
||
|
|
/// Test-only: the lib test harness names *this* spawn's argv log with it.
|
||
|
|
/// The shared log path is written by every child and a previous child's
|
||
|
|
/// write is unsequenced against anything a test does, so a restarted
|
||
|
|
/// child's port cannot be learned from it (see `node::tests`).
|
||
|
|
#[cfg(test)]
|
||
|
|
pub(crate) fn wallet_rpc_pid(&self) -> Option<u32> {
|
||
|
|
self.wallet_rpc
|
||
|
|
.lock()
|
||
|
|
.ok()
|
||
|
|
.and_then(|guard| guard.as_ref().map(std::process::Child::id))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Is a tracked *child process* 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.socks.lock().map(|g| g.is_some()).unwrap_or(false)
|
||
|
|
|| self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// True when a tracked child has exited since the last poll. Watching the
|
||
|
|
/// child is polling + `try_wait`: there is no pidfd plumbing in std, and the
|
||
|
|
/// honest thing is to report what `try_wait` actually says.
|
||
|
|
pub fn child_exited(&self) -> bool {
|
||
|
|
self.reap_exited()
|
||
|
|
}
|
||
|
|
|
||
|
|
fn reap_exited(&self) -> bool {
|
||
|
|
let mut exited = false;
|
||
|
|
for slot in [&self.monerod, &self.socks, &self.wallet_rpc] {
|
||
|
|
let Ok(mut guard) = slot.lock() else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
let gone = match guard.as_mut() {
|
||
|
|
Some(child) => matches!(child.try_wait(), Ok(Some(_))),
|
||
|
|
None => false,
|
||
|
|
};
|
||
|
|
if gone {
|
||
|
|
*guard = None;
|
||
|
|
exited = true;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
exited
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The exact argv used to spawn `arti` as the SOCKS child: `arti proxy -p
|
||
|
|
/// <port>`, with its *own* state and cache dirs so the two Tor clients in
|
||
|
|
/// one app never share state silently.
|
||
|
|
///
|
||
|
|
/// `-p` is the arti CLI's `socks-port` argument (arti 2.6.0 `src/lib.rs`);
|
||
|
|
/// it binds localhost only (`Listen::new_localhost`, tor-config 0.46
|
||
|
|
/// `listen.rs`: "We interpret standalone ports to be localhost
|
||
|
|
/// addresses" — `[::1, 127.0.0.1]`). There is no Unix-socket listen target
|
||
|
|
/// to prefer: `Listen` is IP-only and arti's `port_info` says AF_UNIX is
|
||
|
|
/// future work (arti#1965).
|
||
|
|
pub fn arti_proxy_argv(
|
||
|
|
bin: &Path,
|
||
|
|
port: u16,
|
||
|
|
state_dir: &Path,
|
||
|
|
cache_dir: &Path,
|
||
|
|
) -> Vec<String> {
|
||
|
|
vec![
|
||
|
|
bin.display().to_string(),
|
||
|
|
"proxy".into(),
|
||
|
|
"-p".into(),
|
||
|
|
port.to_string(),
|
||
|
|
"-o".into(),
|
||
|
|
format!("storage.state_dir=\"{}\"", state_dir.display()),
|
||
|
|
"-o".into(),
|
||
|
|
format!("storage.cache_dir=\"{}\"", cache_dir.display()),
|
||
|
|
]
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The `--proxy` value the wallet child is given. `socks5://` is explicit
|
||
|
|
/// on purpose: Monero's `--proxy` defaults to SOCKS4a for a bare
|
||
|
|
/// `host:port` (`docs/proxies.md`).
|
||
|
|
pub fn socks_proxy_url(port: u16) -> String {
|
||
|
|
format!("{SOCKS5_SCHEME}127.0.0.1:{port}")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Poll `127.0.0.1:port` until it accepts, or `budget` elapses.
|
||
|
|
///
|
||
|
|
/// Proves the listener accepted a TCP connection. Does not prove HTTP, a
|
||
|
|
/// wallet file, or a synced chain. `what` is the noun in the error
|
||
|
|
/// (`chain daemon RPC`, `monero-wallet-rpc`).
|
||
|
|
pub fn loopback_listener_ready(port: u16, budget: Duration, what: &str) -> Result<()> {
|
||
|
|
match Self::poll_loopback(port, budget) {
|
||
|
|
Ok(()) => Ok(()),
|
||
|
|
Err(last) => Err(ChildError(format!(
|
||
|
|
"{what} on 127.0.0.1:{port} did not accept a connection within {}s ({}) — not continuing startup against a closed port",
|
||
|
|
budget.as_secs_f32(),
|
||
|
|
last
|
||
|
|
))),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Wait for the SOCKS listener to accept a connection, with an explicit
|
||
|
|
/// budget so a dead proxy fails visibly instead of hanging the wallet
|
||
|
|
/// screen.
|
||
|
|
///
|
||
|
|
/// This proves the *listener* is up (arti binds before it bootstraps);
|
||
|
|
/// it does not prove the Tor circuit works. It also does not resolve the
|
||
|
|
/// `.onion` name locally — the name travels inside the SOCKS request.
|
||
|
|
pub fn socks_listener_ready(port: u16, budget: Duration) -> Result<()> {
|
||
|
|
match Self::poll_loopback(port, budget) {
|
||
|
|
Ok(()) => Ok(()),
|
||
|
|
Err(last) => Err(ChildError(format!(
|
||
|
|
"SOCKS proxy on 127.0.0.1:{port} did not accept a connection within {}s \
|
||
|
|
({last}) — not spawning a wallet child against a dead proxy",
|
||
|
|
budget.as_secs_f32()
|
||
|
|
))),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One accept loop, shared by every loopback readiness gate. `Err` carries
|
||
|
|
/// the last connect error as text, not a formatted message: the caller owns
|
||
|
|
/// the wording (the SOCKS gate and the daemon/wallet-RPC gates say
|
||
|
|
/// different things).
|
||
|
|
fn poll_loopback(port: u16, budget: Duration) -> std::result::Result<(), String> {
|
||
|
|
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
||
|
|
let deadline = Instant::now() + budget;
|
||
|
|
let mut last = None;
|
||
|
|
while Instant::now() <= deadline {
|
||
|
|
match TcpStream::connect_timeout(&addr, SOCKS_PROBE_TIMEOUT) {
|
||
|
|
Ok(_) => return Ok(()),
|
||
|
|
Err(e) => last = Some(e.to_string()),
|
||
|
|
}
|
||
|
|
std::thread::sleep(SOCKS_PROBE_INTERVAL);
|
||
|
|
}
|
||
|
|
Err(last.unwrap_or_else(|| "no attempt".into()))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The honest one-liner a UI can show for the configured chain source. A
|
||
|
|
/// `.onion` daemon buys transport privacy, not host privacy: the daemon
|
||
|
|
/// operator still sees the wallet's addresses during sync.
|
||
|
|
pub fn chain_copy(source: &ChainSource) -> String {
|
||
|
|
match source {
|
||
|
|
ChainSource::None => "receive-only: no daemon, no chain traffic".into(),
|
||
|
|
ChainSource::Local { .. } => {
|
||
|
|
"local monerod on this box (loopback): no Tor, no remote operator".into()
|
||
|
|
}
|
||
|
|
ChainSource::InProcessCuprate { .. } => format!(
|
||
|
|
"in-process daemon: chain and consensus run in this app, on this device \
|
||
|
|
(loopback, no Tor) — {}",
|
||
|
|
crate::cuprate::TESTNET_ONLY
|
||
|
|
),
|
||
|
|
ChainSource::Remote { host, port } if Self::is_onion_host(host) => format!(
|
||
|
|
"remote {host}:{port} over Tor (SOCKS5 on loopback, never clearnet) — Tor hides \
|
||
|
|
the transport, not the host: the daemon operator still sees your addresses \
|
||
|
|
during sync"
|
||
|
|
),
|
||
|
|
ChainSource::Remote { host, port } => format!(
|
||
|
|
"remote {host}:{port} over clearnet, because you typed it — the daemon operator \
|
||
|
|
and your ISP see the traffic"
|
||
|
|
),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The `--daemon-address` for each chain source. A local source is the
|
||
|
|
/// loopback daemon this struct owns — spawned `monerod` or in-process
|
||
|
|
/// Cuprate, the 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 { .. } | 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> {
|
||
|
|
let listener = std::net::TcpListener::bind("127.0.0.1:0")
|
||
|
|
.map_err(|e| ChildError(format!("bind loopback port: {e}")))?;
|
||
|
|
let port = listener
|
||
|
|
.local_addr()
|
||
|
|
.map_err(|e| ChildError(format!("local_addr: {e}")))?
|
||
|
|
.port();
|
||
|
|
drop(listener);
|
||
|
|
Ok(port)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The exact argv used to spawn `monerod`. Single source of truth: `start`
|
||
|
|
/// spawns this and the tests assert on it.
|
||
|
|
pub fn monerod_argv(bin: &Path, datadir: &Path, rpc_port: u16, prune: bool) -> Vec<String> {
|
||
|
|
let mut argv = vec![
|
||
|
|
bin.display().to_string(),
|
||
|
|
"--non-interactive".into(),
|
||
|
|
"--data-dir".into(),
|
||
|
|
datadir.display().to_string(),
|
||
|
|
"--rpc-bind-ip".into(),
|
||
|
|
"127.0.0.1".into(),
|
||
|
|
"--rpc-bind-port".into(),
|
||
|
|
rpc_port.to_string(),
|
||
|
|
];
|
||
|
|
if prune {
|
||
|
|
argv.push("--prune-blockchain".into());
|
||
|
|
}
|
||
|
|
argv
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The exact argv used to spawn `monero-wallet-rpc`. Digest login is
|
||
|
|
/// mandatory and the bind is loopback; `--trusted-daemon` is deliberately
|
||
|
|
/// absent.
|
||
|
|
///
|
||
|
|
/// `socks_proxy` is the wallet child's `--proxy` target. It is only passed
|
||
|
|
/// for a `.onion` daemon, and it is always a `socks5://127.0.0.1:<port>`
|
||
|
|
/// string: the wallet child talks plain SOCKS5 to the app's own `arti proxy`
|
||
|
|
/// child. The messenger's in-process Arti client is never handed to it.
|
||
|
|
pub fn wallet_rpc_argv(
|
||
|
|
bin: &Path,
|
||
|
|
port: u16,
|
||
|
|
login: &str,
|
||
|
|
wallet_dir: &Path,
|
||
|
|
daemon_address: Option<&str>,
|
||
|
|
socks_proxy: Option<&str>,
|
||
|
|
) -> Vec<String> {
|
||
|
|
let mut argv = vec![
|
||
|
|
bin.display().to_string(),
|
||
|
|
"--rpc-bind-ip".into(),
|
||
|
|
"127.0.0.1".into(),
|
||
|
|
"--rpc-bind-port".into(),
|
||
|
|
port.to_string(),
|
||
|
|
"--rpc-login".into(),
|
||
|
|
login.to_string(),
|
||
|
|
"--wallet-dir".into(),
|
||
|
|
wallet_dir.display().to_string(),
|
||
|
|
];
|
||
|
|
if let Some(addr) = daemon_address {
|
||
|
|
argv.push("--daemon-address".into());
|
||
|
|
argv.push(addr.to_string());
|
||
|
|
}
|
||
|
|
if let Some(proxy) = socks_proxy {
|
||
|
|
argv.push("--proxy".into());
|
||
|
|
argv.push(proxy.to_string());
|
||
|
|
}
|
||
|
|
argv
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Start the children (idempotent per source) and hand back the loopback
|
||
|
|
/// client the app should talk to.
|
||
|
|
///
|
||
|
|
/// `None` -> `Ok(None)`: receive-only, nothing is spawned. The `Store` is
|
||
|
|
/// what gates every spawn: the SOCKS child, like the wallet child, is only
|
||
|
|
/// reachable through an unlocked store.
|
||
|
|
pub fn start(&self, store: &Store) -> Result<Option<WalletClient>> {
|
||
|
|
self.start_with_creds(|| self.creds(store))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Same as [`WalletChild::start`], but the store mutex is taken only for
|
||
|
|
/// the generated RPC creds — not across chain-daemon launch.
|
||
|
|
///
|
||
|
|
/// Cuprate's `Node::launch` (and a slow `monerod`) can run for a long time.
|
||
|
|
/// Holding SQLCipher for that whole window freezes every `wallet_status`
|
||
|
|
/// poll, which on Android makes **Start** look like a no-op: the button
|
||
|
|
/// fires, status stays `off`, no error.
|
||
|
|
pub fn start_unlocking_store(&self, store: &Mutex<Store>) -> Result<Option<WalletClient>> {
|
||
|
|
self.start_with_creds(|| {
|
||
|
|
let guard = store
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| ChildError(format!("store lock: {e}")))?;
|
||
|
|
self.creds(&guard)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
fn start_with_creds(
|
||
|
|
&self,
|
||
|
|
creds: impl FnOnce() -> Result<(String, Zeroizing<String>)>,
|
||
|
|
) -> Result<Option<WalletClient>> {
|
||
|
|
if !self.is_enabled() {
|
||
|
|
return Ok(None);
|
||
|
|
}
|
||
|
|
if self.running() {
|
||
|
|
return Err(ChildError("wallet child already running".into()));
|
||
|
|
}
|
||
|
|
match self.start_children(creds) {
|
||
|
|
Ok(client) => Ok(client),
|
||
|
|
Err(e) => {
|
||
|
|
// A failure after the SOCKS child came up must not leave the
|
||
|
|
// listener (or monerod) orphaned behind the error.
|
||
|
|
let _ = self.stop();
|
||
|
|
Err(e)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn start_children(
|
||
|
|
&self,
|
||
|
|
creds: impl FnOnce() -> Result<(String, Zeroizing<String>)>,
|
||
|
|
) -> Result<Option<WalletClient>> {
|
||
|
|
// Local chain source: own the daemon first, so the wallet child has
|
||
|
|
// something to dial. Either a spawned `monerod` or the in-process
|
||
|
|
// Cuprate node — both bind `DEFAULT_MONEROD_RPC_PORT` on loopback, so
|
||
|
|
// `wallet_rpc_argv` below is identical either way.
|
||
|
|
match &self.source {
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin,
|
||
|
|
datadir,
|
||
|
|
prune,
|
||
|
|
} => {
|
||
|
|
ensure_parent(datadir)?;
|
||
|
|
let argv =
|
||
|
|
Self::monerod_argv(monerod_bin, datadir, DEFAULT_MONEROD_RPC_PORT, *prune);
|
||
|
|
let child = spawn(&argv, "monerod")?;
|
||
|
|
let mut guard = self
|
||
|
|
.monerod
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| ChildError(format!("monerod lock: {e}")))?;
|
||
|
|
*guard = Some(child);
|
||
|
|
}
|
||
|
|
ChainSource::InProcessCuprate {
|
||
|
|
datadir,
|
||
|
|
network,
|
||
|
|
prune,
|
||
|
|
} => self.start_in_process_daemon(datadir, *network, *prune)?,
|
||
|
|
ChainSource::None | ChainSource::Remote { .. } => {}
|
||
|
|
}
|
||
|
|
|
||
|
|
if matches!(
|
||
|
|
self.source,
|
||
|
|
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. }
|
||
|
|
) {
|
||
|
|
// Node::launch returning is not "18081 accepts". The spike saw the
|
||
|
|
// unrestricted listener up within 0.2s of return; wait for that
|
||
|
|
// accept so the wallet child is not spawned against a closed port.
|
||
|
|
Self::loopback_listener_ready(
|
||
|
|
DEFAULT_MONEROD_RPC_PORT,
|
||
|
|
DAEMON_LISTENER_TIMEOUT,
|
||
|
|
"chain daemon RPC",
|
||
|
|
)?;
|
||
|
|
}
|
||
|
|
|
||
|
|
// A `.onion` daemon is only reachable through SOCKS. The app bundles the
|
||
|
|
// `arti` binary as that proxy; it must be up before the wallet child
|
||
|
|
// starts, or the wallet child sits there failing to dial its daemon.
|
||
|
|
let socks_proxy = match &self.source {
|
||
|
|
ChainSource::Remote { host, .. } if Self::is_onion_host(host) => {
|
||
|
|
Some(self.start_socks_proxy()?)
|
||
|
|
}
|
||
|
|
_ => None,
|
||
|
|
};
|
||
|
|
|
||
|
|
// Creds are the only store read. Callers that pass
|
||
|
|
// `start_unlocking_store` take the mutex here, after the chain daemon
|
||
|
|
// is already up, so a long Cuprate launch does not freeze SQLCipher.
|
||
|
|
let (user, pass) = creds()?;
|
||
|
|
let port = Self::pick_port()?;
|
||
|
|
let login = format!("{user}:{}", pass.as_str());
|
||
|
|
let daemon = Self::daemon_address(&self.source);
|
||
|
|
let argv = Self::wallet_rpc_argv(
|
||
|
|
&self.wallet_rpc_bin,
|
||
|
|
port,
|
||
|
|
&login,
|
||
|
|
&self.wallet_dir,
|
||
|
|
daemon.as_deref(),
|
||
|
|
socks_proxy.as_deref(),
|
||
|
|
);
|
||
|
|
let child = spawn(&argv, "monero-wallet-rpc")?;
|
||
|
|
{
|
||
|
|
let mut guard = self
|
||
|
|
.wallet_rpc
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| ChildError(format!("wallet-rpc lock: {e}")))?;
|
||
|
|
if guard.is_some() {
|
||
|
|
return Err(ChildError("wallet child already running".into()));
|
||
|
|
}
|
||
|
|
*guard = Some(child);
|
||
|
|
}
|
||
|
|
// monero-wallet-rpc creates the wallet file 0600; make that true even if
|
||
|
|
// it already existed with looser bits.
|
||
|
|
harden_wallet_file(&self.wallet_dir.join(&self.wallet_filename));
|
||
|
|
Ok(Some(WalletClient {
|
||
|
|
url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()),
|
||
|
|
no_spend: false,
|
||
|
|
}))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Spawn `arti proxy -p <port>` and hand back its wallet-child-facing
|
||
|
|
/// `--proxy` value.
|
||
|
|
///
|
||
|
|
/// Its state and cache live under the wallet dir, not in the messenger's
|
||
|
|
/// Arti state dir: the two Tor clients in this app do not share state.
|
||
|
|
fn start_socks_proxy(&self) -> Result<String> {
|
||
|
|
let port = match self.socks_port {
|
||
|
|
Some(p) => p,
|
||
|
|
None => Self::pick_port()?,
|
||
|
|
};
|
||
|
|
let state_dir = self.wallet_dir.join("arti-socks").join("state");
|
||
|
|
let cache_dir = self.wallet_dir.join("arti-socks").join("cache");
|
||
|
|
for dir in [state_dir.parent(), Some(&state_dir), Some(&cache_dir)]
|
||
|
|
.into_iter()
|
||
|
|
.flatten()
|
||
|
|
{
|
||
|
|
create_dir_700(dir).map_err(|e| ChildError(format!("arti dir: {e}")))?;
|
||
|
|
}
|
||
|
|
let argv = Self::arti_proxy_argv(&self.arti_bin, port, &state_dir, &cache_dir);
|
||
|
|
let child = spawn(&argv, "arti proxy")?;
|
||
|
|
{
|
||
|
|
let mut guard = self
|
||
|
|
.socks
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| ChildError(format!("socks lock: {e}")))?;
|
||
|
|
*guard = Some(child);
|
||
|
|
}
|
||
|
|
Self::socks_listener_ready(port, self.socks_ready_timeout)?;
|
||
|
|
Ok(Self::socks_proxy_url(port))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Launch the in-process Cuprate daemon and hold it.
|
||
|
|
///
|
||
|
|
/// Blocking is deliberate: [`CuprateNode::launch`] is synchronous (it runs
|
||
|
|
/// the async launch on a runtime it owns and blocks this thread until the
|
||
|
|
/// node answers), so this works from the TUI's blocking thread *and* from an
|
||
|
|
/// SDK async context. It is the same shape as the SOCKS readiness wait
|
||
|
|
/// above: no daemon, no wallet child.
|
||
|
|
fn start_in_process_daemon(
|
||
|
|
&self,
|
||
|
|
datadir: &Path,
|
||
|
|
network: ChainNetwork,
|
||
|
|
prune: bool,
|
||
|
|
) -> Result<()> {
|
||
|
|
// Feature first: in a build without it, a datadir complaint would be a
|
||
|
|
// misleading answer to "why is there no daemon".
|
||
|
|
if !crate::cuprate::available() {
|
||
|
|
return Err(ChildError(crate::cuprate::NO_FEATURE_MSG.into()));
|
||
|
|
}
|
||
|
|
create_dir_700(datadir).map_err(|e| ChildError(format!("chain datadir: {e}")))?;
|
||
|
|
let node = CuprateNode::launch(
|
||
|
|
datadir,
|
||
|
|
DEFAULT_MONEROD_RPC_PORT,
|
||
|
|
network.cuprate_toml(),
|
||
|
|
prune,
|
||
|
|
)
|
||
|
|
.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 every child. Idempotent, and tolerant of a child that already
|
||
|
|
/// exited on its own. The wallet child goes first so no wallet RPC can be
|
||
|
|
/// mid-request against the chain, then the SOCKS listener, then the chain
|
||
|
|
/// daemon — the in-process one is asked to shut down rather than signalled.
|
||
|
|
pub fn stop(&self) -> Result<()> {
|
||
|
|
kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?;
|
||
|
|
kill_slot(&self.socks, "arti proxy")?;
|
||
|
|
kill_slot(&self.monerod, "monerod")?;
|
||
|
|
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 this node owns, and dropping alone would cut them off.
|
||
|
|
node.shutdown();
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Load the sealed creds, or generate them once and seal them in the store.
|
||
|
|
/// The store is the only place they live; `wallet_dir` never sees them.
|
||
|
|
///
|
||
|
|
/// The record is a read-modify-write: the settings written by a config
|
||
|
|
/// screen are never clobbered by first-start credential generation.
|
||
|
|
fn creds(&self, store: &Store) -> Result<(String, Zeroizing<String>)> {
|
||
|
|
let existing = store
|
||
|
|
.load_wallet_child()
|
||
|
|
.map_err(|e| ChildError(format!("read wallet-child creds: {e}")))?;
|
||
|
|
// Persist what this child is running with, before anything is spawned.
|
||
|
|
let record = merge_record(existing.as_deref(), self.config().record_fields());
|
||
|
|
store
|
||
|
|
.save_wallet_child(&record)
|
||
|
|
.map_err(|e| ChildError(format!("seal wallet-child config: {e}")))?;
|
||
|
|
|
||
|
|
if let Some(raw) = existing.as_deref()
|
||
|
|
&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(raw)
|
||
|
|
&& let Some(user) = parsed
|
||
|
|
.get("user")
|
||
|
|
.and_then(|v| v.as_str())
|
||
|
|
.filter(|s| !s.is_empty())
|
||
|
|
&& let Some(pass) = parsed
|
||
|
|
.get("pass")
|
||
|
|
.and_then(|v| v.as_str())
|
||
|
|
.filter(|s| !s.is_empty())
|
||
|
|
{
|
||
|
|
return Ok((user.to_string(), Zeroizing::new(pass.to_string())));
|
||
|
|
}
|
||
|
|
let (user, pass) = generate_creds();
|
||
|
|
let record = merge_record(
|
||
|
|
Some(&record),
|
||
|
|
serde_json::json!({"user": user, "pass": pass.as_str()}),
|
||
|
|
);
|
||
|
|
store
|
||
|
|
.save_wallet_child(&record)
|
||
|
|
.map_err(|e| ChildError(format!("seal wallet-child creds: {e}")))?;
|
||
|
|
Ok((user, pass))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Everything the app needs to spawn the wallet child, minus the RPC creds:
|
||
|
|
/// which chain to dial, which binaries to run, which wallet file to open.
|
||
|
|
///
|
||
|
|
/// Persisted as part of the sealed `wallet_child` record (the generated creds
|
||
|
|
/// live in the same record), so a configured child survives a restart without
|
||
|
|
/// env vars. This is the shape the SDK's `ChainConfig` record maps to.
|
||
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
|
|
pub struct ChildConfig {
|
||
|
|
/// The user's chain-source choice. `None` is receive-only: nothing spawns.
|
||
|
|
pub source: ChainSource,
|
||
|
|
/// `monero-wallet-rpc`. A bare name is resolved on `PATH`; Android passes an
|
||
|
|
/// absolute path out of the app's native library directory.
|
||
|
|
pub wallet_rpc_bin: PathBuf,
|
||
|
|
/// `arti`, run as the SOCKS child for a `.onion` daemon only.
|
||
|
|
pub arti_bin: PathBuf,
|
||
|
|
/// Wallet file name inside `$ONIONWIRE_HOME/wallet`.
|
||
|
|
pub wallet_filename: String,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Default for ChildConfig {
|
||
|
|
fn default() -> Self {
|
||
|
|
Self {
|
||
|
|
source: ChainSource::None,
|
||
|
|
wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN),
|
||
|
|
arti_bin: PathBuf::from(DEFAULT_ARTI_BIN),
|
||
|
|
wallet_filename: wallet::DEFAULT_WALLET_FILENAME.to_string(),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl ChildConfig {
|
||
|
|
/// Nothing spawns: the wallet screen is receive-only.
|
||
|
|
pub fn receive_only() -> Self {
|
||
|
|
Self::default()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Does this configuration spawn a child at all?
|
||
|
|
pub fn is_enabled(&self) -> bool {
|
||
|
|
!matches!(self.source, ChainSource::None)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The chain-source label a status line shows.
|
||
|
|
pub fn source_label(&self) -> String {
|
||
|
|
self.source.label()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Where a status refresh may ask the chain daemon itself for
|
||
|
|
/// height/target, when the wallet RPC is not answering. Only a daemon this
|
||
|
|
/// box owns: a `monerod`/Cuprate the child spawned binds loopback, and
|
||
|
|
/// asking it is a plain local socket. A remote daemon is the wallet child's
|
||
|
|
/// to dial (over SOCKS, if it is an onion) — a status refresh does not open
|
||
|
|
/// a second path to it.
|
||
|
|
pub fn daemon_probe_addr(&self) -> Option<String> {
|
||
|
|
match self.source {
|
||
|
|
ChainSource::Local { .. } | ChainSource::InProcessCuprate { .. } => {
|
||
|
|
Some(format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}"))
|
||
|
|
}
|
||
|
|
ChainSource::None | ChainSource::Remote { .. } => None,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
/// Reject a configuration that could only fail later (empty binary path,
|
||
|
|
/// empty host, port 0) *before* it is persisted or spawned.
|
||
|
|
pub fn validate(&self) -> Result<()> {
|
||
|
|
if self.wallet_filename.trim().is_empty() {
|
||
|
|
return Err(ChildError("wallet filename required".into()));
|
||
|
|
}
|
||
|
|
// Receive-only spawns nothing, so a binary path there is not a setting
|
||
|
|
// to reject — a Kotlin caller legitimately leaves both empty for it.
|
||
|
|
if matches!(self.source, ChainSource::None) {
|
||
|
|
return Ok(());
|
||
|
|
}
|
||
|
|
if self.wallet_rpc_bin.as_os_str().is_empty() {
|
||
|
|
return Err(ChildError("monero-wallet-rpc path required".into()));
|
||
|
|
}
|
||
|
|
if self.arti_bin.as_os_str().is_empty() {
|
||
|
|
return Err(ChildError("arti path required".into()));
|
||
|
|
}
|
||
|
|
match &self.source {
|
||
|
|
ChainSource::None => {}
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin,
|
||
|
|
datadir,
|
||
|
|
..
|
||
|
|
} => {
|
||
|
|
if monerod_bin.as_os_str().is_empty() {
|
||
|
|
return Err(ChildError("monerod path required for a local node".into()));
|
||
|
|
}
|
||
|
|
if datadir.as_os_str().is_empty() {
|
||
|
|
return Err(ChildError(
|
||
|
|
"monerod data dir required for a local node".into(),
|
||
|
|
));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
ChainSource::InProcessCuprate { datadir, .. } => {
|
||
|
|
if datadir.as_os_str().is_empty() {
|
||
|
|
return Err(ChildError(
|
||
|
|
"chain data dir required for an in-process daemon".into(),
|
||
|
|
));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
ChainSource::Remote { host, port } => {
|
||
|
|
if host.trim().is_empty() {
|
||
|
|
return Err(ChildError(
|
||
|
|
"daemon host required for a remote daemon".into(),
|
||
|
|
));
|
||
|
|
}
|
||
|
|
if *port == 0 {
|
||
|
|
return Err(ChildError(
|
||
|
|
"daemon port required for a remote daemon".into(),
|
||
|
|
));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Build the child this configuration describes. `wallet_dir` is the
|
||
|
|
/// caller's `$ONIONWIRE_HOME/wallet`.
|
||
|
|
pub fn build(&self, wallet_dir: PathBuf) -> Result<WalletChild> {
|
||
|
|
self.validate()?;
|
||
|
|
Ok(WalletChild::new(
|
||
|
|
self.source.clone(),
|
||
|
|
wallet_dir,
|
||
|
|
Some(self.wallet_filename.clone()),
|
||
|
|
)?
|
||
|
|
.with_wallet_rpc_bin(self.wallet_rpc_bin.clone())
|
||
|
|
.with_arti_bin(self.arti_bin.clone()))
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The settings half of the sealed record, for
|
||
|
|
/// [`merge_record`] + `Store::save_wallet_child`.
|
||
|
|
pub fn record_fields(&self) -> serde_json::Value {
|
||
|
|
serde_json::json!({
|
||
|
|
"source": source_to_json(&self.source),
|
||
|
|
"wallet_rpc_bin": self.wallet_rpc_bin.display().to_string(),
|
||
|
|
"arti_bin": self.arti_bin.display().to_string(),
|
||
|
|
"wallet_filename": self.wallet_filename,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Read the stored settings back. `Ok(None)` when the record holds creds but
|
||
|
|
/// no source block — a record written before the settings were persisted.
|
||
|
|
pub fn from_record(raw: &str) -> Result<Option<Self>> {
|
||
|
|
let parsed: serde_json::Value = serde_json::from_str(raw)
|
||
|
|
.map_err(|e| ChildError(format!("parse wallet-child record: {e}")))?;
|
||
|
|
let Some(source) = parsed.get("source") else {
|
||
|
|
return Ok(None);
|
||
|
|
};
|
||
|
|
let mut cfg = Self {
|
||
|
|
source: source_from_json(source)?,
|
||
|
|
..Self::default()
|
||
|
|
};
|
||
|
|
if let Some(v) = parsed.get("wallet_rpc_bin").and_then(|v| v.as_str()) {
|
||
|
|
cfg.wallet_rpc_bin = PathBuf::from(v);
|
||
|
|
}
|
||
|
|
if let Some(v) = parsed.get("arti_bin").and_then(|v| v.as_str()) {
|
||
|
|
cfg.arti_bin = PathBuf::from(v);
|
||
|
|
}
|
||
|
|
if let Some(v) = parsed.get("wallet_filename").and_then(|v| v.as_str()) {
|
||
|
|
cfg.wallet_filename = v.to_string();
|
||
|
|
}
|
||
|
|
Ok(Some(cfg))
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Merge `fields` into the sealed record JSON, keeping every other key — the
|
||
|
|
/// generated RPC creds in particular. A missing or non-object `existing` starts
|
||
|
|
/// a fresh record.
|
||
|
|
pub fn merge_record(existing: Option<&str>, fields: serde_json::Value) -> String {
|
||
|
|
let mut obj = existing
|
||
|
|
.and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
|
||
|
|
.and_then(|v| v.as_object().cloned())
|
||
|
|
.unwrap_or_default();
|
||
|
|
if let serde_json::Value::Object(patch) = fields {
|
||
|
|
for (k, v) in patch {
|
||
|
|
obj.insert(k, v);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
serde_json::Value::Object(obj).to_string()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The observable state of the app-owned wallet child. Derived from the real
|
||
|
|
/// process + the last probe, never from env-var presence.
|
||
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
|
|
pub enum WalletChildState {
|
||
|
|
/// No child configured, or none started yet.
|
||
|
|
Off,
|
||
|
|
/// The child process is up but its wallet RPC has not answered.
|
||
|
|
Connecting,
|
||
|
|
/// The wallet answered, but the chain is not at the tip yet.
|
||
|
|
Syncing,
|
||
|
|
/// Wallet RPC answered and the chain is synced.
|
||
|
|
Ready,
|
||
|
|
/// A started child has exited (crashed or killed). Never reported ready.
|
||
|
|
Exited,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl WalletChildState {
|
||
|
|
/// The lowercase label the SDK and the TUI show.
|
||
|
|
pub fn as_str(self) -> &'static str {
|
||
|
|
match self {
|
||
|
|
WalletChildState::Off => "off",
|
||
|
|
WalletChildState::Connecting => "connecting",
|
||
|
|
WalletChildState::Syncing => "syncing",
|
||
|
|
WalletChildState::Ready => "ready",
|
||
|
|
WalletChildState::Exited => "exited",
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Whether the wallet **file** the child is pointed at is open in the running
|
||
|
|
/// `monero-wallet-rpc`.
|
||
|
|
///
|
||
|
|
/// This is not the same question as "is the RPC up": the daemon starts with no
|
||
|
|
/// wallet open, so a live child that answers every call with `-13 No wallet
|
||
|
|
/// file` is `NeedsPassphrase`, not a start failure.
|
||
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||
|
|
pub enum ChildWalletState {
|
||
|
|
/// Nothing to open, or nothing attempted yet: no catalogue wallet under the
|
||
|
|
/// configured file name, or no child.
|
||
|
|
#[default]
|
||
|
|
Unknown,
|
||
|
|
/// The wallet file is open (`open_wallet` succeeded, or this process just
|
||
|
|
/// created it).
|
||
|
|
Open,
|
||
|
|
/// A wallet file the catalogue holds is not open, and this install holds no
|
||
|
|
/// passphrase that could open it. Not an error: the user supplies it once.
|
||
|
|
NeedsPassphrase,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl ChildWalletState {
|
||
|
|
pub fn as_str(self) -> &'static str {
|
||
|
|
match self {
|
||
|
|
ChildWalletState::Unknown => "unknown",
|
||
|
|
ChildWalletState::Open => "open",
|
||
|
|
ChildWalletState::NeedsPassphrase => "needs-passphrase",
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// One snapshot of the child. Cheap to read: no dial, no lock held across work.
|
||
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
|
|
pub struct WalletChildStatus {
|
||
|
|
pub state: WalletChildState,
|
||
|
|
/// A child process is alive right now.
|
||
|
|
pub running: bool,
|
||
|
|
/// The wallet file the child is pointed at is open in its RPC. `false` is
|
||
|
|
/// the honest answer for an off/exited child and for one whose
|
||
|
|
/// `open_wallet` has not succeeded.
|
||
|
|
pub wallet_open: bool,
|
||
|
|
/// A catalogue wallet is configured but not open, so a passphrase is needed
|
||
|
|
/// before any read can work. Distinct from a failed start.
|
||
|
|
pub needs_passphrase: bool,
|
||
|
|
/// A chain source is configured (not receive-only), whether or not it runs.
|
||
|
|
pub configured: bool,
|
||
|
|
/// The chain-source label: `receive-only` / `local node` /
|
||
|
|
/// `remote onion daemon` / `remote daemon`.
|
||
|
|
pub chain_source: String,
|
||
|
|
/// Blocks the chain daemon currently has. `0` means unknown (not started, or
|
||
|
|
/// the last probe failed). This is daemon height, never wallet-rpc scan height.
|
||
|
|
pub height: u64,
|
||
|
|
/// Blocks the daemon is syncing towards. `0` means the daemon reported none
|
||
|
|
/// (not the same as caught up — see `wallet::chain_ready`).
|
||
|
|
pub target_height: u64,
|
||
|
|
/// The last failure, display-ready. Never carries the generated login.
|
||
|
|
pub last_error: Option<String>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl WalletChildStatus {
|
||
|
|
/// The one-line form a TUI status row or a Kotlin toast can show. Empty when
|
||
|
|
/// nothing is configured, so an unconfigured install renders no row.
|
||
|
|
pub fn line(&self) -> String {
|
||
|
|
if !self.configured && self.state == WalletChildState::Off {
|
||
|
|
return String::new();
|
||
|
|
}
|
||
|
|
let mut line = format!("child {} · {}", self.state.as_str(), self.chain_source);
|
||
|
|
if self.needs_passphrase {
|
||
|
|
line.push_str(" · wallet locked");
|
||
|
|
}
|
||
|
|
// A probe that read nothing says nothing: the line is unchanged until a
|
||
|
|
// daemon (or the wallet's daemon) actually reported numbers. No
|
||
|
|
// percentage is derived — `target_height == 0` is "the daemon told us
|
||
|
|
// nothing", not "caught up".
|
||
|
|
if self.height > 0 || self.target_height > 0 {
|
||
|
|
line.push_str(&format!(" · sync {}/{}", self.height, self.target_height));
|
||
|
|
}
|
||
|
|
if let Some(err) = &self.last_error {
|
||
|
|
line.push_str(" · ");
|
||
|
|
line.push_str(err);
|
||
|
|
}
|
||
|
|
line
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The loopback client built from the generated URL — the production path when
|
||
|
|
/// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but
|
||
|
|
/// numeric loopback.
|
||
|
|
#[derive(Debug, Clone)]
|
||
|
|
pub struct WalletClient {
|
||
|
|
url: String,
|
||
|
|
no_spend: bool,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl WalletClient {
|
||
|
|
/// Build the [`Wallet`] this child serves. The chain-side RPC budget is the
|
||
|
|
/// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync
|
||
|
|
/// or a remote daemon legitimately outlasts a loopback round trip.
|
||
|
|
pub fn into_wallet(self) -> Wallet {
|
||
|
|
Wallet::from_url(&self.url)
|
||
|
|
.expect("wallet child URL is always valid loopback with creds")
|
||
|
|
.with_no_spend(self.no_spend)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The loopback URL. Carries the generated creds — do not log it.
|
||
|
|
pub fn url(&self) -> &str {
|
||
|
|
&self.url
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn no_spend(&self) -> bool {
|
||
|
|
self.no_spend
|
||
|
|
}
|
||
|
|
|
||
|
|
pub fn set_no_spend(&mut self, on: bool) {
|
||
|
|
self.no_spend = on;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Random, shell- and HTTP-safe credentials: `[a-z0-9]` only. No `:`, no quotes,
|
||
|
|
/// no whitespace — the login goes through `--rpc-login` and an HTTP Digest
|
||
|
|
/// header. The user and the password are drawn from separate randomness.
|
||
|
|
fn generate_creds() -> (String, Zeroizing<String>) {
|
||
|
|
let mut user_buf = [0u8; 16];
|
||
|
|
let mut pass_buf = [0u8; 24];
|
||
|
|
let mut rng = rand::thread_rng();
|
||
|
|
rng.fill_bytes(&mut user_buf);
|
||
|
|
rng.fill_bytes(&mut pass_buf);
|
||
|
|
(rand_token(&user_buf), Zeroizing::new(rand_token(&pass_buf)))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn rand_token(buf: &[u8]) -> String {
|
||
|
|
const ALPH: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
|
||
|
|
let mut out = String::with_capacity(buf.len());
|
||
|
|
for b in buf {
|
||
|
|
out.push(ALPH[(*b as usize) % ALPH.len()] as char);
|
||
|
|
}
|
||
|
|
out
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Snapshot of the user's chain-source choice, stored beside the creds so the
|
||
|
|
/// UI can show what the child was started against.
|
||
|
|
fn source_to_json(source: &ChainSource) -> serde_json::Value {
|
||
|
|
match source {
|
||
|
|
ChainSource::None => serde_json::json!({"kind": "none"}),
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin,
|
||
|
|
datadir,
|
||
|
|
prune,
|
||
|
|
} => serde_json::json!({
|
||
|
|
"kind": "local",
|
||
|
|
"monerod_bin": monerod_bin.display().to_string(),
|
||
|
|
"datadir": datadir.display().to_string(),
|
||
|
|
"prune": prune,
|
||
|
|
}),
|
||
|
|
ChainSource::InProcessCuprate {
|
||
|
|
datadir,
|
||
|
|
network,
|
||
|
|
prune,
|
||
|
|
} => serde_json::json!({
|
||
|
|
"kind": "cuprate",
|
||
|
|
"datadir": datadir.display().to_string(),
|
||
|
|
"network": network.dir_name(),
|
||
|
|
"prune": prune,
|
||
|
|
}),
|
||
|
|
ChainSource::Remote { host, port } => serde_json::json!({
|
||
|
|
"kind": "remote",
|
||
|
|
"host": host,
|
||
|
|
"port": port,
|
||
|
|
}),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn source_from_json(value: &serde_json::Value) -> Result<ChainSource> {
|
||
|
|
let kind = value
|
||
|
|
.get("kind")
|
||
|
|
.and_then(|k| k.as_str())
|
||
|
|
.unwrap_or_default();
|
||
|
|
match kind {
|
||
|
|
"none" => Ok(ChainSource::None),
|
||
|
|
"local" => {
|
||
|
|
let monerod_bin = value
|
||
|
|
.get("monerod_bin")
|
||
|
|
.and_then(|v| v.as_str())
|
||
|
|
.filter(|s| !s.is_empty())
|
||
|
|
.ok_or_else(|| {
|
||
|
|
ChildError("stored local chain source has no monerod path".into())
|
||
|
|
})?;
|
||
|
|
let datadir = value
|
||
|
|
.get("datadir")
|
||
|
|
.and_then(|v| v.as_str())
|
||
|
|
.filter(|s| !s.is_empty())
|
||
|
|
.ok_or_else(|| ChildError("stored local chain source has no data dir".into()))?;
|
||
|
|
Ok(ChainSource::Local {
|
||
|
|
monerod_bin: PathBuf::from(monerod_bin),
|
||
|
|
datadir: PathBuf::from(datadir),
|
||
|
|
prune: value.get("prune").and_then(|v| v.as_bool()).unwrap_or(false),
|
||
|
|
})
|
||
|
|
}
|
||
|
|
"cuprate" => {
|
||
|
|
let datadir = value
|
||
|
|
.get("datadir")
|
||
|
|
.and_then(|v| v.as_str())
|
||
|
|
.filter(|s| !s.is_empty())
|
||
|
|
.ok_or_else(|| {
|
||
|
|
ChildError("stored in-process chain source has no data dir".into())
|
||
|
|
})?;
|
||
|
|
let network = match value.get("network").and_then(|v| v.as_str()) {
|
||
|
|
Some("mainnet") => ChainNetwork::Mainnet,
|
||
|
|
_ => ChainNetwork::Testnet,
|
||
|
|
};
|
||
|
|
let prune = value.get("prune").and_then(|v| v.as_bool()).unwrap_or(false);
|
||
|
|
Ok(ChainSource::InProcessCuprate {
|
||
|
|
datadir: PathBuf::from(datadir),
|
||
|
|
network,
|
||
|
|
prune,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
"remote" => {
|
||
|
|
let host = value
|
||
|
|
.get("host")
|
||
|
|
.and_then(|v| v.as_str())
|
||
|
|
.filter(|s| !s.trim().is_empty())
|
||
|
|
.ok_or_else(|| ChildError("stored remote chain source has no host".into()))?;
|
||
|
|
let port = value
|
||
|
|
.get("port")
|
||
|
|
.and_then(|v| v.as_u64())
|
||
|
|
.filter(|p| (1..=65535).contains(p))
|
||
|
|
.ok_or_else(|| ChildError("stored remote chain source has no port".into()))?;
|
||
|
|
Ok(ChainSource::Remote {
|
||
|
|
host: host.to_string(),
|
||
|
|
port: port as u16,
|
||
|
|
})
|
||
|
|
}
|
||
|
|
other => Err(ChildError(format!("unknown chain source kind {other:?}"))),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn spawn(argv: &[String], what: &str) -> Result<Child> {
|
||
|
|
let (bin, args) = argv
|
||
|
|
.split_first()
|
||
|
|
.ok_or_else(|| ChildError(format!("empty argv for {what}")))?;
|
||
|
|
Command::new(bin)
|
||
|
|
.args(args)
|
||
|
|
.spawn()
|
||
|
|
.map_err(|e| ChildError(format!("spawn {what}: {e}")))
|
||
|
|
}
|
||
|
|
|
||
|
|
fn kill_slot(slot: &Mutex<Option<Child>>, what: &str) -> Result<()> {
|
||
|
|
let mut guard = slot
|
||
|
|
.lock()
|
||
|
|
.map_err(|e| ChildError(format!("{what} lock: {e}")))?;
|
||
|
|
if let Some(child) = guard.as_mut() {
|
||
|
|
// An already-exited child (reaped or not) makes kill() an error: check
|
||
|
|
// first so `stop` stays idempotent.
|
||
|
|
if !matches!(child.try_wait(), Ok(Some(_))) {
|
||
|
|
let _ = child.kill();
|
||
|
|
let _ = child.wait();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
*guard = None;
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
fn create_dir_700(path: &Path) -> std::io::Result<()> {
|
||
|
|
fs::create_dir_all(path)?;
|
||
|
|
let mut perms = fs::metadata(path)?.permissions();
|
||
|
|
perms.set_mode(0o700);
|
||
|
|
fs::set_permissions(path, perms)
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Is `name` already a wallet file in `wallet_dir`?
|
||
|
|
///
|
||
|
|
/// monero writes two files per wallet — `<name>` and `<name>.keys` — and either
|
||
|
|
/// one makes `monero-wallet-rpc` refuse a create with `-21 Cannot create wallet.
|
||
|
|
/// Already exists.`, so both count as taken. The catalogue alone is not enough:
|
||
|
|
/// `Store::delete_wallet` drops the row and keeps the file, and a create whose
|
||
|
|
/// row was never written leaves a file too, so a picker that only consults the
|
||
|
|
/// catalogue proposes a colliding name for ever.
|
||
|
|
///
|
||
|
|
/// Fail closed: a directory that cannot be listed is an error, never "every
|
||
|
|
/// name is free". Guessing is how the collision comes back.
|
||
|
|
///
|
||
|
|
/// Reads only: nothing here deletes anything — a file the catalogue does not
|
||
|
|
/// know about may be the only copy of a funded wallet.
|
||
|
|
pub fn wallet_name_taken(wallet_dir: &Path, name: &str) -> Result<bool> {
|
||
|
|
let keys = format!("{name}.keys");
|
||
|
|
let unreadable =
|
||
|
|
|e: std::io::Error| ChildError(format!("wallet dir {}: {e}", wallet_dir.display()));
|
||
|
|
for entry in fs::read_dir(wallet_dir).map_err(unreadable)? {
|
||
|
|
let found = entry.map_err(unreadable)?.file_name();
|
||
|
|
if found == std::ffi::OsStr::new(name) || found == std::ffi::OsStr::new(keys.as_str()) {
|
||
|
|
return Ok(true);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Ok(false)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn ensure_parent(path: &Path) -> Result<()> {
|
||
|
|
if let Some(parent) = path.parent()
|
||
|
|
&& !parent.as_os_str().is_empty()
|
||
|
|
{
|
||
|
|
create_dir_700(parent).map_err(|e| ChildError(format!("datadir parent: {e}")))?;
|
||
|
|
}
|
||
|
|
Ok(())
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The wallet file is a spend authority: keep it 0600.
|
||
|
|
fn harden_wallet_file(path: &Path) {
|
||
|
|
let Ok(meta) = fs::metadata(path) else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
let mut perms = meta.permissions();
|
||
|
|
perms.set_mode(0o600);
|
||
|
|
let _ = fs::set_permissions(path, perms);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::test_support::PublishedPortHold;
|
||
|
|
use super::*;
|
||
|
|
use std::io::Write;
|
||
|
|
|
||
|
|
fn tmp_dir(tag: &str) -> PathBuf {
|
||
|
|
let dir =
|
||
|
|
std::env::temp_dir().join(format!("onionwire-child-{tag}-{}", std::process::id()));
|
||
|
|
let _ = fs::remove_dir_all(&dir);
|
||
|
|
dir
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Fake children live in their own dir: `Store::open_at*` already creates
|
||
|
|
/// `<home>/arti` and `<home>/cache` (the app's Arti state), so a fake `arti`
|
||
|
|
/// at the home root would collide with that directory.
|
||
|
|
fn fake_dir(dir: &Path) -> PathBuf {
|
||
|
|
let path = dir.join("fake-bins");
|
||
|
|
fs::create_dir_all(&path).unwrap();
|
||
|
|
path
|
||
|
|
}
|
||
|
|
|
||
|
|
fn open_store(dir: &Path) -> Store {
|
||
|
|
Store::open_at_with_passphrase(dir, "child-test-pass").expect("open store")
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks.
|
||
|
|
///
|
||
|
|
/// The argv lands in `<log>` with one `mv`, not a truncate-then-append: a
|
||
|
|
/// reader must never see half an argv. It did — the poll below could catch
|
||
|
|
/// `--rpc-bind-port` while the port was still being written and parse
|
||
|
|
/// `427` out of `42765`, a valid-but-wrong port, and the test then bound a
|
||
|
|
/// mock nobody dialled.
|
||
|
|
fn fake_bin(dir: &Path, name: &str, log: &Path) -> PathBuf {
|
||
|
|
let path = dir.join(name);
|
||
|
|
let mut f = fs::File::create(&path).unwrap();
|
||
|
|
writeln!(f, "#!/bin/sh").unwrap();
|
||
|
|
writeln!(f, "tmp='{}'.$$", log.display()).unwrap();
|
||
|
|
writeln!(f, ": > \"$tmp\"").unwrap();
|
||
|
|
writeln!(
|
||
|
|
f,
|
||
|
|
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done"
|
||
|
|
)
|
||
|
|
.unwrap();
|
||
|
|
writeln!(f, "mv -f \"$tmp\" '{}'", log.display()).unwrap();
|
||
|
|
writeln!(f, "sleep 30").unwrap();
|
||
|
|
drop(f);
|
||
|
|
let mut perms = fs::metadata(&path).unwrap().permissions();
|
||
|
|
perms.set_mode(0o700);
|
||
|
|
fs::set_permissions(&path, perms).unwrap();
|
||
|
|
path
|
||
|
|
}
|
||
|
|
|
||
|
|
fn argv_from(log: &Path) -> Vec<String> {
|
||
|
|
fs::read_to_string(log)
|
||
|
|
.unwrap_or_default()
|
||
|
|
.lines()
|
||
|
|
.map(str::to_string)
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The fake child writes its argv after exec: poll instead of racing it.
|
||
|
|
fn wait_for_argv(log: &Path) -> Vec<String> {
|
||
|
|
for _ in 0..60 {
|
||
|
|
let argv = argv_from(log);
|
||
|
|
if !argv.is_empty() {
|
||
|
|
return argv;
|
||
|
|
}
|
||
|
|
std::thread::sleep(std::time::Duration::from_millis(50));
|
||
|
|
}
|
||
|
|
argv_from(log)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn local_source(dir: &Path, monerod: PathBuf) -> ChainSource {
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin: monerod,
|
||
|
|
datadir: dir.join("monerod-data"),
|
||
|
|
prune: false,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn none_source_is_disabled_and_starts_nothing() {
|
||
|
|
let dir = tmp_dir("none");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let arti_log = dir.join("arti.argv");
|
||
|
|
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None)
|
||
|
|
.unwrap()
|
||
|
|
.with_arti_bin(fake_bin(&fake_dir(&dir), "arti", &arti_log));
|
||
|
|
assert!(!child.is_enabled());
|
||
|
|
assert!(child.start(&store).unwrap().is_none());
|
||
|
|
assert!(!child.running());
|
||
|
|
assert!(
|
||
|
|
!arti_log.exists(),
|
||
|
|
"receive-only must not spawn the SOCKS child"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn start_unlocking_store_is_the_same_as_start_for_receive_only() {
|
||
|
|
let dir = tmp_dir("none-unlock");
|
||
|
|
let store = std::sync::Mutex::new(open_store(&dir));
|
||
|
|
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap();
|
||
|
|
assert!(child.start_unlocking_store(&store).unwrap().is_none());
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A live listener for the readiness gate to dial. `arti proxy -p <port>`
|
||
|
|
/// binds localhost only, so 127.0.0.1 is exactly what the gate probes.
|
||
|
|
fn held_loopback_port() -> (std::net::TcpListener, u16) {
|
||
|
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
(listener, port)
|
||
|
|
}
|
||
|
|
|
||
|
|
fn freed_loopback_port() -> u16 {
|
||
|
|
held_loopback_port().1
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A fake child that also records its pid, so a test can prove the process
|
||
|
|
/// is gone after `stop` — an orphaned SOCKS listener is the failure mode.
|
||
|
|
fn fake_bin_with_pid(dir: &Path, name: &str, log: &Path, pid_file: &Path) -> PathBuf {
|
||
|
|
let path = dir.join(name);
|
||
|
|
let mut f = fs::File::create(&path).unwrap();
|
||
|
|
writeln!(f, "#!/bin/sh").unwrap();
|
||
|
|
writeln!(f, "echo $$ > '{}'", pid_file.display()).unwrap();
|
||
|
|
writeln!(f, ": > '{}'", log.display()).unwrap();
|
||
|
|
writeln!(
|
||
|
|
f,
|
||
|
|
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done",
|
||
|
|
log.display()
|
||
|
|
)
|
||
|
|
.unwrap();
|
||
|
|
writeln!(f, "sleep 30").unwrap();
|
||
|
|
drop(f);
|
||
|
|
let mut perms = fs::metadata(&path).unwrap().permissions();
|
||
|
|
perms.set_mode(0o700);
|
||
|
|
fs::set_permissions(&path, perms).unwrap();
|
||
|
|
path
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Poll for the child's pid file: the script writes it after exec.
|
||
|
|
fn child_pid(pid_file: &Path) -> u32 {
|
||
|
|
for _ in 0..60 {
|
||
|
|
if let Ok(raw) = fs::read_to_string(pid_file)
|
||
|
|
&& let Ok(pid) = raw.trim().parse::<u32>()
|
||
|
|
{
|
||
|
|
return pid;
|
||
|
|
}
|
||
|
|
std::thread::sleep(std::time::Duration::from_millis(50));
|
||
|
|
}
|
||
|
|
panic!("child never wrote {}", pid_file.display());
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The process must actually be gone, not merely dropped from a slot.
|
||
|
|
fn wait_for_process_exit(pid: u32) {
|
||
|
|
let proc_dir = PathBuf::from(format!("/proc/{pid}"));
|
||
|
|
for _ in 0..60 {
|
||
|
|
if !proc_dir.exists() {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
std::thread::sleep(std::time::Duration::from_millis(50));
|
||
|
|
}
|
||
|
|
panic!("pid {pid} is still alive — orphaned child");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn pairs(argv: &[String]) -> Vec<(String, String)> {
|
||
|
|
argv.windows(2)
|
||
|
|
.map(|w| (w[0].clone(), w[1].clone()))
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn arti_proxy_argv_binds_a_loopback_port_and_isolates_state() {
|
||
|
|
let dir = tmp_dir("arti-argv");
|
||
|
|
let bin = PathBuf::from("/opt/arti/arti");
|
||
|
|
let state = dir.join("wallet").join("arti-socks").join("state");
|
||
|
|
let cache = dir.join("wallet").join("arti-socks").join("cache");
|
||
|
|
let argv = WalletChild::arti_proxy_argv(&bin, 45123, &state, &cache);
|
||
|
|
assert_eq!(argv[0], bin.display().to_string());
|
||
|
|
assert_eq!(argv[1], "proxy");
|
||
|
|
assert!(
|
||
|
|
pairs(&argv).contains(&("-p".into(), "45123".into())),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
// `-p` binds localhost only (arti's `socks-port` arg); there is no
|
||
|
|
// Unix-socket listen target in arti 2.6.0 / tor-config 0.46.
|
||
|
|
assert!(!argv.iter().any(|a| a == "--port"), "{argv:?}");
|
||
|
|
assert!(
|
||
|
|
argv.iter()
|
||
|
|
.any(|a| a.contains(&state.display().to_string())),
|
||
|
|
"the SOCKS child gets its own state dir: {argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
argv.iter()
|
||
|
|
.any(|a| a.contains(&cache.display().to_string())),
|
||
|
|
"the SOCKS child gets its own cache dir: {argv:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn onion_remote_points_the_wallet_child_at_the_socks_proxy_and_the_onion() {
|
||
|
|
let dir = tmp_dir("onion-argv");
|
||
|
|
let bin = PathBuf::from("/opt/monero/monero-wallet-rpc");
|
||
|
|
let proxy = WalletChild::socks_proxy_url(45678);
|
||
|
|
let argv = WalletChild::wallet_rpc_argv(
|
||
|
|
&bin,
|
||
|
|
39127,
|
||
|
|
"owuser:owpass",
|
||
|
|
&dir,
|
||
|
|
Some("abcdefghijklmnop.onion:18089"),
|
||
|
|
Some(&proxy),
|
||
|
|
);
|
||
|
|
let pairs = pairs(&argv);
|
||
|
|
assert!(
|
||
|
|
pairs.contains(&("--proxy".into(), "socks5://127.0.0.1:45678".into())),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
argv.iter().any(|a| a.contains("127.0.0.1:45678")),
|
||
|
|
"the literal loopback:port the card asks for: {argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
pairs.contains(&(
|
||
|
|
"--daemon-address".into(),
|
||
|
|
"abcdefghijklmnop.onion:18089".into()
|
||
|
|
)),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
// The wallet child speaks plain SOCKS5 to loopback. It never gets the
|
||
|
|
// messenger's in-process Arti client, and the daemon stays untrusted.
|
||
|
|
assert!(!argv.iter().any(|a| a == "--trusted-daemon"), "{argv:?}");
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn onion_detection_is_case_insensitive_and_needs_the_suffix() {
|
||
|
|
assert!(WalletChild::is_onion_host("abcdefgh.onion"));
|
||
|
|
assert!(WalletChild::is_onion_host("ABCDEFGH.ONION"));
|
||
|
|
assert!(WalletChild::is_onion_host(" abcdefgh.onion "));
|
||
|
|
assert!(!WalletChild::is_onion_host("onion.example.com"));
|
||
|
|
assert!(!WalletChild::is_onion_host("127.0.0.1"));
|
||
|
|
assert!(!WalletChild::is_onion_host("node.onion.example.com"));
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn chain_copy_says_tor_hides_the_transport_not_the_host() {
|
||
|
|
let onion = WalletChild::chain_copy(&ChainSource::Remote {
|
||
|
|
host: "abcdefghijklmnop.onion".into(),
|
||
|
|
port: 18089,
|
||
|
|
});
|
||
|
|
assert!(onion.contains("Tor"), "{onion}");
|
||
|
|
assert!(
|
||
|
|
onion.contains("hides the transport, not the host"),
|
||
|
|
"{onion}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
onion.contains("operator still sees your addresses"),
|
||
|
|
"{onion}"
|
||
|
|
);
|
||
|
|
|
||
|
|
let clearnet = WalletChild::chain_copy(&ChainSource::Remote {
|
||
|
|
host: "node.example.com".into(),
|
||
|
|
port: 18089,
|
||
|
|
});
|
||
|
|
assert!(clearnet.contains("clearnet"), "{clearnet}");
|
||
|
|
assert!(!clearnet.contains("Tor"), "{clearnet}");
|
||
|
|
|
||
|
|
let local = WalletChild::chain_copy(&local_source(
|
||
|
|
Path::new("/tmp"),
|
||
|
|
PathBuf::from("/usr/bin/monerod"),
|
||
|
|
));
|
||
|
|
assert!(local.contains("local monerod"), "{local}");
|
||
|
|
assert_eq!(
|
||
|
|
WalletChild::chain_copy(&ChainSource::None),
|
||
|
|
"receive-only: no daemon, no chain traffic"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The readiness gate is real code, not a stub: it accepts a listener that
|
||
|
|
/// is up and gives up with a typed error, inside its budget, when nothing
|
||
|
|
/// is listening.
|
||
|
|
#[test]
|
||
|
|
fn socks_listener_ready_accepts_a_live_listener_and_times_out_without_one() {
|
||
|
|
let (held, port) = held_loopback_port();
|
||
|
|
assert!(
|
||
|
|
WalletChild::socks_listener_ready(port, Duration::from_millis(200)).is_ok(),
|
||
|
|
"a live listener must pass"
|
||
|
|
);
|
||
|
|
drop(held);
|
||
|
|
|
||
|
|
let started = std::time::Instant::now();
|
||
|
|
let err = WalletChild::socks_listener_ready(port, Duration::from_millis(200))
|
||
|
|
.unwrap_err()
|
||
|
|
.to_string();
|
||
|
|
assert!(err.contains("SOCKS"), "{err}");
|
||
|
|
assert!(err.contains(&port.to_string()), "{err}");
|
||
|
|
assert!(
|
||
|
|
started.elapsed() < Duration::from_secs(5),
|
||
|
|
"the probe must honour its budget, took {:?}",
|
||
|
|
started.elapsed()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The shared accept wait: it passes for a live listener and fails, inside
|
||
|
|
/// its budget, for a closed port — with a message that names the thing that
|
||
|
|
/// did not accept, so the wallet screen can say which port is closed.
|
||
|
|
#[test]
|
||
|
|
fn loopback_listener_ready_accepts_a_live_listener_and_times_out_without_one() {
|
||
|
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||
|
|
let port = listener.local_addr().unwrap().port();
|
||
|
|
assert!(
|
||
|
|
WalletChild::loopback_listener_ready(
|
||
|
|
port,
|
||
|
|
Duration::from_millis(200),
|
||
|
|
"chain daemon RPC"
|
||
|
|
)
|
||
|
|
.is_ok(),
|
||
|
|
"a live listener is ready"
|
||
|
|
);
|
||
|
|
drop(listener);
|
||
|
|
let err =
|
||
|
|
WalletChild::loopback_listener_ready(9, Duration::from_millis(200), "chain daemon RPC")
|
||
|
|
.expect_err("a closed port must fail the start, not hang");
|
||
|
|
let msg = err.to_string();
|
||
|
|
assert!(msg.contains("chain daemon RPC"), "{msg}");
|
||
|
|
assert!(msg.contains("127.0.0.1:9"), "{msg}");
|
||
|
|
assert!(msg.contains("not continuing startup"), "{msg}");
|
||
|
|
assert!(!msg.contains("dead proxy"), "{msg}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The spawn path: a `.onion` remote starts `arti proxy -p <port>` first,
|
||
|
|
/// the wallet child is pointed at it, and stopping the wallet child takes
|
||
|
|
/// the SOCKS listener with it.
|
||
|
|
#[test]
|
||
|
|
fn onion_remote_start_spawns_the_socks_child_then_stops_it_with_the_wallet() {
|
||
|
|
let dir = tmp_dir("onion-start");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let arti_log = dir.join("arti.argv");
|
||
|
|
let arti_pid = dir.join("arti.pid");
|
||
|
|
let rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let rpc_pid = dir.join("wallet-rpc.pid");
|
||
|
|
|
||
|
|
// The gate dials 127.0.0.1:<port>; the test holds that port open so the
|
||
|
|
// gate passes without a real arti binary. The gate itself is covered by
|
||
|
|
// `socks_listener_ready_*` above.
|
||
|
|
let (held, socks_port) = held_loopback_port();
|
||
|
|
|
||
|
|
let child = WalletChild::new(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "abcdefghijklmnop.onion".into(),
|
||
|
|
port: 18089,
|
||
|
|
},
|
||
|
|
dir.join("wallet"),
|
||
|
|
None,
|
||
|
|
)
|
||
|
|
.unwrap()
|
||
|
|
.with_arti_bin(fake_bin_with_pid(
|
||
|
|
&fake_dir(&dir),
|
||
|
|
"arti",
|
||
|
|
&arti_log,
|
||
|
|
&arti_pid,
|
||
|
|
))
|
||
|
|
.with_wallet_rpc_bin(fake_bin_with_pid(
|
||
|
|
&dir,
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&rpc_log,
|
||
|
|
&rpc_pid,
|
||
|
|
))
|
||
|
|
.with_socks_port(socks_port);
|
||
|
|
|
||
|
|
// The daemon gate does not apply to a remote source, but the wallet
|
||
|
|
// RPC's own port gate does: hold what the fake publishes.
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
|
||
|
|
let client = child.start(&store).unwrap().expect("enabled child");
|
||
|
|
assert!(child.running(), "both children must be tracked");
|
||
|
|
assert!(client.url().contains("127.0.0.1"), "{}", client.url());
|
||
|
|
|
||
|
|
let arti_argv = wait_for_argv(&arti_log);
|
||
|
|
// The fake logs only the arguments (`$@`), not argv[0].
|
||
|
|
assert_eq!(arti_argv[0], "proxy", "{arti_argv:?}");
|
||
|
|
assert!(
|
||
|
|
pairs(&arti_argv).contains(&("-p".into(), socks_port.to_string())),
|
||
|
|
"{arti_argv:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
let rpc_argv = wait_for_argv(&rpc_log);
|
||
|
|
let rpc_pairs = pairs(&rpc_argv);
|
||
|
|
assert!(
|
||
|
|
rpc_pairs.contains(&("--proxy".into(), format!("socks5://127.0.0.1:{socks_port}"))),
|
||
|
|
"{rpc_argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
rpc_pairs.contains(&(
|
||
|
|
"--daemon-address".into(),
|
||
|
|
"abcdefghijklmnop.onion:18089".into()
|
||
|
|
)),
|
||
|
|
"{rpc_argv:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
let arti_proc = child_pid(&arti_pid);
|
||
|
|
let rpc_proc = child_pid(&rpc_pid);
|
||
|
|
drop(held);
|
||
|
|
|
||
|
|
child.stop().unwrap();
|
||
|
|
assert!(!child.running());
|
||
|
|
wait_for_process_exit(arti_proc);
|
||
|
|
wait_for_process_exit(rpc_proc);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A wallet child that cannot dial its daemon must not be spawned at all:
|
||
|
|
/// a dead SOCKS proxy is a visible error, not a hung wallet screen.
|
||
|
|
#[test]
|
||
|
|
fn onion_remote_start_fails_visibly_when_the_socks_proxy_never_listens() {
|
||
|
|
let dir = tmp_dir("onion-dead-proxy");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let arti_pid = dir.join("arti.pid");
|
||
|
|
let arti_log = dir.join("arti.argv");
|
||
|
|
let rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let port = freed_loopback_port();
|
||
|
|
|
||
|
|
let child = WalletChild::new(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "abcdefghijklmnop.onion".into(),
|
||
|
|
port: 18089,
|
||
|
|
},
|
||
|
|
dir.join("wallet"),
|
||
|
|
None,
|
||
|
|
)
|
||
|
|
.unwrap()
|
||
|
|
.with_arti_bin(fake_bin_with_pid(
|
||
|
|
&fake_dir(&dir),
|
||
|
|
"arti",
|
||
|
|
&arti_log,
|
||
|
|
&arti_pid,
|
||
|
|
))
|
||
|
|
.with_wallet_rpc_bin(fake_bin(&fake_dir(&dir), "monero-wallet-rpc", &rpc_log))
|
||
|
|
.with_socks_port(port)
|
||
|
|
.with_socks_ready_timeout(Duration::from_millis(300));
|
||
|
|
|
||
|
|
let err = child.start(&store).unwrap_err().to_string();
|
||
|
|
assert!(err.contains("SOCKS"), "{err}");
|
||
|
|
assert!(err.contains(&port.to_string()), "{err}");
|
||
|
|
assert!(
|
||
|
|
!rpc_log.exists(),
|
||
|
|
"no wallet child may be spawned against a dead proxy"
|
||
|
|
);
|
||
|
|
assert!(!child.running(), "a failed start leaves nothing running");
|
||
|
|
wait_for_process_exit(child_pid(&arti_pid));
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A loopback or clearnet daemon the user typed never gets a proxy, and
|
||
|
|
/// never starts the SOCKS child: `--proxy` is for `.onion` only.
|
||
|
|
#[test]
|
||
|
|
fn loopback_and_clearnet_remotes_carry_no_proxy_and_spawn_no_socks_child() {
|
||
|
|
for host in ["127.0.0.1", "node.example.com"] {
|
||
|
|
let dir = tmp_dir(&format!("nosocks-{}", host.replace('.', "-")));
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let arti_log = dir.join("arti.argv");
|
||
|
|
let rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let child = WalletChild::new(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: host.into(),
|
||
|
|
port: 18089,
|
||
|
|
},
|
||
|
|
dir.join("wallet"),
|
||
|
|
None,
|
||
|
|
)
|
||
|
|
.unwrap()
|
||
|
|
.with_arti_bin(fake_bin(&fake_dir(&dir), "arti", &arti_log))
|
||
|
|
.with_wallet_rpc_bin(fake_bin(
|
||
|
|
&fake_dir(&dir),
|
||
|
|
"monero-wallet-rpc",
|
||
|
|
&rpc_log,
|
||
|
|
));
|
||
|
|
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
|
||
|
|
child.start(&store).unwrap().expect("enabled child");
|
||
|
|
let rpc_argv = wait_for_argv(&rpc_log);
|
||
|
|
assert!(
|
||
|
|
pairs(&rpc_argv).contains(&("--daemon-address".into(), format!("{host}:18089"))),
|
||
|
|
"{rpc_argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!rpc_argv.iter().any(|a| a == "--proxy"),
|
||
|
|
"no SOCKS for {host}: {rpc_argv:?}"
|
||
|
|
);
|
||
|
|
assert!(!arti_log.exists(), "no SOCKS child for {host}");
|
||
|
|
child.stop().unwrap();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn daemon_address_matches_each_chain_source() {
|
||
|
|
assert_eq!(WalletChild::daemon_address(&ChainSource::None), None);
|
||
|
|
assert_eq!(
|
||
|
|
WalletChild::daemon_address(&local_source(
|
||
|
|
Path::new("/tmp"),
|
||
|
|
PathBuf::from("/usr/bin/monerod")
|
||
|
|
)),
|
||
|
|
Some("127.0.0.1:18081".into())
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
WalletChild::daemon_address(&ChainSource::Remote {
|
||
|
|
host: "node.example.com".into(),
|
||
|
|
port: 18089
|
||
|
|
}),
|
||
|
|
Some("node.example.com:18089".into())
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn wallet_rpc_argv_carries_the_locked_flags() {
|
||
|
|
let dir = tmp_dir("argv");
|
||
|
|
let bin = PathBuf::from("/opt/monero/monero-wallet-rpc");
|
||
|
|
let argv = WalletChild::wallet_rpc_argv(
|
||
|
|
&bin,
|
||
|
|
39127,
|
||
|
|
"owuser:owpass",
|
||
|
|
&dir,
|
||
|
|
Some("127.0.0.1:18081"),
|
||
|
|
None,
|
||
|
|
);
|
||
|
|
let pairs: Vec<(&str, &str)> = argv
|
||
|
|
.windows(2)
|
||
|
|
.map(|w| (w[0].as_str(), w[1].as_str()))
|
||
|
|
.collect();
|
||
|
|
assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}");
|
||
|
|
assert!(pairs.contains(&("--rpc-bind-port", "39127")), "{argv:?}");
|
||
|
|
assert!(
|
||
|
|
pairs.contains(&("--rpc-login", "owuser:owpass")),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
pairs.contains(&("--wallet-dir", dir.to_str().unwrap())),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
pairs.contains(&("--daemon-address", "127.0.0.1:18081")),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert_eq!(argv[0], bin.display().to_string());
|
||
|
|
assert!(
|
||
|
|
!argv.iter().any(|a| a == "--trusted-daemon"),
|
||
|
|
"a remote daemon is untrusted: {argv:?}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn monerod_argv_binds_loopback_and_uses_the_datadir() {
|
||
|
|
let dir = tmp_dir("monerod-argv");
|
||
|
|
let datadir = dir.join("chain");
|
||
|
|
let argv = WalletChild::monerod_argv(
|
||
|
|
&PathBuf::from("/usr/bin/monerod"),
|
||
|
|
&datadir,
|
||
|
|
DEFAULT_MONEROD_RPC_PORT,
|
||
|
|
false,
|
||
|
|
);
|
||
|
|
let pairs: Vec<(&str, &str)> = argv
|
||
|
|
.windows(2)
|
||
|
|
.map(|w| (w[0].as_str(), w[1].as_str()))
|
||
|
|
.collect();
|
||
|
|
assert!(
|
||
|
|
pairs.contains(&("--data-dir", datadir.to_str().unwrap())),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert!(pairs.contains(&("--rpc-bind-ip", "127.0.0.1")), "{argv:?}");
|
||
|
|
assert!(pairs.contains(&("--rpc-bind-port", "18081")), "{argv:?}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The real spawn path: a local chain source starts monerod, then
|
||
|
|
/// monero-wallet-rpc, with exactly the argv the builders produce — and the
|
||
|
|
/// creds come out of the encrypted store, not a file in the wallet dir.
|
||
|
|
#[test]
|
||
|
|
fn start_spawns_both_children_with_the_built_argv() {
|
||
|
|
let dir = tmp_dir("start");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let monerod_log = dir.join("monerod.argv");
|
||
|
|
let rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let datadir = dir.join("monerod-data");
|
||
|
|
|
||
|
|
let child = WalletChild::new(
|
||
|
|
local_source(&dir, fake_bin(&dir, "monerod", &monerod_log)),
|
||
|
|
dir.join("wallet"),
|
||
|
|
None,
|
||
|
|
)
|
||
|
|
.unwrap()
|
||
|
|
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
||
|
|
|
||
|
|
// The gate dials the ports the fakes were told to bind; a shell fake
|
||
|
|
// cannot bind one, so hold them here.
|
||
|
|
let _hold = PublishedPortHold::watching(&[monerod_log.clone(), rpc_log.clone()]);
|
||
|
|
let client = child.start(&store).unwrap().expect("enabled child");
|
||
|
|
assert!(child.running(), "children must be tracked");
|
||
|
|
|
||
|
|
let monerod_argv = wait_for_argv(&monerod_log);
|
||
|
|
assert!(
|
||
|
|
monerod_argv
|
||
|
|
.windows(2)
|
||
|
|
.any(|w| w[0] == "--data-dir" && w[1] == datadir.display().to_string()),
|
||
|
|
"{monerod_argv:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
let rpc_argv = wait_for_argv(&rpc_log);
|
||
|
|
assert!(
|
||
|
|
rpc_argv.iter().any(|a| a == "--rpc-bind-ip"),
|
||
|
|
"{rpc_argv:?}"
|
||
|
|
);
|
||
|
|
assert!(rpc_argv.iter().any(|a| a == "127.0.0.1"), "{rpc_argv:?}");
|
||
|
|
assert!(rpc_argv.iter().any(|a| a == "--rpc-login"), "{rpc_argv:?}");
|
||
|
|
assert!(rpc_argv.iter().any(|a| a == "--wallet-dir"), "{rpc_argv:?}");
|
||
|
|
assert!(
|
||
|
|
rpc_argv.windows(2).any(|w| w[0] == "--daemon-address"),
|
||
|
|
"{rpc_argv:?}"
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
!rpc_argv.iter().any(|a| a == "--trusted-daemon"),
|
||
|
|
"{rpc_argv:?}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// The wallet client is the generated loopback URL, and it carries the
|
||
|
|
// same login the child was spawned with.
|
||
|
|
let url = client.url().to_string();
|
||
|
|
assert!(url.starts_with("http://"), "{url}");
|
||
|
|
assert!(url.contains("@127.0.0.1:"), "{url}");
|
||
|
|
let login_arg = rpc_argv
|
||
|
|
.iter()
|
||
|
|
.position(|a| a == "--rpc-login")
|
||
|
|
.map(|i| rpc_argv[i + 1].clone())
|
||
|
|
.expect("login");
|
||
|
|
let (user, pass) = login_arg.split_once(':').expect("user:pass");
|
||
|
|
assert_ne!(user, pass, "user and password must be independent");
|
||
|
|
assert!(
|
||
|
|
url.contains(user) && url.contains(pass),
|
||
|
|
"{url} vs {login_arg}"
|
||
|
|
);
|
||
|
|
|
||
|
|
// Creds live sealed in the store, and nothing in the wallet dir holds
|
||
|
|
// them in the clear.
|
||
|
|
let sealed = store.load_wallet_child().unwrap().expect("sealed creds");
|
||
|
|
assert!(sealed.contains(user));
|
||
|
|
for entry in fs::read_dir(child.wallet_dir()).unwrap() {
|
||
|
|
let path = entry.unwrap().path();
|
||
|
|
let body = fs::read(&path).unwrap_or_default();
|
||
|
|
assert!(
|
||
|
|
!body.windows(pass.len()).any(|w| w == pass.as_bytes()),
|
||
|
|
"{} holds the RPC password in the clear",
|
||
|
|
path.display()
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
child.stop().unwrap();
|
||
|
|
assert!(!child.running(), "stop must kill both children");
|
||
|
|
child.stop().unwrap(); // idempotent
|
||
|
|
assert!(child.start(&store).is_ok(), "restart after stop");
|
||
|
|
child.stop().unwrap();
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn creds_are_stable_across_restarts_and_never_regenerated() {
|
||
|
|
let dir = tmp_dir("creds");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let child = WalletChild::new(
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "node.example.com".into(),
|
||
|
|
port: 18089,
|
||
|
|
},
|
||
|
|
dir.join("wallet"),
|
||
|
|
None,
|
||
|
|
)
|
||
|
|
.unwrap()
|
||
|
|
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
||
|
|
|
||
|
|
let _hold = PublishedPortHold::watching(std::slice::from_ref(&rpc_log));
|
||
|
|
let first = child.start(&store).unwrap().unwrap().url().to_string();
|
||
|
|
child.stop().unwrap();
|
||
|
|
let second = child.start(&store).unwrap().unwrap().url().to_string();
|
||
|
|
child.stop().unwrap();
|
||
|
|
// Same login, different random port: the creds persist in the store
|
||
|
|
// instead of being regenerated per launch.
|
||
|
|
assert_eq!(login_of(&first), login_of(&second), "creds must persist");
|
||
|
|
assert!(first.contains("127.0.0.1"), "{first}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `http://user:[email protected]:port/json_rpc` -> `user:pass`.
|
||
|
|
fn login_of(url: &str) -> String {
|
||
|
|
let rest = url.strip_prefix("http://").expect("http url");
|
||
|
|
rest.split('@').next().expect("userinfo").to_string()
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn pick_port_is_free_loopback_and_bindable() {
|
||
|
|
let port = WalletChild::pick_port().unwrap();
|
||
|
|
assert!(port > 0);
|
||
|
|
let listener = std::net::TcpListener::bind(format!("127.0.0.1:{port}")).unwrap();
|
||
|
|
drop(listener);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn stop_without_start_is_a_noop() {
|
||
|
|
let dir = tmp_dir("stop");
|
||
|
|
let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap();
|
||
|
|
child.stop().unwrap();
|
||
|
|
assert!(!child.running());
|
||
|
|
assert!(!child.child_exited());
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn wallet_dir_is_created_0700() {
|
||
|
|
let dir = tmp_dir("perm");
|
||
|
|
let wallet_dir = dir.join("wallet");
|
||
|
|
let _ = WalletChild::new(ChainSource::None, wallet_dir.clone(), None).unwrap();
|
||
|
|
let mode = fs::metadata(&wallet_dir).unwrap().permissions().mode() & 0o777;
|
||
|
|
assert_eq!(mode, 0o700, "wallet dir must be 0700");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn in_process_source(dir: &Path) -> ChainSource {
|
||
|
|
ChainSource::InProcessCuprate {
|
||
|
|
datadir: dir.join("chain"),
|
||
|
|
network: ChainNetwork::Testnet,
|
||
|
|
prune: false,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// 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.
|
||
|
|
/// That is the whole reason `wallet_rpc_argv` does not change.
|
||
|
|
#[test]
|
||
|
|
fn the_in_process_source_is_a_local_daemon_on_the_same_port() {
|
||
|
|
let dir = tmp_dir("cuprate-local");
|
||
|
|
let source = in_process_source(&dir);
|
||
|
|
let local = local_source(&dir, PathBuf::from("monerod"));
|
||
|
|
|
||
|
|
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),
|
||
|
|
"a spawned and an in-process local source are the same address"
|
||
|
|
);
|
||
|
|
assert_eq!(
|
||
|
|
WalletChild::chain_datadir(&source),
|
||
|
|
Some(dir.join("chain").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"
|
||
|
|
);
|
||
|
|
|
||
|
|
// The wallet-child argv is byte-for-byte the tested local-node shape:
|
||
|
|
// same `--daemon-address`, and never `--trusted-daemon`.
|
||
|
|
let argv = WalletChild::wallet_rpc_argv(
|
||
|
|
Path::new("monero-wallet-rpc"),
|
||
|
|
39127,
|
||
|
|
"u:p",
|
||
|
|
&dir.join("wallet"),
|
||
|
|
WalletChild::daemon_address(&source).as_deref(),
|
||
|
|
None,
|
||
|
|
);
|
||
|
|
assert!(
|
||
|
|
argv.windows(2).any(|w| w[0] == "--daemon-address"
|
||
|
|
&& w[1] == format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}")),
|
||
|
|
"{argv:?}"
|
||
|
|
);
|
||
|
|
assert!(!argv.iter().any(|a| a == "--trusted-daemon"), "{argv:?}");
|
||
|
|
|
||
|
|
assert!(
|
||
|
|
WalletChild::new(source, dir.join("wallet"), None)
|
||
|
|
.unwrap()
|
||
|
|
.is_enabled(),
|
||
|
|
"an in-process source is a chain source: there is something to start"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The copy names what is on this device and the one thing that must not be
|
||
|
|
/// buried: this daemon is testnet-only.
|
||
|
|
#[test]
|
||
|
|
fn in_process_copy_says_local_and_testnet_only() {
|
||
|
|
let dir = tmp_dir("cuprate-copy");
|
||
|
|
let copy = WalletChild::chain_copy(&in_process_source(&dir));
|
||
|
|
assert!(copy.contains("in this app"), "{copy}");
|
||
|
|
assert!(copy.contains("no Tor"), "{copy}");
|
||
|
|
assert!(copy.contains(crate::cuprate::TESTNET_ONLY), "{copy}");
|
||
|
|
assert_eq!(
|
||
|
|
crate::cuprate::TESTNET_ONLY,
|
||
|
|
"testnet only — mainnet is unvalidated"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The picker's choice has to survive a restart without a child ever
|
||
|
|
/// starting, exactly like the other sources — and read back as itself,
|
||
|
|
/// never as receive-only.
|
||
|
|
#[test]
|
||
|
|
fn the_in_process_choice_round_trips_through_the_sealed_record() {
|
||
|
|
let dir = tmp_dir("cuprate-record");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let source = in_process_source(&dir);
|
||
|
|
let cfg = ChildConfig {
|
||
|
|
source: source.clone(),
|
||
|
|
..ChildConfig::default()
|
||
|
|
};
|
||
|
|
cfg.validate().unwrap();
|
||
|
|
let record = merge_record(None, cfg.record_fields());
|
||
|
|
store.save_wallet_child(&record).unwrap();
|
||
|
|
|
||
|
|
let raw = store.load_wallet_child().unwrap().expect("sealed record");
|
||
|
|
assert_eq!(ChildConfig::from_record(&raw).unwrap().unwrap(), cfg);
|
||
|
|
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(),
|
||
|
|
dir.join("chain").display().to_string()
|
||
|
|
);
|
||
|
|
|
||
|
|
// An empty datadir is rejected before it is stored, never persisted and
|
||
|
|
// then failed over.
|
||
|
|
let empty = ChildConfig {
|
||
|
|
source: ChainSource::InProcessCuprate {
|
||
|
|
datadir: PathBuf::new(),
|
||
|
|
network: ChainNetwork::Testnet,
|
||
|
|
prune: false,
|
||
|
|
},
|
||
|
|
..ChildConfig::default()
|
||
|
|
};
|
||
|
|
let err = empty.validate().unwrap_err().to_string();
|
||
|
|
assert!(err.contains("chain data dir"), "{err}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Without the feature, starting the in-process source names the feature —
|
||
|
|
/// 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 rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None)
|
||
|
|
.unwrap()
|
||
|
|
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
||
|
|
let err = child.start(&store).unwrap_err().to_string();
|
||
|
|
assert!(err.contains("cuprate-daemon"), "{err}");
|
||
|
|
assert!(!child.running(), "nothing may be left running: {err}");
|
||
|
|
assert!(
|
||
|
|
!rpc_log.exists(),
|
||
|
|
"the wallet RPC child must not be spawned against a daemon that never started"
|
||
|
|
);
|
||
|
|
child.stop().unwrap();
|
||
|
|
}
|
||
|
|
|
||
|
|
/// With the feature compiled in, the launch is real: the daemon answers on
|
||
|
|
/// the port the wallet child is pointed at, `stop` shuts it down, and the
|
||
|
|
/// app-owned child list reports it honestly (as a daemon, never as a
|
||
|
|
/// process — there is no pid).
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
#[test]
|
||
|
|
fn in_process_source_launches_a_daemon_and_stop_shuts_it_down() {
|
||
|
|
let dir = tmp_dir("cuprate-on");
|
||
|
|
let store = open_store(&dir);
|
||
|
|
let rpc_log = dir.join("wallet-rpc.argv");
|
||
|
|
let child = WalletChild::new(in_process_source(&dir), dir.join("wallet"), None)
|
||
|
|
.unwrap()
|
||
|
|
.with_wallet_rpc_bin(fake_bin(&dir, "monero-wallet-rpc", &rpc_log));
|
||
|
|
|
||
|
|
// The wallet RPC child is fake, so `start` reaches only the daemon: the
|
||
|
|
// whole point of the in-process source is that the daemon *is* us.
|
||
|
|
let _ = child.start(&store);
|
||
|
|
let addr = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
||
|
|
assert!(
|
||
|
|
waits_for_tcp(&addr, Duration::from_secs(20)),
|
||
|
|
"the in-process daemon never answered on {addr}"
|
||
|
|
);
|
||
|
|
assert!(child.running(), "an owned daemon counts as running");
|
||
|
|
assert!(dir.join("chain").exists(), "the chain dir is created 0700");
|
||
|
|
|
||
|
|
child.stop().unwrap();
|
||
|
|
assert!(!child.running(), "stop must drop the daemon");
|
||
|
|
let mut closed = false;
|
||
|
|
for _ in 0..60 {
|
||
|
|
if std::net::TcpStream::connect(&addr).is_err() {
|
||
|
|
closed = true;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
std::thread::sleep(Duration::from_millis(250));
|
||
|
|
}
|
||
|
|
assert!(closed, "the daemon's RPC listener outlived stop()");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn probe_status(state: WalletChildState, height: u64, target_height: u64) -> WalletChildStatus {
|
||
|
|
WalletChildStatus {
|
||
|
|
state,
|
||
|
|
running: true,
|
||
|
|
wallet_open: true,
|
||
|
|
needs_passphrase: false,
|
||
|
|
configured: true,
|
||
|
|
chain_source: "in-process node".to_string(),
|
||
|
|
height,
|
||
|
|
target_height,
|
||
|
|
last_error: None,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// No probe numbers, no `sync` segment: a snapshot that never read a height
|
||
|
|
/// renders exactly the line it rendered before this existed.
|
||
|
|
#[test]
|
||
|
|
fn a_status_line_without_probe_numbers_carries_no_sync_segment() {
|
||
|
|
let line = probe_status(WalletChildState::Connecting, 0, 0).line();
|
||
|
|
assert_eq!(line, "child connecting · in-process node");
|
||
|
|
assert!(!line.contains("sync"), "{line}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The numbers the user asked for: the daemon's own height over the tip it
|
||
|
|
/// is syncing towards, on the same one-liner the wallet screen already shows.
|
||
|
|
#[test]
|
||
|
|
fn a_status_line_shows_the_daemons_height_and_target() {
|
||
|
|
let line = probe_status(WalletChildState::Connecting, 1160, 3_090_939).line();
|
||
|
|
assert!(line.contains("sync 1160/3090939"), "{line}");
|
||
|
|
assert!(!line.contains('%'), "{line}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// A daemon that reports no target is not a caught-up chain: the height is
|
||
|
|
/// still shown — over `0` — and no percentage is invented for it.
|
||
|
|
#[test]
|
||
|
|
fn a_missing_target_still_shows_the_height_and_no_percent() {
|
||
|
|
let line = probe_status(WalletChildState::Syncing, 4549, 0).line();
|
||
|
|
assert!(line.contains("sync 4549/0"), "{line}");
|
||
|
|
assert!(!line.contains('%'), "{line}");
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The failure text stays last: a probe number never displaces the error a
|
||
|
|
/// reader is looking for.
|
||
|
|
#[test]
|
||
|
|
fn a_status_line_keeps_the_error_after_the_sync_segment() {
|
||
|
|
let mut status = probe_status(WalletChildState::Connecting, 1160, 3_090_939);
|
||
|
|
status.last_error = Some("wallet connect: Connection refused (os error 111)".into());
|
||
|
|
let line = status.line();
|
||
|
|
assert!(line.contains("sync 1160/3090939"), "{line}");
|
||
|
|
assert!(
|
||
|
|
line.ends_with("· wallet connect: Connection refused (os error 111)"),
|
||
|
|
"{line}"
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Only a daemon this box owns is asked directly. A remote daemon is the
|
||
|
|
/// wallet child's to dial — a status refresh must not open a second path to
|
||
|
|
/// it, and receive-only has nothing to ask at all.
|
||
|
|
#[test]
|
||
|
|
fn only_a_loopback_source_gets_a_daemon_probe_address() {
|
||
|
|
let loopback = format!("127.0.0.1:{DEFAULT_MONEROD_RPC_PORT}");
|
||
|
|
for source in [
|
||
|
|
ChainSource::Local {
|
||
|
|
monerod_bin: PathBuf::from("monerod"),
|
||
|
|
datadir: PathBuf::from("/chain"),
|
||
|
|
prune: false,
|
||
|
|
},
|
||
|
|
ChainSource::InProcessCuprate {
|
||
|
|
datadir: PathBuf::from("/chain"),
|
||
|
|
network: ChainNetwork::Mainnet,
|
||
|
|
prune: true,
|
||
|
|
},
|
||
|
|
] {
|
||
|
|
let cfg = ChildConfig {
|
||
|
|
source: source.clone(),
|
||
|
|
..ChildConfig::default()
|
||
|
|
};
|
||
|
|
assert_eq!(cfg.daemon_probe_addr().as_deref(), Some(loopback.as_str()));
|
||
|
|
}
|
||
|
|
for source in [
|
||
|
|
ChainSource::None,
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "peer.onion".to_string(),
|
||
|
|
port: 18081,
|
||
|
|
},
|
||
|
|
ChainSource::Remote {
|
||
|
|
host: "203.0.113.7".to_string(),
|
||
|
|
port: 18081,
|
||
|
|
},
|
||
|
|
] {
|
||
|
|
let cfg = ChildConfig {
|
||
|
|
source,
|
||
|
|
..ChildConfig::default()
|
||
|
|
};
|
||
|
|
assert_eq!(cfg.daemon_probe_addr(), None);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Poll a loopback address until it accepts, inside a budget.
|
||
|
|
#[cfg(feature = "cuprate-daemon")]
|
||
|
|
fn waits_for_tcp(addr: &str, budget: Duration) -> bool {
|
||
|
|
let deadline = Instant::now() + budget;
|
||
|
|
while Instant::now() <= deadline {
|
||
|
|
if std::net::TcpStream::connect(addr).is_ok() {
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
std::thread::sleep(Duration::from_millis(100));
|
||
|
|
}
|
||
|
|
false
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Test-only stand-in for the ports the fake children cannot bind.
|
||
|
|
///
|
||
|
|
/// The readiness gates dial a port the child was told to bind (`18081` for the
|
||
|
|
/// daemon, the argv's `--rpc-bind-port` for `monero-wallet-rpc`) and refuse to
|
||
|
|
/// continue while nothing accepts. A `sh` fake child cannot bind one, and the
|
||
|
|
/// wallet RPC's port is picked at random *inside* the start, so a test cannot
|
||
|
|
/// bind it up front either: without this, every start path in the suite would
|
||
|
|
/// fail the gate instead of exercising the code behind it.
|
||
|
|
///
|
||
|
|
/// Only for a start nothing dials afterwards. A test that answers the wallet RPC
|
||
|
|
/// itself must own the port *before* the gate's probe: a listener that accepts
|
||
|
|
/// the probe and then closes resets the client's own dial, and a reset is an RPC
|
||
|
|
/// answer, not an unreachable child.
|
||
|
|
#[cfg(test)]
|
||
|
|
pub(crate) mod test_support {
|
||
|
|
use std::collections::HashMap;
|
||
|
|
use std::path::{Path, PathBuf};
|
||
|
|
use std::sync::Arc;
|
||
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||
|
|
use std::time::{Duration, SystemTime};
|
||
|
|
|
||
|
|
/// Holds every `--rpc-bind-port` a watched argv log publishes, for as long
|
||
|
|
/// as this value lives.
|
||
|
|
///
|
||
|
|
/// A held port is released the moment something connects to it: that connect
|
||
|
|
/// is the gate's own probe, and every dial after it must see the child's real
|
||
|
|
/// state (refused, or the test's own mock) rather than this stand-in. A
|
||
|
|
/// rewrite of the log is a new publication — the restart of a child whose
|
||
|
|
/// argv is identical (a local daemon's `18081`) is held again, while the
|
||
|
|
/// released publication is not.
|
||
|
|
pub(crate) struct PublishedPortHold {
|
||
|
|
stop: Arc<AtomicBool>,
|
||
|
|
handle: Option<std::thread::JoinHandle<()>>,
|
||
|
|
}
|
||
|
|
|
||
|
|
impl PublishedPortHold {
|
||
|
|
/// Watch these argv logs (`<something>.argv`, `argv.log`) and hold what
|
||
|
|
/// they publish.
|
||
|
|
pub(crate) fn watching(logs: &[PathBuf]) -> Self {
|
||
|
|
let logs: Vec<PathBuf> = logs.to_vec();
|
||
|
|
let stop = Arc::new(AtomicBool::new(false));
|
||
|
|
let flag = Arc::clone(&stop);
|
||
|
|
let handle = std::thread::spawn(move || {
|
||
|
|
// Held listeners and their ports, the write each log was last
|
||
|
|
// read at, and the ports released for its current write.
|
||
|
|
let mut held: Vec<std::net::TcpListener> = Vec::new();
|
||
|
|
let mut held_ports: Vec<u16> = Vec::new();
|
||
|
|
let mut seen_at: HashMap<PathBuf, SystemTime> = HashMap::new();
|
||
|
|
let mut released: HashMap<PathBuf, Vec<u16>> = HashMap::new();
|
||
|
|
while !flag.load(Ordering::Relaxed) {
|
||
|
|
for path in &logs {
|
||
|
|
let Some(mtime) = modified(path) else {
|
||
|
|
continue;
|
||
|
|
};
|
||
|
|
if seen_at.insert(path.clone(), mtime) != Some(mtime) {
|
||
|
|
// A new write of this log: a fresh publication, so a
|
||
|
|
// port released for the previous one is bindable.
|
||
|
|
released.remove(path);
|
||
|
|
}
|
||
|
|
for port in published_ports(path) {
|
||
|
|
let released_here = released
|
||
|
|
.get(path)
|
||
|
|
.is_some_and(|ports| ports.contains(&port));
|
||
|
|
if held_ports.contains(&port) || released_here {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
// A failed bind is not an error: something else is
|
||
|
|
// already answering on that port, which is all the
|
||
|
|
// gate asks for.
|
||
|
|
if let Ok(listener) =
|
||
|
|
std::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, port))
|
||
|
|
{
|
||
|
|
let _ = listener.set_nonblocking(true);
|
||
|
|
held.push(listener);
|
||
|
|
held_ports.push(port);
|
||
|
|
}
|
||
|
|
released.entry(path.clone()).or_default().push(port);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
let mut keeping = Vec::new();
|
||
|
|
let mut keeping_ports = Vec::new();
|
||
|
|
for (listener, port) in held.drain(..).zip(held_ports.drain(..)) {
|
||
|
|
match listener.accept() {
|
||
|
|
// The gate's probe: release the port.
|
||
|
|
Ok(_) => {}
|
||
|
|
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
||
|
|
keeping.push(listener);
|
||
|
|
keeping_ports.push(port);
|
||
|
|
}
|
||
|
|
Err(_) => {}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
held = keeping;
|
||
|
|
held_ports = keeping_ports;
|
||
|
|
std::thread::sleep(Duration::from_millis(10));
|
||
|
|
}
|
||
|
|
});
|
||
|
|
Self {
|
||
|
|
stop,
|
||
|
|
handle: Some(handle),
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
impl Drop for PublishedPortHold {
|
||
|
|
fn drop(&mut self) {
|
||
|
|
self.stop.store(true, Ordering::Relaxed);
|
||
|
|
if let Some(handle) = self.handle.take() {
|
||
|
|
let _ = handle.join();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn modified(log: &Path) -> Option<SystemTime> {
|
||
|
|
std::fs::metadata(log).ok()?.modified().ok()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The ports named after `--rpc-bind-port` in a fake child's argv log.
|
||
|
|
fn published_ports(log: &Path) -> Vec<u16> {
|
||
|
|
let Ok(raw) = std::fs::read_to_string(log) else {
|
||
|
|
return Vec::new();
|
||
|
|
};
|
||
|
|
raw.lines()
|
||
|
|
.collect::<Vec<&str>>()
|
||
|
|
.windows(2)
|
||
|
|
.filter(|pair| pair[0] == "--rpc-bind-port")
|
||
|
|
.filter_map(|pair| pair[1].trim().parse().ok())
|
||
|
|
.collect()
|
||
|
|
}
|
||
|
|
}
|