diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 77fff79b..82257c49 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -255,6 +255,27 @@
Read to the end of the list to sign.
Recovery phrase
Recovery code
+ Your recovery code is nine blocks of four letters and digits. It is the only way back to this profile: the key that signs as you is derived from it.\n\nOnly you have this code. Keep it private — nobody from Giza will ever ask you for it.\n\nWrite all nine blocks down and keep them somewhere safe that is not this phone. If you lose both the phone and the code, this profile is gone for good.
+ Display recovery code
+ Unlocking your code…
+ Keep this code safe.\nDo not share it.
+ The ninth block is part of the code. Write down all nine.
+ Block %1$d
+ Could not unlock your recovery code. Please try again.
+ This device holds no recovery code for the profile that is signed in.
+ No profile is open, so there is no recovery code to show.
+ Show the recovery phrase instead
+ You have not backed up your recovery code
+ Use this profile in another app
+ These 24 words are this profile for apps that take a recovery phrase. Your recovery code is still your backup — these words can't give it back.
+ Show the words
+ To check your backup, type block %1$d and block %2$d from what you wrote down.
+ Check backup
+ Those blocks don't match the code. Check what you wrote down and try again.
+ Your code could not be read to check against. Please try again.
+ Your backup matches your recovery code.
+ I understand that if I lose this phone and my recovery code, I lose this profile.
+ Write down and secure the nine-block code that this profile is derived from.
Ready to sign
Recents
Reindex events
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt
index 155ca4df..d9ae370e 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/KeyRecoveryScreen.kt
@@ -16,6 +16,7 @@ import androidx.compose.material.icons.filled.AddToDrive
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.LocalHospital
import androidx.compose.material.icons.filled.Key
+import androidx.compose.material.icons.filled.Password
import androidx.compose.material.icons.filled.Spellcheck
import androidx.compose.material.icons.filled.VolunteerActivism
import androidx.compose.material.icons.filled.Warning
@@ -53,7 +54,9 @@ import mobi.giza.compose.resources.encrypt_and_back_your_recovery_information
import mobi.giza.compose.resources.key_recovery
import mobi.giza.compose.resources.not_backed_up_yet
import mobi.giza.compose.resources.nostr_secret_key
+import mobi.giza.compose.resources.recovery_code
import mobi.giza.compose.resources.recovery_phrase
+import mobi.giza.compose.resources.write_down_and_secure_the_nine_block_code
import mobi.giza.compose.resources.store_the_nsec_that_signs_as_this_profile
import mobi.giza.compose.resources.these_are_your_keys_keep_them_safe_no_wallet
import mobi.giza.compose.resources.you_said_you_stored_it
@@ -66,6 +69,7 @@ import org.jetbrains.compose.resources.stringResource
import mobi.giza.compose.extensions.hexToNpubHrp
import mobi.giza.compose.ui.composable.navigation.routes.ImplementationPendingRoute
import mobi.giza.compose.ui.composable.navigation.routes.NostrSecretRoute
+import mobi.giza.compose.ui.composable.navigation.routes.RecoveryCodeRoute
import mobi.giza.compose.ui.composable.navigation.routes.RecoveryPhraseRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.widgets.Decorative
@@ -186,8 +190,31 @@ fun KeyRecoveryScreen(
// identity the phrase option through an `else`.
IdentityKind.NostrPublic -> Unit
+ // Nine blocks for a profile made from a code. Its 24 words are on the
+ // code's own screen, for other apps; the code is the backup.
+ IdentityKind.RecoveryCode -> KeyRecoveryOption(
+ icon = Icons.Default.Password,
+ title = stringResource(Res.string.recovery_code),
+ description = stringResource(Res.string.write_down_and_secure_the_nine_block_code),
+ containerColor = MaterialTheme.colorScheme.secondaryContainer,
+ contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
+ status = if (showBackupNotice) {
+ KeyRecoveryStatus(
+ icon = Icons.Default.Warning,
+ text = stringResource(Res.string.not_backed_up_yet)
+ )
+ } else {
+ KeyRecoveryStatus(
+ icon = Icons.Default.CheckCircle,
+ text = stringResource(Res.string.you_said_you_wrote_it_down)
+ )
+ },
+ onClick = {
+ onNavigateToRoute.invoke(RecoveryCodeRoute)
+ }
+ )
+
IdentityKind.Mnemonic,
- IdentityKind.RecoveryCode,
null -> KeyRecoveryOption(
icon = Icons.Default.Spellcheck,
title = stringResource(Res.string.recovery_phrase),
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/RecoveryCodeScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/RecoveryCodeScreen.kt
new file mode 100644
index 00000000..35519cdb
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/RecoveryCodeScreen.kt
@@ -0,0 +1,515 @@
+package mobi.giza.compose.ui.composable
+
+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.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.foundation.text.input.TextFieldLineLimits
+import androidx.compose.foundation.text.input.rememberTextFieldState
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Visibility
+import androidx.compose.material.icons.filled.VisibilityOff
+import androidx.compose.material.icons.filled.Warning
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.Checkbox
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TopAppBar
+import androidx.compose.material3.minimumInteractiveComponentSize
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontFamily
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.KeyboardCapitalization
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.style.TextAlign
+import androidx.lifecycle.viewmodel.compose.viewModel
+import fr.acinq.phoenix.PhoenixGlobal
+import kotlinx.coroutines.flow.StateFlow
+import mobi.giza.compose.identity.Identity
+import mobi.giza.compose.identity.recoverycode.RecoveryCode
+import mobi.giza.compose.resources.Res
+import mobi.giza.compose.resources.backup_confirmation
+import mobi.giza.compose.resources.block_number
+import mobi.giza.compose.resources.check_backup
+import mobi.giza.compose.resources.could_not_unlock_your_recovery_code
+import mobi.giza.compose.resources.display_recovery_code
+import mobi.giza.compose.resources.hide
+import mobi.giza.compose.resources.i_understand_that_if_i_lose_this_phone_and_my_code
+import mobi.giza.compose.resources.keep_this_code_safe_do_not_share_it
+import mobi.giza.compose.resources.loading_preferences
+import mobi.giza.compose.resources.lose_this_phone_before_you_do_and_the
+import mobi.giza.compose.resources.no_profile_is_open_so_there_is_no_code_to_show
+import mobi.giza.compose.resources.recovery_code
+import mobi.giza.compose.resources.show_the_recovery_phrase_instead
+import mobi.giza.compose.resources.show_the_words
+import mobi.giza.compose.resources.the_ninth_block_is_part_of_the_code
+import mobi.giza.compose.resources.the_recovery_code_is_nine_blocks
+import mobi.giza.compose.resources.these_24_words_are_this_profile_for_other_apps
+import mobi.giza.compose.resources.this_device_holds_no_code_for_this_profile
+import mobi.giza.compose.resources.those_blocks_do_not_match
+import mobi.giza.compose.resources.type_blocks_from_what_you_wrote_down
+import mobi.giza.compose.resources.unlocking_your_code
+import mobi.giza.compose.resources.use_this_profile_in_another_app
+import mobi.giza.compose.resources.word_position
+import mobi.giza.compose.resources.you_have_not_backed_up_your_recovery_code
+import mobi.giza.compose.resources.your_backup_matches
+import mobi.giza.compose.resources.your_code_could_not_be_read_to_check
+import mobi.giza.compose.ui.composable.widgets.Decorative
+import mobi.giza.compose.ui.composable.widgets.ErrorState
+import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
+import mobi.giza.compose.ui.composable.widgets.NavigateBackButton
+import mobi.giza.compose.ui.theme.ConformancePreviews
+import mobi.giza.compose.ui.theme.readableContent
+import mobi.giza.compose.ui.theme.spacing
+import mobi.giza.compose.ui.view.model.RecoveryCodeViewModel
+import mobi.giza.compose.ui.view.state.BackupCheckState
+import mobi.giza.compose.ui.view.state.RecoveryCodeUIState
+import org.jetbrains.compose.resources.stringResource
+
+/**
+ * The recovery code behind this profile, shown on request, and a check that the copy on
+ * paper is right. See docs/recovery-code-v3.md, Phase 6.
+ *
+ * The reveal is a separate press, as the phrase's is: reading the code goes to the
+ * keystore, and nobody should walk past a phone that is quietly showing it. Below the code,
+ * behind a press of its own, are the 24 words it is -- for other apps, not a second backup.
+ */
+@Composable
+fun RecoveryCodeScreen(
+ phoenixGlobal: PhoenixGlobal,
+ activeIdentityStateFlow: StateFlow,
+ onNavigateBack: () -> Unit,
+ onShowRecoveryPhrase: () -> Unit,
+) {
+ val viewModel: RecoveryCodeViewModel = viewModel(
+ factory = RecoveryCodeViewModel.factory(
+ phoenixGlobal = phoenixGlobal,
+ activeIdentityStateFlow = activeIdentityStateFlow,
+ )
+ )
+
+ val uiState by viewModel.uiState.collectAsState()
+ val backupCheck by viewModel.backupCheck.collectAsState()
+ val isBackupDone by viewModel.isBackupDone.collectAsState()
+ val isDisclaimerRead by viewModel.isDisclaimerRead.collectAsState()
+ val showBackupNotice by viewModel.showBackupNotice.collectAsState()
+
+ RecoveryCodeContent(
+ uiState = uiState,
+ backupCheck = backupCheck,
+ checkBlocks = viewModel.checkBlocks,
+ isBackupDone = isBackupDone,
+ isDisclaimerRead = isDisclaimerRead,
+ showBackupNotice = showBackupNotice,
+ onReveal = viewModel::reveal,
+ onHide = viewModel::hide,
+ onRevealWords = viewModel::revealWords,
+ onHideWords = viewModel::hideWords,
+ onCheckBackup = viewModel::checkBackup,
+ onDisclaimerReadChange = viewModel::setDisclaimerRead,
+ onShowRecoveryPhrase = onShowRecoveryPhrase,
+ onNavigateBack = onNavigateBack,
+ )
+}
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+internal fun RecoveryCodeContent(
+ uiState: RecoveryCodeUIState,
+ backupCheck: BackupCheckState,
+ checkBlocks: Pair,
+ isBackupDone: Boolean?,
+ isDisclaimerRead: Boolean?,
+ showBackupNotice: Boolean,
+ onReveal: () -> Unit,
+ onHide: () -> Unit,
+ onRevealWords: () -> Unit,
+ onHideWords: () -> Unit,
+ onCheckBackup: (String, String) -> Unit,
+ onDisclaimerReadChange: (Boolean) -> Unit,
+ onShowRecoveryPhrase: () -> Unit,
+ onNavigateBack: () -> Unit,
+) {
+ Scaffold(
+ topBar = {
+ TopAppBar(
+ title = { Text(text = stringResource(Res.string.recovery_code)) },
+ navigationIcon = { NavigateBackButton(onNavigateBack) },
+ )
+ }
+ ) { innerPadding ->
+ LazyColumn(
+ modifier = Modifier
+ .padding(innerPadding)
+ .readableContent()
+ .padding(horizontal = MaterialTheme.spacing.screenMargin),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ item {
+ Text(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = MaterialTheme.spacing.containerPadding),
+ text = stringResource(Res.string.the_recovery_code_is_nine_blocks),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ }
+
+ if (showBackupNotice) {
+ item { BackupNotice() }
+ }
+
+ item {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(MaterialTheme.spacing.containerPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ when (uiState) {
+ is RecoveryCodeUIState.Hidden -> Button(onClick = onReveal) {
+ Icon(Icons.Default.Visibility, contentDescription = Decorative)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125))
+ Text(text = stringResource(Res.string.display_recovery_code))
+ }
+
+ is RecoveryCodeUIState.Revealing -> LoadingDataIndicator(
+ fillScreen = false,
+ text = stringResource(Res.string.unlocking_your_code),
+ )
+
+ is RecoveryCodeUIState.Revealed -> {
+ RecoveryCodeBlocks(uiState.code)
+ TextButton(onClick = onHide) {
+ Icon(Icons.Default.VisibilityOff, contentDescription = Decorative)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125))
+ Text(text = stringResource(Res.string.hide))
+ }
+ }
+
+ is RecoveryCodeUIState.Error -> {
+ ErrorState(
+ message = when (uiState) {
+ RecoveryCodeUIState.Error.NoActiveProfile ->
+ stringResource(Res.string.no_profile_is_open_so_there_is_no_code_to_show)
+ RecoveryCodeUIState.Error.CodesUnreadable ->
+ stringResource(Res.string.could_not_unlock_your_recovery_code)
+ RecoveryCodeUIState.Error.NoCodeForThisProfile ->
+ stringResource(Res.string.this_device_holds_no_code_for_this_profile)
+ },
+ // Nothing to match against until a profile is open.
+ onRetry = if (uiState is RecoveryCodeUIState.Error.NoActiveProfile) null else onReveal,
+ )
+ // Every code profile is also its 24 words in seed.dat, which
+ // a codes file that cannot be read does not touch.
+ if (uiState !is RecoveryCodeUIState.Error.NoActiveProfile) {
+ TextButton(onClick = onShowRecoveryPhrase) {
+ Text(text = stringResource(Res.string.show_the_recovery_phrase_instead))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (uiState is RecoveryCodeUIState.Revealed) {
+ item {
+ OtherAppsWords(
+ words = uiState.words,
+ onRevealWords = onRevealWords,
+ onHideWords = onHideWords,
+ )
+ }
+ }
+
+ item {
+ Text(
+ modifier = Modifier.fillMaxWidth(),
+ text = stringResource(Res.string.backup_confirmation),
+ style = MaterialTheme.typography.titleMedium,
+ )
+ }
+
+ item {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ if (isBackupDone == null || isDisclaimerRead == null) {
+ Text(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(MaterialTheme.spacing.containerPadding),
+ text = stringResource(Res.string.loading_preferences),
+ style = MaterialTheme.typography.bodySmall,
+ )
+ } else {
+ BackupCheck(
+ checkBlocks = checkBlocks,
+ state = if (isBackupDone && backupCheck is BackupCheckState.Idle) BackupCheckState.Matched else backupCheck,
+ onCheck = onCheckBackup,
+ )
+ DisclaimerCheckbox(
+ checked = isDisclaimerRead,
+ onCheckedChange = onDisclaimerReadChange,
+ )
+ }
+ }
+ }
+
+ item { Spacer(modifier = Modifier.padding(bottom = MaterialTheme.spacing.containerPadding)) }
+ }
+ }
+}
+
+@Composable
+private fun BackupNotice() {
+ Card(
+ modifier = Modifier.fillMaxWidth(),
+ colors = CardDefaults.cardColors(
+ containerColor = MaterialTheme.colorScheme.errorContainer,
+ contentColor = MaterialTheme.colorScheme.onErrorContainer,
+ ),
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(MaterialTheme.spacing.containerPadding),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Icon(Icons.Default.Warning, contentDescription = Decorative)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125))
+ Column {
+ Text(
+ text = stringResource(Res.string.you_have_not_backed_up_your_recovery_code),
+ style = MaterialTheme.typography.titleSmall,
+ )
+ Text(
+ text = stringResource(Res.string.lose_this_phone_before_you_do_and_the),
+ style = MaterialTheme.typography.bodySmall,
+ )
+ }
+ }
+ }
+}
+
+/**
+ * Nine blocks in three rows of three, numbered. A grid rather than one line, because a
+ * person copying writes block by block and checks block by block -- and a ninth block on a
+ * line of its own is the one that gets dropped.
+ */
+@Composable
+private fun RecoveryCodeBlocks(code: RecoveryCode) {
+ Text(
+ text = stringResource(Res.string.keep_this_code_safe_do_not_share_it),
+ style = MaterialTheme.typography.labelMedium,
+ textAlign = TextAlign.Center,
+ )
+ Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) {
+ code.blocks.chunked(3).forEachIndexed { row, blocks ->
+ Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap)) {
+ blocks.forEachIndexed { column, block ->
+ val number = row * 3 + column + 1
+ val label = stringResource(Res.string.block_number, number)
+ Column(
+ modifier = Modifier.semantics { contentDescription = "$label: $block" },
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Text(
+ text = stringResource(Res.string.word_position, number),
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ Text(
+ text = block,
+ style = MaterialTheme.typography.titleLarge.copy(fontFamily = FontFamily.Monospace),
+ fontWeight = FontWeight.Bold,
+ )
+ }
+ }
+ }
+ }
+ }
+ Text(
+ text = stringResource(Res.string.the_ninth_block_is_part_of_the_code),
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center,
+ )
+}
+
+/**
+ * The 24 words the code is, for an app that takes a recovery phrase. Behind a press of its
+ * own and with a sentence that says what they are not: a second backup. They restore the
+ * profile in full, and they cannot give the code back.
+ */
+@Composable
+private fun OtherAppsWords(
+ words: List?,
+ onRevealWords: () -> Unit,
+ onHideWords: () -> Unit,
+) {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(MaterialTheme.spacing.containerPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ ) {
+ Text(
+ text = stringResource(Res.string.use_this_profile_in_another_app),
+ style = MaterialTheme.typography.titleSmall,
+ )
+ Text(
+ text = stringResource(Res.string.these_24_words_are_this_profile_for_other_apps),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ if (words == null) {
+ OutlinedButton(modifier = Modifier.align(Alignment.End), onClick = onRevealWords) {
+ Text(text = stringResource(Res.string.show_the_words))
+ }
+ } else {
+ Text(
+ text = words.mapIndexed { index, word -> "${index + 1}. $word" }.joinToString("\n"),
+ style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
+ )
+ TextButton(modifier = Modifier.align(Alignment.End), onClick = onHideWords) {
+ Text(text = stringResource(Res.string.hide))
+ }
+ }
+ }
+ }
+}
+
+/** Two blocks typed back from the paper. A match records the backup; nothing else does. */
+@Composable
+private fun BackupCheck(
+ checkBlocks: Pair,
+ state: BackupCheckState,
+ onCheck: (String, String) -> Unit,
+) {
+ val first = rememberTextFieldState()
+ val second = rememberTextFieldState()
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(MaterialTheme.spacing.containerPadding),
+ verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
+ ) {
+ if (state is BackupCheckState.Matched) {
+ Text(text = stringResource(Res.string.your_backup_matches), style = MaterialTheme.typography.bodyMedium)
+ return@Column
+ }
+ Text(
+ text = stringResource(Res.string.type_blocks_from_what_you_wrote_down, checkBlocks.first, checkBlocks.second),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) {
+ listOf(first to checkBlocks.first, second to checkBlocks.second).forEach { (field, number) ->
+ OutlinedTextField(
+ modifier = Modifier.weight(1f),
+ state = field,
+ label = { Text(text = stringResource(Res.string.block_number, number), maxLines = 1) },
+ lineLimits = TextFieldLineLimits.SingleLine,
+ isError = state is BackupCheckState.Mismatch,
+ textStyle = MaterialTheme.typography.bodyLarge.copy(fontFamily = FontFamily.Monospace),
+ keyboardOptions = KeyboardOptions(
+ capitalization = KeyboardCapitalization.Characters,
+ autoCorrectEnabled = false,
+ keyboardType = KeyboardType.Ascii,
+ ),
+ )
+ }
+ }
+ when (state) {
+ BackupCheckState.Mismatch -> Text(
+ text = stringResource(Res.string.those_blocks_do_not_match),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ )
+ BackupCheckState.Unreadable -> Text(
+ text = stringResource(Res.string.your_code_could_not_be_read_to_check),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error,
+ )
+ else -> Unit
+ }
+ Button(
+ modifier = Modifier.align(Alignment.End),
+ enabled = state !is BackupCheckState.Checking,
+ onClick = { onCheck(first.text.toString(), second.text.toString()) },
+ ) {
+ Text(text = stringResource(Res.string.check_backup))
+ }
+ }
+}
+
+@Composable
+private fun DisclaimerCheckbox(checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ // The whole row toggles, so the row is the target and carries the 48dp.
+ .minimumInteractiveComponentSize()
+ .clickable { onCheckedChange(!checked) }
+ .padding(
+ horizontal = MaterialTheme.spacing.containerPadding,
+ vertical = MaterialTheme.spacing.space150,
+ ),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Checkbox(checked = checked, onCheckedChange = onCheckedChange)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125))
+ Text(
+ text = stringResource(Res.string.i_understand_that_if_i_lose_this_phone_and_my_code),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ }
+}
+
+@ConformancePreviews
+@Composable
+private fun RecoveryCodeScreenPreview() {
+ mobi.giza.compose.ui.theme.GizaTheme {
+ Surface(modifier = Modifier.fillMaxSize()) {
+ RecoveryCodeContent(
+ uiState = RecoveryCodeUIState.Revealed(RecoveryCode.generate()),
+ backupCheck = BackupCheckState.Idle,
+ checkBlocks = 3 to 7,
+ isBackupDone = false,
+ isDisclaimerRead = false,
+ showBackupNotice = true,
+ onReveal = {},
+ onHide = {},
+ onRevealWords = {},
+ onHideWords = {},
+ onCheckBackup = { _, _ -> },
+ onDisclaimerReadChange = {},
+ onShowRecoveryPhrase = {},
+ onNavigateBack = {},
+ )
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt
index c5bcb0f1..511c04cb 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt
@@ -127,7 +127,9 @@ import mobi.giza.compose.ui.composable.navigation.routes.NostrEventDetailRoute
import mobi.giza.compose.ui.composable.navigation.routes.NostrSecretRoute
import mobi.giza.compose.ui.composable.navigation.routes.ProfilePreviewRoute
import mobi.giza.compose.ui.composable.navigation.routes.ProfilesRoute
+import mobi.giza.compose.ui.composable.navigation.routes.RecoveryCodeRoute
import mobi.giza.compose.ui.composable.navigation.routes.RecoveryPhraseRoute
+import mobi.giza.compose.ui.composable.RecoveryCodeScreen
import mobi.giza.compose.ui.composable.ProfilePreviewScreen
import mobi.giza.compose.ui.composable.ProfilesScreen
import mobi.giza.compose.ui.view.model.ProfilesViewModel
@@ -972,6 +974,20 @@ fun GizaNavHost(
}
)
}
+ composable {
+ RecoveryCodeScreen(
+ phoenixGlobal = phoenixGlobal,
+ activeIdentityStateFlow = sovereignWalletViewModel.activeIdentity,
+ onNavigateBack = {
+ navController.popBackStack()
+ },
+ // Every code profile is also its 24 words, which the phrase screen reads
+ // from seed.dat when the codes file cannot be.
+ onShowRecoveryPhrase = {
+ navController.navigate(RecoveryPhraseRoute)
+ },
+ )
+ }
composable {
NostrSecretScreen(
phoenixGlobal = phoenixGlobal,
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/RecoveryCodeRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/RecoveryCodeRoute.kt
new file mode 100644
index 00000000..47d75bf9
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/RecoveryCodeRoute.kt
@@ -0,0 +1,6 @@
+package mobi.giza.compose.ui.composable.navigation.routes
+
+import kotlinx.serialization.Serializable
+
+@Serializable
+data object RecoveryCodeRoute: Route()
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/RecoveryCodeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/RecoveryCodeViewModel.kt
new file mode 100644
index 00000000..44ce073c
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/RecoveryCodeViewModel.kt
@@ -0,0 +1,195 @@
+package mobi.giza.compose.ui.view.model
+
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.viewModelScope
+import androidx.lifecycle.viewmodel.initializer
+import androidx.lifecycle.viewmodel.viewModelFactory
+import co.touchlab.kermit.Logger
+import fr.acinq.phoenix.PhoenixGlobal
+import fr.acinq.phoenix.data.DecryptRecoveryCodesResult
+import fr.acinq.phoenix.data.WalletId
+import fr.acinq.phoenix.managers.RecoveryCodeManager
+import kotlinx.coroutines.CoroutineExceptionHandler
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.IO
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import mobi.giza.compose.identity.Identity
+import mobi.giza.compose.identity.recoverycode.RecoveryCode
+import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys
+import mobi.giza.compose.ui.view.state.BackupCheckState
+import mobi.giza.compose.ui.view.state.RecoveryCodeUIState
+import kotlin.random.Random
+
+/**
+ * Reads back the recovery code behind the open profile, and checks a written-down copy.
+ *
+ * [RecoveryPhraseViewModel]'s counterpart, with the same rules: the code is read on a press
+ * and held only while it is on screen, and the backup flags are the same per-profile
+ * preferences. What is new is [checkBackup]: two blocks typed back from the paper. A typo in
+ * them is a typo on the paper, and the code makes the check two short fields rather than a
+ * list of words. See docs/recovery-code-v3.md, Phase 6.
+ */
+class RecoveryCodeViewModel(
+ val phoenixGlobal: PhoenixGlobal,
+ val activeIdentityStateFlow: StateFlow,
+ random: Random = Random.Default,
+ private val readCodes: () -> DecryptRecoveryCodesResult = { RecoveryCodeManager.loadAndDecrypt(phoenixGlobal) },
+) : ViewModel() {
+
+ private val logger = Logger.withTag(TAG)
+
+ private val _uiState = MutableStateFlow(RecoveryCodeUIState.Hidden)
+ val uiState = _uiState.asStateFlow()
+
+ private val _backupCheck = MutableStateFlow(BackupCheckState.Idle)
+ val backupCheck = _backupCheck.asStateFlow()
+
+ /**
+ * The two blocks the check asks for, 1-based, in order. Never block 1, which starts `LB`
+ * on every code and would check little. Chosen once per visit to the screen.
+ */
+ val checkBlocks: Pair = (2..9).shuffled(random).take(2).sorted().let { it[0] to it[1] }
+
+ @OptIn(ExperimentalCoroutinesApi::class)
+ val isDisclaimerRead: StateFlow = activeIdentityStateFlow
+ .flatMapLatest { it?.internalPrefs?.isSeedLossDisclaimerRead ?: flowOf(null) }
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
+
+ @OptIn(ExperimentalCoroutinesApi::class)
+ val isBackupDone: StateFlow = activeIdentityStateFlow
+ .flatMapLatest { it?.internalPrefs?.isManualSeedBackupDone ?: flowOf(null) }
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
+
+ /** True until the backup is checked and the disclaimer read. */
+ @OptIn(ExperimentalCoroutinesApi::class)
+ val showBackupNotice: StateFlow = activeIdentityStateFlow
+ .flatMapLatest { it?.internalPrefs?.showSeedBackupNotice ?: flowOf(false) }
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
+
+ /** What [read] found: the code, or the error to show. */
+ private sealed interface Read {
+ data class Found(val code: RecoveryCode) : Read
+ data class Missing(val error: RecoveryCodeUIState.Error) : Read
+ }
+
+ private suspend fun read(id: WalletId): Read {
+ // Keystore-backed, and it reads a file: never on the main thread.
+ val result = withContext(Dispatchers.IO) { readCodes() }
+ val stored = when (result) {
+ is DecryptRecoveryCodesResult.Success -> result.codes[id]
+ is DecryptRecoveryCodesResult.Failure.FileNotFound -> null
+ is DecryptRecoveryCodesResult.Failure -> {
+ logger.e { "unable to read the recovery codes: $result" }
+ return Read.Missing(RecoveryCodeUIState.Error.CodesUnreadable)
+ }
+ }
+ val parsed = stored?.let { RecoveryCode.parse(it) as? RecoveryCode.Parse.Valid }
+ if (parsed == null) {
+ logger.e { "the codes file holds no valid code for wallet=$id" }
+ return Read.Missing(RecoveryCodeUIState.Error.NoCodeForThisProfile)
+ }
+ return Read.Found(parsed.code)
+ }
+
+ fun reveal() {
+ if (_uiState.value is RecoveryCodeUIState.Revealing) return
+ val id = activeIdentityStateFlow.value?.id
+ if (id == null) {
+ _uiState.value = RecoveryCodeUIState.Error.NoActiveProfile
+ return
+ }
+ viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
+ logger.e("failed to read the recovery code", throwable)
+ _uiState.value = RecoveryCodeUIState.Error.CodesUnreadable
+ }) {
+ _uiState.value = RecoveryCodeUIState.Revealing
+ _uiState.value = when (val read = read(id)) {
+ is Read.Found -> RecoveryCodeUIState.Revealed(read.code)
+ is Read.Missing -> read.error
+ }
+ }
+ }
+
+ /** The 24 words, under the code that is already on screen. */
+ fun revealWords() {
+ val revealed = _uiState.value as? RecoveryCodeUIState.Revealed ?: return
+ _uiState.value = revealed.copy(words = RecoveryCodeKeys.words(revealed.code))
+ }
+
+ fun hideWords() {
+ val revealed = _uiState.value as? RecoveryCodeUIState.Revealed ?: return
+ _uiState.value = revealed.copy(words = null)
+ }
+
+ fun hide() {
+ _uiState.value = RecoveryCodeUIState.Hidden
+ }
+
+ /**
+ * Compares [first] and [second], typed from the paper, with the code's [checkBlocks]. Reads
+ * the code for the comparison and drops it after, whether or not it is on screen. A match
+ * records the backup as done; a mismatch records nothing.
+ */
+ fun checkBackup(first: String, second: String) {
+ if (_backupCheck.value is BackupCheckState.Checking) return
+ val identity = activeIdentityStateFlow.value ?: return
+ viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
+ logger.e("failed to check the backup", throwable)
+ _backupCheck.value = BackupCheckState.Unreadable
+ }) {
+ _backupCheck.value = BackupCheckState.Checking
+ val code = when (val read = read(identity.id)) {
+ is Read.Found -> read.code
+ is Read.Missing -> {
+ _backupCheck.value = BackupCheckState.Unreadable
+ return@launch
+ }
+ }
+ val blocks = code.blocks
+ val matches = normalise(first) == blocks[checkBlocks.first - 1] && normalise(second) == blocks[checkBlocks.second - 1]
+ if (matches) {
+ identity.internalPrefs.saveManualSeedBackupDone(true)
+ _backupCheck.value = BackupCheckState.Matched
+ } else {
+ _backupCheck.value = BackupCheckState.Mismatch
+ }
+ }
+ }
+
+ private fun normalise(block: String): String = block.uppercase().filter { !it.isWhitespace() && it != '-' }
+
+ fun setDisclaimerRead(isRead: Boolean) {
+ val internalPrefs = activeIdentityStateFlow.value?.internalPrefs ?: return
+ viewModelScope.launch(CoroutineExceptionHandler { _, throwable ->
+ logger.e("could not save the disclaimer flag", throwable)
+ }) {
+ internalPrefs.saveSeedLossDisclaimerRead(isRead)
+ }
+ }
+
+ companion object {
+ private const val TAG = "RecoveryCodeViewModel"
+
+ fun factory(
+ phoenixGlobal: PhoenixGlobal,
+ activeIdentityStateFlow: StateFlow,
+ ): ViewModelProvider.Factory = viewModelFactory {
+ initializer {
+ RecoveryCodeViewModel(
+ phoenixGlobal = phoenixGlobal,
+ activeIdentityStateFlow = activeIdentityStateFlow,
+ )
+ }
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RecoveryCodeUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RecoveryCodeUIState.kt
new file mode 100644
index 00000000..381ddb32
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RecoveryCodeUIState.kt
@@ -0,0 +1,49 @@
+package mobi.giza.compose.ui.view.state
+
+import mobi.giza.compose.identity.recoverycode.RecoveryCode
+
+/**
+ * What the recovery code screen is showing. As with the phrase, the code is held only while
+ * the person is looking at it: [Revealed] is the only state that carries it.
+ */
+sealed interface RecoveryCodeUIState {
+ /** Nothing secret on screen. */
+ data object Hidden : RecoveryCodeUIState
+
+ /** Reading and decrypting the codes file. */
+ data object Revealing : RecoveryCodeUIState
+
+ /**
+ * The code, and -- once asked for, behind a reveal of their own -- the 24 words it is,
+ * for apps that take a recovery phrase.
+ */
+ data class Revealed(val code: RecoveryCode, val words: List? = null) : RecoveryCodeUIState {
+ override fun toString(): String = "Revealed(***)"
+ }
+
+ sealed interface Error : RecoveryCodeUIState {
+ /** No profile is open, so there is no code to read for it. */
+ data object NoActiveProfile : Error
+
+ /** The codes file could not be read or decrypted. The phrase in seed.dat still can be. */
+ data object CodesUnreadable : Error
+
+ /** The codes file holds no code for the open profile. */
+ data object NoCodeForThisProfile : Error
+ }
+}
+
+/** Where the two-block check of a written-down code stands. */
+sealed interface BackupCheckState {
+ data object Idle : BackupCheckState
+ data object Checking : BackupCheckState
+
+ /** The blocks typed are not the code's. */
+ data object Mismatch : BackupCheckState
+
+ /** They are; the backup is recorded as done. */
+ data object Matched : BackupCheckState
+
+ /** The code could not be read to check against. */
+ data object Unreadable : BackupCheckState
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/RecoveryCodeScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/RecoveryCodeScreenJvmTest.kt
new file mode 100644
index 00000000..a24e1244
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/RecoveryCodeScreenJvmTest.kt
@@ -0,0 +1,96 @@
+package mobi.giza.compose.ui.composable
+
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.test.ComposeUiTest
+import androidx.compose.ui.test.ExperimentalTestApi
+import androidx.compose.ui.test.onNodeWithContentDescription
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performScrollToNode
+import androidx.compose.ui.test.hasText
+import androidx.compose.ui.test.runDesktopComposeUiTest
+import androidx.compose.ui.test.hasScrollAction
+import mobi.giza.compose.identity.recoverycode.RecoveryCode
+import mobi.giza.compose.ui.theme.GizaTheme
+import mobi.giza.compose.ui.view.state.BackupCheckState
+import mobi.giza.compose.ui.view.state.RecoveryCodeUIState
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+/**
+ * The code screen, drawn in each state. What is pinned: the code is not on screen until it
+ * is revealed; revealed, all nine blocks are there, the ninth with the others; an unreadable
+ * file offers the phrase; and the check says which two blocks it wants. On the unmerged tree,
+ * as `ReadOnlyEntrancesJvmTest` explains.
+ */
+@OptIn(ExperimentalTestApi::class)
+class RecoveryCodeScreenJvmTest {
+
+ private val code = (RecoveryCode.parse("LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ") as RecoveryCode.Parse.Valid).code
+ private val taps = mutableListOf()
+
+ @Composable
+ private fun Screen(state: RecoveryCodeUIState, check: BackupCheckState = BackupCheckState.Idle) {
+ GizaTheme {
+ RecoveryCodeContent(
+ uiState = state,
+ backupCheck = check,
+ checkBlocks = 3 to 7,
+ isBackupDone = false,
+ isDisclaimerRead = false,
+ showBackupNotice = true,
+ onReveal = { taps += "reveal" },
+ onHide = { taps += "hide" },
+ onRevealWords = { taps += "words" },
+ onHideWords = {},
+ onCheckBackup = { a, b -> taps += "check:$a,$b" },
+ onDisclaimerReadChange = {},
+ onShowRecoveryPhrase = { taps += "phrase" },
+ onNavigateBack = {},
+ )
+ }
+ }
+
+ private fun ComposeUiTest.scrollTo(text: String) {
+ onAllNodes(hasScrollAction(), useUnmergedTree = true)[0].performScrollToNode(hasText(text, substring = true))
+ }
+
+ @Test
+ fun `hidden, the code is not on screen`() = runDesktopComposeUiTest {
+ setContent { Screen(RecoveryCodeUIState.Hidden) }
+
+ onNodeWithText("Display recovery code", useUnmergedTree = true).performClick()
+ assertEquals(listOf("reveal"), taps)
+ onNodeWithText("LBZC", useUnmergedTree = true).assertDoesNotExist()
+ }
+
+ @Test
+ fun `revealed, all nine blocks are on screen`() = runDesktopComposeUiTest {
+ setContent { Screen(RecoveryCodeUIState.Revealed(code)) }
+
+ code.blocks.forEachIndexed { index, block ->
+ onNodeWithContentDescription("Block ${index + 1}: $block", useUnmergedTree = true).assertExists()
+ }
+ scrollTo("Show the words")
+ onNodeWithText("Show the words", useUnmergedTree = true).performClick()
+ assertEquals(listOf("words"), taps)
+ }
+
+ @Test
+ fun `an unreadable codes file offers the phrase`() = runDesktopComposeUiTest {
+ setContent { Screen(RecoveryCodeUIState.Error.CodesUnreadable) }
+
+ onNodeWithText("Show the recovery phrase instead", useUnmergedTree = true).performClick()
+ assertEquals(listOf("phrase"), taps)
+ }
+
+ @Test
+ fun `the check names the two blocks it wants`() = runDesktopComposeUiTest {
+ setContent { Screen(RecoveryCodeUIState.Hidden, check = BackupCheckState.Mismatch) }
+
+ scrollTo("type block 3 and block 7")
+ onNodeWithText("type block 3 and block 7", substring = true, useUnmergedTree = true).assertExists()
+ scrollTo("don't match")
+ onNodeWithText("don't match", substring = true, useUnmergedTree = true).assertExists()
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/RecoveryCodeViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/RecoveryCodeViewModelJvmTest.kt
new file mode 100644
index 00000000..62f9df25
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/RecoveryCodeViewModelJvmTest.kt
@@ -0,0 +1,157 @@
+package mobi.giza.compose.ui.view.model
+
+import androidx.datastore.preferences.core.PreferenceDataStoreFactory
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.phoenix.PhoenixGlobal
+import fr.acinq.phoenix.data.DecryptRecoveryCodesResult
+import fr.acinq.phoenix.data.WalletId
+import fr.acinq.phoenix.utils.PlatformContext
+import fr.acinq.phoenix.utils.preferences.InternalPrefs
+import fr.acinq.phoenix.utils.preferences.UserPrefs
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.UnconfinedTestDispatcher
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.setMain
+import kotlinx.coroutines.withTimeout
+import mobi.giza.compose.identity.Identity
+import mobi.giza.compose.identity.IdentityKind
+import mobi.giza.compose.identity.recoverycode.RecoveryCode
+import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys
+import mobi.giza.compose.ui.view.state.BackupCheckState
+import mobi.giza.compose.ui.view.state.RecoveryCodeUIState
+import okio.Path.Companion.toPath
+import java.nio.file.Files
+import kotlin.random.Random
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertIs
+import kotlin.test.assertNotEquals
+import kotlin.test.assertTrue
+
+/**
+ * The code screen's reads and its check, with the codes file faked at the one function that
+ * reads it. See docs/recovery-code-v3.md, Phase 6.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class RecoveryCodeViewModelJvmTest {
+
+ private val code = (RecoveryCode.parse("LBZC-MYTK-E9P3-7C7B-AHJN-KX79-22CY-WAY7-K7QZ") as RecoveryCode.Parse.Valid).code
+ private val id = WalletId("ab".repeat(20))
+
+ private fun prefsFile(name: String) =
+ Files.createTempFile(name, ".preferences_pb").also { it.toFile().delete() }.toString().toPath()
+
+ private val internalPrefs = InternalPrefs(PreferenceDataStoreFactory.createWithPath { prefsFile("internal") })
+
+ private val identity = Identity.signing(
+ id = id,
+ kind = IdentityKind.RecoveryCode,
+ nostrPrivateKey = PrivateKey(ByteVector32("0a".repeat(32))),
+ userPrefs = UserPrefs(PreferenceDataStoreFactory.createWithPath { prefsFile("user") }),
+ internalPrefs = internalPrefs,
+ )
+
+ private val phoenixGlobal = PhoenixGlobal(PlatformContext(applicationDir = Files.createTempDirectory("giza-code-vm").toFile()))
+
+ @BeforeTest
+ fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
+
+ @AfterTest
+ fun tearDown() = Dispatchers.resetMain()
+
+ private fun viewModel(
+ active: Identity? = identity,
+ read: () -> DecryptRecoveryCodesResult = { DecryptRecoveryCodesResult.Success(mapOf(id to code.canonical)) },
+ ) = RecoveryCodeViewModel(phoenixGlobal, MutableStateFlow(active), Random(7), read)
+
+ private suspend fun RecoveryCodeViewModel.awaitState(pick: (RecoveryCodeViewModel) -> T, done: (T) -> Boolean): T =
+ withTimeout(5_000) {
+ while (!done(pick(this@awaitState))) delay(10)
+ pick(this@awaitState)
+ }
+
+ @Test
+ fun `the code is read on a press, and hidden again`() = runBlocking {
+ val viewModel = viewModel()
+ assertIs(viewModel.uiState.value)
+
+ viewModel.reveal()
+ val revealed = assertIs(viewModel.awaitState({ it.uiState.value }) { it is RecoveryCodeUIState.Revealed })
+ assertEquals(code, revealed.code)
+ assertEquals(null, revealed.words)
+
+ viewModel.hide()
+ assertIs(viewModel.uiState.value)
+ }
+
+ @Test
+ fun `the words are behind a press of their own, under the code`() = runBlocking {
+ val viewModel = viewModel()
+ viewModel.revealWords()
+ assertIs(viewModel.uiState.value, "no words without the code")
+
+ viewModel.reveal()
+ viewModel.awaitState({ it.uiState.value }) { it is RecoveryCodeUIState.Revealed }
+ viewModel.revealWords()
+ assertEquals(RecoveryCodeKeys.words(code), (viewModel.uiState.value as RecoveryCodeUIState.Revealed).words)
+
+ viewModel.hideWords()
+ assertEquals(null, (viewModel.uiState.value as RecoveryCodeUIState.Revealed).words)
+ }
+
+ @Test
+ fun `an unreadable file and a missing code are two errors`() = runBlocking {
+ val unreadable = viewModel(read = { DecryptRecoveryCodesResult.Failure.FileUnreadable })
+ unreadable.reveal()
+ assertEquals(RecoveryCodeUIState.Error.CodesUnreadable, unreadable.awaitState({ it.uiState.value }) { it is RecoveryCodeUIState.Error })
+
+ val missing = viewModel(read = { DecryptRecoveryCodesResult.Failure.FileNotFound })
+ missing.reveal()
+ assertEquals(RecoveryCodeUIState.Error.NoCodeForThisProfile, missing.awaitState({ it.uiState.value }) { it is RecoveryCodeUIState.Error })
+
+ val noProfile = viewModel(active = null)
+ noProfile.reveal()
+ assertEquals(RecoveryCodeUIState.Error.NoActiveProfile, noProfile.uiState.value)
+ }
+
+ @Test
+ fun `the check never asks for block 1`() {
+ repeat(50) { seed ->
+ val (first, second) = RecoveryCodeViewModel(phoenixGlobal, MutableStateFlow(identity), Random(seed)).checkBlocks
+ assertTrue(first in 2..9 && second in 2..9 && first < second, "$first, $second")
+ }
+ }
+
+ @Test
+ fun `the right two blocks record the backup, typed any case`() = runBlocking {
+ val viewModel = viewModel()
+ val (first, second) = viewModel.checkBlocks
+ assertFalse(internalPrefs.isManualSeedBackupDone.first())
+
+ viewModel.checkBackup(code.blocks[first - 1].lowercase(), " ${code.blocks[second - 1]} ")
+
+ assertEquals(BackupCheckState.Matched, viewModel.awaitState({ it.backupCheck.value }) { it != BackupCheckState.Idle && it != BackupCheckState.Checking })
+ assertTrue(internalPrefs.isManualSeedBackupDone.first())
+ }
+
+ @Test
+ fun `the wrong blocks record nothing`() = runBlocking {
+ val viewModel = viewModel()
+ val (first, second) = viewModel.checkBlocks
+ assertNotEquals(code.blocks[first - 1], code.blocks[second - 1])
+
+ viewModel.checkBackup(code.blocks[second - 1], code.blocks[first - 1])
+
+ assertEquals(BackupCheckState.Mismatch, viewModel.awaitState({ it.backupCheck.value }) { it != BackupCheckState.Idle && it != BackupCheckState.Checking })
+ assertFalse(internalPrefs.isManualSeedBackupDone.first())
+ }
+}