Repository navigation
fix: speed up wallet restore - #2249
Conversation
Verified: just compile, just test, just lint; KeychainTest on a Pixel 10 Pro; mainnet restore on a Pixel 10 Pro
Verified: just compile, just lint
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Confidence Score: 5/5
[Medium impact] The PR appears safe to merge; no actionable issues were found. SummarySpeeds up large wallet-backup reads and writes by giving three backup entries a separate Android Keystore key without StrongBox preference.
No actionable issues were found. Tests were inspected, not run. Acknowledged scope:
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Keychain read or write] --> B{One of three backup keys?}
B -->|No| C[Existing key and lock]
B -->|Yes| D[Separate key and lock]
D --> E{Read fails with GeneralSecurityException?}
E -->|Yes| F[Retry with existing key]
E -->|No| G[Return result]
H[Wipe] --> I[Clear stored entries]
I --> J[Reset both keys]
Reviews (1) · Last reviewed commit: "fix: fall back on any keystore error for..." · Reviewed by Greptile |
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR diff against its merge base, at a35c095.
No new actionable code findings.
No actionable code findings. The five WALLET-backup keychain passes in #2227 use keychain_large_values and its own lock, so a fresh restore does not hold the StrongBox key across those passes. Mnemonic, passphrase, PIN, and the other entries stay on the StrongBox key. A value those three keys stored before the update still decrypts with the main key, and wipe resets both keys. The separate node/restore wait left to #2247 was not part of this review.
Compared with bitkit-ios 447a0aed: paykitRecoveryBackup, paykitPendingBackupRestore, and usdtPendingBackupRestore are generic-password items with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly. This StrongBox cost is Android-only.
Device testing was not performed in this review. The author reports KeychainTest passing 9/9 on a Pixel 10 Pro, including the main-key fallback, and a separate 3 MB timing run; those runs were not repeated here. Ready for device testing. Manual test 1 remains the multi-MB restore timing check.
Suggested additional test cases
- Android, StrongBox phone, previous release: start a restore and force-stop after a multi-MB
PAYKIT_PENDING_BACKUP_RESTOREupsert is logged. Install this build, open the app, and retry the failed restore. The retained backup loads and the restore finishes. That one old decrypt can still take about half a minute; upserts after it take about a second each.
Reviewer model: grok-4.7
Reasoning effort: xhigh
coreyphillips
left a comment
There was a problem hiding this comment.
Two independent reviews.
worth doing, does not block
- Large-entry decrypt failures retry on StrongBox and log the wrong key's state (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:61-67)
- Reset can fail while creating an unused keystore key (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:205-209)
- The legacy fallback masks errors reading new backups (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:63-65)
nits
- New instrumented tests leave a pending-restore marker in the app's keychain (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:120-141)
the reviewers disagree, your call
- TEE key creation failure blocks restore with a usable main key (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:58-65)
talosmachina
left a comment
There was a problem hiding this comment.
No findings. Moves the three multi-MB restore entries to a separate non-StrongBox keystore key, with a fallback decrypt through the main key for entries written before the update. Reviewed a35c095, full tier, static: not built here, CI is the gate.
What I checked, and 4 candidates I ruled out
Read in full: AndroidKeyStore.kt, Keychain.kt, the KeychainTest.kt diff
Call sites traced: every reader and writer of PAYKIT_RECOVERY_BACKUP, PAYKIT_PENDING_BACKUP_RESTORE, USDT_PENDING_BACKUP_RESTORE (BackupRepo.kt, PaykitSdkService.kt, UsdtService.kt, WalletRestoreState.kt)
CI: build-and-test, lint, detekt, build-local, compose-ui green; e2e shards still running at review time
Ruled out
- Old entry unreadable after the update:
decryptfalls back to the main key onGeneralSecurityException, which covers theAEADBadTagExceptiona wrong GCM key raises;KeychainTest.ktwrites an entry with the main key and loads it. - Fallback hiding a real failure: a non-crypto error is rethrown, and when both keys fail the main key's exception surfaces as
FailedToLoad, as before. - Wipe leaving the new key behind:
wipe()resets both aliases. - Other keys moving off StrongBox: routing is by an explicit three-key set; the mnemonic, passphrase, PIN and
pinAttemptsRemaining()still go through the main key.
Merge confidence: 4/5, the keystore path is security-relevant and its updated test is @DeviceIntegration, which the PR's CI does not run (ci.yml runs only the ComposeUi suite); the evidence is the author's Pixel 10 Pro run.
Reviewer model: Claude Opus 5.5
Reasoning effort: Unknown (not exposed to the reviewing session)
Entries written with the large-value key carry a `tee:` tag, so reads pick their key from the entry and never retry on StrongBox. A reset deletes the large-value key without creating it, and failed-decrypt diagnostics probe the key the entry uses. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest 10/10 on Pixel 10 Pro
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since a35c095, including affected code paths and prior findings, at a57179d. Baseline: previous QA review. The single new commit rewrites the keystore routing, so this pass re-read Keychain.kt, AndroidKeyStore.kt and the new KeychainTest cases in full. The unchanged changelog fragment keeps its coverage from the baseline.
No new actionable code findings.
No new actionable code findings in the follow-up.
What changed and why it holds:
- Entries written with the large-value key now start with a
tee:tag, and reads choose the key from that tag (Keychain.kt#L61-L73). An untagged pre-updatePAYKIT_PENDING_BACKUP_RESTORE/USDT_PENDING_BACKUP_RESTORE/PAYKIT_RECOVERY_BACKUPvalue still decrypts with the main key and never initializes the large-value key. TheBackupRepocallers rewrite those entries withupsertString, and the rewritten entries get the tag. The new tests check the base64 output fromkotlin.io.encoding, which can't contain:, so the tag can't collide with old data. - If the large-value key can't be created or used, the write falls back to the main key. The lazy key creation runs inside that
runCatching, so aProviderExceptionis caught too. wipe()now deletes the large-value alias without re-creating it.AndroidKeyStore.encryptre-creates the key on the next write. Load diagnostics now check the alias the entry's tag names.- Mnemonic, passphrase, PIN and
pinAttemptsRemaining()still use the main StrongBox key.
Prior review threads: all five Spar threads from coreyphillips' review are marked resolved. Against the new code: the extra StrongBox retry and the wrong-alias diagnostics are gone (tag routing). An error reading a new entry is no longer masked by a fallback. A failure creating the TEE key no longer blocks reads of untagged entries or writes. Reset no longer creates an unused key. The new tests now delete their keys in finally. Each concern is resolved in the source at this head; none of them were run.
Validation and limits: device testing was not performed in this review. KeychainTest is @DeviceIntegration and PR CI doesn't run it. The commit message reports KeychainTest 10/10 on a Pixel 10 Pro; that run was not repeated here. At review time build-and-test and build-local had passed on this head, while lint, compose-ui and the e2e shards were still pending. The encrypt fallback path (large-value key unusable) has no automated test, because the keystore failure would have to be injected. The iOS comparison was not redone; the change is to Android-only StrongBox key routing. Ready for device testing once the pending checks finish. Manual test 1, the multi-MB restore timing check, remains the main runtime check.
Suggested additional test cases
- Android, StrongBox phone, previous release: start a restore and force-stop after a multi-MB
PAYKIT_PENDING_BACKUP_RESTOREupsert is logged. Install this build over it, open the app and retry the restore. The untagged retained backup loads through the main key, the restore finishes, and later upserts of the large keys take about a second each. - Android, this build: Reset wallet, then restore a wallet with a multi-MB Paykit backup on the same install. The restore completes quickly. The log has no
Failed to encrypt ... using the main keywarning, which shows the deleted large-value key was re-created on the first write.
Reviewer model: claude-opus-5-5
Reasoning effort: high
A missing key no longer appears on construction, so reading a tagged entry whose key is gone fails without creating a new key and the diagnostics report it missing. The wipe test writes through the keychain before and after the reset. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest on Pixel 10 Pro, all cases in batches
A write falls back to the main key when the large-value key can't encrypt, and a read of a tagged entry whose key is gone fails without creating one. Key deletion now takes the keystore lock, and a missing key fails with a clear message. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest on Pixel 10 Pro, all 12 cases in batches
|
Pushed 11762f0 and 9924a70 from my own review of the keystore change:
|
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 3 new commits (a57179d, 11762f0, 9924a70). One point still blocks a merge.
addressed
- Large-entry decrypt failures retry on StrongBox and log the wrong key's state (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:61-67). Fixed:
decryptin Keychain.kt:70-73 now picks the key from the entry'stee:tag, so a tagged entry that fails under the large-value key is never retried on StrongBox, and its own error becomes the cause ofFailedToLoad. The diagnostics at Keychain.kt:253-256 now probeLARGE_VALUE_ALIASfor tagged entries, through the staticAndroidKeyStore.containsAlias, which takes no lock and creates no key. Confirmed by reading both paths. - New instrumented tests leave a pending-restore marker in the app's keychain (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:120-141). Fixed: Both tests now call
sut.delete(key)in afinallyblock (KeychainTest.kt:137-139 and 151-153).setUpseedswalletIndex = 0, sodeleteremoves the same${key}_0entry the tests write. The three tests added since then clean up the same way. - TEE key creation failure blocks restore with a usable main key (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:58-65). Fixed: Untagged entries now decrypt with the main key and never touch
largeValueKeyStore(Keychain.kt:71). TheAndroidKeyStoreconstructor no longer generates a key, since theinitblock was removed and generation moved intoencrypt(AndroidKeyStore.kt:62-63). On a write,runCatching(Keychain.kt:63-67) wraps key creation and the encrypt and catches anyException. AProviderExceptionis now caught, and the value is written untagged with the main key.upsertString_largeValueKeyUnusable_shouldUseMainKeycovers that fallback. - Reset can fail while creating an unused keystore key (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:205-209). Fixed:
wipe()now callslargeValueKeyStore.deleteKey()(Keychain.kt:211). It is defined at AndroidKeyStore.kt:99-102 and deletes the alias only if it exists, without generating a key. Since the constructor no longer generates one either, a reset can no longer fail on TEE key creation. - The legacy fallback masks errors reading new backups (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:63-65). Fixed: With tag routing (Keychain.kt:70-73) there is no fallback for tagged entries. An
UnrecoverableKeyExceptionor a missing-keyIllegalStateExceptionfromlargeValueKeyStore.decryptreaches theFailedToLoadinloadIndexedandBlockingAccess.loadas its cause, and no StrongBox pass runs. Confirmed by tracing the call path;loadString_largeValueKeyMissing_shouldFailWithoutCreatingKeycovers the missing-key case.
new since the last review
needs changing before merge
- A transient lookup error can replace the wallet's main key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:61-64)
the reviewers disagree, your call
- Tagged reads bypass the three-entry allowlist (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:70-72)
- New keystore tests can invalidate an existing restore (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:180-210)
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since a57179d, including affected code paths and prior findings, at 9924a703. Baseline: previous QA review.
1 actionable finding — resolve or provide an evidence-backed rebuttal.
Construction no longer creates a keystore key. A missing large-value key fails the read without being created, wipe deletes that alias without creating it, and a write that cannot use it falls back to the main key. Those match the new KeychainTest cases. Device testing was not performed. The author's Pixel 10 Pro run of KeychainTest was in batches and does not cover a failed alias lookup.
encrypt still calls generateKey on every write. A keystore lookup error makes containsAlias report the alias as absent, and keystore2 then replaces the existing key. That can make the mnemonic, passphrase, and PIN unreadable. That generateKey call has been in encrypt since a57179d. On master, generation runs from init, once per process.
The five earlier threads are resolved, and the current source still has those fixes: a tagged decrypt does not retry on StrongBox, a read error is not masked, TEE key creation does not block the main key, reset does not create the large-value key, and the older tests delete their entries. The open tagged-read thread needs a private-datastore edit, and deleting the passphrase entry already loads as empty. The open test thread deletes the shared large-value alias; wipe() in this class already clears that keychain. iOS was not rechecked; this is Android Keystore behavior.
Findings
- [HIGH] Do not replace the main key when an alias lookup fails — inline at
app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:63.
Reviewer model: grok-4.7
Reasoning effort: xhigh
A write generates a key only when getKey returns none, since containsAlias also reports false on a failed lookup and generating then replaces the existing key. Tagged entries load only in the three large-value slots, and the tests that delete the large-value key drop the entries it encrypted. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest on Pixel 10 Pro, all 13 cases in batches
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 1 new commit (9b2f9a3). One point still blocks a merge.
addressed
- Tagged reads bypass the three-entry allowlist (app/src/main/java/to/bitkit/data/keychain/Keychain.kt:70-72). Fixed:
Keychain.kt:72checkskey in largeValueKeysbefore it uses the large-value key, and both read paths now pass the slot name (Keychain.kt:97and:112). Every reader of the three slots (BackupRepo,PaykitSdkService) uses the same key name it writes with.loadString_largeValueEntryInOtherSlot_shouldFailcovers the passphrase case.
still open
- A transient lookup error can replace the wallet's main key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:61-64). A transient keystore lookup error during a routine write can make the existing mnemonic, passphrase, and PIN unreadable.
encrypt()now callsgenerateKey()on every write. Android can returnfalsefromcontainsAlias()when a metadata lookup fails, and generating under the same alias replaces the existing key. Android alias lookup Keystore alias replacement I injected one lookup failure on a write after the main key was already in use. The write failed and the old ciphertext remained readable onorigin/masteranda35c095. On HEAD, the write succeeded with a replacement key and the old ciphertext failed authentication. Create a key only when the lookup confirms it is missing. Codex still sees it: A fault-injected test ofAndroidKeyStore.kt:63-66confirmed that a thrown lookup error preserves the key and a null result replaces it, making prior ciphertext unreadable. Android 9 through 11 can still return null on lookup errors and trigger that replacement. Key lookup Error handling Key generation - New keystore tests can invalidate an existing restore (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:180-210). Running either new failure-path test by itself on a reused test install can invalidate an unrelated pending restore. The fallback test replaces and deletes
keychain_large_values, and the missing-key test deletes it directly. Both clean up only their own preference, so other tagged restore entries remain present and unreadable. Codex still sees it: Both tests now calldeleteLargeValueEntries()atKeychainTest.kt:195,210, and line 237 deletes existing restore entries regardless of which key encrypted them. This still discards a pending backup and can remove the last marker that makesWalletViewModel.kt:442-443offer a retry.
new since the last review
worth doing, does not block
- New allowlist test overwrites and deletes the wallet's passphrase entry (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:215-227)
- The tagged-read test deletes the wallet's stored passphrase (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:216-226)
the reviewers disagree, your call
- On Android 9 to 11 a dead keystore binder still reads as a missing key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:62-67)
A cached keystore keeps a dead binder after a keystore restart on API 28-30, so getKey reads an existing key as missing and a write could replace it. The allowlist test uses a test-only key instead of the wallet's passphrase slot. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest not rerun (test phone disconnected)
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since 9924a703, including affected code paths, at 9b2f9a32. Baseline: previous review.
1 actionable finding — resolve or provide an evidence-backed rebuttal.
AndroidKeyStore.encrypt generates a key only when getKey returns null. On Keystore 2, containsAlias is false for lookup errors, while getKey returns null only when the alias is missing; a thrown lookup leaves the existing key in place. Keychain.decrypt rejects a tee: value stored outside the three large backup slots, on both the indexed and blocking load paths. Writes still add that prefix only for those slots, and base64 cannot contain :. loadString_largeValueEntryInOtherSlot_shouldFail asserts that refusal. Wipe still clears entries and then resets or deletes the keys.
iOS comparison was limited to Keychain.swift at a10c8d74. The same backup items are separate generic-password entries, with no second key or tee: tag, so this key-selection change has no iOS counterpart. That was not a full iOS review.
Device testing: not performed in this review. KeychainTest was inspected and not run.
Earlier findings reconciled at this revision: 2 still present.
Findings
- [HIGH] Do not replace the main key when an alias lookup fails — inline at
app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:65. Still present from the earlier review.
Existing concerns
- [LOW] Keep the allowlist test off the wallet passphrase entry — Running loadString_largeValueEntryInOtherSlot_shouldFail on an installed dev build that already has a passphrase removes that passphrase. The test writes a tee: value to BIP39_PASSPHRASE_0 in the app's real keychain DataStore (KeychainTest.kt:216-221) and sut.delete(key) removes it (KeychainTest.kt:226). The in-memory database is seeded at wallet index 0, which is the same suffix the app uses for the primary wallet. HiltTestRunner does not clear package data, and app/build.gradle.kts sets no clearPackageData. LightningService.kt:446-450 then loads the mnemonic, which is still present, and passes loadString(BIP39_PASSPHRASE) to node setup, so the stored passphrase is gone. The same test is also described in unresolved thread #2249 (comment). Any key outside the three large-value names exercises the check at Keychain.kt:72. Source analysis of this head. This review did not run the instrumented test. Use a test-only key name.
Reviewer model: grok-4.7
Reasoning effort: xhigh
containsAlias also reports false on a failed lookup, so a reset could skip the delete. deleteEntry ignores a missing key and throws on real errors. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest not rerun (test phone disconnected)
|
Pushed e4d19fd from my own review: a reset deletes the keystore key without checking |
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 2 new commits (5b36a76, e4d19fd). 1 blocking finding the reviewers disagree about.
addressed
- A transient lookup error can replace the wallet's main key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:61-64). Fixed:
encrypt()now generates a key only whengetKeyon a freshly loaded keystore returns null (AndroidKeyStore.kt:64-68).resetEncryptionKey/deleteKeyno longer callcontainsAlias(AndroidKeyStore.kt:96-104). I checked keystore2AndroidKeyStoreSpi.engineGetKeyon AOSP master: it returns null only when the cause isKEY_NOT_FOUNDand rethrows every other error, so a failed lookup throws instead of generating. - New allowlist test overwrites and deletes the wallet's passphrase entry (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:215-227). Fixed:
loadString_largeValueEntryInOtherSlot_shouldFailnow uses the test-only key"keyTaggedElsewhere"(KeychainTest.kt:216), so it no longer writes or deletesBIP39_PASSPHRASE_0. It still exercises thecheck(key in largeValueKeys)at Keychain.kt:72. - The tagged-read test deletes the wallet's stored passphrase (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:216-226). Fixed: This is the same test as point 4. Line 216 now uses
"keyTaggedElsewhere", so the write at line 221 and the delete at line 226 no longer touch the wallet's passphrase entry.
still open
- New keystore tests can invalidate an existing restore (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:180-210). Running either new failure-path test by itself on a reused test install can invalidate an unrelated pending restore. The fallback test replaces and deletes
keychain_large_values, and the missing-key test deletes it directly. Both clean up only their own preference, so other tagged restore entries remain present and unreadable. Codex still sees it: Both tests still replace or delete the installed app’s shared alias. Cleanup atKeychainTest.kt:231deletes any pending restore for wallet 0, including one that existed before the test. - On Android 9 to 11 a dead keystore binder still reads as a missing key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:62-67). On API 28 to 30 (minSdk is 28),
getKeyreturning null does not prove the key is missing, so a write inencrypt()can still replace an existing main key. On those versions the provider is the legacyandroid.security.keystore.AndroidKeyStoreSpi. ItsengineGetKeyreturns null wheneverKeyStore.containsis false (android11-releaseAndroidKeyStoreSpi.java:99-102).containsreturns false onRemoteException(KeyStore.java:290-297). The legacyKeyStorekeeps its binder in a final field, andAndroidKeyStore.keyStoreis cached for the life of the process. If the keystore daemon restarts while the app keeps running, every latergetKeyon the cached instance returns null.encrypt()(AndroidKeyStore.kt:63-66) then callsgenerateKey(). The newKeyGeneratortakes a freshKeyStore.getInstance()(AndroidKeyStoreKeyGeneratorSpi.java:106) and callsCredentials.deleteAllTypesForAliasbefore it generates (line 318), so the main key is replaced. The secondgetKeyon the stale instance still returns null, so the write fails as well. A large-value write that fails this way falls back to the main key and replaces that key too. On masterencryptnever generated a key, so the same restart only made writes fail. The comment at line 62 saysgetKeyreturns null only when the key is missing; that is true only from API 31. This comes from reading the AOSP source. I did not reproduce a daemon restart. A possible fix: before generating, confirm the key is absent through a freshly loadedKeyStore, so a stale binder cannot report the key as missing. Codex still sees it: Reloading atAndroidKeyStore.kt:32fixes writes after a completed restart. If the daemon dies duringgetKey()at line 64 on Android 9 through 11, the lookup can still return null, and the generator at line 66 can replace the existing key if the daemon has recovered by then. Legacy lookup Legacy generator
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after replies, with no new commit since e4d19fd. 1 blocking finding the reviewers disagree about.
still open
- New keystore tests can invalidate an existing restore (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:180-210). Running either new failure-path test by itself on a reused test install can invalidate an unrelated pending restore. The fallback test replaces and deletes
keychain_large_values, and the missing-key test deletes it directly. Both clean up only their own preference, so other tagged restore entries remain present and unreadable. Codex still sees it: The cleanup cited in the reply removes the unreadable entries, butKeychainTest.kt:195-210and:231-237show that either test still deletes an unrelated pending restore on a reused dev install. Uninstalling after a connected run does nothing to isolate data already present when the test starts. - On Android 9 to 11 a dead keystore binder still reads as a missing key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:62-67). On API 28 to 30 (minSdk is 28),
getKeyreturning null does not prove the key is missing, so a write inencrypt()can still replace an existing main key. On those versions the provider is the legacyandroid.security.keystore.AndroidKeyStoreSpi. ItsengineGetKeyreturns null wheneverKeyStore.containsis false (android11-releaseAndroidKeyStoreSpi.java:99-102).containsreturns false onRemoteException(KeyStore.java:290-297). The legacyKeyStorekeeps its binder in a final field, andAndroidKeyStore.keyStoreis cached for the life of the process. If the keystore daemon restarts while the app keeps running, every latergetKeyon the cached instance returns null.encrypt()(AndroidKeyStore.kt:63-66) then callsgenerateKey(). The newKeyGeneratortakes a freshKeyStore.getInstance()(AndroidKeyStoreKeyGeneratorSpi.java:106) and callsCredentials.deleteAllTypesForAliasbefore it generates (line 318), so the main key is replaced. The secondgetKeyon the stale instance still returns null, so the write fails as well. A large-value write that fails this way falls back to the main key and replaces that key too. On masterencryptnever generated a key, so the same restart only made writes fail. The comment at line 62 saysgetKeyreturns null only when the key is missing; that is true only from API 31. This comes from reading the AOSP source. I did not reproduce a daemon restart. A possible fix: before generating, confirm the key is absent through a freshly loadedKeyStore, so a stale binder cannot report the key as missing. Codex still sees it: The fresh lookup atAndroidKeyStore.kt:32removes the cached binder problem, butencrypt()at:64-67still generates a key if the binder dies during lookup and the daemon recovers before generation. I traced the legacy lookup and generator and confirmed that this can replace the main key during an ordinary write after startup, whereas master never generated a key fromencrypt(). Lookup Binder error handling Key generation
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since 9b2f9a3, including the keystore load and deletion paths, at e4d19fd. Baseline: previous review. Inherited from that baseline: load-failure diagnostics, the wipe-wallet caller, the changelog fragment, and the unchanged backup callers of the three large-value keys.
No new actionable code findings.
On Android 9–11, a failed keystore lookup during a write still makes encrypt generate a new key, and generation deletes the existing one. Reloading the keystore avoids a cached dead binder; a failed exist on that fresh store still comes back as a null key. API 31 and later throw on those errors instead. Device testing was not performed. KeychainTest was inspected and not run.
Unconditional deleteEntry leaves a missing alias alone: the legacy keystore returns, and keystore2 ignores KEY_NOT_FOUND. The slot-rejection test still expects a load failure for a tee: value outside the three large-value keys. No iOS revision was compared. Recommended before device testing: fail the write when lookup fails. The restore timing checks do not exercise a failed lookup.
Earlier findings reconciled at this revision: 1 still present, 1 verified fixed, 1 duplicate.
Findings
- [HIGH] Fail a keychain write when keystore lookup fails — now at
app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:66. Same issue as the earlier review.
Existing concerns
- [LOW] New keystore tests can invalidate an existing restore — Running either new failure-path test on a dev install that already has a pending restore deletes that restore. upsertString_largeValueKeyUnusable_shouldUseMainKey generates an HMAC key on keychain_large_values (KeychainTest.kt:185-187). Both that test and loadString_largeValueKeyMissing_shouldFailWithoutCreatingKey then delete the alias and call deleteLargeValueEntries (lines 196, 205, 210, and 231-237). That helper deletes PAYKIT_RECOVERY_BACKUP, PAYKIT_PENDING_BACKUP_RESTORE, and USDT_PENDING_BACKUP_RESTORE when they exist. The test database is wallet index 0, and the DataStore is the installed app's keychain, so a pre-existing wallet-0 restore entry is removed while the mnemonic remains. HiltTestRunner does not clear package data, and app/build.gradle.kts sets no clearPackageData or uninstall. The thread is unresolved. The latest reply says the behavior stays. A focused issue search for KeychainTest and keychain_large_values returned no issues. Source analysis of e4d19fd; this review did not run the test.
Reviewer model: grok-4.7
Reasoning effort: xhigh
The main key is created at construction as on master, and a write fails when its key is missing. The large-value key is created on a write only while no tagged entry exists, so replacing it after a failed lookup loses nothing. The failure-path tests skip on an install that already holds restore entries. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest on Pixel 10 Pro, all 13 cases in batches
The tagged-entry check runs before the fallback, so a cancellation or a DataStore read failure is no longer taken for a keystore failure. A test covers a write while tagged entries exist and the key is gone. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest on Pixel 10 Pro, all 14 cases in batches
Suspend writes pass the DataStore preferences they read into encrypt, and only the blocking write path uses a blocking read. The wipe test checks that the entry written before the reset is tagged. Verified: just compile, just lint, just test, compileDevDebugAndroidTestKotlin; KeychainTest on Pixel 10 Pro, all 14 cases in batches
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 3 new commits (b281a8c, fefcffb, 1e722bd). Nothing blocking remains.
addressed
- New keystore tests can invalidate an existing restore (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:180-210). Fixed:
KeychainTest.kt:184,:205and:220now callassumeTrue(largeValueKeys.none(sut::exists)), so each test that replaces or deleteskeychain_large_valuesskips when any of the three restore entries exists at wallet index 0. The onlyConfigEntityconstructed in main code is the seed atAppDb.kt:101, withwalletIndex = 0L, so wallet 0 is the only slot where the app stores a tagged entry. I confirmed this by reading the tests and grepping everyConfigEntity(call site. - On Android 9 to 11 a dead keystore binder still reads as a missing key (app/src/main/java/to/bitkit/data/keychain/AndroidKeyStore.kt:62-67). Fixed:
encryptatAndroidKeyStore.kt:66-67now fails with "Missing key" and no longer generates a key. I grepped everygenerateKeycaller. The first isinitat line 36: it uses the samecontainsAliascheck as master and runs once per process. The second isresetEncryptionKey, which onlywipe()calls. The third iscreateKeyIfMissingat line 103.Keychain.kt:63-65calls that only on the large-value key, and only while the preferences hold notee:entry. A missing key misread on API 28-30 can no longer replace the main key on a write. If it replaces the large-value key, no stored ciphertext depends on that key.
new since the last review
worth doing, does not block
- Missing-key fallback test can pass without a tagged entry (app/src/androidTest/java/to/bitkit/data/keychain/KeychainTest.kt:219-231)
Closes #2227
Description
PAYKIT_RECOVERY_BACKUP,PAYKIT_PENDING_BACKUP_RESTORE,USDT_PENDING_BACKUP_RESTORE) now use their own keystore key created without StrongBox, so each encrypt or decrypt pass over a 3 MB backup takes about 1 s instead of about 44 stee:prefix), so each read uses the key its entry was written with: entries written before the update still decrypt with the main key, and a restore already in flight across the update pays one slow decrypt for its retained backupSecurity: those three entries move from StrongBox to TEE-backed protection (still hardware-backed). The mnemonic, passphrase, PIN and every other entry stay on the StrongBox key.
Out of Scope
BackupRepo.kt: the five keychain passes per restore stay; each is now about 1 sPaykitSdkService.kt:PAYKIT_RECOVERY_BACKUPis written and never read, on iOS too; kept as isDesign
N/A — no UI changes.
Preview
N/A — no user-visible changes.
QA Notes
Setup
Journeys
N/A — not drivable; see Manual Tests.
Manual Tests
PAYKIT_PENDING_BACKUP_RESTORE/USDT_PENDING_BACKUP_RESTORE/PAYKIT_RECOVERY_BACKUPupsert takes about 1 s in the log, andBuilding node…reads the mnemonic without waiting — a mainnet wallet with a multi-MB Paykit backup not in CapabilitiesPAYKIT_PENDING_BACKUP_RESTOREupsert is logged, install this build and retry the restore → the retained backup loads and the restore finishes; that one old decrypt can take about half a minute, later upserts about 1 s each — needs an install across versions on a StrongBox phoneFailed to encrypt ... using the main keywarning — needs a mainnet wallet with a multi-MB Paykit backupAutomated Checks
KeychainTest.kt— a large entry round-trips, tagged and encrypted under the new key; an untagged entry written with the main key still loads; a write falls back to the main key when the new key can't encrypt; a read whose key is gone fails without creating one; a tagged entry outside the three slots fails to load; wipe deletes the new key and the next write recreates itKeychainTest.kton a Pixel 10 Pro — all passEvidence
Full restoretook 29 s, and the mnemonic read at node build took 0.17 s; that wallet's WALLET backup was small at the time, so the multi-MB pass time comes from the instrumented run aboveGaps
Models used
Claude Opus 5.5(reasoning:medium)Claude Opus 5.5(reasoning:medium)Claude Sonnet 5.5(reasoning:high),Gemini 4 Neon(reasoning:high)