diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt index 1d14fa6..200c2b8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/MainActivity.kt @@ -29,6 +29,7 @@ import com.siriusdevops.onionwire.ui.RosterScreen import com.siriusdevops.onionwire.ui.RotateScreen import com.siriusdevops.onionwire.ui.ShareInviteScreen import com.siriusdevops.onionwire.ui.UnlockScreen +import com.siriusdevops.onionwire.ui.WalletManagerScreen import com.siriusdevops.onionwire.ui.WalletScreen import com.siriusdevops.onionwire.ui.OnionWireTheme import kotlinx.coroutines.launch @@ -133,7 +134,15 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: Str } composable("wallet") { - WalletScreen(vm = vm, onBack = { nav.popBackStack() }) + WalletScreen( + vm = vm, + onBack = { nav.popBackStack() }, + onOpenWallets = { nav.navigate("wallets") }, + ) + } + + composable("wallets") { + WalletManagerScreen(vm = vm, onBack = { nav.popBackStack() }) } composable( 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 7be3c6a..3c071c8 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -41,6 +41,8 @@ import uniffi.onionwire_sdk.RotateOutcome import uniffi.onionwire_sdk.SendState import uniffi.onionwire_sdk.TransferRow import uniffi.onionwire_sdk.WalletChildStatus +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow import uniffi.onionwire_sdk.Wire import uniffi.onionwire_sdk.decodeInvite import java.io.File @@ -619,6 +621,50 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { suspend fun walletSeed(): Result = runCatching { requireWire().walletSeed() } + // --- Wallet catalogue, the open wallet, and its secrets ---------------- + // The saved-wallets screen's reads. The catalogue is a store read that + // never dials, so it goes to [Dispatchers.IO] like the other store reads in + // this file — a SQLCipher decrypt on the main thread is an ANR waiting for a + // slow device. + + /** + * Every wallet this install remembers, oldest first. + * + * A store read: it works with the wallet child stopped or never configured, + * and "no wallets" is an empty list rather than a failure — the caller must + * not render the two alike. + */ + suspend fun wallets(): Result> = + withContext(Dispatchers.IO) { runCatching { requireWire().wallets() } } + + /** + * The file name of the wallet the child currently has open, or null when it + * has none. The catalogue's in-use marker is this and nothing else. + */ + suspend fun activeWalletFilename(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().activeWalletFilename() } } + + /** + * Point the wallet child at a catalogue wallet's file. + * + * Slow on purpose: a live child is stopped and started again onto the new + * file. The core refuses a name the catalogue does not hold, and that + * refusal is surfaced verbatim to the caller. + */ + suspend fun openWallet(filename: String): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().openWallet(filename) } } + + /** + * The **open** wallet's private keys, for the saved-wallets screen. + * + * Both values are spend secrets: only ever called from an explicit tap, + * never logged, never persisted, and dropped when the screen goes. There is + * deliberately no accessor for another catalogue row's keys — the only way + * to read a saved wallet's keys is to open it first. + */ + suspend fun walletKeys(): Result = + withContext(Dispatchers.IO) { runCatching { requireWire().walletKeys() } } + fun spendAuthorityWarning(): String = runCatching { requireWire().spendAuthorityWarning() }.getOrElse { diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt new file mode 100644 index 0000000..d041575 --- /dev/null +++ b/android/app/src/main/java/com/siriusdevops/onionwire/ui/WalletManagerScreen.kt @@ -0,0 +1,584 @@ +package com.siriusdevops.onionwire.ui + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.siriusdevops.onionwire.WireViewModel +import kotlinx.coroutines.launch +import uniffi.onionwire_sdk.WalletKeys +import uniffi.onionwire_sdk.WalletRow +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +// --------------------------------------------------------------------------- +// The rules this screen renders from, as pure Kotlin so `WalletManagerTest` +// covers them on the JVM without a device. Same shape as `SeedBackupGate` and +// `WalletChildStatusText`: the composables below only lay these decisions out. +// --------------------------------------------------------------------------- + +/** + * A catalogue row's label: the user's name for the wallet, or the file name + * when there is none. + * + * `WalletRow.name` is documented as `None` when the wallet was never named and + * "never an empty string", but a blank string is treated as absent here too — + * a row labelled with spaces is a row the user cannot identify. + */ +internal fun walletRowLabel(name: String?, filename: String): String = + name?.takeIf { it.isNotBlank() } ?: filename + +/** + * A row's creation date, from the store's unix seconds. + * + * `created_at <= 0` is not a date: the store assigns it on insert, so anything + * else is a row that predates that — say so rather than render 1970. + */ +internal fun walletRowDate(createdAt: Long): String { + if (createdAt <= 0L) return "date unknown" + return Instant.ofEpochSecond(createdAt) + .atZone(ZoneId.systemDefault()) + .format(DateTimeFormatter.ISO_LOCAL_DATE) +} + +/** + * Whether the wallet child has a wallet open that the RPC answers for. + * + * The core's `state` is the only honest signal available here: `connecting` + * means its wallet RPC has not answered, `off`/`exited` mean there is no child + * at all, and `syncing`/`ready` mean it answered — the chain being behind is + * irrelevant to whether the open wallet's keys can be read. A `null` state is + * "nothing read yet", which is not readable. + */ +internal fun walletChildReadable(state: String?): Boolean = + state == "ready" || state == "syncing" + +/** + * Whether the open wallet's secrets may be offered for the row named + * [rowFilename]. + * + * Both halves are load-bearing: + * + * - **active**: the seed and the private keys come from `query_key` against + * the file the child currently has open, so they belong to exactly one + * wallet. A non-active row's buttons stay dead instead of quietly opening + * that wallet under the user — switching is a deliberate tap, not a side + * effect of asking for a backup. + * - **readable**: with no child running there is no file open, and + * `wallet_seed()` / `wallet_keys()` can only fail. Offering a button that + * always errors is worse than saying why it is off. + */ +internal fun walletSecretsEnabled( + activeFilename: String?, + rowFilename: String, + walletReadable: Boolean, +): Boolean = walletReadable && activeFilename != null && activeFilename == rowFilename + +/** + * Why the secret actions are off, in words — or `null` when they are on. + * + * The two reasons are different states of the world and are not collapsed: + * "this is not the open wallet" is fixed by tapping the row, "the child is not + * running" is fixed on the wallet screen. The first wording is the card's own. + */ +internal fun walletSecretsBlockedReason( + isActive: Boolean, + walletReadable: Boolean, +): String? = when { + !isActive -> "open this wallet to view its backup" + !walletReadable -> "the wallet child is not running — start it on the wallet screen to read the backup" + else -> null +} + +/** + * The saved-wallet catalogue: every wallet this install remembers, which one is + * open now, and — for that one — its recovery phrase and private keys. + * + * Three properties are deliberate and are the whole point of the screen: + * + * - The catalogue is re-read on entry and on Refresh, never cached from app + * start, so a wallet created on the wallet screen after this screen was + * first opened shows up without restarting the app. + * - A tap opens a row's file through `open_wallet(filename)` and reloads, so + * the in-use marker moves. The core refuses a name outside the catalogue, + * and its refusal is shown verbatim. + * - The secrets belong to the **open** wallet only. They are read on an + * explicit tap, are never shown for a row that is not the open one, and are + * never logged, persisted, put in a `testTag`/`contentDescription`, or held + * in saved state (`remember`, not `rememberSaveable`, and cleared on + * dispose). + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun WalletManagerScreen( + vm: WireViewModel, + onBack: () -> Unit, +) { + val child by vm.walletChild.collectAsStateWithLifecycle() + val scope = rememberCoroutineScope() + + /** `null` is "not read yet"; an empty list is a catalogue with no rows. */ + var rows by remember { mutableStateOf?>(null) } + /** The file name the core reports as open, or null when it reports none. */ + var active by remember { mutableStateOf(null) } + /** A catalogue/active-wallet read failure, distinct from an empty list. */ + var listError by remember { mutableStateOf(null) } + /** A failed open, verbatim from the core. */ + var actionError by remember { mutableStateOf(null) } + /** The file name currently being opened, so the row can say so. */ + var opening by remember { mutableStateOf(null) } + + // The seed on the blocking card, and the typed confirm word. Neither is + // persisted: a spend key lives in this composition and nowhere else. + var seed by remember { mutableStateOf(null) } + var seedConfirm by remember { mutableStateOf("") } + // The open wallet's private keys, only ever set by an explicit tap on + // "Private keys". Null means no card. + var keys by remember { mutableStateOf(null) } + var keysError by remember { mutableStateOf(null) } + + suspend fun reload() { + vm.wallets().fold( + onSuccess = { + rows = it + listError = null + }, + onFailure = { + rows = null + listError = it.message ?: it.toString() + }, + ) + vm.activeWalletFilename().fold( + onSuccess = { active = it }, + onFailure = { + // Same store as the list: a failure here is a read failure, not + // "no wallet is open", and it must not be rendered as one. + active = null + if (listError == null) { + listError = it.message ?: it.toString() + } + }, + ) + } + + /** Open a row's file, then re-read so the in-use marker moves. */ + fun open(filename: String) { + if (opening != null) return + scope.launch { + actionError = null + opening = filename + vm.openWallet(filename).fold( + onSuccess = { reload() }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + opening = null + } + } + + /** + * "Recovery phrase": re-read the open wallet's 25 words and put them on the + * existing blocking card. Same treatment as the wallet screen's "Back up + * seed" — one gate, one card, no second ungated display. + */ + fun showPhrase() { + scope.launch { + actionError = null + vm.walletSeed().fold( + onSuccess = { + seed = it + seedConfirm = "" + }, + onFailure = { actionError = it.message ?: it.toString() }, + ) + } + } + + /** + * "Private keys": read the open wallet's keys once, on this tap. Failure is + * shown where the card would be, so a wallet that cannot answer says so + * instead of looking like an empty one. + */ + fun showKeys() { + scope.launch { + actionError = null + keysError = null + vm.walletKeys().fold( + onSuccess = { keys = it }, + onFailure = { keysError = it.message ?: it.toString() }, + ) + } + } + + LaunchedEffect(Unit) { + // The cached child read never dials, so the screen paints; the live + // probe after it is what tells the truth about whether a wallet is + // open, which is what the secret actions hang on. + vm.paintWalletChildCached() + reload() + vm.refreshWalletChild() + } + + // Nothing here is `rememberSaveable`, so leaving the screen drops the + // composition's state — including the seed and the keys. Dropping the + // reference is the strongest wipe a Kotlin String allows (see + // `SeedBackupCard`); this makes it explicit rather than incidental. + DisposableEffect(Unit) { + onDispose { + seed = null + seedConfirm = "" + keys = null + keysError = null + } + } + + val walletReadable = walletChildReadable(child?.state) + + Scaffold( + // Root owns systemBars ∪ ime, exactly as the wallet screen does (see + // `screenContentInsets`). + contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + TopAppBar( + title = { Text("Saved wallets") }, + navigationIcon = { + TextButton(onClick = onBack) { Text("Back") } + }, + actions = { + TextButton( + onClick = { + scope.launch { + vm.refreshWalletChild() + reload() + } + }, + ) { Text("Refresh") } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + ), + ) + }, + ) { pad -> + Column( + Modifier + .padding(pad) + .fillMaxSize() + .screenContentInsets() + .verticalScroll(rememberScrollState()), + ) { + // The blocking seed card, when a phrase is on screen: the whole + // body, exactly as on the wallet screen. Done is dead until the + // confirm word is typed, and the app-bar Back still leaves. + val shownSeed = seed + if (shownSeed != null) { + SeedBackupCard( + seed = shownSeed, + typed = seedConfirm, + onTyped = { seedConfirm = it }, + onDone = { + vm.confirmWalletSeed(seedConfirm) + seed = null + seedConfirm = "" + }, + ) + actionError?.let { ErrorText(it) } + return@Column + } + + keys?.let { k -> + PrivateKeysCard( + keys = k, + warning = vm.spendAuthorityWarning(), + onDone = { keys = null }, + ) + } + keysError?.let { message -> + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("could not read the open wallet's private keys") + Spacer(Modifier.height(4.dp)) + Text(message, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { keysError = null }) { Text("Dismiss") } + } + } + } + + actionError?.let { ErrorText(it) } + + val listed = rows + when { + // A read failure is not an empty catalogue, and the two must + // not read alike: one is "the store did not answer", the other + // is "you have no wallets yet". + listError != null -> Column(Modifier.padding(12.dp)) { + Text( + "could not read the wallet catalogue", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(4.dp)) + Text( + listError ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + Spacer(Modifier.height(8.dp)) + TextButton(onClick = { scope.launch { reload() } }) { Text("Retry") } + } + + listed == null -> Text( + "loading…", + style = MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(12.dp), + ) + + listed.isEmpty() -> Column(Modifier.padding(12.dp)) { + Text("No saved wallets yet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text( + "Wallets this install remembers show up here. Create or import one " + + "on the wallet screen and it appears on the next look.", + style = MaterialTheme.typography.bodySmall, + ) + Spacer(Modifier.height(8.dp)) + Button(onClick = onBack) { Text("Create or import a wallet") } + } + + else -> { + Text( + "${listed.size} saved ${if (listed.size == 1) "wallet" else "wallets"}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + listed.forEach { row -> + val isActive = active != null && active == row.walletFilename + WalletRowCard( + row = row, + isActive = isActive, + secretsEnabled = walletSecretsEnabled( + activeFilename = active, + rowFilename = row.walletFilename, + walletReadable = walletReadable, + ), + blockedReason = walletSecretsBlockedReason( + isActive = isActive, + walletReadable = walletReadable, + ), + opening = opening == row.walletFilename, + onOpen = { open(row.walletFilename) }, + onShowPhrase = { showPhrase() }, + onShowKeys = { showKeys() }, + ) + } + } + } + } + } +} + +/** + * One catalogue row: what it is called, which file it is, when it was created, + * and whether it is the open one. + * + * The open row is not tappable. Re-opening it would stop and restart a running + * wallet child onto the file it already has open — a slow no-op whose only + * effect is to make the screen look like it did something. + */ +@Composable +private fun WalletRowCard( + row: WalletRow, + isActive: Boolean, + secretsEnabled: Boolean, + blockedReason: String?, + opening: Boolean, + onOpen: () -> Unit, + onShowPhrase: () -> Unit, + onShowKeys: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 6.dp) + .then(if (isActive) Modifier else Modifier.clickable(enabled = !opening, onClick = onOpen)), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column(Modifier.padding(12.dp)) { + Row( + Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + walletRowLabel(row.name, row.walletFilename), + style = MaterialTheme.typography.titleSmall, + ) + when { + isActive -> Text( + "in use", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + opening -> Text( + "opening…", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + else -> Text( + "tap to open", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + Spacer(Modifier.height(4.dp)) + Text( + "file ${row.walletFilename}", + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Text( + "created ${walletRowDate(row.createdAt)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Spacer(Modifier.height(8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = onShowPhrase, enabled = secretsEnabled) { + Text("Recovery phrase") + } + OutlinedButton(onClick = onShowKeys, enabled = secretsEnabled) { + Text("Private keys") + } + } + blockedReason?.let { + Spacer(Modifier.height(4.dp)) + Text( + it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} + +/** + * The open wallet's private keys, shown only after an explicit tap. + * + * The view key is always there; the spend key only when the wallet has one. + * A view-only wallet says so in words — it has no spend key, and rendering + * that as a failure would teach the user to read a normal wallet as a broken + * one. The values are spend secrets: no `testTag`, no `contentDescription`, + * no logging, no persistence, and the card is dropped when the screen goes. + */ +@Composable +private fun PrivateKeysCard( + keys: WalletKeys, + warning: String, + onDone: () -> Unit, +) { + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 8.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + ), + ) { + Column(Modifier.padding(12.dp)) { + Text("Private keys of the open wallet", style = MaterialTheme.typography.titleSmall) + Spacer(Modifier.height(4.dp)) + Text(warning, style = MaterialTheme.typography.bodySmall) + Spacer(Modifier.height(8.dp)) + Text( + "view key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + keys.viewKey, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + Spacer(Modifier.height(8.dp)) + val spend = keys.spendKey + if (spend != null) { + Text( + "spend key", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + spend, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + } else { + Text( + "view-only wallet — no spend key", + style = MaterialTheme.typography.bodyMedium, + ) + } + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + Button(onClick = onDone) { Text("Done") } + } + } + } +} + +/** A display-ready failure line. Never carries a secret; callers pass errors. */ +@Composable +private fun ErrorText(text: String) { + Text( + text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) +} 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 ec98015..f6ea31c 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 @@ -70,6 +70,7 @@ private enum class SetupKind { Create, Import } fun WalletScreen( vm: WireViewModel, onBack: () -> Unit, + onOpenWallets: () -> Unit, ) { val friends by vm.friends.collectAsStateWithLifecycle() val child by vm.walletChild.collectAsStateWithLifecycle() @@ -161,6 +162,12 @@ fun WalletScreen( navigationIcon = { TextButton(onClick = onBack) { Text("Back") } }, + // The saved-wallet catalogue is its own screen: this one is the + // open wallet, and switching wallets restarts the child, so the + // picker does not belong in this page's scroll. + actions = { + TextButton(onClick = onOpenWallets) { Text("Wallets") } + }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.background, ), @@ -548,9 +555,14 @@ private fun UnbackedSeedCard( * The seed is a Kotlin `String`, so it cannot be wiped in place the way the * TUI's `Zeroizing` is; dropping the reference is the strongest thing * available here. That is another reason it is never written to disk. + * + * `internal` rather than `private`: the saved-wallets screen shows the same + * card for the open wallet's recovery phrase, and a second copy of this gate + * (or of its constants) is the thing that would eventually disagree with this + * one. */ @Composable -private fun SeedBackupCard( +internal fun SeedBackupCard( seed: String, typed: String, onTyped: (String) -> Unit, diff --git a/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt new file mode 100644 index 0000000..99a35e4 --- /dev/null +++ b/android/app/src/test/java/com/siriusdevops/onionwire/ui/WalletManagerTest.kt @@ -0,0 +1,153 @@ +package com.siriusdevops.onionwire.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The saved-wallets screen's rules, on the JVM. + * + * These are the decisions the screen renders from: what a catalogue row is + * called, whether the child has a wallet open at all, and whether the two + * secret actions may be offered for a given row. Pure logic, so no Robolectric + * and no Compose test dependency — same shape as `SeedBackupGateTest` and + * `WalletChildStatusTextTest`. + */ +class WalletManagerTest { + + private val openFile = "onionwire-main" + private val otherFile = "onionwire-second" + + /** The core's `wallet_status().state` for a child that answered. */ + private val readable = true + + /** No child, or one whose wallet RPC has not answered. */ + private val notReadable = false + + // --- what a row is called ----------------------------------------------- + + @Test + fun a_named_wallet_is_labelled_with_its_name() { + assertEquals("spending", walletRowLabel("spending", openFile)) + } + + @Test + fun an_unnamed_wallet_falls_back_to_its_file_name() { + assertEquals(openFile, walletRowLabel(null, openFile)) + } + + @Test + fun a_blank_name_counts_as_absent() { + // `WalletRow.name` is documented as never an empty string, but a + // whitespace label is a row the user cannot identify either way. + assertEquals(openFile, walletRowLabel("", openFile)) + assertEquals(openFile, walletRowLabel(" ", openFile)) + } + + @Test + fun a_name_is_not_trimmed_out_of_the_label() { + // Only the *blank* case falls back. A name with padding is still the + // user's name and is shown as stored. + assertEquals(" spending ", walletRowLabel(" spending ", openFile)) + } + + // --- is the child reading a wallet at all -------------------------------- + + @Test + fun only_an_answered_wallet_rpc_counts_as_readable() { + // `connecting` is "the RPC has not answered"; `off` and `exited` are + // "there is no child". None of them can answer a key query. + assertTrue(walletChildReadable("ready")) + assertTrue(walletChildReadable("syncing")) + assertFalse(walletChildReadable("connecting")) + assertFalse(walletChildReadable("off")) + assertFalse(walletChildReadable("exited")) + } + + @Test + fun nothing_read_yet_is_not_readable() { + assertFalse(walletChildReadable(null)) + } + + @Test + fun a_behind_chain_still_counts_as_readable() { + // Syncing means the RPC answered: the wallet's keys do not need the + // chain to be caught up. + assertTrue(walletChildReadable("syncing")) + } + + // --- whether the secret actions are offered ------------------------------ + + @Test + fun the_open_wallets_secrets_are_offered() { + assertTrue(walletSecretsEnabled(openFile, openFile, readable)) + } + + @Test + fun another_wallets_secrets_are_not_offered() { + // The seed and the keys come from the file the child has open. A row + // that is not the open one must not read as its own backup. + assertFalse(walletSecretsEnabled(openFile, otherFile, readable)) + } + + @Test + fun nothing_open_means_no_secrets_for_any_row() { + assertFalse(walletSecretsEnabled(null, openFile, readable)) + } + + @Test + fun the_open_wallet_offers_no_secrets_while_the_child_is_not_reading_it() { + // Active but no answer: `wallet_seed()` / `wallet_keys()` can only + // fail, so the buttons stay dead rather than always erroring. + assertFalse(walletSecretsEnabled(openFile, openFile, notReadable)) + assertFalse(walletSecretsEnabled(openFile, otherFile, notReadable)) + assertFalse(walletSecretsEnabled(null, openFile, notReadable)) + } + + // --- and why they are off, in words -------------------------------------- + + @Test + fun an_enabled_row_has_nothing_to_explain() { + assertNull(walletSecretsBlockedReason(isActive = true, walletReadable = readable)) + } + + @Test + fun a_row_that_is_not_open_says_to_open_it() { + val why = walletSecretsBlockedReason(isActive = false, walletReadable = readable) + assertEquals("open this wallet to view its backup", why) + } + + @Test + fun an_open_wallet_with_no_child_says_the_child_is_not_running() { + val why = walletSecretsBlockedReason(isActive = true, walletReadable = notReadable) + assertTrue(why != null && why.contains("not running")) + // The two reasons are different fixes and must not read alike. + assertFalse(why == walletSecretsBlockedReason(isActive = false, walletReadable = readable)) + } + + // --- the created-at column ---------------------------------------------- + + @Test + fun a_stored_created_at_renders_as_a_date() { + // 2021-01-01T00:00:00Z. + val rendered = walletRowDate(1609459200L) + assertTrue("got '$rendered'", Regex("""\d{4}-\d{2}-\d{2}""").matches(rendered)) + } + + @Test + fun a_later_created_at_sorts_after_an_earlier_one() { + // The store hands the rows back oldest-first; the rendered date must + // not invert that order in the list. + assertTrue(walletRowDate(1700000000L) > walletRowDate(1609459200L)) + } + + @Test + fun a_row_with_no_assigned_created_at_says_so() { + // The store assigns `created_at` on insert, so 0 is a row that predates + // that — not 1970, and not "today". + assertEquals("date unknown", walletRowDate(0L)) + assertEquals("date unknown", walletRowDate(-1L)) + } +}