wallet: wait for the daemon RPC before spawning monero-wallet-rpc

This commit is contained in:
agent 2026-09-23 20:30:05 -04:00
commit f5e310fdf4
No known key found for this signature in database

View file

@ -565,6 +565,20 @@ impl WalletChild {
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.
@ -1263,6 +1277,7 @@ fn harden_wallet_file(path: &Path) {
#[cfg(test)]
mod tests {
use super::test_support::PublishedPortHold;
use super::*;
use std::io::Write;
@ -1629,6 +1644,9 @@ mod tests {
))
.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());
@ -1731,6 +1749,7 @@ mod tests {
&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!(
@ -1843,6 +1862,9 @@ mod tests {
.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");
@ -1925,6 +1947,7 @@ mod tests {
.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();
@ -2259,3 +2282,134 @@ mod tests {
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()
}
}