Skip to content

fix: speed up wallet restore - #2249

Merged
ovitrif merged 11 commits into
masterfrom
perf/fast-paykit-restore
Dec 3, 2026
Merged

ovitrif merged 11 commits into
masterfrom
perf/fast-paykit-restore

Conversation

@ovitrif

@ovitrif ovitrif commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2227

Description

  • Fixes wallet restore spending minutes in the keychain when the WALLET backup is large: the three multi-MB restore entries (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 s
  • Fixes the node start waiting on those passes for its mnemonic reads, because the new key has its own lock
  • Tags entries written with the new key (tee: 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 backup
  • Falls back to the main key for these writes when the new key can't be created, so a restore still goes ahead
  • Never creates the main key on a write: it is created at construction as on master, so a failed keystore lookup fails the write instead of replacing the key. The new key is created on a write only while no entry uses it, so replacing it loses nothing
  • Deletes the new key on wipe, without creating it first

Security: 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

  • Restore flow: the node start and the WALLET restore still wait on each other until a 30 s timeout — bug: restore waits 30 s for the node to start #2247
  • BackupRepo.kt: the five keychain passes per restore stay; each is now about 1 s
  • PaykitSdkService.kt: PAYKIT_RECOVERY_BACKUP is written and never read, on iOS too; kept as is
  • iOS: no twin, because its keychain stores these as regular items whose data is not encrypted on a slow secure chip

Design

N/A — no UI changes.

Preview

N/A — no user-visible changes.

QA Notes

Setup

  • Mainnet build of this branch, on a phone with StrongBox (Pixel 6 or later)
  • A wallet whose WALLET backup holds a large Paykit state (about 3 MB) for manual test 1

Journeys

N/A — not drivable; see Manual Tests.

Manual Tests

  • 1. Reset and restore a wallet with a large WALLET backup → each PAYKIT_PENDING_BACKUP_RESTORE / USDT_PENDING_BACKUP_RESTORE / PAYKIT_RECOVERY_BACKUP upsert takes about 1 s in the log, and Building node… reads the mnemonic without waiting — a mainnet wallet with a multi-MB Paykit backup not in Capabilities
  • 2. On the previous release, start a restore and force-stop after a multi-MB PAYKIT_PENDING_BACKUP_RESTORE upsert 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 phone
  • 3. Reset the wallet, then restore a wallet with a multi-MB Paykit backup on the same install → the restore completes quickly and the log has no Failed to encrypt ... using the main key warning — needs a mainnet wallet with a multi-MB Paykit backup

Automated Checks

  • updated 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 it
  • ran KeychainTest.kt on a Pixel 10 Pro — all pass

Evidence

  • 3 MB timing on a Pixel 10 Pro, one-off instrumented run: StrongBox key 44.4 s encrypt / 44.4 s decrypt; new key 1.0 s / 1.2 s
  • Mainnet restore from the phrase on a Pixel 10 Pro with an earlier build of this branch (same key routing): Full restore took 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 above

Gaps

  • Manual test 1 not run end to end with a multi-MB backup: the test wallet's backup was small by the time of the run

Models used

  • Planning/scoping: Claude Opus 5.5 (reasoning: medium)
  • Implementation: Claude Opus 5.5 (reasoning: medium)
  • Review: Claude Sonnet 5.5 (reasoning: high), Gemini 4 Neon (reasoning: high)
  • Review rounds: 12

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
@ovitrif ovitrif added this to the 3.3.0 milestone Dec 3, 2026
@ovitrif ovitrif self-assigned this Dec 3, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T15:58:43.339461Z a35c095 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ovitrif
ovitrif requested review from a team, coreyphillips and piotr-iohk and removed request for a team December 3, 2026 15:57
@greptile-apps

greptile-apps Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge; no actionable issues were found.

Summary

Speeds up large wallet-backup reads and writes by giving three backup entries a separate Android Keystore key without StrongBox preference.

  • Large Paykit backup entries use a separate, faster key.

No actionable issues were found. Tests were inspected, not run.

Acknowledged scope:

  • ovitrif explicitly intends to move these three entries away from StrongBox. Other entries keep the existing key.
  • ovitrif explicitly defers the existing node-start/restore wait to bug: restore waits 30 s for the node to start #2247. This PR does not introduce it.

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]
Loading

Reviews (1) · Last reviewed commit: "fix: fall back on any keystore error for..." · Reviewed by Greptile

@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 1e722bd (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_RESTORE upsert 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 coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: decrypt falls back to the main key on GeneralSecurityException, which covers the AEADBadTagException a wrong GCM key raises; KeychainTest.kt writes 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 piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-update PAYKIT_PENDING_BACKUP_RESTORE / USDT_PENDING_BACKUP_RESTORE / PAYKIT_RECOVERY_BACKUP value still decrypts with the main key and never initializes the large-value key. The BackupRepo callers rewrite those entries with upsertString, and the rewritten entries get the tag. The new tests check the base64 output from kotlin.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 a ProviderException is caught too.
  • wipe() now deletes the large-value alias without re-creating it. AndroidKeyStore.encrypt re-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_RESTORE upsert 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 key warning, 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
@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 11762f0 and 9924a70 from my own review of the keystore change:

  • Keys are created only on write or reset, so reading a tagged entry whose key is gone fails without creating a new key, and the decrypt diagnostics report it missing.
  • Deleting the large-value key takes the keystore lock, and a missing key fails with a clear message.
  • New KeychainTest cases cover the main-key fallback on write, a read with the large-value key missing, and a write after a reset. All pass on a Pixel 10 Pro.

@ovitrif
ovitrif requested a review from coreyphillips December 3, 2026 18:00

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: decrypt in Keychain.kt:70-73 now picks the key from the entry's tee: tag, so a tagged entry that fails under the large-value key is never retried on StrongBox, and its own error becomes the cause of FailedToLoad. The diagnostics at Keychain.kt:253-256 now probe LARGE_VALUE_ALIAS for tagged entries, through the static AndroidKeyStore.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 a finally block (KeychainTest.kt:137-139 and 151-153). setUp seeds walletIndex = 0, so delete removes the same ${key}_0 entry 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). The AndroidKeyStore constructor no longer generates a key, since the init block was removed and generation moved into encrypt (AndroidKeyStore.kt:62-63). On a write, runCatching (Keychain.kt:63-67) wraps key creation and the encrypt and catches any Exception. A ProviderException is now caught, and the value is written untagged with the main key. upsertString_largeValueKeyUnusable_shouldUseMainKey covers 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 calls largeValueKeyStore.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 UnrecoverableKeyException or a missing-key IllegalStateException from largeValueKeyStore.decrypt reaches the FailedToLoad in loadIndexed and BlockingAccess.load as its cause, and no StrongBox pass runs. Confirmed by tracing the call path; loadString_largeValueKeyMissing_shouldFailWithoutCreatingKey covers 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 piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:72 checks key in largeValueKeys before it uses the large-value key, and both read paths now pass the slot name (Keychain.kt:97 and :112). Every reader of the three slots (BackupRepo, PaykitSdkService) uses the same key name it writes with. loadString_largeValueEntryInOtherSlot_shouldFail covers 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 calls generateKey() on every write. Android can return false from containsAlias() 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 on origin/master and a35c095. 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 of AndroidKeyStore.kt:63-66 confirmed 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 call deleteLargeValueEntries() at KeychainTest.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 makes WalletViewModel.kt:442-443 offer 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 piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed e4d19fd from my own review: a reset deletes the keystore key without checking containsAlias first, since that also reports false on a failed lookup. deleteEntry ignores a missing key and throws on real errors.

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 when getKey on a freshly loaded keystore returns null (AndroidKeyStore.kt:64-68). resetEncryptionKey/deleteKey no longer call containsAlias (AndroidKeyStore.kt:96-104). I checked keystore2 AndroidKeyStoreSpi.engineGetKey on AOSP master: it returns null only when the cause is KEY_NOT_FOUND and 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_shouldFail now uses the test-only key "keyTaggedElsewhere" (KeychainTest.kt:216), so it no longer writes or deletes BIP39_PASSPHRASE_0. It still exercises the check(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 at KeychainTest.kt:231 deletes 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), getKey returning null does not prove the key is missing, so a write in encrypt() can still replace an existing main key. On those versions the provider is the legacy android.security.keystore.AndroidKeyStoreSpi. Its engineGetKey returns null whenever KeyStore.contains is false (android11-release AndroidKeyStoreSpi.java:99-102). contains returns false on RemoteException (KeyStore.java:290-297). The legacy KeyStore keeps its binder in a final field, and AndroidKeyStore.keyStore is cached for the life of the process. If the keystore daemon restarts while the app keeps running, every later getKey on the cached instance returns null. encrypt() (AndroidKeyStore.kt:63-66) then calls generateKey(). The new KeyGenerator takes a fresh KeyStore.getInstance() (AndroidKeyStoreKeyGeneratorSpi.java:106) and calls Credentials.deleteAllTypesForAlias before it generates (line 318), so the main key is replaced. The second getKey on 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 master encrypt never generated a key, so the same restart only made writes fail. The comment at line 62 says getKey returns 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 loaded KeyStore, so a stale binder cannot report the key as missing. Codex still sees it: Reloading at AndroidKeyStore.kt:32 fixes writes after a completed restart. If the daemon dies during getKey() 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

@ovitrif
ovitrif requested a review from coreyphillips December 3, 2026 19:52

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, but KeychainTest.kt:195-210 and :231-237 show 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), getKey returning null does not prove the key is missing, so a write in encrypt() can still replace an existing main key. On those versions the provider is the legacy android.security.keystore.AndroidKeyStoreSpi. Its engineGetKey returns null whenever KeyStore.contains is false (android11-release AndroidKeyStoreSpi.java:99-102). contains returns false on RemoteException (KeyStore.java:290-297). The legacy KeyStore keeps its binder in a final field, and AndroidKeyStore.keyStore is cached for the life of the process. If the keystore daemon restarts while the app keeps running, every later getKey on the cached instance returns null. encrypt() (AndroidKeyStore.kt:63-66) then calls generateKey(). The new KeyGenerator takes a fresh KeyStore.getInstance() (AndroidKeyStoreKeyGeneratorSpi.java:106) and calls Credentials.deleteAllTypesForAlias before it generates (line 318), so the main key is replaced. The second getKey on 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 master encrypt never generated a key, so the same restart only made writes fail. The comment at line 62 says getKey returns 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 loaded KeyStore, so a stale binder cannot report the key as missing. Codex still sees it: The fresh lookup at AndroidKeyStore.kt:32 removes the cached binder problem, but encrypt() at :64-67 still 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 from encrypt(). Lookup Binder error handling Key generation

@piotr-iohk piotr-iohk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed fefcffb and 1e722bd from my own review: a cancellation during a large-value write is rethrown instead of falling back to the main key, and suspend writes read the keychain without blocking. New tests cover a write while tagged entries exist and the new key is gone.

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, :205 and :220 now call assumeTrue(largeValueKeys.none(sut::exists)), so each test that replaces or deletes keychain_large_values skips when any of the three restore entries exists at wallet index 0. The only ConfigEntity constructed in main code is the seed at AppDb.kt:101, with walletIndex = 0L, so wallet 0 is the only slot where the app stores a tagged entry. I confirmed this by reading the tests and grepping every ConfigEntity( 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: encrypt at AndroidKeyStore.kt:66-67 now fails with "Missing key" and no longer generates a key. I grepped every generateKey caller. The first is init at line 36: it uses the same containsAlias check as master and runs once per process. The second is resetEncryptionKey, which only wipe() calls. The third is createKeyIfMissing at line 103. Keychain.kt:63-65 calls that only on the large-value key, and only while the preferences hold no tee: 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)

@ovitrif

ovitrif commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Merging: CI is green on 1e722bd, it is approved on this head and every review thread is resolved. The one non-blocking test point is tracked in #2254.

@ovitrif
ovitrif merged commit a8a8a71 into master Dec 3, 2026
23 checks passed
@ovitrif
ovitrif deleted the perf/fast-paykit-restore branch December 3, 2026 22:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: wallet restore takes minutes

4 participants