diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 9635337..1cd7124 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -104,24 +104,6 @@ val msgs: List = wire.messages(friend.pubkeyHex) // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. val out: RotateOutcome = wire.rotateOnion() // out.notified / out.friends - -// 6. Saved wallets, and which one is open. -val wallets: List = wire.wallets() // a store read: never dials -val active: String? = wire.activeWalletFilename() // the open file, or null -val open = wallets.firstOrNull { it.walletFilename == active } -wire.openWallet("onionwire-2") // may restart a running wallet child; a name - // outside the catalogue is refused -val keys: WalletKeys = wire.walletKeys() // the OPEN wallet's private keys -// keys.spendKey == null -> a view-only wallet (the RPC's -29 watch-only answer). -// That is not an error. The seed (`walletSeed()`) and these keys always belong -// to `activeWalletFilename()`: to show another wallet's backup, open it first. -// Both are spend secrets — show them from an explicit user action only, never -// log them, never persist them. - -// 7. Your own profile (nickname, bio, Monero address). -val me: SelfProfile = wire.selfProfile() -wire.setSelfProfile("ada", "on the wire", "4AdUnd...") // validated on write -wire.pushSelfProfile(friend.pubkeyHex) // signed `prf`, one-shot and fail-closed ``` All peer references are lowercase hex strings so nothing Rust-shaped leaks into diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 11ca267..d17f7f3 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -28,14 +28,14 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; +use onionwire::Message; use onionwire::hs::TorState as CoreTorState; use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::outbox::{DEFAULT_MAX_ATTEMPTS, OutboxEntry, OutboxStatus}; use onionwire::pay; use onionwire::qr; -use onionwire::wallet::{ChainNetwork, ChainSource, WalletKeys as CoreWalletKeys}; +use onionwire::wallet::{ChainNetwork, ChainSource}; use onionwire::wallet_child::{ChildConfig, WalletChildState}; -use onionwire::{FriendProfile, Message, WalletRecord}; uniffi::setup_scaffolding!(); @@ -540,128 +540,6 @@ impl Wire { .collect()) } - // ---- Wallet catalogue, the open wallet, and its secrets ---- - - /// Every wallet this install remembers, oldest first. - /// - /// A store read: it never dials the wallet RPC or the chain, so it works - /// with the wallet child stopped or never configured. "No wallets" is an - /// empty list, never an error. `WireError.Stopped` after `shutdown`; - /// `WireError.Failed` only when the store itself cannot be read. - /// - /// The Kotlin binding is `Wire.wallets()`. - pub async fn wallets(&self) -> WResult> { - let rows = self.node()?.list_wallets().map_err(WireError::new)?; - Ok(rows.iter().map(wallet_row).collect()) - } - - /// Point the wallet child at a catalogue wallet's file: afterwards the - /// balance, transfers, seed and keys this surface reports are that - /// wallet's. - /// - /// **It may restart a running wallet child.** A live child is stopped and - /// started again onto the new file, which is what makes the change take - /// effect immediately — and why this call is slow (a `.onion` source waits - /// for its SOCKS listener, an in-process chain daemon for its RPC). An idle - /// child is only re-pointed: nothing is spawned, and the change applies at - /// the next [`Wire::start_wallet_child`]. - /// - /// A `filename` the catalogue does not hold is **refused**: the catalogue is - /// the only directory this app keeps wallets in, and a spend-capable child - /// is never pointed at a path a caller invented. Get the name from - /// [`Wire::wallets`]. `WireError.Stopped` after `shutdown`. - pub async fn open_wallet(&self, filename: String) -> WResult<()> { - self.node()?.open_wallet(&filename).map_err(WireError::new) - } - - /// The wallet file the child is currently pointed at, or `None` when no - /// wallet-child settings were ever stored (a fresh install has no open - /// wallet). - /// - /// A picker marks the open row with - /// `row.wallet_filename == active`; every other row means "open it first to - /// see its seed or keys", because the seed and the private keys always come - /// from the file the child has **open**. The value can name a file that is - /// not in the catalogue (an install whose wallet predates it) — that is "no - /// open wallet row", not an error. - /// - /// It never dials and never spawns. `WireError.Stopped` after `shutdown`. - pub async fn active_wallet_filename(&self) -> WResult> { - self.node()? - .active_wallet_filename() - .map_err(WireError::new) - } - - /// The private view key and spend key of the wallet file the child has - /// **open** (`query_key`). This is a dial to the wallet child's loopback - /// RPC, so call it from an explicit user action, not from a refresh loop. - /// - /// `spend_key` is `None` for a view-only wallet: the RPC answers `-29` - /// ("Cannot retrieve spend key") and that is the wallet's own answer, not a - /// failure, so it is not surfaced as one. `WireError.Failed` when no wallet - /// is configured or the child is not answering; `WireError.Stopped` after - /// `shutdown`. - /// - /// The values are spend secrets: show them, never log them, never persist - /// them. `WalletKeys`'s `Debug` redacts both. - pub async fn wallet_keys(&self) -> WResult { - let keys = self.node()?.wallet_keys().await.map_err(WireError::new)?; - Ok(keys_record(keys)) - } - - // ---- This identity's own profile ---- - - /// This identity's own profile (nickname, bio, Monero address) as stored. - /// - /// A store read: never dials. It is the local copy — what friends show for - /// you only changes once [`Wire::push_self_profile`] reaches them. - /// `WireError.Stopped` after `shutdown`. - pub async fn self_profile(&self) -> WResult { - let p = self.node()?.self_profile().map_err(WireError::new)?; - Ok(self_profile_record(&p)) - } - - /// Replace this identity's own profile. - /// - /// Validated before it is written, so a rejected edit leaves the stored - /// profile untouched: a nickname over 64 characters, a bio over 512, or a - /// non-empty address that fails the Monero checksum (the same check `/pay` - /// and `/tip` use) is refused with `WireError.Failed`. An empty address is - /// allowed. - /// - /// It does not tell anyone. Friends still see the previous profile until - /// [`Wire::push_self_profile`] is sent to them. `WireError.Stopped` after - /// `shutdown`. - pub async fn set_self_profile( - &self, - display_name: String, - bio: String, - xmr_addr: String, - ) -> WResult<()> { - self.node()? - .set_self_profile(&display_name, &bio, &xmr_addr) - .map_err(WireError::new) - } - - /// Send this identity's signed profile to one friend, so the nickname and - /// address they show for you are current. - /// - /// One-shot and fail closed: a peer whose onion is down means this fails - /// and **nothing is queued** — no retry, no outbox row (profiles are not - /// chat). Send it again when they are reachable. - /// - /// `pubkey_hex` is the friend's identity pubkey, the encoding - /// [`FriendInfo::pubkey_hex`] carries; an unparseable hex is - /// `WireError.Failed` before anything is dialled. `WireError.Stopped` after - /// `shutdown`. - pub async fn push_self_profile(&self, pubkey_hex: String) -> WResult<()> { - let pk = unhex(&pubkey_hex)?; - self.node()? - .push_self_profile(&pk) - .await - .map_err(WireError::new) - } - /// Send an invoice to a friend: sign an invoice for my receive address and send /// the frame one-shot. Peer onion down → this fails; invoices are not queued. /// @@ -1140,39 +1018,6 @@ fn outbox_row(entry: &OutboxEntry) -> OutboxRow { } } -/// `WalletRecord` → the picker row. `wallet_filename` is the file name only -/// (never a path): the core resolves it inside `$ONIONWIRE_HOME/wallet`. -fn wallet_row(w: &WalletRecord) -> WalletRow { - WalletRow { - id: w.id, - name: w.name.clone(), - wallet_filename: w.wallet_filename.clone(), - onion_locator: w.onion_locator.clone(), - identity_pubkey_hex: hex(&w.identity_pubkey), - created_at: w.created_at, - } -} - -/// The core's key record → the SDK's, with the secrets carried across verbatim -/// (this is a display path; nothing here logs or stores them). -fn keys_record(keys: CoreWalletKeys) -> WalletKeys { - WalletKeys { - view_key: keys.view_key, - spend_key: keys.spend_key, - } -} - -/// `FriendProfile` → the profile screen's record. `updated_at` is deliberately -/// not carried: the SDK surface has no use for it, and a client that wants -/// "did my push land" compares the fields it set. -fn self_profile_record(p: &FriendProfile) -> SelfProfile { - SelfProfile { - display_name: p.display_name.clone(), - bio: p.bio.clone(), - xmr_addr: p.xmr_addr.clone(), - } -} - /// A Monero transfer row for the wallet screen. /// /// `amount` is formatted XMR (not raw piconero) — the SDK formats it from the @@ -1184,71 +1029,6 @@ pub struct TransferRow { pub address: String, } -/// One row of the saved-wallet catalogue, for the wallet picker. -/// -/// Mirrors the core's `WalletRecord`, with the identity pubkey as hex. `id` is -/// the `wallets.id` row id, `wallet_filename` is the file inside -/// `$ONIONWIRE_HOME/wallet` and is what [`Wire::open_wallet`] takes, and the -/// rows come back oldest-first so a list is stable between calls. -/// -/// `identity_pubkey_hex` is the identity this wallet belongs to and is **not** -/// unique; `onion_locator` is a locator that may be empty or stale. Never key a -/// selection, or the roster, on the locator. -#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] -pub struct WalletRow { - pub id: i64, - /// The user's label for this wallet. `None` when it was never named, and - /// never an empty string. - pub name: Option, - pub wallet_filename: String, - pub onion_locator: String, - /// The owning identity's ed25519 pubkey, hex — the same encoding - /// [`FriendInfo::pubkey_hex`] carries. - pub identity_pubkey_hex: String, - /// Unix seconds, assigned by the store when the row was created. - pub created_at: i64, -} - -/// The private keys of the **open** wallet file, for a backup screen. -/// -/// Both values are spend secrets: show them only from an explicit user action, -/// never log them, and never persist them. `Debug` is hand-written to redact -/// them so a stray `{:?}` cannot leak a key into a log. -#[derive(Clone, PartialEq, Eq, uniffi::Record)] -pub struct WalletKeys { - /// The open wallet file's private view key. - pub view_key: String, - /// The open wallet file's private spend key, or `None` for a view-only - /// wallet. `None` is the wallet's own answer — it has no spend key — and - /// not a failure. - pub spend_key: Option, -} - -/// Hand-written so a stray `{:?}` cannot print a private key. -impl std::fmt::Debug for WalletKeys { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WalletKeys") - .field("view_key", &"") - .field("spend_key", &self.spend_key.as_ref().map(|_| "")) - .finish() - } -} - -/// This identity's own profile, as the profile screen reads and edits it. -/// -/// It is what friends are shown for this identity once it has been pushed; -/// nothing here is secret (an empty `xmr_addr` is allowed, a non-empty one is -/// validated). -#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] -pub struct SelfProfile { - pub display_name: String, - pub bio: String, - /// This identity's Monero address. May be empty. When non-empty the core - /// refuses to store it unless it passes the same address check `/pay` and - /// `/tip` use. - pub xmr_addr: String, -} - /// Where the app-owned wallet child gets its chain from. Mirrors the core's /// `ChainSource`: nothing is implied — `Remote` is a daemon the user supplied. #[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] @@ -1561,8 +1341,8 @@ mod tests { //! handle, which is what a shut-down node must guarantee. A `Wire` with no //! node is exactly the state `shutdown()` leaves behind. use super::*; + use onionwire::Store; use onionwire::outbox::OutboxStatus; - use onionwire::{NewWallet, Store}; use std::path::PathBuf; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2325,163 +2105,4 @@ mod tests { let err = block_on(stopped_wire().wallet_child_refresh()).expect_err("must fail"); assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); } - - // ---- wallet catalogue, the open wallet, its keys, and the self profile ---- - - #[test] - fn wallets_on_a_stopped_handle_is_stopped_error() { - let err = block_on(stopped_wire().wallets()).expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn open_wallet_on_a_stopped_handle_is_stopped_error() { - let err = - block_on(stopped_wire().open_wallet("onionwire".to_string())).expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn active_wallet_filename_on_a_stopped_handle_is_stopped_error() { - let err = block_on(stopped_wire().active_wallet_filename()).expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn wallet_keys_on_a_stopped_handle_is_stopped_error() { - let err = block_on(stopped_wire().wallet_keys()).expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn self_profile_on_a_stopped_handle_is_stopped_error() { - let err = block_on(stopped_wire().self_profile()).expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn set_self_profile_on_a_stopped_handle_is_stopped_error() { - let err = block_on(stopped_wire().set_self_profile( - "nick".to_string(), - String::new(), - String::new(), - )) - .expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn push_self_profile_on_a_stopped_handle_is_stopped_error() { - // Valid 32-byte hex, so the hex parse cannot be the thing that failed: - // the handle is. - let err = - block_on(stopped_wire().push_self_profile("11".repeat(32))).expect_err("must fail"); - assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); - } - - #[test] - fn push_self_profile_rejects_a_pubkey_that_is_not_hex_before_any_work() { - let err = - block_on(stopped_wire().push_self_profile("nope".to_string())).expect_err("must fail"); - // The hex check runs first, so this is `Failed`, not `Stopped`. - assert!(matches!(err, WireError::Failed { .. }), "got {err:?}"); - } - - /// The picker row is the catalogue row, row for row: same id, same file - /// name, same label, and the pubkey as hex. A Kotlin picker keys on - /// `wallet_filename` for [`Wire::open_wallet`], so it has to be exact. - #[test] - fn wallet_rows_carry_the_catalogue_verbatim() { - let home = temp_home(); - let store = Store::open_at_with_passphrase(&home, "wallet-catalogue-pass").unwrap(); - let named = store - .create_wallet(&NewWallet { - name: Some("savings".to_string()), - identity_pubkey: [0xab; 32], - onion_locator: "peer.onion".to_string(), - wallet_filename: "onionwire-1".to_string(), - }) - .unwrap(); - let unnamed = store - .create_wallet(&NewWallet { - name: None, - identity_pubkey: [0xab; 32], - onion_locator: String::new(), - wallet_filename: "onionwire-2".to_string(), - }) - .unwrap(); - - let rows: Vec = store - .list_wallets() - .unwrap() - .iter() - .map(wallet_row) - .collect(); - - assert_eq!(rows.len(), 2, "both wallets are listed"); - assert_eq!(rows[0].id, named.id); - assert_eq!(rows[0].name.as_deref(), Some("savings")); - assert_eq!(rows[0].wallet_filename, "onionwire-1"); - assert_eq!(rows[0].onion_locator, "peer.onion"); - assert_eq!(rows[0].identity_pubkey_hex, "ab".repeat(32)); - assert_eq!(rows[0].created_at, named.created_at); - // A wallet created without a label is `None`, never an empty string. - assert_eq!(rows[1].id, unnamed.id); - assert_eq!(rows[1].name, None); - // The locator is a locator: it may be empty, and it is not an identity. - assert_eq!(rows[1].onion_locator, ""); - - std::fs::remove_dir_all(&home).ok(); - } - - #[test] - fn keys_mapping_carries_both_halves_and_the_view_only_answer() { - let both = keys_record(CoreWalletKeys { - view_key: "view-material".to_string(), - spend_key: Some("spend-material".to_string()), - }); - assert_eq!(both.view_key, "view-material"); - assert_eq!(both.spend_key.as_deref(), Some("spend-material")); - - let view_only = keys_record(CoreWalletKeys { - view_key: "view-material".to_string(), - spend_key: None, - }); - assert_eq!(view_only.view_key, "view-material"); - assert_eq!(view_only.spend_key, None); - } - - /// These two are spend secrets: the record the Kotlin side receives must not - /// print them through `Debug`, or a `{:?}` in a crash log leaks a key. - #[test] - fn wallet_keys_debug_never_prints_a_private_key() { - let keys = keys_record(CoreWalletKeys { - view_key: "VIEWKEYMATERIAL".to_string(), - spend_key: Some("SPENDKEYMATERIAL".to_string()), - }); - let printed = format!("{keys:?}"); - assert!( - !printed.contains("VIEWKEYMATERIAL"), - "view key leaked: {printed}" - ); - assert!( - !printed.contains("SPENDKEYMATERIAL"), - "spend key leaked: {printed}" - ); - assert!(printed.contains("redacted"), "got {printed}"); - } - - #[test] - fn self_profile_mapping_carries_the_three_editable_fields() { - let core = FriendProfile { - display_name: "nick".to_string(), - bio: "bio".to_string(), - xmr_addr: String::new(), - updated_at: 1_700_000_000, - }; - let got = self_profile_record(&core); - assert_eq!(got.display_name, "nick"); - assert_eq!(got.bio, "bio"); - assert_eq!(got.xmr_addr, ""); - } } diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index b3a7a44..9781368 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -249,32 +249,6 @@ the app does not pick a public remote node for them. Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs spend, and RPC credentials: [WALLET.md](WALLET.md). -## The recovery phrase and the private keys are displayable on demand - -Both clients can show the **open** wallet's recovery phrase (`query_key -mnemonic`) and its private view and spend keys (`query_key view_key` / -`spend_key`), from an explicit user action. That is new exposure the threat model -did not previously enumerate: the phone screen — and the Linux TUI window — is -now one of the places a spending secret can be read from. - -- The values come from the wallet file the child has **open**. There is no path - that reads another saved wallet's secret without opening it first, and none - that reads a wallet file directly: the RPC is the only source. -- They are never logged, never written to the store or any other file, and never - placed in an error string; the records that carry them (`WalletKeys`) redact - themselves under `Debug`. They exist in process memory only while a screen - shows them. -- They are shown only from an explicit user action, never on a refresh path. -- What this does **not** stop: a shoulder-surfer, a screen recorder, a - screenshot, or a malicious app with screen-capture permission. Whoever reads - the screen gets the keys; a view-only wallet leaks only the view key - (`spend_key` is `None`), but a spend-capable one leaks everything the file can - spend. -- The spend-authority warning above still applies and is now easier to reach: - the seed that makes a wallet spend-capable can be photographed off the device. - Treat any screen that shows a seed or a private key the way you treat the - wallet file itself. - ## Backup file is the identity `/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table. diff --git a/docs/WALLET.md b/docs/WALLET.md index 8b0255a..054c48c 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -203,36 +203,6 @@ launches the node *and* the wallet child. `wallet_status()` carries Monero ships **no Android binaries**. Any vendored blob's provenance doc must say so. Cross-compiled is not device-proven. See `android/MONERO_BINARIES.md`. -### The wallet catalogue, and which wallet is open - -`wallets()` lists every wallet this install remembers (oldest first), each row -carrying the `wallet_filename` the child opens, its label, the owning identity -pubkey as hex, and the locator. `active_wallet_filename()` returns the file the -child is **currently pointed at** (or `None` on a fresh install), so a picker can -mark the open row. `open_wallet(filename)` switches to a catalogue row: a -running child is stopped and restarted onto the new file, an idle one is only -re-pointed (the change applies at the next `start_wallet_child`), and a file the -catalogue does not hold is refused — the catalogue is the only directory this app -keeps wallets in. - -## Secrets belong to the open wallet - -The seed (`wallet_seed()`, `query_key mnemonic`) and the private keys -(`wallet_keys()` → `query_key view_key` / `query_key spend_key`) are answered by -the wallet file the child has **open**, so they always belong to the row -`active_wallet_filename()` names. There is deliberately no accessor that reads -another saved wallet's seed or keys without opening it: show a backups screen, -then `open_wallet(...)` the row — the UI must say *which* wallet it is showing. -`WalletKeys.spend_key` is `None` for a view-only wallet (the RPC's `-29`), which -is an answer, not an error. - -Both values are spend secrets. They are displayable on demand in the TUI and in -the Android app, are never logged, never written to the store or to disk, and -never put into an error string (the core's `WalletKeys` `Debug` redacts them). -The exposure this creates is enumerated in -[THREAT_MODEL.md](THREAT_MODEL.md), "The recovery phrase and the private keys -are displayable on demand". - ## Create vs import `/wallet create` (`F6` then `c`) → `create_wallet`, then seed **once** @@ -293,8 +263,6 @@ Restore from a height at or before the first incoming transaction. | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | | OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | -| Show the backup (seed via `query_key mnemonic`) | **no seed to show** (the RPC answers `-29`) | works | -| Show the private keys (`wallet_keys`) | view key only, `spend_key` is `None` | view + spend key | `ONIONWIRE_WALLET_NO_SPEND=1` refuses `/tip` before RPC with: diff --git a/src/node.rs b/src/node.rs index 923d3ca..bbd0d24 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1232,43 +1232,6 @@ impl Node { w.mnemonic().await.map_err(|e| e.to_string()) } - /// The private view key and, when the wallet can spend, the private spend - /// key of the wallet file the child currently has **open** (`query_key`). - /// - /// Secrets therefore belong to the open wallet: viewing another saved - /// wallet's keys means opening it first. A view-only wallet answers `None` - /// for `spend_key` instead of an error (the RPC's `-29`). An unconfigured - /// wallet is refused locally, before any dial; a configured but unreachable - /// child surfaces the RPC error. - /// - /// The values are spend secrets: never log them and never persist them. - pub async fn wallet_keys(&self) -> Result { - let w = self.wallet_snapshot(); - if !w.configured() { - return Err(wallet::NOT_CONFIGURED_MSG.into()); - } - w.keys().await.map_err(|e| e.to_string()) - } - - /// The wallet file the child is currently pointed at, so a client can mark - /// the open row in the catalogue. `None` when no wallet-child settings have - /// ever been stored (a fresh install): a receive-only install has no open - /// wallet file, and the child never points at one until a wallet is created, - /// imported, or opened. - /// - /// The name is what the child would spawn with, not a message from the - /// running process, and it may not match a catalogue row (an install whose - /// wallet predates the catalogue). Match it against - /// [`Node::list_wallets`] rather than assuming it is there. - pub fn active_wallet_filename(&self) -> Result, String> { - let store = self.store.lock().map_err(|e| e.to_string())?; - let Some(raw) = store.load_wallet_child().map_err(|e| e.to_string())? else { - return Ok(None); - }; - let cfg = ChildConfig::from_record(&raw).map_err(|e| e.to_string())?; - Ok(cfg.map(|cfg| cfg.wallet_filename)) - } - /// 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. @@ -3411,91 +3374,4 @@ pub(crate) mod tests { "a refused switch must leave the child where it was" ); } - - /// The active wallet is a child-config fact, not a catalogue fact: a row in - /// the catalogue that the child was never pointed at is not open, and a - /// fresh install has no open wallet at all. - #[tokio::test] - async fn active_wallet_filename_is_none_until_the_child_has_been_pointed() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - - assert_eq!( - node.active_wallet_filename().expect("read"), - None, - "a fresh install has no open wallet file" - ); - - // A record written before the settings were persisted (creds, no - // source block) is not an open wallet either. - node.store - .lock() - .unwrap() - .save_wallet_child(r#"{"user":"owuser","pass":"ow-pass"}"#) - .unwrap(); - assert_eq!( - node.active_wallet_filename().expect("read"), - None, - "a creds-only record does not name a wallet file" - ); - - test_record_wallet(&node.store.lock().unwrap(), "onionwire-1", "savings"); - assert_eq!( - node.active_wallet_filename().expect("read"), - None, - "a catalogue row alone does not open the wallet" - ); - - node.open_wallet("onionwire-1") - .expect("open a saved wallet"); - assert_eq!( - node.active_wallet_filename().expect("read").as_deref(), - Some("onionwire-1"), - "the open wallet is the file the child was pointed at" - ); - } - - /// No wallet, no dial: the refusal is the configured-guard copy, not a - /// connection error, and it happens before any socket is opened. - #[tokio::test] - async fn wallet_keys_without_a_wallet_refuses_without_dialing() { - let dir = tempfile::tempdir().unwrap(); - let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); - let err = node.wallet_keys().await.expect_err("no wallet configured"); - assert_eq!(err, wallet::NOT_CONFIGURED_MSG); - } - - /// The node-level path a Kotlin caller takes: two `query_key` calls against - /// the open wallet's RPC, with the view-only `-29` arriving as - /// `spend_key: None` rather than as an error. - #[tokio::test] - async fn wallet_keys_of_a_view_only_wallet_returns_no_spend_key() { - 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("spend_key") { - r#"{"jsonrpc":"2.0","id":"0","error":{"code":-29,"message":"The wallet is watch-only. Cannot retrieve spend key."}}"# - .to_string() - } else { - r#"{"jsonrpc":"2.0","id":"0","result":{"key":"aabbccdd"}}"#.to_string() - } - }); - tokio::spawn(serve_mock_rpc(listener, reply)); - - let dir = tempfile::tempdir().unwrap(); - let node = offline_node_with_wallet( - &dir.path().join("bob"), - Arc::new(NoDial), - Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url"), - ); - - let keys = node.wallet_keys().await.expect("keys"); - assert_eq!(keys.view_key, "aabbccdd"); - assert_eq!( - keys.spend_key, None, - "the RPC's -29 is the wallet's answer, not a failure" - ); - } } diff --git a/src/wallet.rs b/src/wallet.rs index 787ee90..e4437da 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -349,27 +349,6 @@ impl std::fmt::Debug for Endpoint { } } -/// The private keys of the wallet file the RPC currently has open. -/// -/// `view_key` is the private view key; `spend_key` is the private spend key and -/// is `None` — not an error — for a view-only wallet, which has no spend key to -/// hand out. Both are secrets: never log them, never persist them, and never put -/// them in an error string. -pub struct WalletKeys { - pub view_key: String, - pub spend_key: Option, -} - -/// Hand-written so a stray `{:?}` cannot print a private key. -impl std::fmt::Debug for WalletKeys { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WalletKeys") - .field("view_key", &"") - .field("spend_key", &self.spend_key.as_ref().map(|_| "")) - .finish() - } -} - #[derive(Debug, Clone)] pub struct Wallet { endpoint: Option, @@ -828,45 +807,6 @@ impl Wallet { json_str(&v, "key") } - /// The wallet file's private keys, as the RPC reports them: `query_key` - /// `view_key` and `query_key` `spend_key`. - /// - /// Both come from the wallet file the child currently has **open** — this is - /// not a "read any saved wallet's keys" accessor, and it cannot be: the RPC - /// only ever answers for its open file. - /// - /// A view-only wallet has no spend key: its `query_key spend_key` answers - /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29), which maps to - /// `spend_key: None` rather than an error, matching the `-29` view-only - /// detection the transfer probe already uses. Refuses locally, before any - /// dial, when the wallet is not configured. - /// - /// The two values are spend secrets: never log them, never store them, never - /// put them in an error string. [`WalletKeys`]'s `Debug` redacts both. - pub async fn keys(&self) -> Result { - if !self.configured() { - return Err(Error(NOT_CONFIGURED_MSG.into())); - } - let v = self - .rpc("query_key", serde_json::json!({"key_type": "view_key"})) - .await?; - let view_key = json_str(&v, "key")?; - // Asked second and separately: on a view-only wallet this is the call - // that carries the `-29`, and `None` is the honest answer there. - let spend_key = match self - .rpc("query_key", serde_json::json!({"key_type": "spend_key"})) - .await - { - Ok(v) => Some(json_str(&v, "key")?), - Err(e) if e.to_string() == VIEW_ONLY_MSG => None, - Err(e) => return Err(e), - }; - Ok(WalletKeys { - view_key, - spend_key, - }) - } - /// Import an existing wallet from its 25-word seed. This is the only path /// that takes a user-supplied secret. pub async fn restore_wallet(&self, filename: &str, password: &str, seed: &str) -> Result<()> { diff --git a/tests/wallet.rs b/tests/wallet.rs index 0724779..9c8649b 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1,6 +1,5 @@ //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use ed25519_dalek::SigningKey; @@ -894,147 +893,6 @@ fn mnemonic_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); } -/// The two private keys come from the open wallet file, in two `query_key` -/// calls: `view_key` first (always available), `spend_key` second (absent on a -/// view-only wallet). A wallet that can spend answers both. -#[tokio::test] -async fn keys_returns_the_view_and_spend_keys_of_the_open_wallet() { - const VIEW: &str = "0f0e0d0c0b0a09080706050403020100"; - const SPEND: &str = "0102030405060708090a0b0c0d0e0f10"; - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let calls = Arc::new(AtomicUsize::new(0)); - let seen = Arc::clone(&calls); - tokio::spawn(serve_rpc_conns( - listener, - Arc::new(move |method: &str| match method { - "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { - 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), - _ => rpc_result(&format!(r#"{{"key":"{SPEND}"}}"#)), - }, - other => panic!("keys must only ask query_key, saw {other}"), - }), - None, - None, - )); - let keys = recording_wallet(port).keys().await.expect("keys"); - assert_eq!(keys.view_key, VIEW); - assert_eq!(keys.spend_key.as_deref(), Some(SPEND)); - assert_eq!(calls.load(Ordering::SeqCst), 2, "one call per key"); -} - -/// A view-only wallet has no spend key: the RPC answers `-29` -/// (`WALLET_RPC_ERROR_CODE_WATCH_ONLY`). That is the wallet's answer, so it must -/// come back as `spend_key: None` — not as an error, which would leave the -/// backup screen unable to show the view key. -#[tokio::test] -async fn keys_of_a_view_only_wallet_have_no_spend_key_and_no_error() { - const VIEW: &str = "aabbccddeeff00112233445566778899"; - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let calls = Arc::new(AtomicUsize::new(0)); - let seen = Arc::clone(&calls); - tokio::spawn(serve_rpc_conns( - listener, - Arc::new(move |method: &str| match method { - "query_key" => match seen.fetch_add(1, Ordering::SeqCst) { - 0 => rpc_result(&format!(r#"{{"key":"{VIEW}"}}"#)), - _ => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), - }, - other => panic!("keys must only ask query_key, saw {other}"), - }), - None, - None, - )); - let keys = recording_wallet(port) - .keys() - .await - .expect("a view-only wallet"); - assert_eq!(keys.view_key, VIEW); - assert_eq!( - keys.spend_key, None, - "view-only means no spend key to hand out" - ); -} - -/// Any *other* RPC failure is a real failure: a view-only `-29` is the only -/// error `keys` turns into `None`. -#[tokio::test] -async fn keys_surfaces_an_rpc_error_that_is_not_the_view_only_answer() { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let calls = Arc::new(AtomicUsize::new(0)); - let seen = Arc::clone(&calls); - tokio::spawn(serve_rpc_conns( - listener, - Arc::new(move |_: &str| { - if seen.fetch_add(1, Ordering::SeqCst) == 0 { - rpc_result(r#"{"key":"aabbccdd"}"#) - } else { - rpc_error(-1, "wallet file is not open") - } - }), - None, - None, - )); - let err = recording_wallet(port) - .keys() - .await - .expect_err("a spend-key error that is not -29 must not read as view-only"); - let msg = err.to_string(); - assert!(msg.contains("wallet file is not open"), "got {err}"); - assert!(!msg.contains("secret"), "password leaked: {err}"); -} - -/// No endpoint, no dial: the refusal is the configured-guard copy the rest of -/// the wallet uses, not a connection error. -#[test] -fn keys_on_an_unconfigured_wallet_is_a_refusal_not_a_dial() { - let w = Wallet::disabled(); - let err = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .unwrap() - .block_on(w.keys()) - .unwrap_err(); - assert_eq!(err.to_string(), NOT_CONFIGURED_MSG); -} - -/// The keys are spend secrets. `WalletKeys` is the value the whole path carries, -/// so its `Debug` must not print either key — a stray `{:?}` in a log is how a -/// key leaks. -#[test] -fn wallet_keys_debug_never_prints_a_private_key() { - let keys = wallet::WalletKeys { - view_key: "VIEWKEYMATERIAL".to_string(), - spend_key: Some("SPENDKEYMATERIAL".to_string()), - }; - let printed = format!("{keys:?}"); - assert!( - !printed.contains("VIEWKEYMATERIAL"), - "view key leaked: {printed}" - ); - assert!( - !printed.contains("SPENDKEYMATERIAL"), - "spend key leaked: {printed}" - ); - assert!(printed.contains("redacted"), "got {printed}"); - - let only_view = wallet::WalletKeys { - view_key: "VIEWKEYMATERIAL".to_string(), - spend_key: None, - }; - let printed = format!("{only_view:?}"); - assert!( - !printed.contains("VIEWKEYMATERIAL"), - "view key leaked: {printed}" - ); - assert!( - printed.contains("None"), - "a view-only wallet must read as None: {printed}" - ); -} - /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) {