diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 4040664..154b602 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -587,27 +587,20 @@ impl Wire { /// Create a new spend-capable wallet. Returns the 25-word seed once so the /// UI can show a backup screen. The user does not paste a key on this path. /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. - /// - /// The core also records the new wallet in its catalogue (`Node::wallet_create` - /// returns the stored row); the seed is what this surface carries. pub async fn create_wallet(&self, password: String) -> WResult { - Ok(self - .node()? + self.node()? .wallet_create(&password) .await - .map_err(WireError::new)? - .seed) + .map_err(WireError::new) } /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret. Like a create, the core records the - /// imported wallet in its catalogue. + /// that takes a user-supplied secret. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { self.node()? .wallet_restore(&password, &seed) .await .map_err(WireError::new) - .map(|_| ()) } /// Start the app-owned wallet child (`monero-wallet-rpc`, plus `monerod` for diff --git a/src/node.rs b/src/node.rs index 120696b..fcc8015 100644 --- a/src/node.rs +++ b/src/node.rs @@ -28,9 +28,7 @@ use crate::ratchet::{RatchetKeyPair, RatchetState}; use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; -use crate::store::{ - Friend, FriendProfile, Message, NewWallet, Payment, PaymentWrite, Store, WalletRecord, -}; +use crate::store::{Friend, FriendProfile, Message, Payment, PaymentWrite, Store}; use crate::wallet::{self, ChainNetwork, ChainSource, Readiness, Wallet, WalletConfig, WalletStatus}; use crate::wallet_child::{ChildConfig, WalletChild, WalletChildState, WalletChildStatus}; @@ -82,29 +80,6 @@ impl Drop for WorkerHandle { } } -/// A wallet just created on the wallet RPC and recorded in the store's -/// catalogue: the row is what makes it survive a restart, and the seed is the -/// one-time backup the UI shows before the wallet is used. The caller owns -/// wiping `seed` (the TUI moves it straight into a `Zeroizing`). -pub struct CreatedWallet { - /// The stored catalogue row, with the id and `created_at` the store - /// assigned. `wallet_filename` is the file this wallet lives in. - pub record: WalletRecord, - /// The 25-word seed, returned once by the create path. - pub seed: String, -} - -/// Hand-written so a stray `{:?}` cannot print the seed: the record is the -/// wallet, the mnemonic is the money. -impl std::fmt::Debug for CreatedWallet { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("CreatedWallet") - .field("record", &self.record) - .field("seed", &"") - .finish() - } -} - pub struct Node { home: PathBuf, store: Arc>, @@ -1192,106 +1167,27 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } - /// Create a new spend-capable wallet and record it in the catalogue. The - /// user never pastes a key on this path. - /// - /// The wallet file gets its own name ([`Self::next_wallet_filename`]): - /// `wallet_filename` is UNIQUE, so a second create that reused the old - /// hardcoded name would open the first wallet's file — or be refused by the - /// RPC outright, which is the "cannot create a new wallet" failure. The - /// stored row is what makes the wallet survive a restart; the wallet dir is - /// not scanned. - pub async fn wallet_create(&self, password: &str) -> Result { + /// Create a new spend-capable wallet. Returns the seed once for backup. + /// The user never pastes a key on this path. + pub async fn wallet_create(&self, password: &str) -> Result { let w = self.wallet_snapshot(); if !w.configured() { return Err(wallet::NOT_CONFIGURED_MSG.into()); } - let filename = self.next_wallet_filename()?; - let seed = w - .create_wallet(&filename, password) + w.create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) .await - .map_err(|e| e.to_string())?; - let record = self - .record_wallet(&filename) - .map_err(|e| format!("wallet {filename} created but not remembered: {e}"))?; - self.point_child_at(&filename).map_err(|e| { - format!("wallet {filename} created but the child is not pointed at it: {e}") - })?; - Ok(CreatedWallet { record, seed }) - } - - /// Import a wallet from an existing 25-word seed. This is the only path - /// that takes a user-supplied secret — and, like a create, it is remembered - /// in the catalogue under its own file name. - pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result { - let w = self.wallet_snapshot(); - if !w.configured() { - return Err(wallet::NOT_CONFIGURED_MSG.into()); - } - let filename = self.next_wallet_filename()?; - w.restore_wallet(&filename, password, seed) - .await - .map_err(|e| e.to_string())?; - let record = self - .record_wallet(&filename) - .map_err(|e| format!("wallet {filename} imported but not remembered: {e}"))?; - self.point_child_at(&filename).map_err(|e| { - format!("wallet {filename} imported but the child is not pointed at it: {e}") - })?; - Ok(record) - } - - /// Every wallet this install remembers, oldest first. A store read: it must - /// work with no wallet RPC configured, and it never dials. - pub fn list_wallets(&self) -> Result, String> { - self.store - .lock() - .map_err(|e| e.to_string())? - .list_wallets() .map_err(|e| e.to_string()) } - /// 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()?; - for n in 1.. { - let candidate = format!("{}-{}", wallet::DEFAULT_WALLET_FILENAME, n); - if !taken.iter().any(|w| w.wallet_filename == candidate) { - return Ok(candidate); - } + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); } - unreachable!("an unused wallet file name always exists") - } - - /// 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 - /// `start_wallet_child`. - fn point_child_at(&self, filename: &str) -> Result<(), String> { - let mut cfg = self.wallet_child_config(); - if cfg.wallet_filename == filename { - return Ok(()); - } - cfg.wallet_filename = filename.to_string(); - self.set_wallet_child_config(&cfg) - } - - /// Add a freshly created wallet file to the catalogue: this node's identity - /// (several wallets may share one) and the onion it is reachable at right - /// now (a locator, and empty until the HS publishes). - fn record_wallet(&self, filename: &str) -> Result { - let new = NewWallet { - name: None, - identity_pubkey: self.identity_pk(), - onion_locator: self.onion(), - wallet_filename: filename.to_string(), - }; - self.store - .lock() - .map_err(|e| e.to_string())? - .create_wallet(&new) + w.restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + .await .map_err(|e| e.to_string()) } @@ -3068,140 +2964,4 @@ mod tests { } assert!(gone, "shutdown must not leave the wallet child behind"); } - - /// A loopback wallet RPC for the setup path: a per-socket digest challenge, - /// then the method's own result. `create_wallet` and - /// `restore_deterministic_wallet` both answer `{}`; only the seed backup - /// query has a body worth reading. - async fn mock_wallet_setup() -> Wallet { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind mock wallet"); - let port = listener.local_addr().expect("mock wallet addr").port(); - let reply: Arc String + Send + Sync> = Arc::new(|req: &str| { - if req.contains("query_key") { - r#"{"jsonrpc":"2.0","id":"0","result":{"key":"lumber tacit lemon ivory risk"}}"# - .to_string() - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{}}"#.to_string() - } - }); - tokio::spawn(serve_mock_rpc(listener, reply)); - Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") - } - - /// The reported bug: a created wallet was never remembered, because the - /// creation path never reached the store's catalogue. - #[tokio::test] - async fn creating_a_wallet_records_it_in_the_catalogue() { - 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 created = node.wallet_create("hunter2").await.expect("create wallet"); - - assert!(created.record.id > 0, "the store assigns the row id"); - assert_eq!(created.record.wallet_filename, "onionwire-1"); - assert_eq!(created.record.identity_pubkey, node.identity_pk()); - assert_eq!(created.record.onion_locator, "test.onion"); - assert_eq!(created.seed, "lumber tacit lemon ivory risk"); - assert_eq!( - node.list_wallets().expect("list wallets"), - vec![created.record], - "the wallet just created is the catalogue" - ); - } - - /// The second half of the bug: a second create reused the one hardcoded file - /// name, so the RPC refused it — and nothing was remembered across a restart. - #[tokio::test] - async fn a_second_wallet_gets_its_own_file_and_both_survive_a_reopen() { - 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 first = node.wallet_create("p1").await.expect("first wallet"); - let second = node.wallet_create("p1").await.expect("second wallet"); - - assert_ne!( - first.record.wallet_filename, second.record.wallet_filename, - "a second wallet must not reuse the first one's file" - ); - drop(node); - let reopened = Store::open_at_with_passphrase(&home, PASS).expect("reopen store"); - assert_eq!( - reopened.list_wallets().expect("list wallets").len(), - 2, - "both wallets are remembered across a restart" - ); - } - - /// Import is a creation path too: it takes the same hardcoded name today. - #[tokio::test] - async fn importing_a_wallet_records_it_in_the_catalogue() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node_with_wallet( - &dir.path().join("bob"), - Arc::new(NoDial), - mock_wallet_setup().await, - ); - - let imported = node - .wallet_restore("hunter2", "lumber tacit lemon ivory risk") - .await - .expect("restore wallet"); - - assert_eq!(imported.wallet_filename, "onionwire-1"); - assert_eq!( - node.list_wallets().expect("list wallets").len(), - 1, - "an imported wallet is remembered too" - ); - } - - /// A catalogue row the child never opens is still a broken wallet: the - /// child's stored config defaults to `onionwire`, which no created wallet - /// uses any more. - #[tokio::test] - async fn creating_a_wallet_points_the_child_at_its_own_file() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node_with_wallet( - &dir.path().join("bob"), - Arc::new(NoDial), - mock_wallet_setup().await, - ); - - let first = node.wallet_create("p1").await.expect("first wallet"); - assert_eq!( - node.wallet_child_config().wallet_filename, - first.record.wallet_filename, - "the child must open the wallet that was just created" - ); - - let second = node.wallet_create("p1").await.expect("second wallet"); - assert_eq!( - node.wallet_child_config().wallet_filename, - second.record.wallet_filename - ); - assert_eq!( - node.list_wallets().expect("list wallets")[0].wallet_filename, - first.record.wallet_filename, - "the first wallet keeps its own file" - ); - } - - /// 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] - async fn a_wallet_off_install_lists_an_empty_catalogue() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - - assert!(node.list_wallets().expect("list wallets").is_empty()); - let err = node - .wallet_create("hunter2") - .await - .expect_err("no wallet RPC"); - assert!(err.contains("ONIONWIRE_WALLET_RPC"), "{err}"); - } } diff --git a/src/tui.rs b/src/tui.rs index b14994c..a72d071 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -2263,9 +2263,9 @@ impl App { return Ok(()); } match self.rt.block_on(self.node.wallet_create(pass.as_str())) { - Ok(created) => { + Ok(seed) => { self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { - seed: Zeroizing::new(created.seed), + seed: Zeroizing::new(seed), typed: String::new(), }); } @@ -2338,7 +2338,7 @@ impl App { .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); seed.zeroize(); match result { - Ok(_) => { + Ok(()) => { self.status_note = Some("wallet imported".into()); return self.open_wallet(); }