feat: a recovery code is an identity, attached to the phrase it is (recovery-code-v3, Phase 4)

IdentityKind.RecoveryCode and StoredIdentity.RecoveryCode: a phrase
profile whose words a stored code derives. merge attaches codes last and
drops one that disagrees with the words beside it. writeRecoveryCode
writes the key, the 24 words and the code, in that order, and attaches
a code to the phrase profile its words already made. An unreadable
codes file lists those profiles as their phrases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-25 23:06:28 +02:00
1 parent b959c70f4f
commit ee5eb68017
12 files changed
+400 -2

No files matched your search

@@ -254,6 +254,7 @@
<string name="asked_again_recently">Asked again just now. You can ask again in a few minutes.</string>
<string name="read_to_the_end_of_the_list_to_sign">Read to the end of the list to sign.</string>
<string name="recovery_phrase">Recovery phrase</string>
<string name="recovery_code">Recovery code</string>
<string name="ready_to_sign">Ready to sign</string>
<string name="recents">Recents</string>
<string name="reindex_events">Reindex events</string>
@@ -7,6 +7,8 @@ import fr.acinq.phoenix.data.DecryptSeedResult
import fr.acinq.phoenix.data.WalletId
import fr.acinq.phoenix.managers.DataStoreManager
import fr.acinq.phoenix.managers.NostrCredentialManager
import fr.acinq.phoenix.managers.RecoveryCodeManager
import fr.acinq.phoenix.data.DecryptRecoveryCodesResult
import kotlinx.coroutines.flow.first
import mobi.giza.compose.extensions.getGlobalPrefs
@@ -48,7 +50,12 @@ object DefaultIdentity {
}
}
val stored = StoredIdentity.merge(wallets, credentials)[defaultId]
val codes = when (val result = RecoveryCodeManager.loadAndDecrypt(phoenixGlobal)) {
is DecryptRecoveryCodesResult.Success -> StoredIdentity.parseCodes(result.codes)
else -> emptyMap()
}
val stored = StoredIdentity.merge(wallets, credentials, codes)[defaultId]
?: wallets[defaultId]?.let { StoredIdentity.mnemonic(it) }
?: return null
@@ -61,6 +68,13 @@ object DefaultIdentity {
userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id),
internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id),
)
is StoredIdentity.RecoveryCode -> Identity.signing(
id = stored.id,
kind = IdentityKind.RecoveryCode,
nostrPrivateKey = stored.privateKey,
userPrefs = dataStoreManager.loadUserPrefsForWallet(stored.id),
internalPrefs = dataStoreManager.loadInternalPrefsForWallet(stored.id),
)
is StoredIdentity.NostrSecret -> Identity.signing(
id = stored.id,
kind = IdentityKind.NostrSecret,
@@ -30,6 +30,13 @@ enum class IdentityKind {
*/
Mnemonic,
/**
* A [Mnemonic] whose words came from a recovery code the device also holds. To
* everything that reads `seed.dat` it is a phrase profile; the code is what a person
* wrote down, and what the backup screen shows. See docs/recovery-code-v3.md.
*/
RecoveryCode,
/** A bare nostr secret. Nothing else can be derived from it. */
NostrSecret,
@@ -37,6 +44,10 @@ enum class IdentityKind {
NostrPublic,
}
/** A backup this device can show again: a phrase, or a code and the phrase it is. */
val IdentityKind.hasBackup: Boolean
get() = this == IdentityKind.Mnemonic || this == IdentityKind.RecoveryCode
/**
* The signing identity the app is running as -- or, for [IdentityKind.NostrPublic],
* the identity it is looking at.
@@ -8,10 +8,12 @@ import fr.acinq.phoenix.data.ElectrumConfig
import fr.acinq.phoenix.data.WalletId
import fr.acinq.phoenix.managers.DataStoreManager
import fr.acinq.phoenix.managers.NostrCredentialManager
import fr.acinq.phoenix.managers.RecoveryCodeManager
import fr.acinq.phoenix.managers.SeedManager
import fr.acinq.phoenix.managers.nostrPrivateKey
import fr.acinq.phoenix.managers.nostrPublicKeyHex
import fr.acinq.phoenix.security.EncryptedNostrCredentials
import fr.acinq.phoenix.security.EncryptedRecoveryCodes
import fr.acinq.phoenix.security.EncryptedSeed
import fr.acinq.phoenix.security.NostrCredential
import fr.acinq.phoenix.utils.preferences.GlobalPrefs
@@ -22,6 +24,8 @@ import kotlinx.coroutines.IO
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import mobi.giza.compose.AppVersion
import mobi.giza.compose.identity.recoverycode.RecoveryCode
import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys
import mobi.giza.compose.ui.view.model.WritingSeedState
/**
@@ -195,6 +199,86 @@ object IdentityWriter {
}
}
sealed class WriteRecoveryCodeResult {
/** The code is on the device, with its words and its key. [isNew] is false when it attached to a phrase profile already here. */
data class Written(val id: WalletId, val isNew: Boolean) : WriteRecoveryCodeResult()
/** This code is already on the device, under [id]. */
data class AlreadyExists(val id: WalletId) : WriteRecoveryCodeResult()
/** One of the three stores exists and could not be read; nothing was written. */
data object CannotLoadKeys : WriteRecoveryCodeResult()
}
/**
* Puts [code] on the device: its key in the credentials file, its 24 words in `seed.dat`,
* and the code in `recovery-codes.dat` -- in that order, the order [writeMnemonic]
* established with the code last, so that a crash between any two leaves something
* valid: a bare key the code derives, or a phrase profile the code attaches to the next
* time it is entered. See docs/recovery-code-v3.md, Phase 4.
*
* What is already here for the derived key decides what the write means, not whether
* it happens -- with one refusal, the same code twice:
*
* - nothing: a new profile;
* - a public entry: the read-only upgrade landing on a backup;
* - a bare secret: the key acquiring the code that derives it. The id changes to the
* words', so the bare key's preference files are deleted, as [writeMnemonic] does;
* - the code's words, no code: the code attached to the phrase profile it already is.
* Same id, same preferences, and nothing but the code is written.
*/
suspend fun writeRecoveryCode(
log: Logger,
phoenixGlobal: PhoenixGlobal,
globalPrefs: GlobalPrefs,
code: RecoveryCode,
isTorEnabled: Boolean,
customElectrumServer: ElectrumConfig.Custom?,
): WriteRecoveryCodeResult {
log.d("writing recovery code to disk...")
val words = RecoveryCodeKeys.words(code)
val id = PhraseKeys.profileId(words)
val privateKey = PhraseKeys.nostrPrivateKey(words)
val publicKey = privateKey.nostrPublicKeyHex()
val seeds = SeedManager.loadAndDecryptOrNull(phoenixGlobal)?.mapValues { it.value.words }
val credentials = NostrCredentialManager.loadAndDecryptOrNull(phoenixGlobal)
val codes = RecoveryCodeManager.loadAndDecryptOrNull(phoenixGlobal)
if (seeds == null || credentials == null || codes == null) {
log.e("could not load the existing keys, aborting...")
return WriteRecoveryCodeResult.CannotLoadKeys
}
if (codes[id] == code.canonical) {
log.i("attempting to import a recovery code that is already here, aborting...")
return WriteRecoveryCodeResult.AlreadyExists(id)
}
val phraseHere = seeds.containsKey(id)
val existingEntry = credentials[publicKey]
if (existingEntry !is NostrCredential.Secret) {
NostrCredentialManager.writeToDisk(
phoenixGlobal,
EncryptedNostrCredentials.encrypt(credentials + (publicKey to NostrCredential.Secret(privateKey))),
)
}
if (!phraseHere) {
SeedManager.writeSeedToDisk(phoenixGlobal, EncryptedSeed.V2.encrypt(seeds + (id to words)), overwrite = true)
}
RecoveryCodeManager.writeToDisk(phoenixGlobal, EncryptedRecoveryCodes.encrypt(codes + (id to code.canonical)))
if (phraseHere) {
log.i("attached a recovery code to wallet=$id")
return WriteRecoveryCodeResult.Written(id, isNew = false)
}
if (existingEntry != null) {
log.i("the code's nostr key was here without a backup; it is now a profile with one")
DataStoreManager(phoenixGlobal.ctx, chain = PROFILE_CHAIN).deleteNodeUserPrefs(StoredIdentity.nostrPublic(publicKey).id)
}
prepareIdentity(phoenixGlobal, globalPrefs, id, isTorEnabled, customElectrumServer)
log.i("successfully wrote recovery code for wallet=$id")
return WriteRecoveryCodeResult.Written(id, isNew = true)
}
sealed class WriteNostrCredentialResult {
data class Written(val id: WalletId) : WriteNostrCredentialResult()
@@ -10,6 +10,8 @@ import fr.acinq.phoenix.data.WalletId
import fr.acinq.phoenix.managers.nostrPrivateKey
import fr.acinq.phoenix.managers.nostrPublicKeyHex
import fr.acinq.phoenix.security.NostrCredential
import mobi.giza.compose.identity.recoverycode.RecoveryCodeKeys
import mobi.giza.compose.identity.recoverycode.RecoveryCode as Code
/**
* A profile this device holds something for, as listed before any of them is started.
@@ -51,6 +53,23 @@ sealed interface StoredIdentity {
override fun toString(): String = "StoredIdentity.Mnemonic(id=$id, npub=$nostrPublicKey, key=<redacted>)"
}
/**
* A [Mnemonic] whose 24 words a recovery code derives, and the code. Everything a
* phrase profile is, this is too -- same id, same key, same seed -- and the code is the
* one thing more: what the person wrote down, which the words cannot give back. Listed
* only when [code] derives [userWallet]'s words; see [merge].
*/
data class RecoveryCode(
val userWallet: UserWallet,
val code: Code,
val privateKey: PrivateKey,
) : StoredIdentity {
override val id: WalletId get() = userWallet.walletId
override val kind: IdentityKind get() = IdentityKind.RecoveryCode
override val nostrPublicKey: HexKey = privateKey.nostrPublicKeyHex()
override fun toString(): String = "StoredIdentity.RecoveryCode(id=$id, npub=$nostrPublicKey, key=<redacted>)"
}
data class NostrSecret(
override val id: WalletId,
override val nostrPublicKey: HexKey,
@@ -116,10 +135,18 @@ sealed interface StoredIdentity {
* A seed with no credential at all -- the repair failed to write, or a crash fell
* between the seed writer's two files -- is listed as it always was, with its key
* derived from the words. A failed write must never hide a wallet.
*
* Last, [codes] are attached. A [Mnemonic] whose id has a code that derives its words
* becomes a [RecoveryCode]; a code that derives other words than the ones beside it
* is dropped with a log line, and the profile stays the phrase every build reads it
* as -- two files that disagree mean one is wrong, and `seed.dat` is the one every
* build trusts. A code with no seed at all attaches to nothing. See
* docs/recovery-code-v3.md, Phase 3.
*/
fun merge(
wallets: Map<WalletId, UserWallet>,
credentials: Map<HexKey, NostrCredential>,
codes: Map<WalletId, Code> = emptyMap(),
): Map<WalletId, StoredIdentity> {
val walletsByPublicKey = wallets.values.associateBy { nostrPublicKeyOf(it.words) }
val merged = LinkedHashMap<WalletId, StoredIdentity>()
@@ -146,9 +173,33 @@ sealed interface StoredIdentity {
merged[wallet.walletId] = mnemonic(wallet)
}
}
codes.forEach { (id, code) ->
val phrase = merged[id] as? Mnemonic ?: return@forEach
if (RecoveryCodeKeys.words(code) == phrase.userWallet.words) {
merged[id] = RecoveryCode(phrase.userWallet, code, phrase.privateKey)
} else {
log.w { "the recovery code for wallet=$id does not derive its words; listing it as its phrase" }
}
}
return merged
}
/**
* The codes `recovery-codes.dat` holds, parsed. A stored code that does not parse as a
* valid code -- a file edited by hand, a bug -- is dropped with a log line: it derives
* nothing, and its profile is still the phrase in `seed.dat`.
*/
fun parseCodes(stored: Map<WalletId, String>): Map<WalletId, Code> =
stored.mapNotNull { (id, text) ->
when (val parsed = Code.parse(text)) {
is Code.Parse.Valid -> id to parsed.code
else -> {
log.w { "the stored recovery code for wallet=$id does not parse; ignoring it" }
null
}
}
}.toMap()
private val log = Logger.withTag("StoredIdentity")
}
}
@@ -137,6 +137,7 @@ fun KeyRecoveryScreen(
IdentityKind.NostrSecret,
IdentityKind.NostrPublic -> stringResource(Res.string.these_are_your_keys_keep_them_safe_no_wallet)
IdentityKind.Mnemonic,
IdentityKind.RecoveryCode,
null -> stringResource(Res.string.these_are_your_keys_keep_them_safe_so_they)
},
style = MaterialTheme.typography.bodyMedium,
@@ -186,6 +187,7 @@ fun KeyRecoveryScreen(
IdentityKind.NostrPublic -> Unit
IdentityKind.Mnemonic,
IdentityKind.RecoveryCode,
null -> KeyRecoveryOption(
icon = Icons.Default.Spellcheck,
title = stringResource(Res.string.recovery_phrase),
@@ -213,6 +213,15 @@ fun SovereignWalletStartupScreen(
internalPrefs = dataStoreManager.loadInternalPrefsForWallet(identity.id),
)
)
is StoredIdentity.RecoveryCode -> sovereignWalletViewModel.setActiveIdentity(
Identity.signing(
id = identity.id,
kind = IdentityKind.RecoveryCode,
nostrPrivateKey = identity.privateKey,
userPrefs = dataStoreManager.loadUserPrefsForWallet(identity.id),
internalPrefs = dataStoreManager.loadInternalPrefsForWallet(identity.id),
)
)
is StoredIdentity.NostrSecret -> sovereignWalletViewModel.setActiveIdentity(
Identity.signing(
id = identity.id,
@@ -51,6 +51,7 @@ import fr.acinq.phoenix.utils.preferences.getByWalletIdOrDefault
import mobi.giza.compose.extensions.hexToNpubHrp
import mobi.giza.compose.resources.Res
import mobi.giza.compose.resources.read_only
import mobi.giza.compose.resources.recovery_code
import mobi.giza.compose.resources.recovery_phrase
import org.jetbrains.compose.resources.stringResource
import mobi.giza.compose.database.model.Profile
@@ -195,6 +196,7 @@ private fun AvailableWalletView(
}
val held = when (identity) {
is StoredIdentity.Mnemonic -> Res.string.recovery_phrase
is StoredIdentity.RecoveryCode -> Res.string.recovery_code
is StoredIdentity.NostrPublic -> Res.string.read_only
is StoredIdentity.NostrSecret -> null
}
@@ -20,6 +20,8 @@ import fr.acinq.phoenix.data.ListWalletState
import fr.acinq.phoenix.data.UserWallet
import fr.acinq.phoenix.data.WalletId
import fr.acinq.phoenix.managers.NostrCredentialManager
import fr.acinq.phoenix.managers.RecoveryCodeManager
import fr.acinq.phoenix.data.DecryptRecoveryCodesResult
import fr.acinq.phoenix.security.NostrCredential
import fr.acinq.phoenix.managers.nostrPrivateKey
import fr.acinq.phoenix.utils.preferences.GlobalPrefs
@@ -277,7 +279,20 @@ class SovereignWalletViewModel(
}
}
val identities = StoredIdentity.merge(wallets, credentials)
// Read, never written, and never fatal: every profile with a code is also the
// phrase in seed.dat, so a codes file that cannot be read loses nothing but the
// code itself, which the backup screen reports when it is asked for. See
// docs/recovery-code-v3.md, Phase 4.
val codes = when (val result = RecoveryCodeManager.loadAndDecrypt(phoenixGlobal)) {
is DecryptRecoveryCodesResult.Success -> StoredIdentity.parseCodes(result.codes)
is DecryptRecoveryCodesResult.Failure.FileNotFound -> emptyMap()
is DecryptRecoveryCodesResult.Failure -> {
log.e { "cannot read the recovery codes file: $result; listing those profiles as their phrases" }
emptyMap()
}
}
val identities = StoredIdentity.merge(wallets, credentials, codes)
val metadataMap = getAvailableWalletsMeta(phoenixGlobal).first()
identities.keys.forEach { walletId ->