From 59175f69318df3e357adec7ca6b8eaec529b88b5 Mon Sep 17 00:00:00 2001 From: rust-dev Date: Tue, 22 Sep 2026 13:41:35 -0400 Subject: [PATCH] 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()); +}