diff --git a/src/node.rs b/src/node.rs index 46c622f..26ee177 100644 --- a/src/node.rs +++ b/src/node.rs @@ -34,7 +34,6 @@ 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 { @@ -698,7 +697,10 @@ impl Node { if already_running { return Ok(()); } - let child = Arc::new(cfg.build(self.wallet_dir()).map_err(|e| e.to_string())?); + let child = Arc::new( + cfg.build(self.home.join("wallet")) + .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. @@ -1569,42 +1571,20 @@ 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 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. + /// 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. 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) { - continue; + if !taken.iter().any(|w| w.wallet_filename == candidate) { + return Ok(candidate); } - 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 @@ -2528,9 +2508,6 @@ 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() @@ -3074,38 +3051,14 @@ 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. - /// - /// 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\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 + "#!/bin/sh\n: > '{}'\nprintf '%s\\n' \"$0\" >> '{}'\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done\n{body}\n", + log.display(), + log.display(), + log.display() ); std::fs::write(&path, script).expect("write fake bin"); let mut perms = std::fs::metadata(&path).expect("stat").permissions(); @@ -3677,84 +3630,6 @@ 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] @@ -3976,71 +3851,24 @@ pub(crate) mod tests { }) } - /// 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 { + /// 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 { 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(); - 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; + 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; + } } tokio::time::sleep(Duration::from_millis(10)).await; } panic!( - "the fake child {pid} never wrote an --rpc-bind-port to {}", - path.display() + "the fake child never wrote an --rpc-bind-port to {}", + argv_log.display() ); } @@ -4090,19 +3918,15 @@ 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 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); + // fresh port, so the mock is bound to what the new argv names while the + // open waits for the RPC to answer. 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 pid = wait_for_new_child_pid(&node, first_pid).await; - let port = wait_for_child_rpc_port(&argv_log, pid).await; + let port = wait_for_child_rpc_port(&argv_log).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}")); @@ -4152,89 +3976,6 @@ 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 @@ -4265,7 +4006,6 @@ 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 @@ -4275,8 +4015,7 @@ 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 pid = wait_for_new_child_pid(&node, first_pid).await; - let port = wait_for_child_rpc_port(&argv_log, pid).await; + let port = wait_for_child_rpc_port(&argv_log).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 1bde4c5..2f67f95 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -207,20 +207,6 @@ 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. /// @@ -1175,33 +1161,6 @@ 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() @@ -1247,24 +1206,17 @@ 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, "tmp='{}'.$$", log.display()).unwrap(); - writeln!(f, ": > \"$tmp\"").unwrap(); + writeln!(f, ": > '{}'", log.display()).unwrap(); writeln!( f, - "for a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$tmp\"; done" + "for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done", + log.display() ) .unwrap(); - writeln!(f, "mv -f \"$tmp\" '{}'", log.display()).unwrap(); writeln!(f, "sleep 30").unwrap(); drop(f); let mut perms = fs::metadata(&path).unwrap().permissions(); diff --git a/tests/wallet.rs b/tests/wallet.rs index de6f02e..d9951d8 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -9,7 +9,6 @@ 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}; @@ -1834,61 +1833,3 @@ 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()); -}