From 081bdfac3ebc74ed7bf6649d99fdd6a93d6244ee Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 23 Sep 2026 20:30:57 -0400 Subject: [PATCH] wallet: wait for monero-wallet-rpc to accept before publishing the child --- src/node.rs | 179 +++++++++++++++++++++++++++++++++----------- src/wallet_child.rs | 3 + 2 files changed, 138 insertions(+), 44 deletions(-) diff --git a/src/node.rs b/src/node.rs index 46c622f..8213dce 100644 --- a/src/node.rs +++ b/src/node.rs @@ -2446,6 +2446,7 @@ pub(crate) fn test_node_with_wallets(home: &Path, wallets: &[(&str, &str)]) -> A pub(crate) mod tests { use super::*; use crate::wallet_child::DEFAULT_MONEROD_RPC_PORT; + use crate::wallet_child::test_support::PublishedPortHold; use std::pin::Pin; use crate::wallet::ChainSource; @@ -3114,6 +3115,32 @@ pub(crate) mod tests { path } + /// [`fake_child_bin`] with the shared log written *last*: this child's own + /// `.` lands immediately and the path a harness that reads it + /// would take lags behind — a killed child's write landing after a clear + /// (CI run 905, job 1373). + fn fake_child_bin_shared_late( + dir: &Path, + name: &str, + log: &Path, + delay: &str, + body: &str, + ) -> PathBuf { + std::fs::create_dir_all(dir).expect("fake bin dir"); + let path = dir.join(name); + let script = format!( + "#!/bin/sh\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\nmv -f \"$tmp\" '{log}'.$$\n{delay}\ncp -f '{log}'.$$ '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\n{body}\n", + log = log.display(), + delay = delay, + body = body + ); + std::fs::write(&path, script).expect("write fake bin"); + let mut perms = std::fs::metadata(&path).expect("stat").permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o700); + std::fs::set_permissions(&path, perms).expect("chmod"); + path + } + /// A loopback daemon is the one source that spawns no SOCKS child, so the /// test drives exactly one process. fn loopback_child_config(bin: PathBuf, filename: &str) -> ChildConfig { @@ -3211,6 +3238,9 @@ pub(crate) mod tests { ); node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) .expect("set config"); + // The gate dials the port the fake was told to bind; a shell fake cannot + // bind one, so hold it here. + let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); node.start_wallet_child().expect("start"); // The child is a fake process; the wallet the node actually talks to is // the mock RPC, which is where the numbers come from. @@ -3264,6 +3294,9 @@ pub(crate) mod tests { wallet_filename: "onionwire".to_string(), }) .expect("set config"); + // The gate dials the port the fake was told to bind; a shell fake cannot + // bind one, so hold the port it publishes. + let _hold = PublishedPortHold::watching(&[dir.path().join("rpc.argv")]); node.start_wallet_child().expect("start"); let status = node.wallet_child_refresh().await; @@ -3335,6 +3368,7 @@ pub(crate) mod tests { node.set_wallet_child_config(&loopback_child_config(bin.clone(), "onionwire")) .expect("set config"); + let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); node.start_wallet_child().expect("start"); let status = node.wallet_child_status(); assert!(status.running, "{status:?}"); @@ -3401,6 +3435,9 @@ pub(crate) mod tests { node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) .expect("set config"); + // The fake exits instead of binding its port; the gate must still see + // the accept the real child would have offered before it died. + let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); node.start_wallet_child().expect("start"); let mut status = node.wallet_child_status(); for _ in 0..300 { @@ -3435,6 +3472,7 @@ pub(crate) mod tests { { let node = offline_node(&home, Arc::new(NoDial)); node.set_wallet_child_config(&saved).expect("set config"); + let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); node.start_wallet_child().expect("start"); let before = sealed_creds(&node); @@ -3524,6 +3562,7 @@ pub(crate) mod tests { ); node.set_wallet_child_config(&loopback_child_config(bin, "onionwire")) .expect("set config"); + let _hold = PublishedPortHold::watching(std::slice::from_ref(&log)); node.start_wallet_child().expect("start"); let mut pid = 0u32; @@ -3987,25 +4026,6 @@ pub(crate) mod tests { .expect("a running wallet child") } - /// Wait for the pid of a child that is not `previous` — the restart's. - async fn wait_for_new_child_pid(node: &Node, previous: u32) -> u32 { - for _ in 0..600 { - let pid = node - .wallet_child - .lock() - .ok() - .and_then(|guard| guard.clone()) - .and_then(|child| child.wallet_rpc_pid()); - if let Some(pid) = pid - && pid != previous - { - return pid; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - panic!("the restart never reported a new wallet-child pid"); - } - /// `--rpc-bind-port ` out of a fake child's argv log. fn rpc_port_in(raw: &str) -> Option { let lines: Vec<&str> = raw.lines().collect(); @@ -4044,6 +4064,68 @@ pub(crate) mod tests { ); } + /// The port the *next* child was spawned with, read from the argv log that + /// child alone owns — `.`. + /// + /// The pid comes from the directory, not from the node: the node publishes + /// the child only after the readiness gate saw its RPC accept, so a test + /// that must *be* that listener has to find the port from the outside. The + /// shared path is still the wrong one for the same reason + /// [`wait_for_child_rpc_port`] documents. + async fn wait_for_restarted_rpc_port(argv_log: &Path, previous_pid: u32) -> u16 { + let name = argv_log + .file_name() + .and_then(|name| name.to_str()) + .expect("the argv log has a file name"); + let dir = argv_log.parent().expect("the argv log has a directory"); + let prefix = format!("{name}."); + for _ in 0..600 { + if let Ok(entries) = std::fs::read_dir(dir) { + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + let Some(suffix) = name.strip_prefix(prefix.as_str()) else { + continue; + }; + // `.` only. A child killed between its shared write + // and its own leaves `..writing` behind, and that + // temp file still names the *previous* child's port. + let Ok(pid) = suffix.parse::() else { + continue; + }; + if pid == previous_pid { + continue; + } + if let Ok(raw) = std::fs::read_to_string(&path) + && let Some(port) = rpc_port_in(&raw) + { + return port; + } + } + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!( + "no child other than pid {previous_pid} published an --rpc-bind-port under {}", + dir.display() + ); + } + + /// Bind the restarted child's mock on `port`, retrying while the readiness + /// stand-in still holds it: the stand-in releases the port on the gate's own + /// probe, and the mock must own it from then on. + async fn bind_when_free(port: u16) -> tokio::net::TcpListener { + for _ in 0..500 { + if let Ok(listener) = tokio::net::TcpListener::bind(("127.0.0.1", port)).await { + return listener; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + panic!("the readiness stand-in never released port {port}"); + } + /// The wallet-file passphrase this install remembers, `""` when none. fn sealed_passphrase(node: &Node) -> String { node.store @@ -4081,19 +4163,29 @@ pub(crate) mod tests { test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); // First start: the catalogue holds the file, but this install holds no - // passphrase for it. That is a state, not a failure. + // passphrase for it. That is a state, not a failure. The gate needs the + // port the fake was told to bind; the restart below is answered by this + // test's own mock, so the hold is dropped before it. + let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log)); node.start_wallet_child().expect("first start"); let status = node.wallet_child_status(); assert!(status.running, "{status:?}"); assert!(!status.wallet_open, "{status:?}"); assert!(status.needs_passphrase, "{status:?}"); assert!(status.last_error.is_none(), "{status:?}"); + drop(hold); // Restart it with the passphrase the user supplied. The child picks a // fresh port, so the mock is bound to the port *this* spawn named while // the open waits for its RPC to answer — read from the argv log the new // pid owns, never from the shared path the previous child wrote: a loaded // runner lands that write after a clear (CI run 905, job 1373). + // + // The node cannot name that pid any more (it publishes the child only + // once the gate has seen the RPC accept), so the port comes from the + // directory — and the mock must own it *before* the gate's probe, not + // after: a listener that accepts the probe and then closes resets the + // client's own dial, which is an RPC answer, not an unreachable child. let first_pid = child_pid(&node); std::fs::write(&argv_log, b"").expect("clear the argv log"); let requests = Arc::new(Mutex::new(Vec::new())); @@ -4101,11 +4193,8 @@ pub(crate) mod tests { let started = tokio::task::spawn_blocking(move || { starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass") }); - let pid = wait_for_new_child_pid(&node, first_pid).await; - let port = wait_for_child_rpc_port(&argv_log, pid).await; - let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) - .await - .unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}")); + let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await; + let listener = bind_when_free(port).await; tokio::spawn(serve_mock_rpc( listener, recording_wallet_reply(Arc::clone(&requests)), @@ -4177,16 +4266,19 @@ pub(crate) mod tests { .expect("set config"); test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); + let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log)); node.start_wallet_child().expect("first start"); let first_pid = child_pid(&node); // The killed child's argv is in the shared path (its own log lands first, // so this waits for both) — the content the old harness would read. let stale_port = wait_for_child_rpc_port(&argv_log, first_pid).await; - // The restart's exec is late here, the way a loaded runner delays it, so - // the shared path still holds the killed child's argv while the restarted - // child is already being dialled. - let restart = fake_child_bin_after( + // The restart's own log lands at once, while the shared path lags 2s + // behind — the way a loaded runner lands the killed child's write after + // a clear. The lag is what makes the shared read below wrong; it is not + // the child's exec that is late, because the readiness gate now runs + // before the child is published and cannot wait 2s for an argv file. + let restart = fake_child_bin_shared_late( &dir.path().join("fake-bins-restart"), "monero-wallet-rpc", &argv_log, @@ -4197,24 +4289,20 @@ pub(crate) mod tests { .expect("re-point the child at the late-write stand-in"); let requests = Arc::new(Mutex::new(Vec::new())); let starter = Arc::clone(&node); + drop(hold); let started = tokio::task::spawn_blocking(move || { starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass") }); - let pid = wait_for_new_child_pid(&node, first_pid).await; - // The premise of the test: the shared path still holds the killed - // child's argv, so a harness that reads it binds the mock on the wrong - // port. Reading the restarted child's own log instead is what the fix - // is — with the shared read, this test fails on the port above after the - // whole `WALLET_OPEN_WAIT`. + // The premise of the test, asserted while it is true: the shared path + // still holds the killed child's argv, so a harness that reads it binds + // the mock on the wrong port and the restart never reaches a mock at all. assert_eq!( rpc_port_in(&std::fs::read_to_string(&argv_log).unwrap_or_default()), Some(stale_port), "the restarted child must not have written the shared path yet" ); - let port = wait_for_child_rpc_port(&argv_log, pid).await; - let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) - .await - .unwrap_or_else(|e| panic!("bind the restarted child's mock on {port}: {e}")); + let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await; + let listener = bind_when_free(port).await; tokio::spawn(serve_mock_rpc( listener, recording_wallet_reply(Arc::clone(&requests)), @@ -4259,6 +4347,7 @@ pub(crate) mod tests { .expect("set config"); test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); + let hold = PublishedPortHold::watching(std::slice::from_ref(&argv_log)); node.start_wallet_child() .expect("a wallet-less child still starts"); let status = node.wallet_child_status(); @@ -4274,12 +4363,14 @@ pub(crate) mod tests { std::fs::write(&argv_log, b"").expect("clear the argv log"); let requests = Arc::new(Mutex::new(Vec::new())); let starter = Arc::clone(&node); + // The second start is answered by the mock this test binds, and the node + // cannot name its pid: it publishes the child only once the gate has seen + // the RPC accept. The mock is bound from the child's own log, in time for + // the gate's next probe. + drop(hold); let started = tokio::task::spawn_blocking(move || starter.start_wallet_child()); - let pid = wait_for_new_child_pid(&node, first_pid).await; - let port = wait_for_child_rpc_port(&argv_log, pid).await; - let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)) - .await - .unwrap_or_else(|e| panic!("bind the fake child's mock on {port}: {e}")); + let port = wait_for_restarted_rpc_port(&argv_log, first_pid).await; + let listener = bind_when_free(port).await; tokio::spawn(serve_mock_rpc( listener, recording_wallet_reply(Arc::clone(&requests)), diff --git a/src/wallet_child.rs b/src/wallet_child.rs index c0fee7b..e4d7b13 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -618,6 +618,9 @@ impl WalletChild { // 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)); + // Do not hand back a client whose port is still closed: `pick_port` only + // proved the port was free, not that the child bound it. + Self::loopback_listener_ready(port, WALLET_RPC_LISTENER_TIMEOUT, "monero-wallet-rpc")?; Ok(Some(WalletClient { url: format!("http://{user}:{}@127.0.0.1:{port}/json_rpc", pass.as_str()), no_spend: false,