From cf0a517cd20169c1bce952a420500880893680a2 Mon Sep 17 00:00:00 2001 From: Lance Walters Date: Sun, 13 Sep 2026 23:25:25 -0400 Subject: [PATCH] wallet: create/import in-app (no key paste on create) + opt-in spend / wallet create generates a wallet on the RPC and shows the 25-word seed once for backup; /wallet import is the only path that takes an existing seed, and it is collected on a dedicated screen so it never reaches the composer line or chat history. Threat model now states the real policy: payments are opt-in, default is no spend key, spend is a local authority at create/restore, and the chain source is the user's choice (spawned local monerod or a daemon address they supply). WALLET.md and README follow. Tests: canned-RPC create/restore, slash parse, help overlay. --- README.md | 11 +- .../siriusdevops/onionwire/WireViewModel.kt | 12 + .../siriusdevops/onionwire/ui/WalletScreen.kt | 167 +++++++++++- crates/onionwire-sdk/src/lib.rs | 24 ++ docs/THREAT_MODEL.md | 87 +++++-- docs/WALLET.md | 58 ++++- src/node.rs | 23 ++ src/tui.rs | 241 +++++++++++++++++- src/wallet.rs | 65 +++++ tests/pay.rs | 3 + tests/tui_chrome.rs | 3 + tests/wallet.rs | 106 ++++++++ 12 files changed, 755 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index e74628f..7c86293 100644 --- a/README.md +++ b/README.md @@ -185,9 +185,14 @@ resume, no images in the TUI. `/profile` edits your friend-visible display name, bio, and optional Monero address (64 / 512 byte limits, no images). Enter saves and one-shot sends a signed `prf` frame to the selected friend. `F5` or `/who` shows their last signed profile. There is no directory: unknown pubkeys are ignored. -## Monero sidecar +## Monero (opt-in) -OnionWire is not a wallet. Optional JSON-RPC to a user-hosted `monero-wallet-rpc`. The wallet **must** use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest challenge) and refuses URLs with no credentials. +Chat does not need a wallet. Spend is opt-in at wallet create/restore; default +is no spend key on the device. Optional JSON-RPC to `monero-wallet-rpc` on +loopback (you run it, or the app spawns it). Chain source is your choice: a +spawned local `monerod`, or a daemon address you supply. The wallet **must** +use `--rpc-login`; OnionWire refuses an open RPC (HTTP 200 without a Digest +challenge) and refuses URLs with no credentials. ```bash # monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret @@ -206,6 +211,8 @@ locally before any RPC dial — `/pay` and receipt verification keep working. Details: [docs/WALLET.md](docs/WALLET.md). - `/pay [memo]` — invoice (we want to receive). Uses a wallet subaddress if RPC is up, else the profile `xmr_addr`. +- `/wallet create` — generate a new spend-capable wallet (no key paste; seed shown once). Needs `--wallet-dir` on the RPC. +- `/wallet import` — restore from an existing 25-word seed (the only path that takes a secret). - `/tip [memo]` — pay the selected friend’s profile address, then send a signed `rcp` (disabled under `ONIONWIRE_WALLET_NO_SPEND`). Incoming receipts stay unverified until RPC `get_transfers` matches. ## Backup / restore diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index b25a0c0..dfe66e0 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -428,4 +428,16 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun sendTip(pubkeyHex: String, amountXmr: String, memo: String = ""): Result = runCatching { requireWire().sendTip(pubkeyHex, amountXmr, memo) } + + suspend fun createWallet(password: String): Result = + runCatching { requireWire().createWallet(password) } + + suspend fun importWallet(password: String, seed: String): Result = + runCatching { requireWire().importWallet(password, seed) } + + fun spendAuthorityWarning(): String = runCatching { + requireWire().spendAuthorityWarning() + }.getOrElse { + "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed." + } } diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt index a4d3776..0e5d8e8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletScreen.kt @@ -47,11 +47,13 @@ import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.qrcode.QRCodeWriter import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import uniffi.onionwire_sdk.FriendInfo import uniffi.onionwire_sdk.TransferRow private enum class PayKind { Invoice, Tip } +private enum class SetupKind { Create, Import } @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -67,6 +69,8 @@ fun WalletScreen( var transfers by remember { mutableStateOf>(emptyList()) } var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } + var setup by remember { mutableStateOf(null) } + var backupSeed by remember { mutableStateOf(null) } suspend fun reload() { runCatching { balance = vm.walletBalance() } @@ -183,6 +187,7 @@ fun WalletScreen( } val kind = composer + val setupKind = setup if (kind != null) { PayComposer( kind = kind, @@ -205,24 +210,72 @@ fun WalletScreen( } }, ) + } else if (setupKind != null) { + WalletSetupCard( + kind = setupKind, + warning = vm.spendAuthorityWarning(), + onCancel = { setup = null }, + onCreated = { seed -> + setup = null + backupSeed = seed + scope.launch { reload() } + }, + onImported = { + setup = null + scope.launch { reload() } + }, + onError = { error = it }, + create = { pw -> vm.createWallet(pw) }, + importWallet = { pw, seed -> vm.importWallet(pw, seed) }, + scope = scope, + ) } else { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - OutlinedButton( - onClick = { composer = PayKind.Invoice }, - modifier = Modifier.weight(1f), - ) { Text("Invoice") } - OutlinedButton( - onClick = { composer = PayKind.Tip }, - modifier = Modifier.weight(1f), - ) { Text("Tip") } + Column(Modifier.fillMaxWidth().padding(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = { composer = PayKind.Invoice }, + modifier = Modifier.weight(1f), + ) { Text("Invoice") } + OutlinedButton( + onClick = { composer = PayKind.Tip }, + modifier = Modifier.weight(1f), + ) { Text("Tip") } + } + Spacer(Modifier.height(8.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + onClick = { setup = SetupKind.Create }, + modifier = Modifier.weight(1f), + ) { Text("Create") } + OutlinedButton( + onClick = { setup = SetupKind.Import }, + modifier = Modifier.weight(1f), + ) { Text("Import") } + } } } + backupSeed?.let { seed -> + Text( + "write this seed down once. anyone with it can spend.", + style = MaterialTheme.typography.labelSmall, + modifier = Modifier.padding(horizontal = 12.dp), + ) + Text( + seed, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + TextButton(onClick = { backupSeed = null }) { Text("I wrote it down") } + } + error?.let { Text( it, @@ -347,6 +400,92 @@ private fun PayComposer( } } +@Composable +private fun WalletSetupCard( + kind: SetupKind, + warning: String, + onCancel: () -> Unit, + onCreated: (String) -> Unit, + onImported: () -> Unit, + onError: (String) -> Unit, + create: suspend (String) -> Result, + importWallet: suspend (String, String) -> Result, + scope: CoroutineScope, +) { + var accepted by remember { mutableStateOf(kind != SetupKind.Create) } + var password by remember { mutableStateOf("") } + var seed by remember { mutableStateOf("") } + val ready = password.isNotEmpty() && (kind == SetupKind.Create || seed.isNotBlank()) + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text( + if (kind == SetupKind.Create) "Create wallet" else "Import wallet", + style = MaterialTheme.typography.titleSmall, + ) + Spacer(Modifier.height(8.dp)) + if (kind == SetupKind.Create && !accepted) { + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button(onClick = { accepted = true }) { Text("I accept spend authority") } + } + return@Column + } + if (kind == SetupKind.Import) { + Text( + "Paste the 25-word seed. Create does not need a key.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = seed, + onValueChange = { seed = it }, + label = { Text("seed") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + } + OutlinedTextField( + value = password, + onValueChange = { password = it }, + singleLine = true, + label = { Text("wallet passphrase") }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button( + onClick = { + scope.launch { + when (kind) { + SetupKind.Create -> create(password).fold( + onSuccess = onCreated, + onFailure = { onError(it.message ?: it.toString()) }, + ) + SetupKind.Import -> importWallet(password, seed.trim()).fold( + onSuccess = { onImported() }, + onFailure = { onError(it.message ?: it.toString()) }, + ) + } + } + }, + enabled = ready, + ) { Text(if (kind == SetupKind.Create) "Create" else "Import") } + } + } + } +} + /** Generate a QR bitmap for the given URI string. Returns null on encode failure. */ internal fun generateQrBitmap(uri: String): Bitmap? { return try { diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index df25c28..136b815 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -575,6 +575,30 @@ impl Wire { .await .map_err(WireError::new) } + + /// Create a new spend-capable wallet. Returns the 25-word seed once so the + /// UI can show a backup screen. The user does not paste a key on this path. + /// Requires `ONIONWIRE_WALLET_RPC` pointed at a `--wallet-dir` RPC. + pub async fn create_wallet(&self, password: String) -> WResult { + self.node()? + .wallet_create(&password) + .await + .map_err(WireError::new) + } + + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn import_wallet(&self, password: String, seed: String) -> WResult<()> { + self.node()? + .wallet_restore(&password, &seed) + .await + .map_err(WireError::new) + } + + /// Spend-authority warning shown before create. Not a tooltip. + pub fn spend_authority_warning(&self) -> String { + onionwire::wallet::SPEND_AUTHORITY_WARNING.to_string() + } } fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 48daf63..006ee1f 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -69,21 +69,61 @@ The queue is bounded in scope: chat only. File transfer and `rcp` frames are one A signed `prf` frame is shown to people who already have a session with you. Apply only for existing friends. There is still no name lookup, DHT, or public profile server. Anyone who already has a Noise session can see the profile you send them; that is not confidentiality against that friend. -## Monero sidecar is not a wallet +## Payments are opt-in; spend is a local authority -OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy. +Chat does not need a wallet. Payment frames (`inv`, `rcp`, `tip`) are signed +claims over Noise: a signature proves which friend sent the claim, not that +money moved. `verified=1` only after a conjunctive match — one `get_transfers` +row with the same non-empty `txid`, `amount`, and `address`. RPC down, error, or +no exact row → stay `verified=0`. Subaddress reuse is the user’s wallet policy. -Run it **view-only** (recommended). `/pay` and receipt verification need only -`create_address`/`get_transfers`, which a wallet without a spend key serves -fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC -dial, and a view-only wallet is detected over RPC (`query_key` -`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says -so plainly instead of failing with a raw wallet error. The trade-off is -explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local -spend authority — any process that can read the RPC credentials can move the -balance, and `/tip` gives a chat peer a supported way to ask for a transfer. -Loopback binding is not an authorization boundary. Full setup, view-only wallet -creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md). +**Default: no spend.** No seed and no spend key on the device. Receive can use +the profile `xmr_addr`, or a view-only wallet (`create_address` / +`get_transfers` only). `/tip` is off (`ONIONWIRE_WALLET_NO_SPEND`, or a +watch-only wallet detected over RPC via `query_key spend_key` → `-29`). + +**Spend is opt-in**, at wallet create or restore, not a hidden default. A +seed-backed spend-capable wallet makes OnionWire a **local spend authority** +for that file: anyone with the wallet passphrase or the wallet-RPC credentials +can move the balance, and `/tip` is a supported way for a chat peer to get paid. +The spend-authority warning is unavoidable at that create/restore step. Loopback +binding is not an authorization boundary. Back up the seed; do not leave a +spend-capable wallet on a device you do not trust; a separate hot wallet with a +small balance is the sane spend shape, not savings. + +The app talks to `monero-wallet-rpc` over **loopback HTTP Digest** only +(`--rpc-login` required; open RPC refused). That process may be one the user +already runs, or one the app spawns. Wallet RPC is never dialed over clearnet or +over `.onion` — a remote wallet RPC would move spend authority off the box +through a channel the messenger’s `--password` gate does not cover. + +### Chain source is the user’s choice + +Scan, receipt verification, and spend need a Monero daemon. The user picks one; +the app does not pick a public remote node for them. + +1. **Spawn a local `monerod`** (pruned is the on-device target). Chain traffic + stays on the device. The user accepts disk (tens of GB for a pruned mainnet + node), first-sync time, and — on Android — process kills: the daemon is not + always running. A pruned node is not an archive. Seed restore of deep history + can degrade; once the wallet has scanned, its own cache is the history. + Unsynced or not running is an honest “not ready” / unverified state, not a + fake success. + +2. **A daemon address they supply.** The wallet child points `--daemon-address` + at that host. Trust follows the address: + - **Loopback** — same privacy as (1); the user owns `monerod`. + - **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener + the app provides for the wallet child (not the messenger’s Arti + `connect()`, and not a C-tor fallback for chat). Tor hides the transport. + The daemon operator still sees the wallet’s addresses during sync. The + host is the trust boundary. + - **Clearnet** — only if the user typed it. Not a default, not implied. + The ISP sees Monero-node traffic; the daemon operator sees addresses. Show + that trust shift before using the address. + +Remote daemons are untrusted (`--trusted-daemon` off). Setup, view-only vs +spend, and RPC credentials: [WALLET.md](WALLET.md). ## Backup file is the identity @@ -96,12 +136,23 @@ Incoming rendezvous accepts are token-bucket limited (30/60s, burst 10). Excess ## Network (UDP / clearnet) The application does not open UDP sockets and does not resolve friends via -system DNS. Peer dials are Arti `connect((onion, 80))` only. The one -intentional clearnet socket is optional `monero-wallet-rpc` on **loopback TCP** -(numeric loopback preferred; `localhost` still does `getaddrinfo`). +system DNS. Peer dials are Arti `connect((onion, 80))` only. -Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback, or “direct TCP when -the onion is slow.” Those are the Tox-over-Tor leak class. +Wallet **RPC** (HTTP Digest to `monero-wallet-rpc`) is loopback TCP only +(numeric `127.0.0.1` / `::1` preferred; `localhost` still does `getaddrinfo`). +That socket is the app talking to the wallet process, not to the chain. + +**Chain** traffic is the wallet child’s connection to a Monero daemon. It is +off unless the user opted into a wallet and chose a chain source: spawned local +`monerod` (loopback), or a daemon address they entered. A `.onion` daemon is +reached through a localhost SOCKS5 proxy used only by that wallet child. A +clearnet daemon address is an explicit user choice — a clearnet socket they +asked for — not the messenger path and not a hidden default. + +Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback for **peer dials**, or +“direct TCP when the onion is slow.” Those are the Tox-over-Tor leak class. A +SOCKS listener used only by the wallet child to reach a user-chosen `.onion` +daemon is not that class. ## Peer text is untrusted display data diff --git a/docs/WALLET.md b/docs/WALLET.md index 7da17bc..9975bc7 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -1,14 +1,23 @@ # OnionWire + monero-wallet-rpc -OnionWire is not a wallet. It never holds a seed, a spend key, or a view key. -It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on -loopback, only to: +Chat does not require a wallet. A wallet is opt-in. + +**Default: no spend.** No seed and no spend key on the device. Receive uses the +profile `xmr_addr`, or a view-only wallet for invoices (`create_address`) and +receipt checks (`get_transfers`). `/tip` is off. + +**Spend is opt-in** at wallet create or restore (seed-backed). That makes +OnionWire a local spend authority for that wallet file — see the spend-authority +warning below. The threat-model write-up is [THREAT_MODEL.md](THREAT_MODEL.md). + +The app talks to `monero-wallet-rpc` over loopback HTTP Digest only, whether +that process is one you already run or one the app spawns: - hand out a receive subaddress for `/pay` invoices (`create_address`), - read incoming transfers to verify a peer's receipt (`get_transfers`), -- and — only if you let it — spend for `/tip` (`transfer`). +- and — only if you opted into spend — `/tip` (`transfer`). -**Run it view-only, and switch `/tip` off explicitly.** Everything else in this +**Prefer view-only until you actually want `/tip`.** Everything else in this document explains why, and what breaks when you do. ## Env vars @@ -21,6 +30,20 @@ document explains why, and what breaks when you do. `README.md` carries the operator summary; this file is the long form. +## Create vs import + +Create does **not** take a private key. `/wallet create` (TUI: F6 then `c`) asks +the RPC to generate a new spend-capable wallet (`create_wallet`), then shows the +seed **once** for backup (`query_key mnemonic`). Type `SPEND` to accept the +spend-authority warning, set a passphrase, write the seed down, type `SEEN`. + +Import is the only path that takes an existing secret: `/wallet import` (F6 then +`i`) pastes the 25-word seed into `restore_deterministic_wallet`. Do not put the +seed on the composer line — it would sit in chat history. + +The RPC must be started with `--wallet-dir` (not only `--wallet-file`) or create +and import fail. The in-app filename is `onionwire`. + ## Recommended topology ``` @@ -34,9 +57,26 @@ document explains why, and what breaks when you do. └──────────────────────────────────────────────────────────────┘ ``` -Loopback is the only address OnionWire will dial. `.onion` RPC URLs are -rejected: there is no Arti dial for the wallet, and a remote wallet would move -your key material off the box. +Loopback is the only address OnionWire will dial for **wallet RPC**. `.onion` +wallet-RPC URLs are rejected: there is no Arti dial for the wallet process, and +a remote wallet RPC would move spend authority off the box. + +## Chain source + +The wallet needs a daemon for scan, verify, and spend. You pick one; OnionWire +does not pick a public remote node for you. + +1. **Spawn a local `monerod`** (pruned on-device). Chain traffic stays on the + box. You accept disk, first sync, and (on Android) the daemon not always + running. +2. **A daemon address you supply** — `--daemon-address` on the wallet child. + Loopback if you already run `monerod`. `.onion` if you want chain traffic + over Tor (wallet child `--proxy` to a localhost SOCKS listener; the daemon + operator still sees addresses). Clearnet only if you type it — ISP sees + Monero-node traffic; not a default. + +Remote daemons are untrusted (`--trusted-daemon` off). Unsynced or unreachable +→ receipts stay unverified and spend is refused. That is the honest state. ## Create a view-only wallet @@ -88,7 +128,7 @@ Restore the wallet from a height *at or before* its first incoming transaction | Receipt verification (`get_transfers`) | works | works | | Profile `xmr_addr` fallback when RPC is down | works | works | | `/tip ` (`transfer`) | **cannot work** | works | -| OnionWire learns your spend key | never | never (it stays in the wallet) | +| OnionWire copies your spend key into its own process | never | never (it stays in the wallet file / RPC) | With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is contacted, with: diff --git a/src/node.rs b/src/node.rs index ee21275..5ca5bbe 100644 --- a/src/node.rs +++ b/src/node.rs @@ -684,6 +684,29 @@ impl Node { Ok(rows.into_iter().take(cap).collect()) } + /// Create a new spend-capable wallet. Returns the seed once for backup. + /// The user never pastes a key on this path. + pub async fn wallet_create(&self, password: &str) -> Result { + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); + } + self.wallet + .create_wallet(wallet::DEFAULT_WALLET_FILENAME, password) + .await + .map_err(|e| e.to_string()) + } + + /// Import a wallet from an existing 25-word seed. This is the only path + /// that takes a user-supplied secret. + pub async fn wallet_restore(&self, password: &str, seed: &str) -> Result<(), String> { + if !self.wallet.configured() { + return Err("wallet not connected — set ONIONWIRE_WALLET_RPC".into()); + } + self.wallet + .restore_wallet(wallet::DEFAULT_WALLET_FILENAME, password, seed) + .await + .map_err(|e| e.to_string()) + } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { self.ensure_running()?; diff --git a/src/tui.rs b/src/tui.rs index e149d9a..8622ca5 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -454,9 +454,12 @@ OnionWire keys\n\ F3 paste invite\n\ F4 rotate onion locator\n\ F5 selected friend's profile (/who)\n\ + F6 wallet (receive QR, create/import)\n\ /profile edit name, bio, Monero address\n\ /pay [memo] invoice to receive\n\ /tip [memo] pay selected friend\n\ + /wallet create new spend wallet (seed shown once)\n\ + /wallet import restore from existing seed\n\ /file /path send file to selected friend (1 MiB)\n\ /backup /path encrypted identity export\n\ /restore /path overwrite self keys\n\ @@ -562,6 +565,8 @@ pub enum SlashCmd { Backup { path: String }, Restore { path: String }, File { path: String }, + WalletCreate, + WalletImport, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -710,6 +715,11 @@ pub fn parse_cmd(raw: &str) -> Option { { return parse_path_cmd(rest).map(|path| SlashCmd::File { path }); } + match s { + "/wallet create" => return Some(SlashCmd::WalletCreate), + "/wallet import" => return Some(SlashCmd::WalletImport), + _ => {} + } None } @@ -1118,11 +1128,20 @@ enum Screen { transfers: Vec, qr_modal: Option, }, + WalletSetup(WalletSetup), Quit { prompt: QuitPrompt, }, } +enum WalletSetup { + CreateWarn { typed: String }, + CreatePass { entry: PassphraseEntry }, + CreateSeed { seed: Zeroizing, typed: String }, + ImportSeed { buf: Zeroizing }, + ImportPass { seed: Zeroizing, entry: PassphraseEntry }, +} + impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; @@ -1276,6 +1295,18 @@ impl App { self.composer.clear(); file_cmd = Some(path); } + Some(ComposerAction::Cmd(SlashCmd::WalletCreate)) => { + self.composer.clear(); + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + Some(ComposerAction::Cmd(SlashCmd::WalletImport)) => { + self.composer.clear(); + self.screen = Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }); + } Some(ComposerAction::Send(text)) => { self.composer.clear(); chat_send = Some(text); @@ -1394,8 +1425,19 @@ impl App { Screen::Wallet { .. } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Char('r') | KeyCode::Enter => self.wallet_toggle_qr(), + KeyCode::Char('c') => { + self.screen = Screen::WalletSetup(WalletSetup::CreateWarn { + typed: String::new(), + }); + } + KeyCode::Char('i') => { + self.screen = Screen::WalletSetup(WalletSetup::ImportSeed { + buf: Zeroizing::new(String::new()), + }); + } _ => {} }, + Screen::WalletSetup(_) => self.handle_wallet_setup(key)?, Screen::Quit { prompt } => match key.code { KeyCode::Esc => self.screen = Screen::Main, KeyCode::Enter => match prompt.on_char('\n') { @@ -1663,6 +1705,151 @@ impl App { }); } + fn handle_wallet_setup(&mut self, key: KeyEvent) -> Result<(), String> { + let Screen::WalletSetup(setup) = &mut self.screen else { + return Ok(()); + }; + if key.code == KeyCode::Esc { + match setup { + WalletSetup::CreatePass { entry } | WalletSetup::ImportPass { entry, .. } => { + entry.close(); + } + WalletSetup::CreateSeed { seed, .. } => seed.zeroize(), + WalletSetup::ImportSeed { buf } => buf.zeroize(), + WalletSetup::CreateWarn { .. } => {} + } + self.screen = Screen::Main; + return Ok(()); + } + match setup { + WalletSetup::CreateWarn { typed } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SPEND") { + self.screen = Screen::WalletSetup(WalletSetup::CreatePass { + entry: PassphraseEntry::new(), + }); + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::CreatePass { 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(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + match self.rt.block_on(self.node.wallet_create(pass.as_str())) { + Ok(seed) => { + self.screen = Screen::WalletSetup(WalletSetup::CreateSeed { + seed: Zeroizing::new(seed), + typed: String::new(), + }); + } + Err(e) => { + self.alert = Some(e); + self.screen = Screen::Main; + } + } + } else { + self.screen = Screen::WalletSetup(WalletSetup::CreatePass { + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, + WalletSetup::CreateSeed { typed, seed } => match key.code { + KeyCode::Char(c) if c.is_ascii_alphabetic() => { + typed.push(c); + if typed.eq_ignore_ascii_case("SEEN") { + seed.zeroize(); + self.status_note = Some("wallet created — seed shown once".into()); + return self.open_wallet(); + } + } + KeyCode::Backspace => { + typed.pop(); + } + _ => {} + }, + WalletSetup::ImportSeed { buf } => match key.code { + KeyCode::Backspace => { + buf.pop(); + } + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { + buf.push(c); + } + KeyCode::Enter => { + let seed = std::mem::replace(buf, Zeroizing::new(String::new())); + if seed.trim().is_empty() { + self.alert = Some("seed required to import a wallet".into()); + self.screen = Screen::Main; + return Ok(()); + } + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + entry: PassphraseEntry::new(), + }); + } + _ => {} + }, + WalletSetup::ImportPass { entry, seed } => 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(); + seed.zeroize(); + self.alert = Some("passphrases do not match".into()); + self.screen = Screen::Main; + return Ok(()); + } + let result = self + .rt + .block_on(self.node.wallet_restore(pass.as_str(), seed.as_str())); + seed.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 seed = std::mem::replace(seed, Zeroizing::new(String::new())); + self.screen = Screen::WalletSetup(WalletSetup::ImportPass { + seed, + entry: PassphraseEntry::with_first(pass.as_str()), + }); + } + } + _ => {} + }, + } + Ok(()) + } + fn submit_paste(&mut self, raw: &str) -> Result<(), String> { match qr::decode(raw.trim()) { Err(e) => { @@ -1835,6 +2022,7 @@ impl App { Screen::Wallet { receive_addr, balance, transfers, qr_modal } => { draw_wallet(f, receive_addr, balance, transfers, qr_modal.as_ref()) } + Screen::WalletSetup(setup) => draw_wallet_setup(f, setup), } if self.help_open { draw_text_overlay(f, "? help", help_overlay_text()); @@ -2152,7 +2340,13 @@ match screen { BackupKind::Restore => "type RESTORE Esc cancel ? help", }, Screen::Passphrase { .. } => "Enter submit Esc cancel ? help", - Screen::Wallet { .. } => "r toggle qr Esc back ? help", + Screen::Wallet { .. } => "c create i import r qr Esc back ? help", + Screen::WalletSetup(WalletSetup::CreateWarn { .. }) => "type SPEND Esc cancel ? help", + Screen::WalletSetup(WalletSetup::CreatePass { .. } | WalletSetup::ImportPass { .. }) => { + "Enter submit Esc cancel ? help" + } + Screen::WalletSetup(WalletSetup::CreateSeed { .. }) => "type SEEN Esc cancel ? help", + Screen::WalletSetup(WalletSetup::ImportSeed { .. }) => "paste seed Enter Esc ? help", Screen::Quit { .. } => "CLEAR or QUIT then Enter Esc cancel ? help", } } @@ -2489,7 +2683,7 @@ recent transfers lines.push(format!(" {} {} XMR", t.txid.chars().take(16).collect::(), xmr)); } } - let help = "r toggle qr Esc back"; + let help = "c create i import r toggle qr Esc back"; lines.push("".into()); f.render_widget( Paragraph::new(lines.join("\n")) @@ -2502,6 +2696,49 @@ recent transfers f.render_widget(Paragraph::new(help).style(style_dim()), cols[3]); } +fn draw_wallet_setup(f: &mut Frame, setup: &WalletSetup) { + let (title, body) = match setup { + WalletSetup::CreateWarn { typed } => ( + "create spend wallet", + format!( + "{}\n\nType SPEND to confirm Esc to cancel\n{typed}", + wallet::SPEND_AUTHORITY_WARNING + ), + ), + WalletSetup::CreatePass { entry } => ( + "wallet passphrase", + if entry.first().is_some() { + "re-type passphrase\n\nEnter submits Esc cancels".into() + } else { + "set a passphrase for the wallet file\n\nEnter continues Esc cancels".into() + }, + ), + WalletSetup::CreateSeed { seed, typed } => ( + "write down this seed", + format!( + "{}\n\nthis is shown once. anyone with it can spend.\nType SEEN when you have written it down\n{typed}", + seed.as_str() + ), + ), + WalletSetup::ImportSeed { buf } => ( + "import wallet", + format!( + "paste the 25-word seed. this is the only path that takes an existing key.\n\n{}\n\nEnter continues Esc cancels", + buf.as_str() + ), + ), + WalletSetup::ImportPass { 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() + }, + ), + }; + draw_text_overlay(f, title, &body); +} + fn io_err(e: io::Error) -> String { e.to_string() } diff --git a/src/wallet.rs b/src/wallet.rs index cf255a0..61234cc 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -61,6 +61,12 @@ pub struct TransferRow { pub address: String, } +/// Wallet file name used for in-app create/import (`--wallet-dir` on the RPC). +pub const DEFAULT_WALLET_FILENAME: &str = "onionwire"; + +/// Shown before a spend-capable create. Not a tooltip — the user must confirm. +pub const SPEND_AUTHORITY_WARNING: &str = "this wallet file can spend. anyone with its passphrase or the RPC creds can move the balance. write down the seed. do not leave it on a box you do not trust."; + const RPC_TIMEOUT: Duration = Duration::from_secs(5); impl Wallet { @@ -215,6 +221,65 @@ impl Wallet { json_str(&v, "balance") } + /// Create a new spend-capable wallet on the RPC (`create_wallet`). The + /// user does not paste a key — the daemon generates the seed. Returns that + /// seed once (from `query_key mnemonic`) so the UI can show a backup + /// screen. Needs `--wallet-dir` on the RPC. + pub async fn create_wallet(&self, filename: &str, password: &str) -> 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())); + } + self.rpc( + "create_wallet", + serde_json::json!({ + "filename": filename, + "password": password, + "language": "English" + }), + ) + .await?; + let v = self + .rpc("query_key", serde_json::json!({"key_type": "mnemonic"})) + .await + .map_err(|e| { + Error(format!( + "wallet created but seed backup unavailable: {e}" + )) + })?; + json_str(&v, "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<()> { + 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 seed = seed.trim(); + if seed.is_empty() { + return Err(Error("seed required to import a wallet".into())); + } + self.rpc( + "restore_deterministic_wallet", + serde_json::json!({ + "filename": filename, + "password": password, + "seed": seed, + "language": "English" + }), + ) + .await?; + Ok(()) + } + async fn rpc(&self, method: &str, params: serde_json::Value) -> Result { let ep = self .endpoint diff --git a/tests/pay.rs b/tests/pay.rs index c2ab11c..1dc600b 100644 --- a/tests/pay.rs +++ b/tests/pay.rs @@ -206,6 +206,9 @@ fn slash_pay_tip_and_wipe_still_parse() { assert_eq!(parse_cmd("/wipe"), Some(SlashCmd::Wipe(WipeKind::Messages))); assert_eq!(parse_slash("/wipe-all"), Some(WipeKind::All)); assert_eq!(parse_slash("/pay 0.12"), None); + assert_eq!(parse_cmd("/wallet create"), Some(SlashCmd::WalletCreate)); + assert_eq!(parse_cmd("/wallet import"), Some(SlashCmd::WalletImport)); + assert_eq!(parse_cmd("/wallet"), None); } #[test] diff --git a/tests/tui_chrome.rs b/tests/tui_chrome.rs index a0ada29..1eacccf 100644 --- a/tests/tui_chrome.rs +++ b/tests/tui_chrome.rs @@ -45,10 +45,13 @@ fn help_overlay_lists_core_bindings() { "F3", "F4", "F5", + "F6", "send chat", "/profile", "/pay", "/tip", + "/wallet create", + "/wallet import", "/file", "/backup", "/restore", diff --git a/tests/wallet.rs b/tests/wallet.rs index 1d4a451..10fb7a1 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -429,6 +429,112 @@ async fn spend_capable_wallet_keeps_the_original_transfer_error() { assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}"); } +/// Create generates a spend-capable wallet on the RPC; the user never pastes a key. +/// Seed is read back once via `query_key mnemonic` for the backup screen. +#[tokio::test] +async fn create_wallet_does_not_send_a_seed_and_returns_mnemonic() { + 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 { + "create_wallet" => rpc_result(r#"{}"#), + "query_key" => rpc_result(r#"{"key":"lumber tacit lemon ivory risk"}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + let seed = recording_wallet(port) + .create_wallet("onionwire", "hunter2") + .await + .expect("create_wallet"); + assert_eq!(seed, "lumber tacit lemon ivory risk"); + let seen = log.lock().expect("log").clone(); + let create = seen + .iter() + .find(|r| r.contains(r#""method":"create_wallet""#)) + .expect("create_wallet RPC"); + assert!( + !create.contains("lumber") && !create.contains("seed"), + "create must not take a seed: {create}" + ); + assert!( + create.contains(r#""filename":"onionwire""#), + "filename missing: {create}" + ); + assert!( + seen.iter().any(|r| r.contains(r#""method":"query_key""#) + && r.contains("mnemonic")), + "must read mnemonic after create: {seen:?}" + ); +} + +#[test] +fn create_wallet_empty_filename_or_password_is_local_error() { + let w = Wallet::from_url("http://ow:secret@127.0.0.1:18083").unwrap(); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let err = rt + .block_on(w.create_wallet("", "pw")) + .unwrap_err() + .to_string(); + assert!(err.contains("filename"), "got {err}"); + let err = rt + .block_on(w.create_wallet("onionwire", "")) + .unwrap_err() + .to_string(); + assert!( + err.to_ascii_lowercase().contains("password") + || err.to_ascii_lowercase().contains("passphrase"), + "got {err}" + ); +} + +/// Import is the only path that takes an existing secret (the 25-word seed). +#[tokio::test] +async fn restore_wallet_sends_seed_to_restore_deterministic_wallet() { + 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":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","seed":"lumber tacit lemon ivory risk"}"#), + _ => rpc_error(-1, "unexpected method"), + }), + )); + recording_wallet(port) + .restore_wallet("onionwire", "hunter2", "lumber tacit lemon ivory risk") + .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("lumber tacit lemon ivory risk"), + "seed missing: {restore}" + ); +} + +#[test] +fn restore_wallet_empty_seed_is_local_error() { + let w = Wallet::from_url("http://ow:secret@127.0.0.1:18083").unwrap(); + let err = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(w.restore_wallet("onionwire", "pw", " ")) + .unwrap_err() + .to_string(); + assert!(err.to_ascii_lowercase().contains("seed"), "got {err}"); +} + /// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused. #[tokio::test] async fn open_rpc_without_digest_challenge_is_still_refused() {