From 59175f69318df3e357adec7ca6b8eaec529b88b5 Mon Sep 17 00:00:00 2001 From: rust-dev Date: Tue, 22 Sep 2026 13:41:35 -0400 Subject: [PATCH 1/3] wallet: the file-name picker consults the disk, not only the catalogue next_wallet_filename returned - for the first n the SQLCipher catalogue did not hold, and never looked at the wallet directory. monero writes two files per wallet ( and .keys) and refuses a create that would collide with either, so a file whose catalogue row is gone - Store::delete_wallet keeps the file, and a create whose record_wallet failed leaves one - meant every attempt proposed the same taken name and the daemon answered -21 Cannot create wallet. Already exists. for ever. Add wallet_name_taken (src/wallet_child.rs): it lists the wallet dir and answers whether or .keys is already there. next_wallet_filename now needs the candidate free in both places, and Node::wallet_dir() is the single source of $ONIONWIRE_HOME/wallet, used by the child spawn too. Fail closed: an unreadable (or missing) wallet dir is an error, not a guess. Reads only - nothing here deletes a file the catalogue does not hold, which may be the only copy of a funded wallet. --- src/node.rs | 119 ++++++++++++++++++++++++++++++++++++++++---- src/wallet_child.rs | 27 ++++++++++ tests/wallet.rs | 59 ++++++++++++++++++++++ 3 files changed, 196 insertions(+), 9 deletions(-) diff --git a/src/node.rs b/src/node.rs index 26ee177..7d185d8 100644 --- a/src/node.rs +++ b/src/node.rs @@ -34,6 +34,7 @@ use crate::store::{ use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ ChildConfig, ChildWalletState, WalletChild, WalletChildState, WalletChildStatus, + wallet_name_taken, }; pub struct RotateResult { @@ -697,10 +698,7 @@ impl Node { if already_running { return Ok(()); } - let child = Arc::new( - cfg.build(self.home.join("wallet")) - .map_err(|e| e.to_string())?, - ); + let child = Arc::new(cfg.build(self.wallet_dir()).map_err(|e| e.to_string())?); // Do not hold SQLCipher across Cuprate/`monerod` launch: `wallet_status` // also locks the store, and a blocked poller is how Android Start looks // like it did nothing. @@ -1571,20 +1569,42 @@ impl Node { self.open_wallet_file(filename, passphrase) } - /// The file name a wallet created now should live in. `wallet_filename` is - /// UNIQUE and the catalogue is the only directory the app has, so this is - /// `-` for the first `n` the catalogue does not already hold. + /// The file name a wallet created now should live in. + /// + /// `wallet_filename` is UNIQUE and the catalogue is not the whole story: + /// `Store::delete_wallet` drops the row and keeps the file, and a create + /// whose `record_wallet` failed leaves a file with no row, so a *file* the + /// catalogue does not know about is still a name the daemon refuses with + /// `-21 Cannot create wallet. Already exists.` — for ever, because the + /// catalogue never changed. So the first `-` that is free in + /// both places wins, and a wallet dir that cannot be listed is an error + /// rather than a guess ([`wallet_name_taken`]). + /// + /// Nothing is deleted here: a file the catalogue does not hold may be the + /// only copy of a funded wallet. fn next_wallet_filename(&self) -> Result { let taken = self.list_wallets()?; + let dir = self.wallet_dir(); for n in 1.. { let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n); - if !taken.iter().any(|w| w.wallet_filename == candidate) { - return Ok(candidate); + if taken.iter().any(|w| w.wallet_filename == candidate) { + continue; } + if wallet_name_taken(&dir, &candidate).map_err(|e| e.to_string())? { + continue; + } + return Ok(candidate); } unreachable!("an unused wallet file name always exists") } + /// Where this install's wallet files live: `$ONIONWIRE_HOME/wallet`, the + /// `--wallet-dir` the app-owned child is spawned with. The one path, so + /// the picker and the child can never disagree about the directory. + fn wallet_dir(&self) -> PathBuf { + self.home.join("wallet") + } + /// Point the wallet child at a wallet file. A read-modify-write of the /// sealed record, so the generated RPC creds and every other setting are /// kept. A running child is not restarted: the change applies on the next @@ -2508,6 +2528,9 @@ pub(crate) mod tests { wallet: Wallet, ) -> Node { std::fs::create_dir_all(home).expect("create home"); + // The app-owned child creates the wallet dir 0700 before a wallet can + // be configured, and the picker now insists on listing it. + std::fs::create_dir_all(home.join("wallet")).expect("create wallet dir"); let store = Store::open_at_with_passphrase(home, PASS).expect("open store"); let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys"); let client = arti_client::TorClient::builder() @@ -3630,6 +3653,84 @@ pub(crate) mod tests { ); } + /// A catalogue name is still skipped: the disk check is an addition, not a + /// replacement, and a remembered wallet must keep its own file. + #[tokio::test] + async fn a_catalogue_name_is_still_skipped_by_the_picker() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + { + let store = node.store.lock().expect("store"); + test_record_wallet(&store, "onionwire-1", ""); + } + + let created = node.wallet_create("p1").await.expect("create wallet"); + + assert_eq!(created.record.wallet_filename, "onionwire-2"); + } + + /// The reported bug: a wallet file whose catalogue row is gone — an + /// explicit `Store::delete_wallet`, or a create whose `record_wallet` + /// failed — is still on disk, so a catalogue-only picker proposes the same + /// name for ever and the daemon answers `-21 Cannot create wallet. Already + /// exists.` with no way out from the UI. + #[tokio::test] + async fn wallet_files_on_disk_are_skipped_when_picking_a_name() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + // No catalogue rows at all: only the disk knows about these two, and + // monero writes two files per wallet, so either one means "taken". + std::fs::write(home.join("wallet").join("onionwire-1.keys"), b"keys").unwrap(); + std::fs::write(home.join("wallet").join("onionwire-2"), b"wallet").unwrap(); + + let created = node.wallet_create("p1").await.expect("create wallet"); + + assert_eq!( + created.record.wallet_filename, "onionwire-3", + "the stray `.keys` file and the stray wallet file are both taken" + ); + } + + /// A stray file under some *other* name must not bump the picker: the + /// check is about this candidate, not about the directory being busy. + #[tokio::test] + async fn an_unrelated_file_on_disk_does_not_cost_the_first_name() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + std::fs::write(home.join("wallet").join("someone-elses"), b"x").unwrap(); + + let created = node.wallet_create("p1").await.expect("create wallet"); + + assert_eq!(created.record.wallet_filename, "onionwire-1"); + } + + /// Fail closed: a wallet directory that cannot be listed is an error, not + /// "every name is free". Guessing here is how the collision comes back. + #[tokio::test] + async fn the_wallet_name_picker_fails_closed_when_the_dir_cannot_be_read() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let node = offline_node_with_wallet(&home, Arc::new(NoDial), mock_wallet_setup().await); + std::fs::remove_dir_all(home.join("wallet")).unwrap(); + + let err = node + .wallet_create("p1") + .await + .expect_err("an unreadable wallet dir must refuse, not guess"); + + assert!( + err.contains("wallet dir"), + "the error must name the directory it could not list: {err}" + ); + assert!( + node.list_wallets().expect("list wallets").is_empty(), + "a refused create records nothing" + ); + } + /// The catalogue is a store fact, not a wallet-RPC fact: listing must work /// with no wallet configured, and creating must still refuse without one. #[tokio::test] diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 2f67f95..d07b3fb 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -1161,6 +1161,33 @@ fn create_dir_700(path: &Path) -> std::io::Result<()> { fs::set_permissions(path, perms) } +/// Is `name` already a wallet file in `wallet_dir`? +/// +/// monero writes two files per wallet — `` and `.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 { + 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() diff --git a/tests/wallet.rs b/tests/wallet.rs index d9951d8..de6f02e 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -9,6 +9,7 @@ use onionwire::wallet::{ self, NOT_CONFIGURED_MSG, NOT_CONNECTED_MSG, Readiness, TransferRow, VIEW_ONLY_MSG, Wallet, WalletConfig, WalletStatus, readiness, }; +use onionwire::wallet_child; use onionwire::{PaymentWrite, Store}; use rand::rngs::OsRng; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -1833,3 +1834,61 @@ async fn open_wallet_surfaces_the_rpcs_own_refusal() { "the passphrase must never be echoed back in an error: {err}" ); } + +// --------------------------------------------------------------------------- +// `next_wallet_filename`'s disk half: monero writes two files per wallet and +// the daemon refuses a create that would collide with either, so the picker +// has to look at the directory, not only at the catalogue. +// --------------------------------------------------------------------------- + +/// `` and `.keys` both mean taken; nothing else does. +#[test] +fn wallet_name_taken_sees_the_file_and_its_keys_sibling() { + let dir = tempfile::tempdir().expect("tempdir"); + let wallet_dir = dir.path(); + std::fs::write(wallet_dir.join("onionwire-1.keys"), b"keys").unwrap(); + std::fs::write(wallet_dir.join("onionwire-2"), b"wallet").unwrap(); + + assert!( + wallet_child::wallet_name_taken(wallet_dir, "onionwire-1").unwrap(), + "the `.keys` sibling is enough to make the name taken" + ); + assert!( + wallet_child::wallet_name_taken(wallet_dir, "onionwire-2").unwrap(), + "the wallet file itself is enough" + ); + assert!(!wallet_child::wallet_name_taken(wallet_dir, "onionwire-3").unwrap()); + assert!( + !wallet_child::wallet_name_taken(wallet_dir, "onionwire").unwrap(), + "a prefix is not a collision" + ); + assert!( + !wallet_child::wallet_name_taken(wallet_dir, "onionwire-20").unwrap(), + "neither is a longer name that starts with a taken one" + ); + + // The files may be the only copy of a funded wallet: naming the collision + // must not remove it. + assert!(wallet_dir.join("onionwire-1.keys").is_file()); + assert!(wallet_dir.join("onionwire-2").is_file()); +} + +/// Fail closed: a directory that cannot be listed is an error, not "every name +/// is free". Guessing here is how the collision comes back. +#[test] +fn wallet_name_taken_fails_closed_when_the_dir_cannot_be_read() { + let dir = tempfile::tempdir().expect("tempdir"); + let missing = dir.path().join("no-such-wallet-dir"); + let err = wallet_child::wallet_name_taken(&missing, "onionwire-1") + .expect_err("a missing wallet dir must refuse, not answer 'free'") + .to_string(); + assert!( + err.contains("wallet dir"), + "the error must name what could not be listed: {err}" + ); + + // A path that is a file, not a directory, is unreadable too. + let file = dir.path().join("not-a-dir"); + std::fs::write(&file, b"x").unwrap(); + assert!(wallet_child::wallet_name_taken(&file, "onionwire-1").is_err()); +} From 8d80a4fd55d1a6a2626b0cdbb0af44568d33b91e Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 14:33:32 -0400 Subject: [PATCH 2/3] tests: write the fake child's argv log with one mv, not append-per-line The wallet-child tests learn a spawned stand-in's port by polling its argv log, and `fake_bin`/`fake_child_bin` truncated the log and then appended one line per argument -- so a poller could read a prefix. A truncated port is a *valid* u16 ("427" out of "42765"), so `wait_for_child_rpc_port` happily returned a port nothing was listening on and the restart's `open_wallet` died with `Connection refused` after its 10s budget; the same prefix read is what `loopback_and_clearnet_remotes_carry_no_proxy...` printed with its `--daemon-address` value missing. Both tests failed on the first CI run of this branch (ci / test) and are green in isolation, which is the signature of this race rather than of a code defect. The argv now lands in the log with a single `mv`, so a reader sees either no log or the complete one. Measured with a tight read loop (argv-race-probe.sh): the append version was caught mid-write 1/300 reads, the mv version 0/300. --- src/node.rs | 8 ++++++-- src/wallet_child.rs | 13 ++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/node.rs b/src/node.rs index 7d185d8..3e33a32 100644 --- a/src/node.rs +++ b/src/node.rs @@ -3074,12 +3074,16 @@ pub(crate) mod tests { /// A stand-in for `monero-wallet-rpc`: it records its argv, then does what /// the test needs. The wallet child spawns a real process, so this is the /// only honest way to drive the start path offline. + /// + /// The argv is `mv`d into place in one step rather than truncated and + /// appended: a poller must never read half of it. It did — the port was + /// parsed while it was still being written, so `42765` read as `427`, and + /// the mock was bound on a port nothing dialled. fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf { std::fs::create_dir_all(dir).expect("fake bin dir"); let path = dir.join(name); let script = format!( - "#!/bin/sh\n: > '{}'\nprintf '%s\\n' \"$0\" >> '{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done\n{body}\n", - log.display(), + "#!/bin/sh\ntmp='{}'.$$\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\nmv -f \"$tmp\" '{}'\n{body}\n", log.display(), log.display() ); diff --git a/src/wallet_child.rs b/src/wallet_child.rs index d07b3fb..13357de 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -1233,17 +1233,24 @@ mod tests { } /// A stand-in for monerod / monero-wallet-rpc: records its argv, then parks. + /// + /// The argv lands in `` 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, ": > '{}'", log.display()).unwrap(); + writeln!(f, "tmp='{}'.$$", log.display()).unwrap(); + writeln!(f, ": > \"$tmp\"").unwrap(); writeln!( f, - "for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done", - log.display() + "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(); From 6edcd65e96a054b171813f57d76bedea0e184473 Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 22 Sep 2026 15:37:55 -0400 Subject: [PATCH 3/3] tests: take the restart's port from the child that dials it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `a_restart_opens_the_stored_wallet_file` failed on the Pi runner twice in a row — CI run 905 job 1373 and run 901 job 1365 — and passed 3/3 on a 16-core host: open the wallet with a passphrase: "wallet file onionwire-1 is not open — the wallet RPC never answered (wallet connect: Connection refused (os error 111))" The whole `WALLET_OPEN_WAIT` was burned on refusals, so the mock was bound on a port the restarted child never dialled. Production is not the suspect: `WalletChild::start_children` builds the child's argv and the `WalletClient` URL from the same `pick_port` value, and `start_wallet_child_with` installs that client in `self.wallet` before `open_child_wallet` dials it, so the client can never carry the previous child's port. The harness is the suspect. It learned the restarted child's port from the *shared* argv log — a file every child writes — and cleared that file first. A clear is not a synchronisation: on a loaded runner the killed child's write lands after it, so the poller read the port of a child that was already dead and bound the mock there. Reproduced deterministically with a stand-in whose exec is late; with the old read the new test fails with the CI message, byte for byte. Each fake child now writes `.` as well, and the shared copy lands first, so a pid-named file implies the shared one is complete. A test that spans two children reads the pid-named file: only that child can write it, so the port belongs to the child that dials it. `WalletChild::wallet_rpc_pid` (test-only) supplies the pid. `open_wallet_blocking` already retries while the RPC is unreachable and gives up after a bounded wait with a typed `OpenFailure::NotAnswering`, so it cannot refuse forever against a merely slow child: no production change. new test: node::tests::a_restart_is_not_given_the_stopped_childs_port --- src/node.rs | 196 +++++++++++++++++++++++++++++++++++++++----- src/wallet_child.rs | 14 ++++ 2 files changed, 190 insertions(+), 20 deletions(-) diff --git a/src/node.rs b/src/node.rs index 3e33a32..46c622f 100644 --- a/src/node.rs +++ b/src/node.rs @@ -3079,13 +3079,33 @@ pub(crate) mod tests { /// appended: a poller must never read half of it. It did — the port was /// parsed while it was still being written, so `42765` read as `427`, and /// the mock was bound on a port nothing dialled. + /// + /// Every child also writes its own copy at `.`, which no other + /// child can touch, and the shared copy lands first, so a pid-named file + /// implies the shared one is already complete. The shared path is what the + /// single-child tests read; a test that spans two children reads the + /// pid-named one, because a previous child's write into the shared path is + /// unsequenced against the test (see [`wait_for_child_rpc_port`]). fn fake_child_bin(dir: &Path, name: &str, log: &Path, body: &str) -> PathBuf { + fake_child_bin_after(dir, name, log, "", body) + } + + /// [`fake_child_bin`] with `prelude` run *before* the argv is written: the + /// stand-in for a runner that schedules this child's exec late. + fn fake_child_bin_after( + dir: &Path, + name: &str, + log: &Path, + prelude: &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='{}'.$$\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\nmv -f \"$tmp\" '{}'\n{body}\n", - log.display(), - log.display() + "#!/bin/sh\n{prelude}\ntmp='{log}'.$$.writing\n: > \"$tmp\"\nprintf '%s\\n' \"$0\" >> \"$tmp\"\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done\ncp -f \"$tmp\" '{log}'.$$.shared\nmv -f '{log}'.$$.shared '{log}'\nmv -f \"$tmp\" '{log}'.$$\n{body}\n", + prelude = prelude, + log = log.display(), + body = body ); std::fs::write(&path, script).expect("write fake bin"); let mut perms = std::fs::metadata(&path).expect("stat").permissions(); @@ -3956,24 +3976,71 @@ pub(crate) mod tests { }) } - /// The port the fake child was spawned with. The fake bin writes its argv one - /// argument per line, so `--rpc-bind-port` is followed by the number; the - /// write happens right after `spawn` returns, hence the wait. - async fn wait_for_child_rpc_port(argv_log: &Path) -> u16 { + /// The pid of the running wallet child. Panics when there is none: every + /// caller has just started one. + fn child_pid(node: &Node) -> u32 { + node.wallet_child + .lock() + .ok() + .and_then(|guard| guard.clone()) + .and_then(|child| child.wallet_rpc_pid()) + .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 { - if let Ok(raw) = std::fs::read_to_string(argv_log) { - let lines: Vec<&str> = raw.lines().collect(); - if let Some(i) = lines.iter().position(|line| *line == "--rpc-bind-port") - && let Some(port) = lines.get(i + 1).and_then(|p| p.trim().parse::().ok()) - { - return port; - } + 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(); + let i = lines.iter().position(|line| *line == "--rpc-bind-port")?; + lines + .get(i + 1) + .and_then(|port| port.trim().parse::().ok()) + } + + /// The port the child with this pid was spawned with, read out of the argv + /// log that child alone writes — `.`, `mv`d into place in one step. + /// + /// The shared path must not be used for this. Every child writes it and a + /// previous child's write is unsequenced against the test, so on a loaded + /// runner it lands after a poller has cleared the file: the poller then binds + /// its mock on the port of a child that has already been killed, and the + /// restarted child's `open_wallet` is refused for the whole + /// `WALLET_OPEN_WAIT` (CI run 905, job 1373 — the same message in run 901, + /// green 3/3 on a 16-core host). A pid in the file name is a handshake the + /// child cannot lose. + async fn wait_for_child_rpc_port(argv_log: &Path, pid: u32) -> u16 { + let mut name = argv_log.as_os_str().to_owned(); + name.push(format!(".{pid}")); + let path = PathBuf::from(name); + for _ in 0..600 { + 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!( - "the fake child never wrote an --rpc-bind-port to {}", - argv_log.display() + "the fake child {pid} never wrote an --rpc-bind-port to {}", + path.display() ); } @@ -4023,15 +4090,19 @@ pub(crate) mod tests { assert!(status.last_error.is_none(), "{status:?}"); // Restart it with the passphrase the user supplied. The child picks a - // fresh port, so the mock is bound to what the new argv names while the - // open waits for the RPC to answer. + // 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). + 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())); let starter = Arc::clone(&node); let started = tokio::task::spawn_blocking(move || { starter.open_wallet_with_passphrase("onionwire-1", "walletfile-pass") }); - let port = wait_for_child_rpc_port(&argv_log).await; + 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}")); @@ -4081,6 +4152,89 @@ pub(crate) mod tests { node.stop_wallet_child().expect("stop"); } + /// The port the restarted child's mock listens on must come from *that* + /// child, not from the shared argv path a previous child has already written. + /// The old harness cleared that path and read it anyway, and the clear is not + /// a synchronisation: on a loaded runner the killed child's write lands after + /// it, so the mock was bound on a port nothing dialled and the restarted + /// child's `open_wallet` was refused for the whole `WALLET_OPEN_WAIT` (CI run + /// 905, job 1373; the same message in run 901, green 3/3 on a 16-core host). + /// Here the killed child's argv is left in place — the worst case of that + /// race — and the restart still reaches the mock on its own port. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_restart_is_not_given_the_stopped_childs_port() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("child"); + let argv_log = dir.path().join("argv.log"); + let bin = fake_child_bin( + &dir.path().join("fake-bins"), + "monero-wallet-rpc", + &argv_log, + "sleep 30", + ); + let node = Arc::new(offline_node(&home, Arc::new(NoDial))); + node.set_wallet_child_config(&loopback_child_config(bin, "onionwire-1")) + .expect("set config"); + test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); + + 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( + &dir.path().join("fake-bins-restart"), + "monero-wallet-rpc", + &argv_log, + "sleep 2", + "sleep 30", + ); + node.set_wallet_child_config(&loopback_child_config(restart, "onionwire-1")) + .expect("re-point the child at the late-write stand-in"); + let requests = Arc::new(Mutex::new(Vec::new())); + let starter = Arc::clone(&node); + 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`. + 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}")); + tokio::spawn(serve_mock_rpc( + listener, + recording_wallet_reply(Arc::clone(&requests)), + )); + started + .await + .expect("join the start") + .expect("open the wallet with a passphrase"); + + assert!( + requests + .lock() + .unwrap() + .iter() + .any(|request| request.contains("open_wallet")), + "the restart never reached the mock on the port it dialled" + ); + node.stop_wallet_child().expect("stop"); + } + /// No stored passphrase: the child starts with no wallet open and the status /// says `needs passphrase`. It must not fail the start — a wallet created /// before the passphrase was stored still has a working node — and it must @@ -4111,6 +4265,7 @@ pub(crate) mod tests { assert!(status.running, "{status:?}"); assert!(!status.wallet_open, "{status:?}"); assert!(status.needs_passphrase, "{status:?}"); + let first_pid = child_pid(&node); node.stop_wallet_child().expect("stop"); // A second start, this time with an RPC listening on the port it was @@ -4120,7 +4275,8 @@ pub(crate) mod tests { let requests = Arc::new(Mutex::new(Vec::new())); let starter = Arc::clone(&node); let started = tokio::task::spawn_blocking(move || starter.start_wallet_child()); - let port = wait_for_child_rpc_port(&argv_log).await; + 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}")); diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 13357de..1bde4c5 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -207,6 +207,20 @@ impl WalletChild { 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 { + 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. ///