diff --git a/README.md b/README.md index 5545d90..23f984e 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,9 @@ wallet-file passphrase; blank skips it, a wrong one opens a different wallet and does not fail). Type `SPEND` then `SEEN` on create. Each wallet gets its own file name (`onionwire-1`, `onionwire-2`, …); the RPC must be started with `--wallet-dir`. +`F6` then `n` sends to a pasted address as a plain local `transfer` (no chat +frame), and `F6` then `v` imports an address to watch from its view key with no +spend key at all. `monero-wallet-rpc` keeps a wallet open only for the life of one process, so the app opens the configured file itself after the child is up (`open_wallet`) — and diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index 35d4b70..c9ce8ee 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -498,7 +498,10 @@ impl Wire { /// Current wallet balance as a display string, or `"off"` / `"err"`. /// /// Returns `"off"` when the wallet is not configured (no `ONIONWIRE_WALLET_RPC`), - /// `"err"` when the wallet RPC call failed, and `"balance X.X XMR"` on success. + /// `"err"` when the wallet RPC call failed, and the amount in XMR as a bare + /// number on success (the core's `atomic_to_xmr_str`, e.g. `"0.5"`) — the + /// sentinels are what a caller branches on, so the number is not wrapped in + /// any label here. /// A stopped node (shut-down handle) returns `"off"` — the wallet is not /// accessible without a live node, and the UI treats "off" as "wallet not /// available" rather than an error state. @@ -509,6 +512,59 @@ impl Wire { } } + /// The spendable part of the balance, as a display string with exactly the + /// same sentinels as [`Wire::wallet_balance`]: `"off"` when the wallet is not + /// configured or the node is gone, `"err"` when the RPC did not answer with + /// a number, else the bare XMR number. The rest of the balance is either + /// locked (unconfirmed income) or immature (recent coinbase), so a UI shows + /// both: funds that exist, and funds that can move now. + pub async fn wallet_unlocked_balance(&self) -> String { + match self.node() { + Ok(node) => node.wallet_unlocked_balance().await, + Err(_) => "off".to_string(), + } + } + + /// Is the wallet file the child has open **watch-only** (imported from an + /// address and a view key, so it holds no spend key)? + /// + /// Proven over RPC: `query_key` for the spend key is refused with monero's + /// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (`-29`) exactly on a wallet that + /// cannot spend; a spend key that does come back is discarded inside the + /// node, never returned and never logged. An unconfigured wallet — or a + /// stopped node — is an error, **not** `true`: claiming a watch-only wallet + /// exists when there is none would be a lie. `WireError.Failed` carries the + /// core's own not-configured message, `WireError.Stopped` a shut-down node. + /// + /// The Kotlin binding is `Wire.walletViewOnly()`. + pub async fn wallet_view_only(&self) -> WResult { + self.node()? + .wallet_view_only() + .await + .map_err(WireError::new) + } + + /// Send XMR to a pasted address. Returns the transaction hash. + /// + /// A **local** transfer on this node's own wallet: no friend, no `tip` + /// frame, no chat line and no payment row — the wallet's outgoing transfer + /// list is the record. `address` and `amount_xmr` are checked here first, so + /// an empty field, an invalid address or an unparsable amount fails without + /// touching the RPC (`WireError.Failed` with the core's own message). + /// + /// The spend gates are the core's and are surfaced as they are: a wallet + /// configured `ONIONWIRE_WALLET_NO_SPEND=1` or a watch-only file is refused + /// with the view-only message, and a wallet that has not reached the chain + /// tip is refused rather than allowed to fail opaquely. + /// + /// The Kotlin binding is `Wire.walletSend(address, amountXmr)`. + pub async fn wallet_send(&self, address: String, amount_xmr: String) -> WResult { + self.node()? + .wallet_send(&address, &amount_xmr) + .await + .map_err(WireError::new) + } + /// Receive address for the wallet screen: a freshly created subaddress when /// the wallet is configured, else the profile `xmr_addr` fallback. /// @@ -536,6 +592,7 @@ impl Wire { txid: r.txid, amount: pay::atomic_to_xmr_str(&r.amount), address: r.address, + direction: r.direction, }) .collect()) } @@ -770,7 +827,7 @@ impl Wire { /// seed-offset passphrase. pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { self.node()? - .wallet_restore(&password, &seed, None) + .wallet_restore(&password, &seed, None, None) .await .map_err(WireError::new) .map(|_| ()) @@ -800,7 +857,78 @@ impl Wire { Some(offset) }; self.node()? - .wallet_restore(&password, &seed, offset) + .wallet_restore(&password, &seed, offset, None) + .await + .map_err(WireError::new) + .map(|_| ()) + } + + /// Import a wallet from an existing 25-word seed, with the two optional + /// inputs the core takes beside it: Monero's seed-offset passphrase and a + /// restore height. + /// + /// This is the call a first-run import screen makes: it supersedes + /// [`Wire::import_wallet`] and [`Wire::import_wallet_with_offset`] without + /// changing either of them, so an existing caller keeps compiling. + /// + /// `seed_offset` is Monero's second spend secret (not the file passphrase): + /// blank or whitespace means "no offset" and the request carries no + /// `seed_offset` field. `restore_height` is a block number as typed: + /// blank means "scan from 0" and the request carries no `restore_height` + /// field either — never a `0`. Anything else that is not a block number is + /// refused locally with `restore height must be a block number`. + /// + /// A height *after* the first receive hides the older funds, and this + /// version has no rescan to undo that: the UI has to say so, not fix it. + pub async fn import_seed( + &self, + password: String, + seed: String, + seed_offset: String, + restore_height: String, + ) -> WResult<()> { + let offset = seed_offset.trim(); + let offset = if offset.is_empty() { + None + } else { + Some(offset) + }; + let height = restore_height_arg(&restore_height)?; + self.node()? + .wallet_restore(&password, &seed, offset, height) + .await + .map_err(WireError::new) + .map(|_| ()) + } + + /// Import an address to **watch**: `generate_from_keys` with the address and + /// its private view key, and no spend key at all. The wallet file this + /// creates can see incoming transfers and cannot spend — it is not a spend + /// authority, and `Wire::walletSend` on it is refused with the view-only + /// message. + /// + /// `view_key` is trimmed and must be 64 hex characters; the request never + /// carries a `spendkey` field, and the key is neither stored nor sealed + /// (`password` is the wallet *file* passphrase and is what gets sealed, so + /// the file reopens on the next start). A wrong-shape key is refused locally + /// with `view key must be 64 hex characters` and the typed key is never part + /// of that message. + /// + /// `restore_height` behaves exactly as in [`Wire::import_seed`]: blank omits + /// the field, and a non-numeric value is the same local refusal. + /// + /// The Kotlin binding is `Wire.importViewOnly(password, address, viewKey, + /// restoreHeight)`. + pub async fn import_view_only( + &self, + password: String, + address: String, + view_key: String, + restore_height: String, + ) -> WResult<()> { + let height = restore_height_arg(&restore_height)?; + self.node()? + .wallet_import_view_only(&password, &address, &view_key, height) .await .map_err(WireError::new) .map(|_| ()) @@ -1247,6 +1375,11 @@ pub struct TransferRow { pub txid: String, pub amount: String, pub address: String, + /// Which bucket the row came from: `in`, `out`, or `pending` — a pending + /// item that names its own `type` carries that instead. A client renders the + /// sign of the amount from this, and must not treat it as a dedupe key: a + /// txid may appear in two buckets and both rows are real. + pub direction: String, } /// One row of the saved-wallet catalogue, for the wallet picker. @@ -1602,6 +1735,23 @@ pub fn verify_tip(pubkey_hex: String, tip: Tip) -> bool { } } +/// A typed restore height as the core's `Option`. +/// +/// Blank (or whitespace) is `None` — "scan from the beginning", and the request +/// carries no `restore_height` field at all. A typed `0` is `Some(0)` and *is* +/// sent: the user asked for it. Anything that is not a block number is refused +/// here, before any dial; the message says what a block number is and never +/// echoes the typed text back. +fn restore_height_arg(text: &str) -> WResult> { + let text = text.trim(); + if text.is_empty() { + return Ok(None); + } + text.parse::() + .map(Some) + .map_err(|_| WireError::new("restore height must be a block number")) +} + /// Convert a user-facing XMR amount string to a piconero string. /// /// Accepts `"0.5"`, `"1"`, `"0.001"` etc. Returns the piconero string on @@ -1877,6 +2027,60 @@ mod tests { assert_eq!(block_on(stopped_wire().wallet_balance()), "off"); } + #[test] + fn wallet_unlocked_balance_on_stopped_handle_returns_off() { + assert_eq!(block_on(stopped_wire().wallet_unlocked_balance()), "off"); + } + + #[test] + fn wallet_send_on_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallet_send( + "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge" + .to_string(), + "1".to_string(), + )) + .expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + #[test] + fn wallet_view_only_on_stopped_handle_is_stopped_error() { + let err = block_on(stopped_wire().wallet_view_only()).expect_err("must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + } + + /// A blank height is "no field", a typed number is that number, and a typo + /// is a local refusal — never a silent `0`. + #[test] + fn restore_height_arg_blanks_omits_and_refuses_a_typo() { + assert_eq!(restore_height_arg("").unwrap(), None); + assert_eq!(restore_height_arg(" ").unwrap(), None); + assert_eq!(restore_height_arg("3210000").unwrap(), Some(3_210_000)); + assert_eq!(restore_height_arg(" 42 ").unwrap(), Some(42)); + assert_eq!( + restore_height_arg("0").unwrap(), + Some(0), + "a typed 0 is what the user asked for, not an omission" + ); + let err = restore_height_arg("block 42").expect_err("not a block number"); + assert_eq!(err.to_string(), "restore height must be a block number"); + } + + /// The import refuses a bad height before it ever reaches the node, so the + /// message is the SDK's own and no dial is implied. + #[test] + fn import_seed_refuses_a_non_numeric_height_locally() { + let err = block_on(stopped_wire().import_seed( + "pw".to_string(), + "lumber tacit lemon ivory risk".to_string(), + String::new(), + "not-a-height".to_string(), + )) + .expect_err("must fail"); + assert_eq!(err.to_string(), "restore height must be a block number"); + assert!(matches!(err, WireError::Failed { .. }), "got {err:?}"); + } + #[test] fn wallet_receive_address_on_stopped_handle_is_stopped_error() { let err = block_on(stopped_wire().wallet_receive_address()).expect_err("must fail"); diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 8075e96..e75d564 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -299,6 +299,30 @@ now one of the places a spending secret can be read from. Treat any screen that shows a seed or a private key the way you treat the wallet file itself. +## A view key entered at import is a secret, and a view-only file cannot spend + +Importing an address to watch means typing that address's **private view key** +into OnionWire. It is a secret of a different kind from a seed: it cannot spend, +but anyone holding it *and* the address sees every incoming transfer — amounts, +timing, and which outputs belong to the wallet. + +- It is entered on a hidden entry (the TUI asks for it twice; a mismatch is + `view keys do not match` and never dials), travels in the `generate_from_keys` + request body, and is kept nowhere else: never sealed, never in the wallet + catalogue, never logged, never on an argv. The core wipes its own copy when the + call returns and the screen wipes the typed buffer on every exit, `Esc` + included. +- The request carries **no `spendkey` field**, so the file the RPC writes is not + a spend authority: `transfer` on it is the RPC's own `-29` watch-only refusal. +- The file **passphrase** is still sealed, exactly as for a created or + seed-imported wallet — that is what reopens the file on the next start, and an + attacker with the store passphrase and a spend-capable file can move the + balance. The seal protects the file passphrase; it is not a protection for the + view key, and a view-only file is not a spend authority either way. +- What this does **not** stop: a view key pasted from a clipboard, a shoulder + surfer, a screen recorder, or a compromised wallet host. Import a view key only + on a machine you would trust with your incoming-transfer history. + ## 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/TUI.md b/docs/TUI.md index a5ea38d..a5227f1 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -24,7 +24,7 @@ ASCII chrome. | `ConfirmKeys` / `Passphrase` | `/backup`, `/restore` | Type `BACKUP`/`RESTORE`, then passphrase | | `Wallet` | `F6` | Receive QR, balance, transfers, child, chain source | | `WalletSelect` | `F6` `w` | Saved wallets, pick one or create one | -| `WalletSetup` | `F6` `c` / `i`, or `/wallet create` / `import` | Spend warning, seed, optional seed-offset passphrase, import | +| `WalletSetup` | `F6` `c` / `i` / `n` / `v`, or `/wallet create` / `import` | Spend warning, seed, optional seed-offset passphrase, restore height, import, send, view-only import | | `WalletsSettings` | `F9` or `/settings` | Discovery menu (does not replace F-keys) | | `PeerPayments` | F9 then `p` | Peer-scoped `/pay` / `/tip` history | | `Quit` | `Ctrl-Q` | Type `CLEAR` or `QUIT` | @@ -110,7 +110,7 @@ Pane-specific (`pane_footer_hints`): Footer: ``` -c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help +c create i import v view-only y copy n send r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help ``` | Key | Effect | @@ -118,7 +118,10 @@ c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc | `r` or Enter | Toggle receive-address QR | | `w` | Saved wallets (`WalletSelect`) | | `c` | Create wallet (`SPEND` then seed once, type `SEEN`) | -| `i` | Import 25-word seed | +| `i` | Import 25-word seed (then an optional seed-offset passphrase and restore height) | +| `v` | Import an address to **watch** (address, view key twice, restore height, file passphrase) | +| `y` | Copy the receive address (OSC 52). Never a seed, never a view key | +| `n` | Send to a pasted address (address, amount, then `SEND`) — a local `transfer`, not a `/tip` | | `s` | Start app-owned wallet child | | `x` | Stop child (idempotent) | | `p` | Probe child (RPC answering? chain at tip?) | @@ -132,8 +135,20 @@ The chain line for an in-process source always carries Cuprate needs `--features cuprate-daemon`; without it, start fails with that feature name. +`F6` shows one balance line — `balance 0.9 XMR · unlocked 0.45 XMR`, the total +and the part a spend can use out of a single `get_balance` (`wallet off` when no +wallet RPC is configured, `balance —` when the RPC did not answer with a total). + Create/import require the wallet RPC started with `--wallet-dir`. Filename: -`onionwire`. Seed is never collected on the composer. +`onionwire`. Seed is never collected on the composer, and never copied. + +The import's two optional steps have their own footers: the offset step says +`blank Enter skips Esc cancel ? help`, the restore-height step says +`blank Enter scans from 0 Esc cancel ? help` (blank means "scan from 0"; a +height after your first receive hides the older funds and this version has no +rescan). The send confirmation says `type SEND Esc cancel ? help`, and `Esc` +there spends nothing. The view-only import has no seed, so it has no `SEEN` +step. ## Saved wallets (`F6` then `w`) diff --git a/docs/WALLET.md b/docs/WALLET.md index 457e4d5..606fa75 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -289,10 +289,57 @@ wallet actually holds (the derived seed), so a later seed backup restores this wallet **without** the offset; the original words plus the offset are the other backup, and the app keeps neither. +The import asks for an optional **restore height** after the offset step. Blank +`Enter` scans from block 0, which is what a plain import wants. A height *after* +your first receive **hides the older funds** — the wallet never scans below it — +and this version has **no rescan** to undo that, so set a height at or before the +first incoming transfer or leave it blank. The request carries a `restore_height` +field only when you typed one (a typed `0` is sent as `0`); a height that is not +a block number is refused locally with `restore height must be a block number`. + +`F6` then `v` imports an address to **watch** instead: `generate_from_keys` with +the address and its private **view key**, and no `spendkey` in the request at +all. The file it writes can see incoming transfers and cannot spend — `transfer` +on it is the RPC's own `-29`, surfaced as the view-only message. The view key is +a secret (anyone holding it and the address sees the incoming transfers): it is +typed into a hidden entry (twice — a mismatch is `view keys do not match` with no +dial), goes to the RPC, and is kept nowhere else — not sealed, not in the +catalogue, not logged, never on an argv. What *is* sealed is the wallet-file +passphrase, exactly as for a created or seed-imported wallet, so the file reopens +on the next start. There is no seed on this path, so there is no `SEEN` step. + RPC must be started with `--wallet-dir` (not only `--wallet-file`). A created wallet gets its own file name (`onionwire-1`, `onionwire-2`, …): `wallet_filename` is UNIQUE in the catalogue, so a second create must not reuse the first file. +## Balance: total and unlocked + +`get_balance` answers with two numbers and OnionWire exposes both: the **total** +(`wallet_balance`, everything the wallet has scanned, including amounts still +locked behind confirmations or immature) and the **unlocked** part +(`wallet_unlocked_balance`), the funds a spend can use right now. The wallet +screen shows them on one line, from one request: + + balance 0.9 XMR · unlocked 0.45 XMR + +`Node::wallet_balance_line` builds it, and the two sentinels are its own: +`wallet off` when no wallet RPC is configured, `balance —` when the RPC did not +answer with a total. (`wallet_balance` and `wallet_unlocked_balance` keep the +bare `off` / `err` words the WALLETS & SETTINGS menu tones and the SDK read.) A +wallet that shows a balance but refuses to spend is usually this distinction: the +incoming transfer is still confirming. Both numbers come out of one `get_balance` +request, never two. + +## Send to a pasted address (`F6` then `n`) + +A **local** `transfer` on the wallet this install has configured: an address, an +amount, then `SEND` to confirm. There is no friend, no `tip` frame, no chat line +and no payment row — the wallet's own outgoing transfer list is the record, so +`n` works with no peer online and leaves nothing in a conversation. A view-only +or unsynced wallet is refused with the same strings `/tip` uses. The receive +address has its own key, `y`, which copies it through the terminal's clipboard +(OSC 52); the seed path stays clipboard-free. + ## Recommended topology (view-only) ``` @@ -340,6 +387,7 @@ Restore from a height at or before the first incoming transaction. | Receipt verification (`get_transfers`) | works, if daemon is synced | works, if daemon is synced | | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | +| send to a pasted address (`F6` `n`, `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 | diff --git a/src/node.rs b/src/node.rs index 6b128c9..b336d1a 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1097,6 +1097,22 @@ impl Node { } } + /// The spendable part of the balance, as a human-readable XMR string, with + /// the same sentinels as [`Self::wallet_balance`]: `off` when the wallet is + /// not configured, `err` when the RPC did not answer with a number, else + /// the unlocked piconero formatted the same way. One `get_balance` call + /// carries both numbers, so this does not dial twice. + pub async fn wallet_unlocked_balance(&self) -> String { + let w = self.wallet_snapshot(); + if !w.configured() { + return "off".into(); + } + match w.balances().await { + Ok((_, Some(unlocked))) => crate::pay::atomic_to_xmr_str(&unlocked.to_string()), + _ => "err".into(), + } + } + pub fn wipe_messages(&self) -> Result<(), String> { self.store .lock() @@ -1319,7 +1335,7 @@ impl Node { } let profile_addr = self.self_profile()?.xmr_addr; if profile_addr.is_empty() { - return Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into()); + return Err(NO_RECEIVE_ADDRESS_MSG.into()); } pay::check_address(&profile_addr).map_err(|e| e.to_string())?; Ok(profile_addr) @@ -1342,30 +1358,73 @@ impl Node { pay::check_address(&profile_addr).map_err(|e| e.to_string())?; return Ok(profile_addr); } - Err("no receive address — set profile xmr or ONIONWIRE_WALLET_RPC".into()) + Err(NO_RECEIVE_ADDRESS_MSG.into()) } - /// Formatted balance for the wallet screen, or "off" when the wallet is not - /// configured. Calls `pay::atomic_to_xmr_str` so the UI never parses - /// piconero itself. + /// The wallet screen's balance line. One `get_balance` answer carries both + /// numbers, so it shows the total and the part a spend can use: + /// `balance {total} XMR · unlocked {unlocked} XMR`. The `balance 0 XMR` + /// prefix stays when the total is 0, with the unlocked segment beside it; an + /// unlocked half the RPC did not report leaves the total-only line. The two + /// sentinels are not `Node::wallet_balance`'s: `wallet off` when no wallet + /// RPC is configured, and `balance —` when the RPC did not answer with a + /// total. `pay::atomic_to_xmr_str` formats the numbers, so the UI never + /// parses piconero itself. pub async fn wallet_balance_line(&self) -> String { let w = self.wallet_snapshot(); - if w.configured() { - match w.get_balance().await { - Ok(b) if !b.is_empty() => { - let xmr = pay::atomic_to_xmr_str(&b); - if xmr == "0" { - "balance 0 XMR".to_string() - } else { - format!("balance {xmr} XMR") - } - } - Ok(_) => "balance —".to_string(), - Err(_) => "balance —".to_string(), - } - } else { - "wallet off".to_string() + if !w.configured() { + return "wallet off".to_string(); } + let (total, unlocked) = match w.balances().await { + Ok(pair) => pair, + Err(_) => return "balance —".to_string(), + }; + if total.is_empty() { + return "balance —".to_string(); + } + let xmr = pay::atomic_to_xmr_str(&total); + let head = if xmr == "0" { + "balance 0 XMR".to_string() + } else { + format!("balance {xmr} XMR") + }; + match unlocked { + Some(unlocked) => { + let unlocked = pay::atomic_to_xmr_str(&unlocked.to_string()); + format!("{head} · unlocked {unlocked} XMR") + } + None => head, + } + } + + /// Send XMR to a pasted address. A **local** `transfer` on the wallet this + /// node has configured: no friend, no `tip` frame, no chat line and no + /// payment row — the outgoing transfer list is the record of it. + /// + /// The address and the amount are checked first, so an empty field, a bad + /// address or an unparsable amount is a local refusal with no dial. Returns + /// the tx hash. `Wallet::transfer` owns the gates that matter and surfaces + /// them as they are: an explicit no-spend wallet, an unsynced chain, and the + /// RPC's own view-only refusal. + pub async fn wallet_send(&self, address: &str, amount_xmr: &str) -> Result { + let address = address.trim(); + let amount_xmr = amount_xmr.trim(); + if address.is_empty() { + return Err("address required".into()); + } + if amount_xmr.is_empty() { + return Err("amount required".into()); + } + pay::check_address(address).map_err(|e| e.to_string())?; + let atomic = pay::xmr_to_atomic(amount_xmr).map_err(|e| e.to_string())?; + let amount: u64 = atomic + .parse() + .map_err(|_| "amount too large for wallet RPC".to_string())?; + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.transfer(address, amount).await.map_err(|e| e.to_string()) } /// Recent in/out transfers for the wallet screen, newest first, capped to a @@ -1480,18 +1539,23 @@ impl Node { /// never logged, never on the argv, and a wrong one is not an error — the /// RPC succeeds and the wallet is a different one. Only `password` is sealed /// here, into the same record the next start opens the file with. + /// `restore_height` is the import's optional block number, forwarded beside + /// the offset: `None` omits the field and the wallet scans from the + /// beginning. A height after the first receive hides the older funds, and + /// this version has no rescan. pub async fn wallet_restore( &self, password: &str, seed: &str, seed_offset: Option<&str>, + restore_height: Option, ) -> 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, seed_offset) + w.restore_wallet(&filename, password, seed, seed_offset, restore_height) .await .map_err(|e| e.to_string())?; let record = self @@ -1509,6 +1573,70 @@ impl Node { Ok(record) } + /// Import an address to **watch**: a wallet file with a view key and no + /// spend key. Same shape as [`Self::wallet_restore`] — its own file name, a + /// catalogue row, the child pointed at it, the *file* passphrase sealed and + /// marked open — because a watch-only file is still a wallet the app has to + /// reopen on the next start. + /// + /// The view key is a secret: it goes to the RPC and nowhere else. It is not + /// sealed, not written to the catalogue (which grows no column for it) and + /// never logged; the node's own copy is a `Zeroizing` that is wiped when the + /// call returns. `generate_from_keys` is sent without a spend key, so the + /// resulting file is not a spend authority — `transfer` refuses it with the + /// RPC's own view-only answer. + /// + /// `restore_height` is the same optional block number as + /// [`Self::wallet_restore`]'s: `None` omits it. + pub async fn wallet_import_view_only( + &self, + password: &str, + address: &str, + view_key: &str, + restore_height: Option, + ) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + let filename = self.next_wallet_filename()?; + let imported = { + let key = Zeroizing::new(view_key.to_string()); + w.import_view_only(&filename, password, address, key.as_str(), restore_height) + .await + }; + imported.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}") + })?; + // The file passphrase and nothing else: `seal_wallet_passphrase` opens + // this file on the next start, exactly as it does for a created wallet. + self.seal_wallet_passphrase(password).map_err(|e| { + format!("wallet {filename} imported but its passphrase was not stored: {e}") + })?; + self.mark_child_wallet_open(); + Ok(record) + } + + /// Is the wallet file the child has open **watch-only**? + /// + /// `query_key spend_key` is the signal monero exposes for a wallet with no + /// spend key: `true` for the `-29` refusal, `false` when a spend key comes + /// back — that key is discarded, never returned and never logged. An + /// unconfigured wallet is refused locally with the same message the other + /// wallet calls use, *not* `true`: claiming a view-only wallet exists when + /// none does would be a lie. + pub async fn wallet_view_only(&self) -> Result { + let w = self.wallet_snapshot(); + if !w.configured() { + return Err(wallet::NOT_CONFIGURED_MSG.into()); + } + w.view_only_wallet().await.map_err(|e| e.to_string()) + } + /// 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> { @@ -2426,6 +2554,12 @@ fn session_err(e: session::Error) -> String { } } +/// The one wording for "this install has no address to receive to". The wallet +/// screen's copy action and the receive-address accessors all say it, so a user +/// never has to work out whether two strings are the same problem. +pub const NO_RECEIVE_ADDRESS_MSG: &str = + "no receive address — set profile xmr or ONIONWIRE_WALLET_RPC"; + pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { let mut stack = vec![dir.to_path_buf()]; while let Some(p) = stack.pop() { @@ -3628,6 +3762,33 @@ pub(crate) mod tests { assert!(gone, "shutdown must not leave the wallet child behind"); } + /// [`mock_wallet_setup`] with its request log kept: for tests that assert on + /// *which* RPC method a path called, not only on the answer. `reply` runs + /// once per authenticated request, so the log holds one line per RPC call. + async fn recording_wallet_setup(log: Arc>>) -> 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(move |req: &str| { + log.lock().expect("log").push(req.to_string()); + if req.contains("get_info") { + r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"# + .to_string() + } else if req.contains("get_balance") { + r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"900000000000","unlocked_balance":"450000000000"}}"# + .to_string() + } else 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":{"tx_hash":"abc123"}}"#.to_string() + } + }); + tokio::spawn(serve_mock_rpc(listener, reply)); + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("wallet url") + } + /// 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 @@ -3712,7 +3873,7 @@ pub(crate) mod tests { ); let imported = node - .wallet_restore("hunter2", "lumber tacit lemon ivory risk", None) + .wallet_restore("hunter2", "lumber tacit lemon ivory risk", None, None) .await .expect("restore wallet"); @@ -3724,6 +3885,190 @@ pub(crate) mod tests { ); } + /// A pasted-address send is a plain wallet `transfer`: the outgoing transfer + /// list is its record, so there is no friend, no `tip` frame and no chat + /// line to show for it. + #[tokio::test] + async fn wallet_send_transfers_without_a_tip_frame_or_a_chat_line() { + let dir = tempfile::tempdir().unwrap(); + let log = Arc::new(std::sync::Mutex::new(Vec::new())); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(DialOk), + recording_wallet_setup(Arc::clone(&log)).await, + ); + let peer = Keys::generate(); + { + let store = node.store.lock().unwrap(); + befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion"); + } + + let txid = node.wallet_send(&xmr_addr(), "0.5").await.expect("send"); + + assert_eq!(txid, "abc123"); + let seen = log.lock().expect("log").clone(); + assert!( + seen.iter().any(|r| r.contains(r#""method":"transfer""#)), + "a pasted-address send is the wallet's transfer: {seen:?}" + ); + assert!( + !seen.iter().any(|r| r.contains(r#""method":"tip""#)), + "there is no tip frame on this path: {seen:?}" + ); + assert!( + chat_lines(&node, &peer).is_empty(), + "a local send appends no chat line" + ); + } + + /// Every local refusal of `wallet_send` happens before a dial: the address + /// and the amount are argued with here, not by the RPC. + #[tokio::test] + async fn wallet_send_refuses_locally_without_dialing() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + + let err = node.wallet_send("", "1").await.unwrap_err(); + assert_eq!(err, "address required"); + let err = node.wallet_send(" ", "1").await.unwrap_err(); + assert_eq!(err, "address required"); + let err = node.wallet_send(&xmr_addr(), "").await.unwrap_err(); + assert_eq!(err, "amount required"); + let err = node.wallet_send("not-an-address", "1").await.unwrap_err(); + assert_eq!(err, "invalid Monero address"); + let err = node + .wallet_send(&xmr_addr(), "not-a-number") + .await + .unwrap_err(); + assert_eq!(err, "invalid XMR amount"); + let err = node.wallet_send(&xmr_addr(), "0").await.unwrap_err(); + assert_eq!(err, "amount must be > 0"); + // Nothing above may reach the RPC; an unconfigured wallet is the last + // gate, and it is still local. + let err = node.wallet_send(&xmr_addr(), "1").await.unwrap_err(); + assert_eq!(err, wallet::NOT_CONFIGURED_MSG); + } + + /// `wallet_view_only` on an unconfigured wallet is the refusal the other + /// wallet calls give — *not* `true`, which would claim a wallet exists. + #[tokio::test] + async fn wallet_view_only_on_an_unconfigured_wallet_is_a_refusal() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + assert_eq!( + node.wallet_view_only().await.unwrap_err(), + wallet::NOT_CONFIGURED_MSG + ); + } + + /// The balance line carries both numbers out of one `get_balance` answer, + /// and the unlocked sentinels match the total's. + #[tokio::test] + async fn the_balance_line_shows_the_unlocked_part_from_one_answer() { + let dir = tempfile::tempdir().unwrap(); + let log = Arc::new(std::sync::Mutex::new(Vec::new())); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + recording_wallet_setup(Arc::clone(&log)).await, + ); + + assert_eq!( + node.wallet_balance_line().await, + "balance 0.9 XMR \u{b7} unlocked 0.45 XMR" + ); + assert_eq!(node.wallet_unlocked_balance().await, "0.45"); + let calls = log + .lock() + .expect("log") + .iter() + .filter(|r| r.contains(r#""method":"get_balance""#)) + .count(); + assert_eq!( + calls, 2, + "one dial per call and never two for one line: {calls}" + ); + } + + /// A stopped wallet still reads as `off`, not as an error or a zero. + #[tokio::test] + async fn unlocked_balance_on_an_unconfigured_wallet_is_off() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + assert_eq!(node.wallet_unlocked_balance().await, "off"); + assert_eq!(node.wallet_balance_line().await, "wallet off"); + } + + /// The view-only import is a creation path: a catalogue row, the child + /// pointed at the new file, and the *file* passphrase sealed. The view key + /// itself is nowhere. + #[tokio::test] + async fn importing_a_view_only_wallet_records_it_and_seals_only_the_passphrase() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("bob"); + let log = Arc::new(std::sync::Mutex::new(Vec::new())); + let node = offline_node_with_wallet( + &home, + Arc::new(NoDial), + recording_wallet_setup(Arc::clone(&log)).await, + ); + let key = "0123456789abcdef".repeat(4); + + let record = node + .wallet_import_view_only("hunter2", &xmr_addr(), &key, Some(3210000)) + .await + .expect("view-only import"); + + assert_eq!(record.wallet_filename, "onionwire-1"); + assert_eq!( + node.wallet_child_config().wallet_filename, + record.wallet_filename, + "the child has to open the file that was just written" + ); + assert_eq!(sealed_passphrase(&node), "hunter2"); + let seen = log.lock().expect("log").clone(); + let req = seen + .iter() + .find(|r| r.contains(r#""method":"generate_from_keys""#)) + .expect("generate_from_keys"); + assert!( + req.contains(&key), + "the view key is what makes it watch: {req}" + ); + assert!(!req.contains("spendkey"), "no spend key may be sent: {req}"); + // The catalogue keeps no copy of the view key, and neither does the + // sealed child record. + assert_eq!( + node.list_wallets().expect("list wallets").len(), + 1, + "a view-only import is remembered like any other wallet" + ); + } + + /// A view key of the wrong shape never reaches the RPC. The wallet here is + /// "configured" against a dead loopback port, so a refusal that came from a + /// dial could not read like this one. + #[tokio::test] + async fn importing_a_view_only_wallet_refuses_a_bad_key_locally() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node_with_wallet( + &dir.path().join("bob"), + Arc::new(NoDial), + Wallet::from_url("http://ow:secret@127.0.0.1:1").expect("wallet url"), + ); + for bad in ["", "not-hex", &"a".repeat(63)] { + let err = node + .wallet_import_view_only("pw", &xmr_addr(), bad, None) + .await + .unwrap_err(); + assert_eq!(err, "view key must be 64 hex characters"); + } + assert!( + node.list_wallets().expect("list wallets").is_empty(), + "a refused import must not create a catalogue row" + ); + } + /// 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. diff --git a/src/tui.rs b/src/tui.rs index 34a8843..1b25def 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1273,6 +1273,8 @@ enum Screen { }, Wallet { receive_addr: String, + /// `Node::wallet_balance_line`: the total and the unlocked part, or + /// `wallet off` / `balance —` when there is nothing to read. balance: String, transfers: Vec, qr_modal: Option, @@ -1320,8 +1322,19 @@ enum WalletSetup { ImportPass { seed: Zeroizing, offset: Zeroizing, + /// The height the previous step collected: `None` omits the field. + height: Option, entry: PassphraseEntry, }, + /// The optional restore height, asked after the offset and before the file + /// passphrase: a block number to start scanning from, or blank for "from the + /// beginning". A height *after* the first receive hides the older funds and + /// this version has no rescan, so the screen says so. + ImportHeight { + seed: Zeroizing, + offset: Zeroizing, + buf: String, + }, /// A restore that used an offset: the app keeps neither the offset nor a /// copy of the pasted words, so this one notice is all the user gets. The /// wallet file already exists; `Esc` does not leave this screen and only @@ -1337,6 +1350,63 @@ enum WalletSetup { filename: String, entry: PassphraseEntry, }, + /// `n` on the wallet screen: send XMR to a pasted address. Three steps — + /// address, amount, then a repeat of both behind the word `SEND` — so a + /// spend is never one keystroke away. Both values are shown; neither is a + /// secret, and `Esc` at any step spends nothing. + SendAddress { + buf: String, + }, + SendAmount { + address: String, + buf: String, + }, + SendConfirm { + address: String, + amount: String, + typed: String, + }, + /// `v` on the wallet screen: import an address to watch. Address (shown), + /// view key (hidden, typed twice — it is the secret that sees incoming + /// transfers), the same optional restore height as the seed path, then the + /// wallet-file passphrase. There is no seed here, so there is no `SEEN` + /// wall to clear. + ViewOnlyAddress { + buf: String, + }, + ViewOnlyKey { + address: String, + entry: PassphraseEntry, + }, + ViewOnlyHeight { + address: String, + view_key: Zeroizing, + buf: String, + }, + ViewOnlyPass { + address: String, + view_key: Zeroizing, + height: Option, + entry: PassphraseEntry, + }, +} + +/// The one wording for a restore height that is not a block number. The SDK +/// uses it too; a height is not a secret, but the error is about the shape of +/// the answer, so it echoes nothing the user typed. +const RESTORE_HEIGHT_MSG: &str = "restore height must be a block number"; + +/// The restore-height step's typed digits as the core's `Option`: blank is +/// "scan from 0" and omits the field entirely, a typed `0` is sent as `0`, and +/// digits that cannot be a block number are refused here — before any dial. +fn parse_restore_height(text: &str) -> Result, String> { + let text = text.trim(); + if text.is_empty() { + return Ok(None); + } + text.parse::() + .map(Some) + .map_err(|_| RESTORE_HEIGHT_MSG.to_string()) } /// A function key the TUI answers before the per-screen `match`; the screen's @@ -1741,6 +1811,21 @@ impl App { buf: Zeroizing::new(String::new()), }); } + // `n`: send to a pasted address. A wallet RPC `transfer` and + // nothing else — no friend, no frame, no chat line. + KeyCode::Char('n') => { + self.screen = + Screen::WalletSetup(WalletSetup::SendAddress { buf: String::new() }); + } + // `y`: the receive address onto the clipboard. The seed path + // stays clipboard-free. + KeyCode::Char('y') => self.copy_wallet_address(), + // `v`: import an address to watch. Not the seed importer: there + // is no seed on this path at all. + KeyCode::Char('v') => { + self.screen = + Screen::WalletSetup(WalletSetup::ViewOnlyAddress { buf: String::new() }); + } _ => {} }, Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, @@ -2021,7 +2106,9 @@ impl App { fn open_wallet(&mut self) -> Result<(), String> { let addr = self.rt.block_on(self.node.wallet_receive_address())?; - let balance = self.rt.block_on(self.node.wallet_balance()); + // One line, both numbers: `wallet_balance_line` reads the total and the + // unlocked part out of a single `get_balance` answer. + let balance = self.rt.block_on(self.node.wallet_balance_line()); let transfers = self.rt.block_on(self.node.wallet_recent_transfers(8)).unwrap_or_default(); self.screen = Screen::Wallet { receive_addr: addr, @@ -2228,6 +2315,31 @@ impl App { }); } + /// `y` on the wallet screen: the receive address through the terminal's own + /// clipboard (OSC 52 — no crate, and it survives SSH). The address never + /// touches a file. This is the only clipboard action the wallet has: a seed + /// is the money and is never copied, and neither is a view key. + fn copy_wallet_address(&mut self) { + let addr = match &self.screen { + Screen::Wallet { receive_addr, .. } => receive_addr.clone(), + _ => return, + }; + if addr.is_empty() { + self.status_note = Some(crate::node::NO_RECEIVE_ADDRESS_MSG.into()); + return; + } + let seq = osc52_copy_sequence(&addr); + let wrote = { + let mut out = io::stdout(); + out.write_all(seq.as_bytes()).is_ok() && out.flush().is_ok() + }; + self.status_note = Some(if wrote { + "copied address".into() + } else { + "could not write the clipboard sequence".into() + }); + } + /// `C` on the invite screen: the same OSC 52 handoff as the receive address, /// so a terminal that blocks the write still leaves the mouse selection as /// the way out. The payload never touches a file. @@ -2420,15 +2532,30 @@ impl App { seed, offset, entry, + .. } => { entry.close(); seed.zeroize(); offset.zeroize(); } + WalletSetup::ImportHeight { seed, offset, .. } => { + seed.zeroize(); + offset.zeroize(); + } WalletSetup::ImportOffset { seed, entry } => { entry.close(); seed.zeroize(); } + // The view key is a secret and every exit has to wipe it: it + // lives in the entry while it is being typed and in the step's + // own buffer afterwards. + WalletSetup::ViewOnlyKey { entry, .. } => entry.close(), + WalletSetup::ViewOnlyHeight { view_key, .. } + | WalletSetup::ViewOnlyPass { view_key, .. } => view_key.zeroize(), + WalletSetup::ViewOnlyAddress { .. } + | WalletSetup::SendAddress { .. } + | WalletSetup::SendAmount { .. } + | WalletSetup::SendConfirm { .. } => {} WalletSetup::CreateSeed { seed, .. } => seed.zeroize(), WalletSetup::ImportSeed { buf } => buf.zeroize(), WalletSetup::CreateWarn { .. } => {} @@ -2521,6 +2648,34 @@ impl App { } _ => {} }, + WalletSetup::ImportHeight { seed, offset, buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + // Digits only: a height is a block number and nothing else. + KeyCode::Char(c) if c.is_ascii_digit() => buf.push(c), + KeyCode::Enter => { + let height = match parse_restore_height(buf) { + Ok(h) => h, + Err(e) => { + seed.zeroize(); + offset.zeroize(); + self.alert = Some(e); + self.screen = Screen::Main; + return Ok(()); + } + }; + let seed = std::mem::replace(seed, Zeroizing::new(String::new())); + let offset = std::mem::replace(offset, Zeroizing::new(String::new())); + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + offset, + height, + entry: PassphraseEntry::new(), + }); + } + _ => {} + }, WalletSetup::ImportOffset { seed, entry } => match key.code { KeyCode::Backspace => entry.backspace(), KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { @@ -2539,19 +2694,19 @@ impl App { } entry.close(); let seed = std::mem::replace(seed, Zeroizing::new(String::new())); - self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + self.screen = Screen::WalletSetup(WalletSetup::ImportHeight { seed, offset, - entry: PassphraseEntry::new(), + buf: String::new(), }); } else if offset.trim().is_empty() { // Blank Enter skips the offset: no confirm, no RPC field. entry.close(); let seed = std::mem::replace(seed, Zeroizing::new(String::new())); - self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + self.screen = Screen::WalletSetup(WalletSetup::ImportHeight { seed, offset: Zeroizing::new(String::new()), - entry: PassphraseEntry::new(), + buf: String::new(), }); } else { self.screen = Screen::WalletSetup(WalletSetup::ImportOffset { @@ -2566,6 +2721,7 @@ impl App { entry, seed, offset, + height, } => match key.code { KeyCode::Backspace => entry.backspace(), KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { @@ -2594,6 +2750,7 @@ impl App { pass.as_str(), seed.as_str(), offset_arg, + *height, )); seed.zeroize(); offset.zeroize(); @@ -2622,6 +2779,7 @@ impl App { self.screen = Screen::WalletSetup(WalletSetup::ImportPass { seed, offset, + height: *height, entry: PassphraseEntry::with_first(pass.as_str()), }); } @@ -2640,6 +2798,211 @@ impl App { } _ => {} }, + WalletSetup::SendAddress { buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => buf.push(c), + KeyCode::Enter => { + if buf.trim().is_empty() { + self.alert = Some("address required".into()); + self.screen = Screen::Main; + return Ok(()); + } + let address = std::mem::take(buf); + self.screen = Screen::WalletSetup(WalletSetup::SendAmount { + address, + buf: String::new(), + }); + } + _ => {} + }, + WalletSetup::SendAmount { address, buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => buf.push(c), + KeyCode::Enter => { + if buf.trim().is_empty() { + self.alert = Some("amount required".into()); + self.screen = Screen::Main; + return Ok(()); + } + let amount = buf.trim().to_string(); + self.screen = Screen::WalletSetup(WalletSetup::SendConfirm { + address: address.clone(), + amount, + typed: String::new(), + }); + } + _ => {} + }, + WalletSetup::SendConfirm { + address, + amount, + typed, + } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SEND") { + // Neither value is a secret, and the address is checked + // inside `wallet_send` before any dial. + let (address, amount) = (address.clone(), amount.clone()); + let result = self.rt.block_on(self.node.wallet_send(&address, &amount)); + match result { + Ok(txid) => { + // A txid is not a secret: it is the receipt. + self.status_note = Some(format!("sent {txid}")); + return self.open_wallet(); + } + Err(e) => { + // A view-only or unsynced refusal is the core's + // own string, surfaced as it is. + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::ViewOnlyAddress { buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => buf.push(c), + KeyCode::Enter => { + if buf.trim().is_empty() { + self.alert = Some("address required".into()); + self.screen = Screen::Main; + return Ok(()); + } + let address = std::mem::take(buf); + self.screen = Screen::WalletSetup(WalletSetup::ViewOnlyKey { + address, + entry: PassphraseEntry::new(), + }); + } + _ => {} + }, + WalletSetup::ViewOnlyKey { address, entry } => match key.code { + KeyCode::Backspace => entry.backspace(), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + entry.push(c); + } + KeyCode::Enter => { + let first = entry.take_first(); + let key = entry.take_buf(); + if let Some(first) = first { + if first.as_str() != key.as_str() { + // No dial, and the key itself is not named. + entry.close(); + self.alert = Some("view keys do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + entry.close(); + self.screen = Screen::WalletSetup(WalletSetup::ViewOnlyHeight { + address: address.clone(), + view_key: key, + buf: String::new(), + }); + } else { + self.screen = Screen::WalletSetup(WalletSetup::ViewOnlyKey { + address: address.clone(), + entry: PassphraseEntry::with_first(key.as_str()), + }); + } + } + _ => {} + }, + WalletSetup::ViewOnlyHeight { + address, + view_key, + buf, + } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if c.is_ascii_digit() => buf.push(c), + KeyCode::Enter => { + let height = match parse_restore_height(buf) { + Ok(h) => h, + Err(e) => { + view_key.zeroize(); + self.alert = Some(e); + self.screen = Screen::Main; + return Ok(()); + } + }; + let address = address.clone(); + let view_key = std::mem::replace(view_key, Zeroizing::new(String::new())); + self.screen = Screen::WalletSetup(WalletSetup::ViewOnlyPass { + address, + view_key, + height, + entry: PassphraseEntry::new(), + }); + } + _ => {} + }, + WalletSetup::ViewOnlyPass { + address, + view_key, + height, + entry, + } => match key.code { + KeyCode::Backspace => entry.backspace(), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + entry.push(c); + } + KeyCode::Enter => { + let first = entry.take_first(); + let pass = entry.take_buf(); + if let Some(first) = first { + if first.as_str() != pass.as_str() { + entry.close(); + view_key.zeroize(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + let (address, height) = (address.clone(), *height); + let result = self.rt.block_on(self.node.wallet_import_view_only( + pass.as_str(), + &address, + view_key.as_str(), + height, + )); + // The node wiped its own copy; this one is the typed + // buffer and goes too. + view_key.zeroize(); + match result { + Ok(_) => { + self.status_note = Some("wallet imported".into()); + return self.open_wallet(); + } + Err(e) => { + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } else { + let address = address.clone(); + let view_key = std::mem::replace(view_key, Zeroizing::new(String::new())); + self.screen = Screen::WalletSetup(WalletSetup::ViewOnlyPass { + address, + view_key, + height: *height, + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, WalletSetup::UnlockPass { filename, entry } => match key.code { KeyCode::Backspace => entry.backspace(), KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { @@ -3514,12 +3877,24 @@ match screen { }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", Screen::Wallet { .. } => { - "c create i import r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" + "c create i import v view-only y copy n send r qr w wallets s/x child 1 pruned 2 full 3 testnet Esc back ? help" } Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", - Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::UnlockPass { .. }) => { - "Enter submit Esc cancel ? help" - } + Screen::WalletSetup( + WalletSetup::CreatePass { .. } + | WalletSetup::UnlockPass { .. } + | WalletSetup::SendAddress { .. } + | WalletSetup::SendAmount { .. } + | WalletSetup::ViewOnlyAddress { .. } + | WalletSetup::ViewOnlyKey { .. } + | WalletSetup::ViewOnlyPass { .. }, + ) => "Enter submit Esc cancel ? help", + // The height step has its own copy: it is not the offset's `blank Enter + // skips`, and saying "skip" would hide that blank means "scan from 0". + Screen::WalletSetup( + WalletSetup::ImportHeight { .. } | WalletSetup::ViewOnlyHeight { .. }, + ) => "blank Enter scans from 0 Esc cancel ? help", + Screen::WalletSetup(WalletSetup::SendConfirm { .. }) => "type SEND Esc cancel ? help", Screen::WalletSetup(WalletSetup::ImportOffset { entry, .. }) => { if entry.first().is_some() { "Enter submit Esc cancel ? help" @@ -5349,8 +5724,7 @@ fn draw_wallet( "address {addr_line} -balance - {balance} +{balance} " ); let mut lines: Vec = body.lines().map(str::to_string).collect(); @@ -5370,14 +5744,17 @@ balance lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::(), xmr)); } } - let help = "s start child x stop child p probe c create i import r qr Esc back"; + let help = "s start child x stop child p probe c create i import v view-only y copy n send r qr Esc back"; lines.push("".into()); + // The flexible region, not the fixed-height slot below it: a bordered block + // in a two-row area draws its borders and clips every line of the body, + // which would hide the address and the balance line. f.render_widget( Paragraph::new(lines.join("\n")) .style(style_text()) .wrap(Wrap { trim: false }) .block(apply_chrome_borders(Block::default()).border_style(style_border())), - cols[2], + cols[1], ); f.render_widget(Paragraph::new(help).style(style_dim()), cols[3]); @@ -5439,6 +5816,64 @@ fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) { 25 words that open this wallet without the offset. type SEEN\n{typed}" ), ), + WalletSetup::ImportHeight { buf, .. } => ( + "restore height", + format!( + "optional block height. blank Enter scans from 0. a height after your first \n\ + receive hides older funds.\n\n{buf}\n\nEnter continues Esc cancels" + ), + ), + WalletSetup::SendAddress { buf } => ( + "send xmr", + format!("paste the address to send to.\n\n{buf}\n\nEnter continues Esc cancels"), + ), + WalletSetup::SendAmount { address, buf } => ( + "send amount", + format!("amount in XMR\n\nto\n {address}\n\n{buf}\n\nEnter continues Esc cancels"), + ), + WalletSetup::SendConfirm { + address, + amount, + typed, + } => ( + "confirm send", + format!( + "address\n {address}\n\namount\n {amount} XMR\n\nthis spends from your wallet \ + and cannot be undone.\nType SEND to send Esc cancels\n{typed}" + ), + ), + WalletSetup::ViewOnlyAddress { buf } => ( + "import view-only wallet", + format!( + "paste the address to watch. this wallet can see incoming transfers and cannot \ + spend.\n\n{buf}\n\nEnter continues Esc cancels" + ), + ), + WalletSetup::ViewOnlyKey { entry, .. } => ( + "view key", + if entry.first().is_some() { + "re-type the view key\n\nEnter submits Esc cancels".into() + } else { + "the 64-character private view key for that address. it is a secret: anyone \ + holding it can see the incoming transfers.\n\nEnter continues Esc cancels" + .into() + }, + ), + WalletSetup::ViewOnlyHeight { buf, .. } => ( + "restore height", + format!( + "optional block height. blank Enter scans from 0. a height after your first \n\ + receive hides older funds.\n\n{buf}\n\nEnter continues Esc cancels" + ), + ), + WalletSetup::ViewOnlyPass { entry, .. } => ( + "wallet passphrase", + if entry.first().is_some() { + "re-type passphrase\n\nEnter submits Esc cancels".into() + } else { + "passphrase for the imported wallet file\n\nEnter continues Esc cancels".into() + }, + ), WalletSetup::UnlockPass { filename, .. } => ( "wallet passphrase", format!( @@ -5860,7 +6295,8 @@ mod wallet_offset_tests { } /// A blank (or whitespace-only) offset is skipped without a confirm, and the - /// passphrase step carries an empty offset — which means "no field" later. + /// restore-height step carries an empty offset — which means "no field" + /// later. #[test] fn a_blank_offset_enter_skips_the_confirm() { for blank in ["", " "] { @@ -5871,14 +6307,13 @@ mod wallet_offset_tests { app.handle_key(key(KeyCode::Enter)).expect("enter"); - let Screen::WalletSetup(WalletSetup::ImportPass { offset, entry, .. }) = &app.screen - else { - panic!("a blank offset must go straight to the file passphrase"); + let Screen::WalletSetup(WalletSetup::ImportHeight { offset, .. }) = &app.screen else { + panic!("a blank offset must go to the restore-height step, unconfirmed"); }; assert!(offset.is_empty(), "blank {blank:?} became {offset:?}"); - assert!( - entry.first().is_none(), - "a blank offset must not be confirmed" + assert_eq!( + footer_hints(&app.screen), + "blank Enter scans from 0 Esc cancel ? help" ); } } @@ -6011,3 +6446,382 @@ mod wallet_offset_tests { ); } } +/// The rest of the wallet batch in the TUI: the restore-height step, a +/// pasted-address send behind the word `SEND`, the receive-address copy, and the +/// view-only import. +/// +/// The harness node's wallet is `Wallet::disabled()`, so every step that would +/// dial ends in the core's own not-configured refusal. That is the assertion +/// here: the flow reaches the node with the values that were typed, and nothing +/// spends or imports before it does. The request bytes are `tests/wallet.rs` and +/// the node-side effects `src/node.rs`. +#[cfg(test)] +mod wallet_next_batch_tests { + use super::*; + use crate::node::test_node_with_wallets; + + fn app(home: &std::path::Path) -> (App, tokio::runtime::Runtime) { + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + let _guard = rt.enter(); + let node = test_node_with_wallets(home, &[]); + let app = App::new(node, rt.handle().clone()).expect("app"); + (app, rt) + } + + fn key(code: KeyCode) -> KeyEvent { + KeyEvent::new(code, KeyModifiers::NONE) + } + + fn type_str(app: &mut App, s: &str) { + for c in s.chars() { + app.handle_key(key(KeyCode::Char(c))).expect("typed key"); + } + } + + fn addr() -> String { + "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge" + .to_string() + } + + fn view_key() -> String { + "0123456789abcdef".repeat(4) + } + + fn wallet_screen(receive_addr: &str) -> Screen { + Screen::Wallet { + receive_addr: receive_addr.to_string(), + balance: "off".to_string(), + transfers: Vec::new(), + qr_modal: None, + } + } + + fn height_screen() -> Screen { + Screen::WalletSetup(WalletSetup::ImportHeight { + seed: Zeroizing::new("lumber tacit lemon ivory risk".to_string()), + offset: Zeroizing::new("harbor-offset".to_string()), + buf: String::new(), + }) + } + + /// The screen draws the line the helper built: the word `balance` appears + /// once, because the label is part of the line and not a second header. + #[test] + fn the_wallet_screen_draws_the_balance_line() { + let line = "balance 0.9 XMR · unlocked 0.45 XMR"; + let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)) + .expect("test terminal"); + term.draw(|f| draw_wallet(f, &addr(), line, &[], None, "")) + .expect("draw"); + let frame = term.backend().buffer().clone(); + let mut drawn = String::new(); + for y in 0..frame.area.height { + for x in 0..frame.area.width { + drawn.push_str(frame[(x, y)].symbol()); + } + } + assert!(drawn.contains(line), "the line is on the screen: {drawn}"); + assert_eq!( + drawn.matches("balance").count(), + 1, + "one balance label only: {drawn}" + ); + assert!(drawn.contains("address"), "the body is drawn: {drawn}"); + assert!( + drawn.contains("recent transfers"), + "the body region is tall enough for the whole screen, not two rows: {drawn}" + ); + } + + /// The wallet footer teaches the three new keys and keeps every old one. + #[test] + fn the_wallet_footer_names_the_new_keys_and_keeps_the_old_ones() { + let footer = footer_hints(&wallet_screen("")); + for token in [ + "c create", + "i import", + "v view-only", + "y copy", + "n send", + "r qr", + "w wallets", + "s/x child", + "1 pruned", + "2 full", + "3 testnet", + ] { + assert!( + footer.contains(token), + "the footer lost `{token}`: {footer}" + ); + } + // The screen's own help line teaches the same three. + let help = "s start child x stop child p probe c create i import v view-only y copy n send r qr Esc back"; + assert!(help.contains("v view-only") && help.contains("y copy") && help.contains("n send")); + } + + /// Blank Enter is "scan from 0" and carries `None`; digits are kept and a + /// typed `0` is a real height. The step must not confuse itself with the + /// offset's `blank Enter skips`. + #[test] + fn the_restore_height_step_skips_on_blank_and_keeps_the_digits() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + + app.screen = height_screen(); + assert_eq!( + footer_hints(&app.screen), + "blank Enter scans from 0 Esc cancel ? help" + ); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + let Screen::WalletSetup(WalletSetup::ImportPass { height, offset, .. }) = &app.screen + else { + panic!("blank Enter must go on to the file passphrase"); + }; + assert_eq!(*height, None, "blank means the field is omitted"); + assert_eq!(offset.as_str(), "harbor-offset", "the offset survives"); + + // Digits only: the junk typed between the numbers is dropped. + app.screen = height_screen(); + type_str(&mut app, "abc321x0000z"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + let Screen::WalletSetup(WalletSetup::ImportPass { height, .. }) = &app.screen else { + panic!("a typed height must go on to the file passphrase"); + }; + assert_eq!(*height, Some(3_210_000)); + + app.screen = height_screen(); + type_str(&mut app, "0"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + let Screen::WalletSetup(WalletSetup::ImportPass { height, .. }) = &app.screen else { + panic!("a typed 0 is a height the user asked for"); + }; + assert_eq!(*height, Some(0)); + } + + /// Esc leaves the height step and takes the seed and the offset with it. + #[test] + fn esc_leaves_the_height_step_and_the_import() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + app.screen = height_screen(); + + app.handle_key(key(KeyCode::Esc)).expect("esc"); + + assert!(matches!(app.screen, Screen::Main)); + assert!( + app.status_note.is_none(), + "Esc on the height step must not import anything" + ); + } + + /// `y` copies the receive address through OSC 52 — and when there is no + /// address it says the one thing the rest of the app says. + #[test] + fn y_copies_the_receive_address_or_names_the_missing_one() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + + app.screen = wallet_screen(&addr()); + app.handle_key(key(KeyCode::Char('y'))).expect("y"); + + assert_eq!(app.status_note.as_deref(), Some("copied address")); + assert!( + !app.status_note.as_deref().unwrap().contains(&addr()), + "the address itself never goes in the status note" + ); + + app.status_note = None; + app.screen = wallet_screen(""); + app.handle_key(key(KeyCode::Char('y'))).expect("y"); + assert_eq!( + app.status_note.as_deref(), + Some(crate::node::NO_RECEIVE_ADDRESS_MSG) + ); + } + + /// `n` walks address → amount → confirm, and the confirm spends only once + /// the whole word `SEND` is typed. The wallet is off here, so what comes + /// back is the core's own refusal — reached with the address and amount that + /// were typed, which is what this pins. + #[test] + fn n_sends_only_after_the_whole_word_and_esc_spends_nothing() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + app.screen = wallet_screen(&addr()); + + app.handle_key(key(KeyCode::Char('n'))).expect("n"); + assert!( + matches!( + app.screen, + Screen::WalletSetup(WalletSetup::SendAddress { .. }) + ), + "n opens the address step, not the composer" + ); + assert_eq!( + footer_hints(&app.screen), + "Enter submit Esc cancel ? help" + ); + + // A blank address is refused before the amount step. + app.handle_key(key(KeyCode::Enter)).expect("enter"); + assert_eq!(app.alert.as_deref(), Some("address required")); + assert!(matches!(app.screen, Screen::Main)); + + app.alert = None; + app.screen = wallet_screen(&addr()); + app.handle_key(key(KeyCode::Char('n'))).expect("n"); + type_str(&mut app, &addr()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + let Screen::WalletSetup(WalletSetup::SendAmount { address, .. }) = &app.screen else { + panic!("the address must go on to the amount step"); + }; + assert_eq!(address.as_str(), addr()); + type_str(&mut app, "0.5"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + + let Screen::WalletSetup(WalletSetup::SendConfirm { + address, amount, .. + }) = &app.screen + else { + panic!("the amount must go on to the confirmation"); + }; + assert_eq!(address.as_str(), addr()); + assert_eq!(amount.as_str(), "0.5"); + assert_eq!(footer_hints(&app.screen), "type SEND Esc cancel ? help"); + + // A prefix spends nothing. + type_str(&mut app, "sen"); + assert!( + matches!( + app.screen, + Screen::WalletSetup(WalletSetup::SendConfirm { .. }) + ), + "only the whole word leaves the confirmation" + ); + assert!(app.alert.is_none()); + + // Esc leaves it, and nothing has been sent. + app.handle_key(key(KeyCode::Esc)).expect("esc"); + assert!(matches!(app.screen, Screen::Main)); + assert!(app.status_note.is_none()); + + // The whole word (case-insensitively) reaches the wallet, which is off + // here: the refusal is the core's own. + app.screen = wallet_screen(&addr()); + app.handle_key(key(KeyCode::Char('n'))).expect("n"); + type_str(&mut app, &addr()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + type_str(&mut app, "0.5"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + type_str(&mut app, "send"); + assert_eq!( + app.alert.as_deref(), + Some(wallet::NOT_CONFIGURED_MSG), + "the refusal has to be the core's, not a softer one" + ); + assert!(matches!(app.screen, Screen::Main)); + assert!( + app.status_note.is_none() || app.status_note.as_deref() != Some("sent"), + "nothing was sent" + ); + } + + /// `v` walks address → view key → height → file passphrase, and everything + /// on that path stays off the wallet until the last step. + #[test] + fn v_imports_a_view_only_wallet_in_four_steps() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + app.screen = wallet_screen(""); + + app.handle_key(key(KeyCode::Char('v'))).expect("v"); + assert!( + matches!( + app.screen, + Screen::WalletSetup(WalletSetup::ViewOnlyAddress { .. }) + ), + "v opens the view-only address step, not the seed importer" + ); + assert_eq!( + footer_hints(&app.screen), + "Enter submit Esc cancel ? help" + ); + + type_str(&mut app, &addr()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + assert_eq!( + footer_hints(&app.screen), + "Enter submit Esc cancel ? help" + ); + let Screen::WalletSetup(WalletSetup::ViewOnlyKey { entry, .. }) = &app.screen else { + panic!("the address must go on to the view key"); + }; + assert!( + entry.first().is_none(), + "the first view-key prompt is not a confirmation" + ); + + // The view key is asked twice, and a mismatch never reaches the node. + type_str(&mut app, &view_key()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + type_str(&mut app, "different-key"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + assert_eq!(app.alert.as_deref(), Some("view keys do not match")); + assert!(matches!(app.screen, Screen::Main)); + assert!(app.status_note.is_none()); + + // Matching keys go on to the same height step the seed path uses. + app.alert = None; + app.screen = wallet_screen(""); + app.handle_key(key(KeyCode::Char('v'))).expect("v"); + type_str(&mut app, &addr()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + type_str(&mut app, &view_key()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + type_str(&mut app, &view_key()); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + let Screen::WalletSetup(WalletSetup::ViewOnlyHeight { address, .. }) = &app.screen else { + panic!("the confirmed view key must go on to the height"); + }; + assert_eq!(address.as_str(), addr()); + assert_eq!( + footer_hints(&app.screen), + "blank Enter scans from 0 Esc cancel ? help" + ); + + // Blank height, then the file passphrase twice. The wallet is off, so + // the import ends in the core's own refusal — the flow is what is being + // pinned, and `wallet imported` is covered by the node's own tests. + app.handle_key(key(KeyCode::Enter)).expect("enter"); + let Screen::WalletSetup(WalletSetup::ViewOnlyPass { height, entry, .. }) = &app.screen + else { + panic!("the height must go on to the file passphrase"); + }; + assert_eq!(*height, None); + assert!(entry.first().is_none()); + type_str(&mut app, "hunter2"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + type_str(&mut app, "hunter2"); + app.handle_key(key(KeyCode::Enter)).expect("enter"); + assert_eq!(app.alert.as_deref(), Some(wallet::NOT_CONFIGURED_MSG)); + assert!(matches!(app.screen, Screen::Main)); + } + + /// A view key typed once and then abandoned takes the secret with it. + #[test] + fn esc_on_the_view_key_step_leaves_it() { + let dir = tempfile::tempdir().unwrap(); + let (mut app, _rt) = app(&dir.path().join("home")); + app.screen = Screen::WalletSetup(WalletSetup::ViewOnlyKey { + address: addr(), + entry: PassphraseEntry::new(), + }); + type_str(&mut app, &view_key()); + + app.handle_key(key(KeyCode::Esc)).expect("esc"); + + assert!(matches!(app.screen, Screen::Main)); + assert!(app.status_note.is_none()); + } +} diff --git a/src/wallet.rs b/src/wallet.rs index a31990a..079d92c 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -478,6 +478,11 @@ pub struct TransferRow { pub txid: String, pub amount: String, pub address: String, + /// Which `get_transfers` bucket the row came from: `in`, `out`, or + /// `pending` — a pending item that names its own `type` carries that + /// instead. Not a dedupe key: a txid may appear in two buckets and both + /// rows are real. + pub direction: String, } /// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC). @@ -739,29 +744,54 @@ impl Wallet { /// ("Cannot retrieve spend key"); a spend-capable wallet returns the key, /// which this discards. /// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`. - async fn view_only(&self) -> bool { - matches!( - self.rpc("query_key", serde_json::json!({"key_type": "spend_key"})) - .await, - Err(e) if e.to_string() == VIEW_ONLY_MSG - ) + pub async fn view_only_wallet(&self) -> Result { + match self + .rpc("query_key", serde_json::json!({"key_type": "spend_key"})) + .await + { + // A spend key came back. It is discarded here: never returned, + // never logged, never persisted. + Ok(_) => Ok(false), + Err(e) if e.to_string() == VIEW_ONLY_MSG => Ok(true), + Err(e) => Err(e), + } } + /// [`Self::view_only_wallet`] as the bool the transfer path wants: a probe + /// that cannot answer is not a view-only wallet, so the transfer's own + /// error stands. + async fn view_only(&self) -> bool { + self.view_only_wallet().await.unwrap_or(false) + } + + /// Incoming, outgoing and pending transfers, each row labelled with the + /// bucket it came from — the wallet screen shows a send as well as a + /// receive. A txid that appears in two buckets stays twice: the buckets are + /// not the same event. pub async fn get_transfers(&self) -> Result> { let v = self .chain_rpc( "get_transfers", - serde_json::json!({"in": true, "pending": true}), + serde_json::json!({"in": true, "out": true, "pending": true}), ) .await?; let mut out = Vec::new(); - for key in ["in", "pending"] { + for key in ["in", "out", "pending"] { if let Some(arr) = v.get(key).and_then(|x| x.as_array()) { for item in arr { + // A pending item says what it will become; that is a better + // label than the bucket's own name. Anything else is the + // bucket name. + let direction = if key == "pending" { + json_str(item, "type").unwrap_or_else(|_| key.to_string()) + } else { + key.to_string() + }; out.push(TransferRow { txid: json_str(item, "txid").unwrap_or_default(), amount: json_amount(item), address: json_str(item, "address").unwrap_or_default(), + direction, }); } } @@ -790,6 +820,22 @@ impl Wallet { .map_err(|_| Error("wallet RPC returned a non-numeric unlocked_balance".into())) } + /// One `get_balance` round trip carrying both numbers the wallet screen + /// prints: the total piconero, and the unlocked piconero when the RPC + /// reported it as a number. `None` for the unlocked half means the field + /// was absent or not a number, and the line then shows the total alone. + /// Two numbers, one dial — the screen must not ask twice. + pub async fn balances(&self) -> Result<(String, Option)> { + let v = self + .rpc("get_balance", serde_json::json!({"account_index": 0})) + .await?; + let total = json_str(&v, "balance")?; + let unlocked = json_str(&v, "unlocked_balance") + .ok() + .and_then(|s| s.trim().parse::().ok()); + Ok((total, unlocked)) + } + /// The real readiness predicate: the daemon has reached the chain tip and /// the wallet has scanned up to it. `synchronized` must be explicitly true — /// a missing field is not-ready, never a silent pass. @@ -969,12 +1015,18 @@ impl Wallet { /// `None`, empty or whitespace-only leaves `seed_offset` out of the request /// entirely (never `"seed_offset":""`). Otherwise the ends are trimmed and /// the value is sent beside the seed; interior spaces are kept. + /// `restore_height` is `restore_deterministic_wallet`'s optional block + /// number, forwarded beside the offset: `None` leaves the field out + /// entirely (never `0`), which is what a plain import wants — the wallet + /// scans from the beginning. A height *after* the first receive hides the + /// older funds, and this version has no rescan to undo that. pub async fn restore_wallet( &self, filename: &str, password: &str, seed: &str, seed_offset: Option<&str>, + restore_height: Option, ) -> Result<()> { let filename = filename.trim(); if filename.is_empty() { @@ -996,10 +1048,61 @@ impl Wallet { if let Some(offset) = seed_offset.map(str::trim).filter(|s| !s.is_empty()) { params["seed_offset"] = serde_json::Value::String(offset.to_string()); } + if let Some(height) = restore_height { + // A JSON number, not a string: the RPC types this field as an + // integer. + params["restore_height"] = serde_json::Value::Number(height.into()); + } self.rpc("restore_deterministic_wallet", params).await?; Ok(()) } + /// Import an address to **watch**, not to spend: `generate_from_keys` with + /// the address and its private view key, and no `spendkey` in the request + /// at all. + /// + /// The view key is a secret — anyone holding it and the address can see the + /// incoming transfers — so it is trimmed, shape-checked (`64` hex + /// characters) and never echoed in an error. It is not sealed, not stored, + /// not logged and never on the argv; only the file `password` is sealed by + /// the caller. A watch-only file is not a spend authority: `transfer` + /// refuses it with the RPC's own `-29`. + /// + /// `restore_height` is the same optional block number as + /// [`Self::restore_wallet`]'s: `None` omits it. + pub async fn import_view_only( + &self, + filename: &str, + password: &str, + address: &str, + view_key: &str, + restore_height: Option, + ) -> Result<()> { + let filename = filename.trim(); + if filename.is_empty() { + return Err(Error("wallet filename required".into())); + } + if password.is_empty() { + return Err(Error("wallet passphrase required".into())); + } + let view_key = view_key.trim(); + if view_key.len() != 64 || !view_key.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(Error("view key must be 64 hex characters".into())); + } + crate::pay::check_address(address).map_err(|e| Error(e.to_string()))?; + let mut params = serde_json::json!({ + "filename": filename, + "password": password, + "address": address, + "viewkey": view_key, + }); + if let Some(height) = restore_height { + params["restore_height"] = serde_json::Value::Number(height.into()); + } + self.rpc("generate_from_keys", params).await?; + Ok(()) + } + /// Loopback management call: the wallet child is on the same box, so it gets /// the short budget. async fn rpc(&self, method: &str, params: serde_json::Value) -> Result { diff --git a/tests/wallet.rs b/tests/wallet.rs index 1337439..c14b985 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -23,9 +23,15 @@ fn row(txid: &str, amount: &str, address: &str) -> TransferRow { txid: txid.into(), amount: amount.into(), address: address.into(), + direction: "in".into(), } } +/// A 64-hex view key, the only shape `generate_from_keys` takes. +fn view_key() -> String { + "0123456789abcdef".repeat(4) +} + fn xmr_addr() -> String { // Same documented mainnet standard as tests/pay.rs — F4 checksums this. "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge" @@ -640,6 +646,7 @@ async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() { "hunter2", "lumber tacit lemon ivory risk", None, + None, ) .await .expect("restore_wallet"); @@ -680,6 +687,7 @@ async fn restore_wallet_sends_a_non_empty_seed_offset() { "hunter2", "lumber tacit lemon ivory risk", Some("harbor-offset"), + None, ) .await .expect("restore_wallet"); @@ -721,6 +729,7 @@ async fn restore_wallet_omits_a_whitespace_only_seed_offset() { "hunter2", "lumber tacit lemon ivory risk", Some(" "), + None, ) .await .expect("blank offset restore"); @@ -755,6 +764,7 @@ async fn restore_wallet_trims_the_ends_of_a_seed_offset() { "hunter2", "lumber tacit lemon ivory risk", Some(" harbor offset "), + None, ) .await .expect("trimmed offset restore"); @@ -782,6 +792,7 @@ async fn a_failed_restore_does_not_echo_the_seed_offset() { "hunter2", "lumber tacit lemon ivory risk", Some("harbor-offset"), + None, ) .await .unwrap_err() @@ -803,7 +814,7 @@ fn restore_wallet_empty_seed_is_local_error() { .enable_all() .build() .unwrap() - .block_on(w.restore_wallet("onionwire", "pw", " ", None)) + .block_on(w.restore_wallet("onionwire", "pw", " ", None, None)) .unwrap_err() .to_string(); assert!(err.to_ascii_lowercase().contains("seed"), "got {err}"); @@ -2040,3 +2051,269 @@ fn wallet_name_taken_fails_closed_when_the_dir_cannot_be_read() { std::fs::write(&file, b"x").unwrap(); assert!(wallet_child::wallet_name_taken(&file, "onionwire-1").is_err()); } + +// --------------------------------------------------------------------------- +// The next wallet batch, still at the request-byte level: there is no live +// `monero-wallet-rpc` on this host. Unlocked balance, restore height, outgoing +// rows and the view-only import all have to be pinned by the bytes they send. +// --------------------------------------------------------------------------- + +/// `restore_height` is `restore_deterministic_wallet`'s own optional block +/// number: a JSON number when the user typed one, and no field at all when they +/// did not (never `0`, which would hide older funds). +#[tokio::test] +async fn restore_wallet_sends_a_restore_height_as_a_number() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "restore_deterministic_wallet" => rpc_result(r#"{"address":"4","seed":""}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + recording_wallet(port) + .restore_wallet( + "onionwire-1", + "hunter2", + "lumber tacit lemon ivory risk", + None, + Some(3210000), + ) + .await + .expect("restore_wallet"); + let seen = log.lock().expect("log").clone(); + let restore = seen + .iter() + .find(|r| r.contains(r#""method":"restore_deterministic_wallet""#)) + .expect("restore RPC"); + assert!( + restore.contains(r#""restore_height":3210000"#), + "the height must be a JSON number: {restore}" + ); + assert!( + !restore.contains(r#""restore_height":"3210000""#), + "a quoted height is a string, not a block number: {restore}" + ); +} + +/// The default import sends no height at all. The seed offset still travels, so +/// the omission is the height's and not a lost field. +#[tokio::test] +async fn restore_wallet_omits_an_absent_restore_height() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "restore_deterministic_wallet" => rpc_result(r#"{"address":"4","seed":""}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + recording_wallet(port) + .restore_wallet( + "onionwire-1", + "hunter2", + "lumber tacit lemon ivory risk", + Some("harbor-offset"), + None, + ) + .await + .expect("restore_wallet"); + let seen = log.lock().expect("log").clone(); + let restore = seen + .iter() + .find(|r| r.contains(r#""method":"restore_deterministic_wallet""#)) + .expect("restore RPC"); + assert!( + !restore.contains("restore_height"), + "an absent height must not become a field: {restore}" + ); + assert!( + restore.contains(r#""seed_offset":"harbor-offset""#), + "the offset is beside the height and must still be there: {restore}" + ); +} + +/// The wallet screen shows outgoing transfers too, so the request has to ask for +/// them and each row has to say which bucket it came from. +#[tokio::test] +async fn get_transfers_asks_for_outgoing_rows_and_labels_every_bucket() { + let addr = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + let body = format!( + r#"{{"in":[{{"txid":"aa","amount":1,"address":"{addr}"}}],"out":[{{"txid":"bb","amount":2,"address":"{addr}"}}],"pending":[{{"txid":"cc","amount":3,"address":"{addr}","type":"out"}}]}}"# + ); + let reply: Arc String + Send + Sync> = { + let body = body.clone(); + Arc::new(move |method| match method { + "get_transfers" => rpc_result(&body), + _ => rpc_error(-1, "unexpected method"), + }) + }; + tokio::spawn(serve_recording(listener, Arc::clone(&log), reply)); + + let rows = recording_wallet(port) + .get_transfers() + .await + .expect("get_transfers"); + let seen = log.lock().expect("log").clone(); + let req = seen + .iter() + .find(|r| r.contains(r#""method":"get_transfers""#)) + .expect("get_transfers RPC"); + assert!( + req.contains(r#""out":true"#) || req.contains(r#""out": true"#), + "the request must ask for outgoing transfers: {req}" + ); + let direction = |txid: &str| { + rows.iter() + .find(|r| r.txid == txid) + .map(|r| r.direction.clone()) + }; + assert_eq!(direction("aa").as_deref(), Some("in")); + assert_eq!(direction("bb").as_deref(), Some("out")); + assert_eq!( + direction("cc").as_deref(), + Some("out"), + "a pending item's own `type` is its direction" + ); +} + +/// Both numbers the wallet screen prints come out of one `get_balance` answer. +#[tokio::test] +async fn balances_reads_the_total_and_the_unlocked_from_one_call() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "get_balance" => { + rpc_result(r#"{"balance":"900000000000","unlocked_balance":"450000000000"}"#) + } + _ => rpc_error(-1, "unexpected method"), + }), + )); + let (total, unlocked) = recording_wallet(port).balances().await.expect("balances"); + assert_eq!(total, "900000000000"); + assert_eq!(unlocked, Some(450_000_000_000)); + // The recorder sees the unauthenticated request that earns the 401 too, so + // count the answered ones: exactly one `get_balance` may reach the RPC. + let calls = log + .lock() + .expect("log") + .iter() + .filter(|r| r.contains(r#""method":"get_balance""#) && r.contains("Authorization:")) + .count(); + assert_eq!(calls, 1, "one response carries both fields"); +} + +/// The view-only import is `generate_from_keys` with a view key and **no** spend +/// key: a body that carried `spendkey` would import a spend authority. +#[tokio::test] +async fn import_view_only_sends_the_view_key_and_no_spend_key() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "generate_from_keys" => rpc_result(r#"{}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + let key = view_key(); + recording_wallet(port) + .import_view_only("onionwire-1", "hunter2", &xmr_addr(), &key, Some(100)) + .await + .expect("import_view_only"); + let seen = log.lock().expect("log").clone(); + let req = seen + .iter() + .find(|r| r.contains(r#""method":"generate_from_keys""#)) + .expect("generate_from_keys RPC"); + assert!(req.contains(&key), "view key missing: {req}"); + assert!(req.contains(&xmr_addr()), "address missing: {req}"); + assert!( + !req.contains("spendkey"), + "a view-only import must omit the spend key entirely: {req}" + ); + assert!( + req.contains(r#""restore_height":100"#), + "the height is optional but not dropped when given: {req}" + ); +} + +/// A view key has exactly one shape and it is not a secret to be echoed back: +/// refusing locally also means no socket is opened. +#[tokio::test] +async fn import_view_only_refuses_a_bad_view_key_without_dialing() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|_: &str| rpc_error(-1, "unexpected method")), + )); + let w = recording_wallet(port); + for bad in ["", " ", "not-hex", &"a".repeat(63), &"a".repeat(65)] { + let err = w + .import_view_only("onionwire-1", "hunter2", &xmr_addr(), bad, None) + .await + .unwrap_err() + .to_string(); + assert_eq!( + err, + "view key must be 64 hex characters", + "a {}-char view key must be refused locally", + bad.len() + ); + assert!( + !err.contains(bad) || bad.trim().is_empty(), + "the typed key must never be echoed: {err}" + ); + } + assert!( + log.lock().expect("log").is_empty(), + "a local refusal must not dial" + ); +} + +/// The address is checked before the dial, like every other wallet path. +#[tokio::test] +async fn import_view_only_refuses_a_bad_address_without_dialing() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|_: &str| rpc_error(-1, "unexpected method")), + )); + let err = recording_wallet(port) + .import_view_only( + "onionwire-1", + "hunter2", + "not-an-address", + &view_key(), + None, + ) + .await + .unwrap_err() + .to_string(); + assert_eq!(err, "invalid Monero address"); + assert!( + log.lock().expect("log").is_empty(), + "a local refusal must not dial" + ); +}