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/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index fb5db30..dcdb344 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -609,6 +609,49 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun walletBalance(): String = requireWire().walletBalance() + /** + * The spendable part of the balance, with exactly the same sentinels as + * [walletBalance]: `"off"` when no chain source is configured, `"err"` when + * the read failed, else the bare XMR number. The screen shows it as a second + * dim line under the headline and omits it entirely for the two sentinels — + * it is the same wallet's answer, not a second error the user has to read. + * It is shown even when it equals the total: "all of it is spendable" is a + * fact worth one line, and a UI that hid the line would be indistinguishable + * from one that never asked. + */ + suspend fun walletUnlockedBalance(): String = requireWire().walletUnlockedBalance() + + /** + * Send XMR to a pasted address. Returns the transaction hash. + * + * A plain local transfer on this node's own wallet — no friend, no tip + * frame, no chat line — so this is deliberately not [sendInvoice] / + * [sendTip]: those are one-shot to a peer's onion and stay friend-only. + * + * The core validates the address and the amount before it dials, and its own + * refusals come back verbatim: a `ONIONWIRE_WALLET_NO_SPEND` wallet or a + * view-only file is refused with the view-only message, and a chain that is + * not at the tip is refused rather than allowed to fail opaquely. Nothing is + * rewritten here — [ui.walletFailureText] passes those strings through. + * + * [address] is never logged. The caller clears its fields on success. + */ + suspend fun walletSend(address: String, amountXmr: String): Result = + runCatching { requireWire().walletSend(address, amountXmr) } + + /** + * Is the wallet the child has open **watch-only**? + * + * This is the core's own probe — a spend-key `query_key` refused with + * monero's watch-only code — and never [walletKeys], which would pull the + * spend key into the screen just to answer a yes/no. A failure (no chain + * source configured, no wallet open, child down) is a `Result.failure`, not + * a `false`: the screen treats "not answered yet" as unknown and keeps the + * gate's ordinary rules until it hears something. + */ + suspend fun walletViewOnly(): Result = + runCatching { requireWire().walletViewOnly() } + suspend fun walletReceiveAddress(): String? = runCatching { requireWire().walletReceiveAddress() }.getOrElse { null } @@ -635,7 +678,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { /** * Import a wallet from a user-supplied seed, optionally mixed with the seed - * offset passphrase that seed was created with. + * offset passphrase that seed was created with, and optionally scanning from + * a given height. + * + * One RPC: `importSeed` carries the offset and the restore height together, + * which is why this replaced the old `importWallet` / `importWalletWithOffset` + * pair — two calls could not both be "the import", and a height supplied + * after an offset import would have been silently dropped. * * A blank (or whitespace) [offset] is the plain import: the words alone * restore that wallet, and — like today — it counts as backed up the moment @@ -652,22 +701,25 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { * * [offset] is trimmed here and handed to the core, whose own blank check is * the same rule: whitespace is an absent offset, never an empty string. + * [height] is passed through exactly as typed — the screen already filtered + * it to digits — and blank means "scan from 0" with no `restore_height` + * field in the request at all. It is **not** sealed, stored or logged: it is + * a block number, not a secret, but it is also not a backup, and a UI that + * remembered it would imply the next import could skip the field. */ - suspend fun importWallet( + suspend fun importSeed( password: String, seed: String, offset: String = "", + height: String = "", ): Result { val trimmed = offset.trim() - val result = if (trimmed.isEmpty()) { - runCatching { requireWire().importWallet(password, seed) } - } else { - // The offset is a UniFFI `String` for the life of this call, the - // same limit `openWalletWithPassphrase` documents. Never logged and - // never put in an error string: the core's failures are about the - // restore, not the offset, and a message built here is one a crash - // report would carry. - runCatching { requireWire().importWalletWithOffset(password, seed, trimmed) } + // The offset is a UniFFI `String` for the life of this call, the same + // limit `openWalletWithPassphrase` documents. Never logged and never put + // in an error string: the core's failures are about the restore, not the + // offset, and a message built here is one a crash report would carry. + val result = runCatching { + requireWire().importSeed(password, seed, trimmed, height) } return result.onSuccess { val pending = SeedBackupGate.offsetPendingAfterImport(trimmed) @@ -678,6 +730,33 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } } + /** + * Import an address to **watch**: an address and its private view key, and + * no spend key at all. The file this creates can see incoming transfers and + * cannot spend. + * + * The seed-backup gate does not apply and must not be run: this wallet has + * no seed, so there is nothing to write down. [SEED_BACKED_UP_KEY] is + * deliberately **not** written here — that flag is install-wide, and setting + * it from this path would claim the *create* seed was backed up when the + * wallet on screen never had one. + * + * [viewKey] is a spend-adjacent secret (it unblinds every incoming output): + * never logged, never copied, never put in an error string, and dropped with + * the caller's own reference when the card closes. The core refuses a + * wrong-shape key locally with its own message that does not contain the key. + * [password] is the wallet *file* passphrase — that one the core seals, so + * the file reopens on the next start. + */ + suspend fun importViewOnly( + password: String, + address: String, + viewKey: String, + height: String = "", + ): Result = runCatching { + requireWire().importViewOnly(password, address, viewKey, height) + } + /** * Re-read the open wallet's 25-word seed, for the "Back up seed" recovery * path. A spend key: only ever called from that explicit user action, shown diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt index c44f32b..c918ca6 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/SeedBackupGate.kt @@ -92,10 +92,20 @@ object SeedBackupGate { * so folding it in here would put the create-seed text on an import that * never had a create. */ - fun warningVisible(confirmed: Boolean?, walletReadable: Boolean): Boolean = when (confirmed) { - true -> false - false -> true - null -> walletReadable + fun warningVisible( + confirmed: Boolean?, + walletReadable: Boolean, + viewOnly: Boolean = false, + ): Boolean = when { + // A view-only wallet has no seed at all — there is nothing to write + // down and nothing to warn about. "write down the 25 words" would be a + // lie about a file that only ever got an address and a view key, which + // is why this input also outranks [card]'s offset branch: a view-only + // import never had an offset to lose. + viewOnly -> false + confirmed == true -> false + confirmed == false -> true + else -> walletReadable } /** @@ -112,7 +122,8 @@ object SeedBackupGate { confirmed: Boolean?, walletReadable: Boolean, offsetPending: Boolean = false, - ): Boolean = card(confirmed, walletReadable, offsetPending) == WalletGateCard.None + viewOnly: Boolean = false, + ): Boolean = card(confirmed, walletReadable, offsetPending, viewOnly) == WalletGateCard.None /** Which blocking card the wallet screen is under, if any. */ enum class WalletGateCard { @@ -128,15 +139,20 @@ object SeedBackupGate { /** * The one place that decides which card — if any — the wallet screen is - * under. The offset card wins when both are set: it is about the wallet that - * was just opened, and the seed card cannot be shown for an import that was - * never gated. + * under. [viewOnly] wins outright: a wallet with no seed cannot be nagged + * about one, and an import that had no offset has nothing to acknowledge, + * so the view-only answer is [WalletGateCard.None] and the address stays on + * screen. With it `false`, the offset card still beats the seed card when + * both are set: it is about the wallet that was just opened, and the seed + * card cannot be shown for an import that was never gated. */ fun card( confirmed: Boolean?, walletReadable: Boolean, offsetPending: Boolean = false, + viewOnly: Boolean = false, ): WalletGateCard = when { + viewOnly -> WalletGateCard.None offsetPending -> WalletGateCard.OffsetNotSaved warningVisible(confirmed, walletReadable) -> WalletGateCard.UnbackedSeed else -> WalletGateCard.None @@ -203,3 +219,71 @@ object SeedBackupGate { "this offset was not saved. write it down. a later seed backup is a " + "different 25 words that open this wallet without the offset." } + +/** + * The optional `restore height` both import cards carry, as a pure filter. + * + * The core takes the height as typed and refuses anything that is not a block + * number (`restore height must be a block number`), so the field can only ever + * hand it digits: a stray pasted character is dropped at the keystroke rather + * than travelling all the way to an RPC that will reject it. + * + * Blank is not zero and is not an error — it means "scan from the start", and + * the core sends no `restore_height` field at all for it. + * + * Lives in this file because this is the wallet screen's pure-decision module + * (`SeedBackupGateTest` covers it on the JVM, no device). + */ +object RestoreHeight { + + /** The one rule: digits survive, everything else is dropped. */ + fun digitsOnly(typed: String): String = typed.filter { it.isDigit() } + + /** + * The field's helper. Visible, not a placeholder: the warning has to + * survive the first keystroke, because that is the moment the user can still + * choose a height that hides their history. + */ + const val HELPER: String = + "Blank scans from 0. A height after your first receive hides older funds." +} + +/** + * The send composer's confirm step: a pasted address and an amount, then the + * word, because a paste is not a person. + * + * Deliberately **not** [SeedBackupGate.CONFIRM_WORD] (`SEEN`) — the seed gate's + * word means "I wrote the key down", and reusing it here would let a user who + * learned the one word type it into the other flow by reflex. A send is + * irreversible; it gets its own word and its own object. + * + * No camera and no QR: the address is what the user pasted, and this SDK call + * takes a raw address string, so there is nothing to scan. + */ +object WalletSendGate { + + /** The word that releases the send. Its own, not `SEEN`. */ + const val CONFIRM_WORD: String = "SEND" + + /** Trimmed and case-insensitive, exactly like the seed gate's word. */ + fun accepts(typed: String): Boolean = + typed.trim().equals(CONFIRM_WORD, ignoreCase = true) + + /** Send stays dead until the word is right. */ + fun confirmEnabled(typed: String): Boolean = accepts(typed) + + /** + * Both fields non-blank is the local precondition. An empty address or + * amount never reaches the SDK — this is what "local empty-field state never + * calls the SDK" means in code. + * + * It is only a precondition, not a validation: whether the address is a real + * one and the amount parsable is the core's answer, and its refusals are + * shown verbatim rather than guessed at here. + */ + fun ready(address: String, amount: String): Boolean = + address.isNotBlank() && amount.isNotBlank() + + /** The confirm card's own line, so the two fields are read back verbatim. */ + const val CONFIRM_PROMPT: String = "Type $CONFIRM_WORD to send. This cannot be undone." +} 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 b16ccfc..771a459 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 @@ -1,7 +1,10 @@ package com.siriusdevops.onionwire.ui +import android.content.ClipData +import android.content.ClipDescription import android.graphics.Bitmap import android.graphics.Color +import android.os.PersistableBundle import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement @@ -42,6 +45,8 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics @@ -64,7 +69,7 @@ import uniffi.onionwire_sdk.TransferRow import uniffi.onionwire_sdk.WalletChildStatus private enum class PayKind { Invoice, Tip } -private enum class SetupKind { Create, Import } +private enum class SetupKind { Create, Import, ViewOnly } /** * The offset field's helper. Visible, not a placeholder: a placeholder @@ -78,6 +83,19 @@ private const val OFFSET_HELPER: String = /** The re-type gate's only message. Shown on the card, never sent anywhere. */ private const val OFFSET_MISMATCH: String = "offset passphrases do not match" +/** + * The view-only card's re-type gate. Its own string, deliberately not + * [OFFSET_MISMATCH]: the two mismatch messages name two different secrets, and + * a user who typed a bad view key must not be told their offset is wrong. + */ +private const val VIEW_KEY_MISMATCH: String = "view keys do not match" + +/** The one status the address copy sets. Quiet, and it says what was copied. */ +private const val COPIED_ADDRESS_STATUS: String = "copied address" + +/** The balance card's label for a watch-only file. `onSurfaceVariant`, same as every quiet line. */ +private const val VIEW_ONLY_LABEL: String = "view-only" + @OptIn(ExperimentalMaterial3Api::class) @Composable fun WalletScreen( @@ -103,11 +121,27 @@ fun WalletScreen( val nodeFreeBytes = remember { vm.chainFreeBytes() } var showQr by remember { mutableStateOf(false) } var balance by remember { mutableStateOf(null) } + var unlocked by remember { mutableStateOf(null) } var address by remember { mutableStateOf(null) } var transfers by remember { mutableStateOf>(emptyList()) } var error by remember { mutableStateOf(null) } var composer by remember { mutableStateOf(null) } var setup by remember { mutableStateOf(null) } + // The pasted-address send. Its own flag, not a third `PayKind`: Invoice and + // Tip go to a friend's onion and this one does not, so folding them together + // would put a friend picker in front of a transfer the core sends locally. + var sendOpen by remember { mutableStateOf(false) } + // The clipboard is app-wide and this screen only borrows it; the status is + // per-screen and cleared by the next address read. + val clipboard = LocalClipboard.current + var copiedAddress by remember { mutableStateOf(false) } + // The core's own watch-only probe. Null until it answers: the gate must not + // read "no answer" as "spendable". + var viewOnlyProbe by remember { mutableStateOf(null) } + // Set by a successful view-only import on this screen. A probe that has not + // returned yet would otherwise flash the unbacked-seed card over a wallet + // that has no seed at all. Beside it, not persisted: it is about this visit. + var viewOnlyImported by remember { mutableStateOf(false) } // The seed currently on the blocking card: set by a successful create, or by // "Back up seed" re-reading it from the wallet child. Null means no card. // Never persisted and never logged — it is a spend key. @@ -123,10 +157,26 @@ fun WalletScreen( suspend fun reload() { runCatching { balance = vm.walletBalance() } .onFailure { error = walletFailureText(it.message ?: it.toString()) } + // Same wallet, same call shape, same sentinels — but a failure here is + // not worth an error line: the headline already carries this wallet's + // state, and the unlocked number is a detail of it. + runCatching { unlocked = vm.walletUnlockedBalance() } runCatching { address = vm.walletReceiveAddress() } + copiedAddress = false runCatching { transfers = vm.walletRecentTransfers(25) } } + /** + * Re-ask the core whether the open wallet is watch-only, and fold the answer + * into the gate. A failure leaves the previous answer alone rather than + * clearing it: an unconfigured wallet answers with an error, and dropping + * back to `null` there would flip a view-only wallet's card on and off as + * the chain source is edited. + */ + suspend fun probeViewOnly() { + vm.walletViewOnly().onSuccess { viewOnlyProbe = it } + } + /** * "Back up seed": re-read the open wallet's seed from the wallet child and * put it on the blocking card. This is the only path to a seed that was @@ -149,6 +199,7 @@ fun WalletScreen( LaunchedEffect(Unit) { reload() + probeViewOnly() vm.refreshChainSource() } @@ -163,6 +214,10 @@ fun WalletScreen( LaunchedEffect(childInput?.state) { if (shouldReloadWalletReads(childInput?.state)) { reload() + // The probe needs a live child to answer at all, so it is asked + // here rather than only on entry — a wallet is usually imported + // while the child is still connecting. + probeViewOnly() } } @@ -215,6 +270,26 @@ fun WalletScreen( .screenContentInsets() .verticalScroll(rememberScrollState()), ) { + // The two blocking cards below and the balance card all read these, so + // they are computed once, above them. + // + // `walletReadable` is the core's own evidence that the child has a + // wallet open: `wallet_balance` returns exactly "off" for a chain + // source that was never configured, "err" for a configured one whose + // read failed (no wallet file open yet, or the child is down), and a + // real amount otherwise. The gate uses it only for an install that + // has never created a wallet here, so a first-run user who has + // configured a daemon but not yet created anything is not nagged + // about a seed they do not have. + val walletReadable = balance != null && balance != "off" && balance != "err" + // The probe once it has answered, and this visit's own import until + // then. `viewOnlyProbe` alone would flash the unbacked-seed card in + // the window between a successful view-only import and the first + // probe that can reach the child. + val viewOnly = viewOnlyImported || viewOnlyProbe == true + val gateCard = + SeedBackupGate.card(seedConfirmed, walletReadable, offsetPending, viewOnly) + // The blocking seed step. While a seed is on screen this card is the // whole body: no Cancel, and Done stays dead until the confirm word // is typed, so the one-shot seed cannot be dismissed unread. The @@ -245,7 +320,11 @@ fun WalletScreen( // nowhere — it is not sealed and never stored — so this is the only // chance to say so. Keyed off a persisted flag rather than screen // state, so a kill or a Back before SEEN brings it straight back. - if (offsetPending) { + // + // Not on a view-only wallet: that file has no seed and no offset, so + // a flag left over from an earlier import must not block a wallet + // this screen just created from an address and a view key. + if (offsetPending && !viewOnly) { OffsetNotSavedCard( typed = offsetConfirm, onTyped = { offsetConfirm = it }, @@ -262,16 +341,6 @@ fun WalletScreen( } // The persistent unbacked strip, above everything else on the page. - // `walletReadable` is the core's own evidence that the child has a - // wallet open: `wallet_balance` returns exactly "off" for a chain - // source that was never configured, "err" for a configured one whose - // read failed (no wallet file open yet, or the child is down), and a - // real amount otherwise. The gate uses it only for an install that - // has never created a wallet here, so a first-run user who has - // configured a daemon but not yet created anything is not nagged - // about a seed they do not have. - val walletReadable = balance != null && balance != "off" && balance != "err" - val gateCard = SeedBackupGate.card(seedConfirmed, walletReadable, offsetPending) if (gateCard == SeedBackupGate.WalletGateCard.UnbackedSeed) { UnbackedSeedCard(error = error, onBackUpSeed = { openSeedBackup() }) } @@ -298,11 +367,42 @@ fun WalletScreen( style = MaterialTheme.typography.headlineSmall, fontFamily = FontFamily.Monospace, ) + val unlockedLine = unlocked?.takeIf { it != "off" && it != "err" } + if (unlockedLine != null) { + Spacer(Modifier.height(2.dp)) + Text( + "unlocked $unlockedLine XMR", + style = MaterialTheme.typography.labelSmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.testTag("wallet-unlocked-line"), + ) + } + // A watch-only file: the headline is its balance and none of + // it is spendable. The label says so on the card rather than + // as another error line — the send composer is where the + // refusal belongs, and this is the reason it will be there. + if (viewOnly) { + Spacer(Modifier.height(2.dp)) + Text( + VIEW_ONLY_LABEL, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.testTag("wallet-view-only-label"), + ) + } // Hidden until the seed is confirmed written down: XMR into a // wallet whose 25 words were never recorded is unrecoverable, // so the address and its QR are gated, not just warned about. + // A view-only wallet is the exception: it has no seed, and an + // address nobody can back up is one the owner has to share. val addr = address?.takeIf { - SeedBackupGate.receiveAddressVisible(seedConfirmed, walletReadable, offsetPending) + SeedBackupGate.receiveAddressVisible( + seedConfirmed, + walletReadable, + offsetPending, + viewOnly, + ) } if (addr != null) { Spacer(Modifier.height(8.dp)) @@ -318,6 +418,33 @@ fun WalletScreen( fontFamily = FontFamily.Monospace, modifier = Modifier.fillMaxWidth(), ) + // The address, and only the address. The seed card has no + // copy button and gets none: the clipboard is readable by + // every other app on the device, which is fine for an + // address and not fine for a spend key. The clip is marked + // sensitive so Android 13+ keeps it out of the clipboard + // history preview. + TextButton( + onClick = { + scope.launch { + val clip = ClipData.newPlainText("onionwire receive address", addr) + clip.description.extras = PersistableBundle().apply { + putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) + } + clipboard.setClipEntry(ClipEntry(clip)) + copiedAddress = true + } + }, + modifier = Modifier.testTag("wallet-copy-address"), + ) { Text("Copy") } + if (copiedAddress) { + Text( + COPIED_ADDRESS_STATUS, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.testTag("wallet-copy-status"), + ) + } TextButton(onClick = { showQr = !showQr }) { Text(if (showQr) "Hide QR" else "Show QR") } @@ -459,25 +586,78 @@ fun WalletScreen( }, ) } else if (setupKind != null) { - WalletSetupCard( - kind = setupKind, - warning = vm.spendAuthorityWarning(), - onCancel = { setup = null }, - onCreated = { seed -> - setup = null - // The card is the whole body from here until SEEN. - pendingSeed = seed - seedConfirm = "" - scope.launch { reload() } + if (setupKind == SetupKind.ViewOnly) { + ViewOnlyImportCard( + onCancel = { setup = null }, + onImported = { + setup = null + // A view-only file has no seed, so the gate must not + // flash the unbacked card over it before the probe can + // reach the child. A session flag, not a pref: it is + // about this import on this visit. + viewOnlyImported = true + scope.launch { + reload() + probeViewOnly() + } + }, + onError = { error = walletFailureText(it) }, + importViewOnly = { pw, addr, key, height -> + vm.importViewOnly(pw, addr, key, height) + }, + scope = scope, + ) + } else { + WalletSetupCard( + kind = setupKind, + warning = vm.spendAuthorityWarning(), + onCancel = { setup = null }, + onCreated = { seed -> + setup = null + viewOnlyImported = false + // The card is the whole body from here until SEEN. + pendingSeed = seed + seedConfirm = "" + scope.launch { reload() } + }, + onImported = { + setup = null + viewOnlyImported = false + scope.launch { reload() } + }, + onError = { error = walletFailureText(it) }, + create = { pw -> vm.createWallet(pw) }, + importSeed = { pw, seed, offset, height -> + vm.importSeed(pw, seed, offset, height) + }, + scope = scope, + ) + } + } else if (sendOpen) { + SendComposer( + onCancel = { sendOpen = false }, + onSend = { pasted, amount -> + scope.launch { + error = null + // The address never reaches a log line, here or in + // the ViewModel. + vm.walletSend(pasted, amount).fold( + onSuccess = { + // Composer closed (its fields die with it) + // and the transfer list re-read, so the new + // `out` row is on screen. + sendOpen = false + reload() + }, + onFailure = { + // The core's own words: a view-only file and + // a chain that is not at the tip each have + // their own refusal and both are shown as-is. + error = walletFailureText(it.message ?: it.toString()) + }, + ) + } }, - onImported = { - setup = null - scope.launch { reload() } - }, - onError = { error = walletFailureText(it) }, - create = { pw -> vm.createWallet(pw) }, - importWallet = { pw, seed, offset -> vm.importWallet(pw, seed, offset) }, - scope = scope, ) } else { Column(Modifier.fillMaxWidth().padding(12.dp)) { @@ -507,14 +687,37 @@ fun WalletScreen( onClick = { setup = SetupKind.Import }, modifier = Modifier.weight(1f), ) { Text("Import") } + // Import stays; this is beside it, not instead of it. A + // view-only wallet is a different file with a different + // risk profile, so it gets its own entry point rather + // than a mode toggle on the import card. + OutlinedButton( + onClick = { setup = SetupKind.ViewOnly }, + modifier = Modifier + .weight(1f) + .testTag("wallet-view-only-action"), + ) { Text("View-only") } } + Spacer(Modifier.height(8.dp)) + // The wallet's own send: a pasted address, no friend picker. + // Invoice and Tip above are one-shot to a peer's onion and + // stay that way. + OutlinedButton( + onClick = { sendOpen = true }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-send-action"), + ) { Text("Send") } // The recovery path for a wallet whose seed was missed. The // strip above carries its own copy of this button while the // seed is unconfirmed, so exactly one is ever on screen — // and this copy is only offered once the child can actually // read a wallet, which is the only state in which the seed - // read can succeed. - if (walletReadable && !SeedBackupGate.warningVisible(seedConfirmed, walletReadable)) { + // read can succeed. Never for a view-only wallet: there is no + // seed to read, and the tap could only ever fail. + if (walletReadable && !viewOnly && + !SeedBackupGate.warningVisible(seedConfirmed, walletReadable) + ) { Spacer(Modifier.height(8.dp)) OutlinedButton( onClick = { openSeedBackup() }, @@ -758,11 +961,24 @@ private fun TransferCard(t: TransferRow) { horizontalArrangement = Arrangement.SpaceBetween, ) { Column(modifier = Modifier.weight(1f)) { - Text( - t.txid.take(16) + "…", - style = MaterialTheme.typography.bodySmall, - fontFamily = FontFamily.Monospace, - ) + Row { + // The core's own `in` / `out` / `pending`, dim, before the + // txid. It is the only thing that tells a received transfer + // from a sent one — the amount is unsigned — so it goes first + // and the id is still truncated after it. + Text( + "${t.direction} ", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.testTag("wallet-transfer-direction"), + ) + Text( + t.txid.take(16) + "…", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + } Text( t.address, style = MaterialTheme.typography.labelSmall, @@ -864,7 +1080,7 @@ private fun WalletSetupCard( onImported: () -> Unit, onError: (String) -> Unit, create: suspend (String) -> Result, - importWallet: suspend (String, String, String) -> Result, + importSeed: suspend (String, String, String, String) -> Result, scope: CoroutineScope, ) { var accepted by remember { mutableStateOf(kind != SetupKind.Create) } @@ -876,6 +1092,9 @@ private fun WalletSetupCard( var offset by remember { mutableStateOf("") } var offsetAgain by remember { mutableStateOf("") } var offsetError by remember { mutableStateOf(null) } + // The optional restore height. Digits only, blank allowed; the core reads + // blank as "scan from 0". Not a secret, but nothing remembers it either. + var height by remember { mutableStateOf("") } val ready = password.isNotEmpty() && (kind == SetupKind.Create || seed.isNotBlank()) Card( @@ -966,6 +1185,26 @@ private fun WalletSetupCard( ) } Spacer(Modifier.height(8.dp)) + // Optional, and after the offset field because that is the order + // the restore reads in. Blank is not "0": the core omits the + // field entirely and the wallet scans from the start. + OutlinedTextField( + value = height, + onValueChange = { height = RestoreHeight.digitsOnly(it) }, + singleLine = true, + label = { Text("restore height (optional)") }, + supportingText = { + Text( + RestoreHeight.HELPER, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-restore-height-input"), + ) + Spacer(Modifier.height(8.dp)) } OutlinedTextField( value = password, @@ -1003,12 +1242,21 @@ private fun WalletSetupCard( offsetError = null // `typedOffset` is never logged, never put // in an error string, and dropped with this - // frame — see [WireViewModel.importWallet]. - importWallet(password, seed.trim(), typedOffset).fold( + // frame — see [WireViewModel.importSeed]. + // Offset and height ride the same RPC, so a + // height is never lost to a second call. + importSeed(password, seed.trim(), typedOffset, height).fold( onSuccess = { onImported() }, onFailure = { onError(it.message ?: it.toString()) }, ) } + // Unreachable: the wallet screen routes + // [SetupKind.ViewOnly] to [ViewOnlyImportCard], + // which has no seed and no offset. Spelled out + // rather than folded into an `else` so a future + // kind cannot silently import a wallet here. + SetupKind.ViewOnly -> + onError("view-only import uses its own card") } } }, @@ -1019,6 +1267,306 @@ private fun WalletSetupCard( } } +/** + * The view-only import: an address and its private view key, no seed. + * + * The view key is masked and re-typed like the seed-offset field, and for the + * same reason: a wrong view key does not fail — it opens a file that watches a + * *different* address, so the user would see an empty wallet and believe the + * funds were never there. The mismatch is refused on the card, before any RPC, + * with its own string (`view keys do not match`, never the offset's). + * + * Both key fields die with this composable. The key is never logged, never + * copied, never put in an error string, and there is no "show" toggle: the + * wallet file this creates holds it, and that is the only place it needs to be. + * + * `password` is the wallet **file** passphrase — the same field create/import + * carry — not the view key and not anything derived from it. + */ +@Composable +private fun ViewOnlyImportCard( + onCancel: () -> Unit, + onImported: () -> Unit, + onError: (String) -> Unit, + importViewOnly: suspend (String, String, String, String) -> Result, + scope: CoroutineScope, +) { + var address by remember { mutableStateOf("") } + var viewKey by remember { mutableStateOf("") } + var viewKeyAgain by remember { mutableStateOf("") } + var viewKeyError by remember { mutableStateOf(null) } + var height by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + val ready = address.isNotBlank() && viewKey.isNotBlank() && password.isNotEmpty() + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp) + .testTag("wallet-view-only-card"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("View-only wallet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + Text( + "Watch an address without holding its spend key. This file can " + + "see incoming transfers and cannot send.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = address, + onValueChange = { address = it }, + label = { Text("address") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-view-only-address"), + ) + Spacer(Modifier.height(8.dp)) + // Masked, like every other secret on this screen. A view key is not + // a spend key, but it unblinds every incoming output to this address, + // so it is treated as one. + OutlinedTextField( + value = viewKey, + onValueChange = { + viewKey = it + viewKeyError = null + }, + singleLine = true, + label = { Text("view key") }, + visualTransformation = PasswordVisualTransformation(), + isError = viewKeyError != null, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-view-only-key"), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = viewKeyAgain, + onValueChange = { + viewKeyAgain = it + viewKeyError = null + }, + singleLine = true, + label = { Text("re-type view key") }, + visualTransformation = PasswordVisualTransformation(), + isError = viewKeyError != null, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-view-only-key-retype"), + ) + val problem = viewKeyError + if (problem != null) { + Spacer(Modifier.height(4.dp)) + Text( + problem, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("wallet-view-only-error"), + ) + } + Spacer(Modifier.height(8.dp)) + // Same field, same helper, same rule as the seed import: blank scans + // from 0, digits only. The core refuses anything else locally. + OutlinedTextField( + value = height, + onValueChange = { height = RestoreHeight.digitsOnly(it) }, + singleLine = true, + label = { Text("restore height (optional)") }, + supportingText = { + Text( + RestoreHeight.HELPER, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-view-only-height"), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + singleLine = true, + label = { Text("wallet passphrase") }, + supportingText = { + Text( + "The password that locks this wallet file. It is sealed on " + + "this device, so the file reopens on the next start.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-view-only-passphrase"), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + Button( + onClick = { + scope.launch { + // The re-type gate runs before the RPC and never + // leaves the screen. A stored view key that does not + // match is one typo from watching the wrong address, + // and there is nothing here worth dialling for. + if (viewKey.trim() != viewKeyAgain.trim()) { + // Both fields cleared, so the user re-types the + // whole key rather than repairing one of two + // strings they cannot read. + viewKey = "" + viewKeyAgain = "" + viewKeyError = VIEW_KEY_MISMATCH + return@launch + } + viewKeyError = null + importViewOnly(password, address.trim(), viewKey.trim(), height).fold( + onSuccess = { onImported() }, + onFailure = { onError(it.message ?: it.toString()) }, + ) + } + }, + enabled = ready, + modifier = Modifier.testTag("wallet-view-only-import"), + ) { Text("Import") } + } + } + } +} + +/** + * The wallet's own send: a pasted address and an amount, then a confirm step. + * + * No friend picker, no memo, no camera. `wallet_send` is a plain local transfer + * to a raw address, so the address is what the user pasted and nothing else in + * this flow needs to exist. Invoice and Tip are the peer-onion paths and are + * untouched. + * + * The confirm step exists because a paste is not intent: the address is an + * opaque string, and a wrong one sends real money to nobody. The word is + * [WalletSendGate.CONFIRM_WORD] (`SEND`), deliberately not the seed gate's + * `SEEN` — the two mean different things and neither should unlock the other. + * + * Neither field reaches the SDK while either is blank, and neither is logged. + */ +@Composable +private fun SendComposer( + onCancel: () -> Unit, + onSend: (address: String, amount: String) -> Unit, +) { + var address by remember { mutableStateOf("") } + var amount by remember { mutableStateOf("") } + var confirming by remember { mutableStateOf(false) } + var confirmWord by remember { mutableStateOf("") } + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp) + .testTag("wallet-send-card"), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Send XMR", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(8.dp)) + if (!confirming) { + OutlinedTextField( + value = address, + onValueChange = { address = it }, + // Visible on purpose: this is an address, not a secret, and + // the user has to be able to check what they pasted. + label = { Text("address") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-send-address"), + ) + Spacer(Modifier.height(8.dp)) + OutlinedTextField( + value = amount, + onValueChange = { amount = it }, + singleLine = true, + label = { Text("amount XMR") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-send-amount"), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = onCancel) { Text("Cancel") } + TextButton( + onClick = { + confirming = true + confirmWord = "" + }, + // Both fields first; an empty one never reaches the + // confirm step, let alone the SDK. + enabled = WalletSendGate.ready(address, amount), + modifier = Modifier.testTag("wallet-send-review"), + ) { Text("Review") } + } + } else { + // Both values read back verbatim: the amount so a wrong decimal + // is visible, the address whole rather than truncated, because + // the whole point of the step is to look at it. + Text("address", style = MaterialTheme.typography.labelSmall) + Text( + address, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-send-confirm-address"), + ) + Spacer(Modifier.height(8.dp)) + Text("amount", style = MaterialTheme.typography.labelSmall) + Text( + "$amount XMR", + style = MaterialTheme.typography.bodyMedium, + fontFamily = FontFamily.Monospace, + modifier = Modifier.testTag("wallet-send-confirm-amount"), + ) + Spacer(Modifier.height(12.dp)) + Text( + WalletSendGate.CONFIRM_PROMPT, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(4.dp)) + OutlinedTextField( + value = confirmWord, + onValueChange = { confirmWord = it }, + singleLine = true, + label = { Text("type ${WalletSendGate.CONFIRM_WORD}") }, + modifier = Modifier + .fillMaxWidth() + .testTag("wallet-send-confirm-input"), + ) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton( + onClick = { + confirming = false + confirmWord = "" + }, + ) { Text("Back") } + Button( + onClick = { onSend(address.trim(), amount.trim()) }, + enabled = WalletSendGate.confirmEnabled(confirmWord), + modifier = Modifier.testTag("wallet-send-confirm-send"), + ) { Text("Send") } + } + } + } + } +} + /** * The app-owned `monero-wallet-rpc` control (issue #107), now with the third chain * source: the chain daemon **inside this app** (Cuprate). diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt index 1346401..5bb8fe8 100644 --- a/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/SeedBackupGateTest.kt @@ -255,4 +255,138 @@ class SeedBackupGateTest { // two are separate constants so neither can drift into the other. assertNotEquals(SeedBackupGate.WARNING, text) } + + // --- a view-only (watch-only) wallet ------------------------------------ + + @Test + fun a_view_only_wallet_hides_the_unbacked_seed_warning() { + // The case that matters most: a fresh create's flag is `false`, and a + // view-only file would otherwise be told to write down 25 words that do + // not exist. This is the flash the session flag on the screen exists to + // prevent before the core's probe answers. + assertFalse(SeedBackupGate.warningVisible(false, readable, viewOnly = true)) + assertFalse(SeedBackupGate.warningVisible(null, readable, viewOnly = true)) + assertFalse(SeedBackupGate.warningVisible(false, notReadable, viewOnly = true)) + } + + @Test + fun a_view_only_wallet_shows_its_receive_address() { + // An address nobody can back up is one the owner has to be able to share. + assertTrue(SeedBackupGate.receiveAddressVisible(false, readable, viewOnly = true)) + assertTrue( + SeedBackupGate.receiveAddressVisible( + confirmed = false, + walletReadable = readable, + offsetPending = true, + viewOnly = true, + ), + ) + assertEquals( + SeedBackupGate.WalletGateCard.None, + SeedBackupGate.card(false, readable, offsetPending = true, viewOnly = true), + ) + } + + @Test + fun view_only_false_keeps_every_existing_rule() { + // The default is the old behaviour, so nothing that predates this input + // changes meaning. Each pair is the same call with the input omitted and + // with it explicitly false. + assertEquals( + SeedBackupGate.warningVisible(false, readable), + SeedBackupGate.warningVisible(false, readable, viewOnly = false), + ) + assertTrue(SeedBackupGate.warningVisible(false, readable, viewOnly = false)) + assertFalse(SeedBackupGate.receiveAddressVisible(false, readable, viewOnly = false)) + assertTrue(SeedBackupGate.receiveAddressVisible(true, readable, viewOnly = false)) + // The offset card still wins when there is no view-only wallet. + assertEquals( + SeedBackupGate.WalletGateCard.OffsetNotSaved, + SeedBackupGate.card(true, readable, offsetPending = true, viewOnly = false), + ) + assertEquals( + SeedBackupGate.WalletGateCard.UnbackedSeed, + SeedBackupGate.card(false, readable, viewOnly = false), + ) + } + + // --- the restore height on both import cards ---------------------------- + + @Test + fun the_restore_height_field_takes_digits_and_nothing_else() { + assertEquals("", RestoreHeight.digitsOnly("")) + assertEquals("3210000", RestoreHeight.digitsOnly("3210000")) + // A paste, a stray keystroke, a formatted number: all filtered at the + // field, because the core refuses a non-block-number locally anyway. + assertEquals("3210000", RestoreHeight.digitsOnly("3,210,000")) + assertEquals("3210000", RestoreHeight.digitsOnly(" 3210000 ")) + assertEquals("3210000", RestoreHeight.digitsOnly("h3210000")) + assertEquals("", RestoreHeight.digitsOnly("abc")) + // Nothing negative survives: a `-` is dropped and the digits stay. + assertEquals("12", RestoreHeight.digitsOnly("-12")) + } + + @Test + fun a_blank_restore_height_is_not_zero_and_not_an_error() { + // Blank is the core's "scan from 0" — the request carries no field at + // all — so the field must hand it through empty, never as a literal "0". + // Whitespace-only goes the same way: the digits filter strips it to "". + assertEquals("", RestoreHeight.digitsOnly("")) + assertEquals("", RestoreHeight.digitsOnly(" ")) + // A typed zero is a real height and stays one: this is the one place the + // blank/zero distinction is visible on the Kotlin side. + assertEquals("0", RestoreHeight.digitsOnly("0")) + // The helper names the trap it is there to prevent. + assertTrue(RestoreHeight.HELPER.contains("Blank scans from 0")) + assertTrue(RestoreHeight.HELPER.contains("hides older funds")) + } + + // --- the send composer's confirm step ----------------------------------- + + @Test + fun the_send_word_is_not_the_seed_word() { + assertEquals("SEND", WalletSendGate.CONFIRM_WORD) + // A user who learned the seed gate's word must not be able to spend by + // reflex, and vice versa. + assertNotEquals(SeedBackupGate.CONFIRM_WORD, WalletSendGate.CONFIRM_WORD) + assertFalse(WalletSendGate.accepts(SeedBackupGate.CONFIRM_WORD)) + assertFalse(SeedBackupGate.accepts(WalletSendGate.CONFIRM_WORD)) + } + + @Test + fun the_send_word_releases_the_send_whatever_its_case_or_padding() { + assertTrue(WalletSendGate.accepts("SEND")) + assertTrue(WalletSendGate.accepts("send")) + assertTrue(WalletSendGate.accepts(" SeNd ")) + assertFalse(WalletSendGate.accepts("")) + assertFalse(WalletSendGate.accepts(" ")) + assertFalse(WalletSendGate.accepts("SEN")) + assertFalse(WalletSendGate.accepts("SENDS")) + } + + @Test + fun send_is_dead_until_the_word_is_right() { + assertFalse(WalletSendGate.confirmEnabled("")) + assertFalse(WalletSendGate.confirmEnabled("SENDX")) + assertTrue(WalletSendGate.confirmEnabled("SEND")) + assertTrue(WalletSendGate.confirmEnabled("send")) + } + + @Test + fun an_empty_field_never_reaches_the_confirm_or_the_sdk() { + assertFalse(WalletSendGate.ready("", "")) + assertFalse(WalletSendGate.ready("4abc", "")) + assertFalse(WalletSendGate.ready("", "0.5")) + // Whitespace is empty, the same rule the core's own local check applies. + assertFalse(WalletSendGate.ready(" ", "0.5")) + assertFalse(WalletSendGate.ready("4abc", " ")) + assertTrue(WalletSendGate.ready("4abc", "0.5")) + assertTrue(WalletSendGate.ready(" 4abc ", " 0.5 ")) + } + + @Test + fun the_send_confirm_prompt_names_the_word() { + assertTrue(WalletSendGate.CONFIRM_PROMPT.contains("SEND")) + assertTrue(WalletSendGate.CONFIRM_PROMPT.contains("cannot be undone")) + } } 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" + ); +}