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")) + } }