Skip to content

feat(identity): recover keys stranded by legacy migration (#889) - #941

Merged
lklimek merged 22 commits into
v1.0-devfrom
feat/issue-889-legacy-key-recovery
Jul 30, 2026
Merged

lklimek merged 22 commits into
v1.0-devfrom
feat/issue-889-legacy-key-recovery

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR: Adds a discoverable, opt-in "restore stranded keys" flow so identities partially migrated from the previous app version can recover keys and masternode role links that were left behind, without re-entering any secrets.

User story

As an Everyday User who upgraded from the previous app version, I want a simple way to restore keys and role associations that got stranded during migration, to achieve a fully working identity or masternode without hunting for backups or re-typing private keys.

Scenario

Base flow

A user who ran the previous app version (v0.9.3) had identity and masternode key data stored in the old local database. Upgrading to the current version migrates what it safely can into the new storage, but some installs are left with a "bare" or partially-populated identity — a key, or a voting/owner/payout role association, that exists in the old database but never made it into the new one.

Actual behavior

Today there is no way to recover that stranded data through the UI. The old database still holds it (nothing is ever deleted), but the only paths back in are re-entering a WIF key by hand or re-running the full migration, neither of which is discoverable from where the user actually notices the problem (a masternode showing a missing voting key, or a Key Info screen missing a key the user knows they had).

Expected behavior

On the masternode detail screen and the identity Key Info screen, a self-appearing/self-disappearing section offers to restore exactly the keys and role links that are genuinely missing — never touching anything already present. For a password-protected identity, restoring requires the identity's password, same as any other key-sealing operation. The offer disappears on its own once there is nothing left to recover, and running it again after a full recovery is a safe no-op.

Detailed discussion

What was done

Closes #889.

Ground-up design (not derived from PR #925 — see "Prior work" below) covering:

  • model/legacy_recovery.rs — pure, side-effect-free candidate computation (compute_recovery_plan) and additive-only merge (apply_recovery_plan). A candidate is only ever something the current identity record lacks; nothing held today can be overwritten or removed by construction. Candidates also require a correspondence check (the restored key must still resolve to a live, non-disabled key on the identity, and a wallet-derivation reference must name a wallet this install holds) so a stale or rotated-away legacy key can't silently satisfy a role without actually fixing anything. For a key or role link held on a separate voting/operator identity, that correspondence can only be verified against this identity's own current records — the previous version's saved copy of that other identity, or of the link itself, is never trusted to vouch for itself, which also closes a two-step case where an unverified link, once restored, would otherwise become the very evidence a later pass uses to justify restoring more from the same source. An unlinked voting/operator key or link is listed with an explanation rather than silently restored — see "Known limitation" below for what this means in practice for a brand-new masternode's voting key, and feat(identity): verify a masternode voting key against its current on-chain address before restoring/accepting it #942 for the planned follow-up.
  • database/legacy_import.rs — single-row read of the frozen legacy database, SQLITE_OPEN_READ_ONLY. No write path to the legacy store exists anywhere in this change.
  • backend_task/identity/recover_legacy_keys.rs — the enforcement layer: recomputes candidates server-side (never trusts the UI's preview), gates on the identity's password when the identity is protected, and performs exactly one write to persist the merge. Holds the identity-load claim for the duration but keeps the storage-migration guard scoped to synchronous work only, so an open password prompt can't block unrelated operations.
  • UI: a shared, render-only "restore stranded keys" component surfaced from both the masternode detail screen and the identity Key Info screen, reusing this app's existing key-role labelling so there is one source of truth for how a key's role is displayed.
  • No new database tables/columns, no new persisted key-value state — detection is a pure recomputation on every screen visit, which is also what makes recovery safely idempotent and repeatable.

Testing

  • Unit tests for the merge algorithm (model layer), including the correspondence rules and the voter/operator-link exclusion described above.
  • Backend integration tests against an offline AppContext: end-to-end restore for both protection tiers, wrong/cancelled/unavailable password prompts, double-run idempotency, deleted-identity handling, unreadable/absent legacy rows, concurrent-load exclusion, wallet-link preservation, and a mid-flight protection-tier-change guard.
  • UI tests: the section's appear/disappear behavior, cross-identity result attribution (a restore completing for one identity never touches another identity's screen state), and off-screen restore survival (returning to a screen after a restore landed elsewhere no longer risks overwriting it).
  • cargo test --all-features --lib --test kittest: 2198 lib + 293 kittest tests passing, 0 failures, 0 regressions across the workspace (independently re-verified from a clean recompile, not just self-reported).
  • cargo clippy --all-features --all-targets -- -D warnings and cargo fmt --all clean.
  • Round-3 hardening (see Review status below) added 8 further tests: a key_id/embedded-id mismatch rejection, a malformed-key-derivation rejection, a same-material-different-slot collision rejection, a live concurrent-writer-vs-recovery-guard race across all five whole-record writers, and a stale-password re-protect-during-recovery regression.

Known limitation

A masternode loaded from just its ProTxHash (no locally-held keys yet) can have its owner and payout keys restored automatically by this flow, but not its voting key when that key lives on a separate voter identity the current record has no independent link to — which is the common case for this scenario. This isn't an oversight: it's the direct, necessary consequence of the correspondence check above refusing to let old, unverifiable data vouch for itself. The voting key still has a path back in — entering it by hand, same as before this PR — it's just not a one-click restore. Closing that gap safely requires checking a restored/entered voting key against the masternode's actual current on-chain voting address, which neither this flow nor the existing manual-entry path currently does; tracked as a separate follow-up in #942 rather than expanding this PR's scope beyond what #889 asked for (migrating stranded data, not adding new on-chain verification).

Review status

This PR went through two independent review passes after opening, deliberately not shown prior review history to avoid confirmation bias:

  1. Adversarial review (three reviewers, security/project-consistency/QA lenses): 23 findings, none CRITICAL/HIGH. 4 assessed as blocking, fixed — a circular-validation gap in the voter/operator key check, a fresh-install detection gate that didn't actually engage in the shipped binary, a residual stale-data window on the identity Key Info screen, and a cross-identity misattribution bug in the restore-completion handler. The remaining 19 are minor (security hygiene, doc accuracy, code-quality nits), deliberately left for a follow-up.
  2. Goal-alignment audit (does the current code, not just the diff, actually satisfy Recovery flow for legacy-only identity keys stranded by a partial pre-migration load #889's literal acceptance criteria): found that the voter/operator correspondence fix above narrowed voting-key auto-restore more than initially understood (see "Known limitation"), plus left some now-dead UI code and doc/CHANGELOG text describing the pre-fix behavior. Both fixed; the scope question was resolved as above (filed as feat(identity): verify a masternode voting key against its current on-chain address before restoring/accepting it #942, not expanded here). This pass also caught the same self-vouching shape applying to the operator-link case, closed in this PR, and flagged a structurally similar (currently unreachable, closed only by luck rather than design) case on the voter-link side — noted on feat(identity): verify a masternode voting key against its current on-chain address before restoring/accepting it #942 rather than fixed here, since a full fix would remove an existing auto-approval feature and is a larger, separate change.
  3. Automated review (thepastaclaw): 8 findings, 4 flagged blocking — all verified as real defects against current code (not stale reviewer snapshots) and fixed. A recovered key is now checked against the exact live key slot it's meant to replace (matching key_id, not just type+bytes scanned across every key on the identity), closing both a malformed-key-derivation bypass and a same-material-under-a-different-slot collision. A new per-identity record lock serializes recovery's read-merge-write against every other whole-record writer — refresh, top-up, key edit, rename, protect/unprotect, delete — not only the migration/load guards it previously relied on. The verified password is now re-checked against the identity's current protected state immediately before sealing, closing a window where a mid-flight re-protect-with-a-new-password could seal recovered keys under the stale one. An unrelated backend-task error can no longer reset an in-progress restore back to "offered" on the Key Info or Masternodes screens. One suggestion (preserving SQLite error causes in a recovery-read failure) and two documentation nitpicks were left unaddressed, out of this round's scope.

Breaking changes

None. No schema change, no new dependency, no change to any existing flow's behavior — the feature is entirely dormant on any install without a legacy database.

Checklist

  • Tests added/updated
  • cargo fmt --all
  • cargo clippy --all-features --all-targets -- -D warnings
  • docs/user-stories.md updated (new story, IDN-020)
  • CHANGELOG.md updated
  • Design record added (docs/ai-design/2026-07-28-legacy-identity-recovery/)

Prior work

Attribution

🤖 Co-authored by Claudius the Magnificent AI Agent

Summary by CodeRabbit

  • New Features
    • Added an opt-in legacy recovery flow to restore keys and role associations left behind after an upgrade.
    • Recovery offers appear per identity on identity details, Key Info, and masternode/evonode detail screens when eligible.
    • Users can preview what will be restored and apply by role (owner/voting/payout) without replacing or removing existing keys.
    • Protected identities prompt for the identity password; cancel/wrong password leaves state unchanged and restore remains repeatable.
    • Unavailable/unreadable or non-matching keys are shown with explanations (not silently restored).
  • Bug Fixes
    • Improved refresh/retirement of recovery offers and success messaging after returning from Key Info.
  • Tests
    • Added UI tests covering restoring, exclusions, and in-flight behavior.

lklimek and others added 10 commits July 28, 2026 19:03
Issue #889: a v0.9.3 identity that was already partially loaded before the
upgrade keeps its remaining keys stranded in `data.db`, because the migration
skips a present identity wholesale. That rule is correct — three earlier
reconcile heuristics each failed by inferring user intent from record shape.

`compute_recovery_plan` only lists what the legacy record holds and the modern
one does not, keyed on the `(target, key_id)` map slot and on `None`
associations; it never decides whether an item should come back. That decision
travels back in as an item-level allowlist, so the absence-versus-removal
ambiguity lands with the only party holding the provenance.

`apply_recovery_plan` is additive by construction, not by discipline: it starts
from the fresh modern record, inserts with `or_insert` so the modern copy wins
every collision, recomputes candidacy rather than trusting the allowlist, and
has no write path at all for alias, status, the dpp identity, DPNS names, or
the wallet link. A voting key drags its voter-identity link along, since one
without the other cannot vote.

M1-M10 from the design doc's test matrix. M2/M5/M6/M9/M10 were confirmed RED
against a naive legacy-wins merge before this implementation landed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ecoder

Issue #889: the recovery flow needs one identity out of the preserved legacy
`data.db`, not the whole table. A second hand-written reader would be free to
drift from the importer's idea of which rows are readable — and then recovery
could merge from a record the migration never considered importable, or miss
one it did.

So the per-row decode moves into `decode_identity_row` and both readers call
it, along with one shared `SELECT` that binds the same pair of accepted network
spellings. `read_identity_row` adds only the `id` predicate on top.

`LegacyIdentityLookup` keeps "nothing to recover" and "the row will not decode"
apart. An absent table, an absent row, an observed-identity cache row and a
NULL blob are all `Absent` — the ordinary answer. Only a genuinely corrupt row
is `Unreadable`, so no caller can mistake corruption for an empty record and
merge against it.

`open_legacy_read_only` is hoisted next to `database/mod.rs`'s existing one, so
`SQLITE_OPEN_READ_ONLY` is a property of the one function that opens the file
rather than of each caller remembering the flag.

The importer's 12 existing row-decode tests are the regression net for the
extraction; 8 new tests cover the lookup, including one asserting both readers
decode the same row identically.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
… data

Issue #889: an identity that was only partially loaded before the v1.0 upgrade
keeps its remaining keys in `data.db`, reachable by nothing — the load form
rejects the duplicate ProTxHash, and the per-key screen wants a WIF the user may
no longer hold. This is the way in, and it is entirely user-driven.

`CheckLegacyRecovery` lists; `RecoverLegacyIdentityData` writes. Detection is
read-only, offline and side-effect-free, so a screen can dispatch it on arrival
and hide the affordance when the plan comes back empty. Candidacy is recomputed
inside the executing task rather than trusted from the caller: only
`recomputed-candidates ∩ approved` is merged, so an approval that went stale
since the preview is reported rather than acted on, and an item the user never
approved is never restored even when it is missing. An empty allowlist is
refused, not widened into "restore everything".

The protection-downgrade trip that sank an earlier reconcile attempt is
unreachable here by branch condition, not by care: the flow branches on the same
predicate the at-rest guard evaluates. On a protected identity the password is
verified up front through the shipped prompt, the resident-plaintext preflight
runs before any vault write, and every merged key is sealed under that password
before the record is persisted — so the encoder never sees plaintext on a
protected identity. On a keyless identity there is no protected key for the
guard to protect. Cancel, wrong password and headless all fail closed with the
stored record byte-identical.

Exactly one record write, so the merge either lands whole or changes nothing.
No new persisted state: eligibility recomputes from the two existing stores, so
a re-run is a no-op and `data.db` — opened read-only — stays a repeatable
recovery source.

`reject_resident_identity_plaintext` widens to `pub(super)`; it now guards both
seal boundaries. Two test-only readers expose the at-rest blob and the wallet
link, which the hydrated record cannot show.

B1-B12 from the design doc's test matrix, on the offline wired `AppContext`
harness, plus the excluded-key and empty-allowlist cases.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
…node page

Issue #889: the restore path exists but nothing reaches it. The node detail
page is the canonical surface — its operator is the one holding a node that
cannot vote because its voting key stayed behind in the previous version's
saved data.

The offer is passive and contextual, never a launch-time nag. On opening a
node the view dispatches the read-only detection task once, and only on an
install that actually has a previous-version database; the section renders in
the Keys area only when detection found something, and retires itself once a
restore lands, because eligibility recomputes from the two stores every time.

For a node with no voting key that becomes the primary remedy: the
missing-voter message points at restoring, which asks nothing of an operator
who no longer has the key, and the existing WIF prompt keeps its place as the
fallback for one who does.

`LegacyRecoveryState` (`ui/state/`) owns the fetch state — dispatch-once,
in-flight, offered, retryable — and `LegacyRecoverySection` (`ui/components/`)
renders it, per the placement rule's render/no-render split. A failed restore
returns to its offer so a mistyped identity password can be corrected and
retried; a failed detection does not re-ask.

A preview result is routed into the open detail view rather than triggering the
list screen's reload-and-reopen, which would rebuild the view, re-dispatch its
check and never settle. A completed restore does reload, since the store
changed, and the rebuilt view's fresh check finds nothing left.

`RecoveryItemDescriptor::is_voting_key` factors out the rule `label` already
applied, so "is this the voting key" has one definition.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
Issue #889: the node page covers the masternode case, but a `User` identity
that was partially loaded before the upgrade has no node page. The Key Info
screen is the issue's own suggested location and the one surface every identity
type reaches — from the Identities list for a user identity, and through Manage
keys for a node.

The offer is identity-scoped rather than key-scoped, so it renders whatever the
opened key's own state is: what it lists are precisely the keys the identity
does *not* hold, which no per-key view could show. Both surfaces share
`LegacyRecoveryState` and `LegacyRecoverySection`, so detection, the allowlist
and the copy have one definition each.

Dispatch follows this screen's established queue-then-drain pattern, alongside
the protect/unprotect ones. The check and a restore can never contend for the
frame's single `AppAction`: the check goes out once on arrival, and a restore
only after a press. A completed restore re-probes the protection status, since
the restored keys have just landed in the vault.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
…ration gap

Issue #889: the migration design's §7 named this limitation and deferred it to
"a dedicated, provenance-aware flow". That flow now exists, so the limitation
gets its resolution rather than staying an open pointer to an issue — with the
one clarification a reader of that section needs: the importer itself did not
change, skip-if-present still stands, and nothing about recovery runs at
migration or launch time.

The design record moves into `docs/ai-design/` under this repo's dated-directory
convention, so the cross-reference resolves inside the repo.

U1 covers the widget from the outside: an empty plan renders nothing, items are
named by role with the voter link folded into its voting key, pressing Restore
approves exactly the previewed set, an in-flight restore has no button to press
twice, unrestorable keys are listed with no restore offered, and an install with
no previous-version data never even asks.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
The plan admitted any legacy key the modern record happened not to hold,
keyed on the map slot alone. Nothing checked that the saved private half
derived the public half it was stored with, that the public half was still
a live key of the identity, or that a wallet-derivation reference named a
wallet this install holds — the exact checks the manual "type the WIF"
path this flow replaces already enforces.

That matters because `masternode_key_presence` reports a role as held from
the record alone. Restoring a key the node rotated away from flipped the
role to "present", retiring both the recovery offer and the missing-voter
remedy, and the operator found out from a rejected transaction. The voter
link alone did the same thing with no key behind it at all.

Failing candidates now go to `excluded` with their own reason and are
never restorable. `AppliedRecovery` also reports that `excluded` list, so
an approval naming something that was never restorable is no longer also
reported as a stale approval ("already back in place" — the opposite
answer), and the caller stops recomputing the same plan to read one field
off it. Whatever plaintext the legacy record still holds after a merge is
zeroized instead of being dropped intact.

The item labels and exclusion copy move out of `model/` into the UI, where
they now delegate to the shipped `role_label_and_tip` vocabulary rather
than a second mapping that disagreed with it on the same screen ("Payout
key" next to "Payout address key"), and two rows in one role are told
apart by key id instead of rendering identically.

Test fixtures move onto genuinely derived key pairs with the chain's
public keys published on the record — a correspondence check that passes
against placeholder key material verifies nothing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
`recover_legacy_identity_data` took `migration_run` for the whole async
span, prompt included. The delete path it copied that pattern from is
fully synchronous and holds the mutex for microseconds; this held it for
as long as a modal sat in front of the user. Two independent reviewers
reproduced the fallout: removing an *unrelated* identity failed with
"storage is still being updated" when no migration was running, and
`finish_unwire`'s awaiting acquire could park indefinitely.

The flow is now a preflight and one fully synchronous critical section.
The preflight reads, dry-runs the merge to see whether anything would be
restored at all, decides whether a password is needed, and prompts —
holding nothing. The write section then re-acquires the guard, re-checks
the migration state, re-reads the record, merges again and writes, all
without an await in between.

Re-reading is not just tidiness. The prompt window let any other writer
land in between — refresh, DPNS registration, transfer, none of which take
the load claim — and the write of a pre-prompt snapshot silently reverted
it. It also makes the no-resurrection guarantee explicit: a delete during
the prompt now surfaces as `IdentityNotFoundLocally` instead of being
undone by the upsert, which until now held only as a side effect of how
long the lock was kept.

The at-rest protection predicate is evaluated over the merged record, the
one the encoder's downgrade guard actually sees, rather than over the
pre-merge record. If the identity gained password protection during the
prompt the verified password no longer covers what is about to be written,
so the restore stops with a typed `LegacyRecoveryIdentityChanged` rather
than sealing under a password for a different state.

Also: the nothing-to-recover success no longer records a `Failed` load, the
preview zeroizes the stranded plaintext it decodes on every screen open
instead of releasing it intact, and the "nothing restored" banner is worded
to be true of both outcomes that produce it.

Both concurrency tests were confirmed RED against the old lock scope,
reproducing the reviewers' exact failures.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
Three ways the two shipped surfaces disagreed with the store after a
restore, and the state machine behind them had no tests at all.

The Key Info screen keeps the identity clone it opened with, and its own
add-key and remove-key paths persist that whole clone. This feature added
a second writer to the same record reachable from the same screen: restore
keys, then add or remove any key, and the pre-restore copy was written
back — the restored keys gone, right after a banner said they were back.
The completion now re-reads the record and the key on screen from it.

The node page never hears about a restore run from the Key Info screen it
pushed: the pushed screen is on top, so it takes the result. Coming back
left the page offering keys already restored and warning about a voting
key it now held. Arrival re-reads the node and re-arms its check; vote
selections and any open prompt survive, which a blanket rebuild would have
discarded. The `recovery_completed()` call in the result handler goes with
it — the reload that follows re-opens the view and re-arms the check
anyway, so it was mutating a view discarded three statements later.

Writing the state machine's tests turned up a third one: `completed()`
re-armed unconditionally, so calling it on an install with no
previous-version database armed a check that must never run. Harmless
until arrival started calling it; now `Unavailable` stays unavailable.

The Restore button loses its ellipsis: on a keyless identity — the common
case this feature exists for — it commits immediately rather than opening
anything.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
The committed design record was landed marked "implemented" with exactly
one edit — the status line — so the repo's permanent account of this
feature described a dispatch model, a progress mechanism, a module set and
a gating rule that were all deliberately changed, plus the pre-review
merge rules that the fix round replaced.

A §10 now records all nine departures with the reasoning that produced
them, rather than rewriting §1–§9 into a story nobody actually followed;
the status line says which of the two is authoritative. §7's claim that
`finish_unwire.rs` is untouched is reconciled with §4.2's hoist in the
same document: the importer's behaviour is unchanged, the file is not.

`reject_resident_identity_plaintext`'s header claimed to guard "every
boundary that seals an identity's keys". It does not — the merge-load path
seals without it. The header now says which boundaries it covers, and that
path carries a TODO describing the gap. Fixing it is a separate issue:
it is pre-existing code, unrelated to this feature.

Also: user story and CHANGELOG pick up the correspondence check and the
non-blocking prompt, the components catalog names the copy this feature's
component now owns, and three private rustdoc blocks come back inside the
internal-commentary budget.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds opt-in recovery of missing identity keys from preserved legacy data. The change adds typed lookup and planning, guarded backend persistence, password revalidation, identity-scoped UI state, recovery offers on identity screens, concurrency-aware error handling, tests, and documentation.

Changes

Legacy identity recovery

Layer / File(s) Summary
Recovery model and legacy row reader
src/model/legacy_recovery.rs, src/database/..., src/context/...
Adds typed legacy-row lookup, shared decoding, exact key-slot validation, cached legacy detection, and supporting test helpers.
Backend recovery execution
src/backend_task/..., src/context/..., src/wallet_backend/...
Adds recovery tasks, structured results and errors, per-identity record locks, protection coordination, write-time password validation, and guarded persistence.
Recovery state and restore component
src/ui/state/..., src/ui/components/..., src/ui/masternodes/mod.rs, tests/kittest/...
Adds identity-scoped recovery state, role labels, restore controls, exclusion explanations, progress rendering, and component tests.
Identity screen recovery integration
src/ui/identities/..., src/ui/masternodes/...
Wires recovery checks and restores into identity screens, refreshes completed identities, filters results by identity, and preserves in-flight restores across unrelated errors.
Design and release records
CHANGELOG.md, docs/ai-design/..., docs/user-stories.md
Documents the shipped recovery flow, migration boundaries, concurrency behavior, acceptance story, and release notes.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant IdentityScreen
  participant RecoveryState
  participant IdentityTask
  participant LegacyDataDb
  participant IdentityStore

  IdentityScreen->>RecoveryState: request recovery check
  RecoveryState->>IdentityTask: CheckLegacyRecovery
  IdentityTask->>LegacyDataDb: read legacy identity row
  LegacyDataDb-->>IdentityTask: recovery plan
  IdentityTask-->>IdentityScreen: display recovery offer
  IdentityScreen->>IdentityTask: submit approved items
  IdentityTask->>IdentityStore: persist guarded additive merge
  IdentityStore-->>IdentityScreen: recovery completion
Loading

Possibly related issues

Possibly related PRs

Suggested labels: claudius-review

Suggested reviewers: lklimek

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Clear, concise, and accurately summarizes the new legacy-key recovery flow.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/issue-889-legacy-key-recovery

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@lklimek
lklimek marked this pull request as ready for review July 29, 2026 00:01
@thepastaclaw

thepastaclaw commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Ready for review — 7 ahead in queue (commit 61ae154)
Queue position: 8/10 · 3 reviews active
ETA: start ~13:16 UTC · complete ~13:42 UTC (median 25m across 30 recent reviews; 3 slots)
Queued 3h 7m ago · Last checked: 2026-07-30 12:20 UTC

The correspondence check that keeps a rotated-away key out of the offer
resolved a voter/operator-target key's identity as "the modern link, or
the legacy one if there is no modern link". In the case the check exists
for -- a masternode whose record carries no voter link -- that fallback
read the identity snapshot out of the same unauthenticated legacy blob
as the key under test, so any self-consistent pair passed. A voting key
the chain retired months before the upgrade still reads as live in that
snapshot, and restoring it flips the node's voting role to "present",
retiring the manual remedy that would actually fix the node.

reference_identity now reads the modern record only. A key on a voter or
operator identity the modern record does not link to has no admissible
witness and is excluded as LinkedIdentityUnverified, carrying the same
"load this identity again and enter the key" remedy as its neighbours.

Fetching the linked identity from Platform was rejected twice over. It
would put the network in the middle of an offline, read-only preview
that every screen arrival dispatches, and model/ is pure by contract.
More decisively, it would not establish the property: a voter identity's
id is derived from its voting key (Identifier::create_voter_identifier),
so rotating the key on-chain creates a *different* voter identity rather
than retiring a key on the existing one. Fetching the legacy-named voter
identity would confirm the stale key against its own orphaned identity.

Behaviour change worth noticing on its own: a masternode loaded from its
ProTxHash alone no longer gets its voter-identity-target voting key back
in one click. The key is listed as unverifiable, the voter link goes with
it, the node keeps reporting the role as missing, and render_missing_voter
keeps offering manual entry -- the honest outcome, since nothing available
offline can tell that key from one the chain replaced. A record that does
carry the voter link (a re-load keeps it) restores the key as before.

Grouping follows the same rule: voter_association_is_grouped now keys on
the voting role, the predicate that already decides whether the link is
worth offering, so the two cannot disagree about which key the link
belongs to.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/backend_task/identity/load_identity.rs (1)

500-506: 📐 Maintainability & Code Quality | 🔵 Trivial

Track this TODO so the merge-load seal gap doesn't get lost.

The note correctly identifies that this seal lacks the reject_resident_identity_plaintext preflight that verify_recovery_password (src/backend_task/identity/recover_legacy_keys.rs lines 165-169) and the protect opt-in both run, leaving a half-protected identity that trips the downgrade guard at persist. Agreed it's out of scope here, but a bare TODO(#889 review) has no tracking home.

Want me to open a follow-up issue capturing the failure mode and the proposed preflight?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/backend_task/identity/load_identity.rs` around lines 500 - 506, Track the
merge-load seal gap in a follow-up issue instead of leaving it only as TODO(`#889`
review). Update the TODO near the merge-load seal to reference the new issue and
retain the failure mode and proposed reject_resident_identity_plaintext
preflight; keep the implementation unchanged because this is out of scope for
the current change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@CHANGELOG.md`:
- Around line 37-38: Qualify the restore-first recovery statements in
CHANGELOG.md lines 37-38 and docs/user-stories.md line 677 so they apply only
when a recoverable voting key is found, while preserving manual key entry as the
fallback option in both documents.

In `@docs/ai-design/2026-07-28-legacy-identity-recovery/design.md`:
- Line 250: Add language identifiers to the fenced pseudocode blocks in the
design document at the referenced sections, using an appropriate identifier such
as text for both fences so markdownlint MD040 passes.
- Around line 292-300: The legacy recovery design must distinguish an empty
approval list from a successful no-op during execution. Update the TaskError
table and the execution description around LegacyRecoveryNothingApproved and
LegacyRecoveryCompleted so the error applies only when approved.is_empty()
before execution, while non-empty approvals that produce no applied items return
successful LegacyRecoveryCompleted { nothing_to_recover }.

---

Nitpick comments:
In `@src/backend_task/identity/load_identity.rs`:
- Around line 500-506: Track the merge-load seal gap in a follow-up issue
instead of leaving it only as TODO(`#889` review). Update the TODO near the
merge-load seal to reference the new issue and retain the failure mode and
proposed reject_resident_identity_plaintext preflight; keep the implementation
unchanged because this is out of scope for the current change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: ef0575ca-788e-4ffd-846c-f0afa2d7448d

📥 Commits

Reviewing files that changed from the base of the PR and between 3e05d5f and fc125f4.

📒 Files selected for processing (29)
  • CHANGELOG.md
  • docs/ai-design/2026-07-13-legacy-identity-migration/design.md
  • docs/ai-design/2026-07-28-legacy-identity-recovery/design.md
  • docs/user-stories.md
  • src/backend_task/error.rs
  • src/backend_task/identity/load_identity.rs
  • src/backend_task/identity/mod.rs
  • src/backend_task/identity/protect_identity_keys.rs
  • src/backend_task/identity/recover_legacy_keys.rs
  • src/backend_task/migration/finish_unwire.rs
  • src/backend_task/mod.rs
  • src/context/identity_db.rs
  • src/context/identity_load_registry.rs
  • src/database/legacy_import.rs
  • src/database/mod.rs
  • src/model/legacy_recovery.rs
  • src/model/mod.rs
  • src/model/wallet/mod.rs
  • src/ui/components/README.md
  • src/ui/components/legacy_recovery_section.rs
  • src/ui/components/mod.rs
  • src/ui/identities/keys/key_info_screen.rs
  • src/ui/masternodes/detail_screen.rs
  • src/ui/masternodes/list_screen.rs
  • src/ui/masternodes/mod.rs
  • src/ui/state/legacy_recovery.rs
  • src/ui/state/mod.rs
  • tests/kittest/legacy_recovery_section.rs
  • tests/kittest/main.rs

Comment thread CHANGELOG.md Resolved
lklimek and others added 3 commits July 29, 2026 00:22
… existing

FetchState::Unavailable was documented as the state a fresh install never
leaves, but no shipped install could reach it. AppState::boot_inputs
opens an existing data.db read-only *or* creates one and runs the
fresh-install schema ladder, so db_file_path().exists() is true for every
user, and every identity or node screen dispatched a detection task
against a table the ladder had just created empty. The kittest that
claimed otherwise passed only because the `testing` feature substitutes
an in-memory database whose path is None -- a test of the substitution,
not of the gate.

AppContext::has_legacy_identities now asks whether the legacy `identity`
table holds a local row for this network: one SELECT EXISTS over the same
filter read_identities uses (so "there is something here" and "here it
is" cannot drift), false when the table does not exist at all, answered
once per context and cached. A probe that errors arms the offer instead
of retiring it -- the detection task reports its own typed error, while a
silent false would withdraw a recovery the user's data still supports.

The kittest is replaced by lib tests over a real file-backed data.db,
which assert the premise the old gate missed (the file is there and the
gate still says no) and cover the network scoping a file check could
never have. Confirmed red against the old gate before the fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
…estore

Two ways a restore's result reached the wrong screen state.

KeyInfoScreen had an empty refresh(), which refresh_on_arrival defaults
to, so returning to a screen that missed its result never re-read the
record. That screen persists the whole identity clone it opened with on
every key add or remove, so the clone -- predating the restore -- was
written back over the restored keys on the next edit, silently and with a
successful save to show for it. It now re-reads on arrival, re-probes the
protection line and re-arms its check, exactly as the masternode detail
view already does.

The LegacyRecoveryCompleted arm discarded identity_id, unlike the
LegacyRecoveryCandidates arm directly above it, which routes through
LegacyRecoveryState::offered's identity check. Results reach whichever
screen is visible when they arrive, not the screen that dispatched them,
so a restore dispatched from identity A's Key Info screen could land on
identity B's: B showed "your keys have been restored to this identity"
for a restore that was never B's, and B's own in-flight recovery state
was reset under it.

The attribution rule now lives once, in LegacyRecoveryState as
completed_for -- the twin of offered -- so both call sites share it
rather than each remembering to check. The masternodes list applies the
same rule through shows_node: a completion for an identity no card and no
open detail names is dropped, banner, reload and detail rebuild included.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
TaskError::LegacyRecoveryIdentityChanged is listed in
persist_legacy_recovery's rustdoc and spelled out in design.md 10.6, but
was the only documented error branch of that function with no test --
every sibling (IdentityLoadInProgress, WalletStorageNotReady,
IdentityNotFoundLocally, LegacyIdentityUnreadable, the prompt's cancel
and unavailable errors, IdentityKeyProtectionIncomplete, the deleted
identity, the undecodable row) has one.

B13 drives the 10.6 scenario: the dry run on a keyless identity decides
no password is needed, a ProtectIdentityKeys lands before the write
section re-reads the record, and the write refuses with the typed error
and a byte-identical stored blob.

It calls persist_legacy_recovery directly with the None the dry run
produced, as B5 calls verify_recovery_password directly: a Tier-1 restore
never prompts, so there is no await point between the two where a
concurrent task could be made to land deterministically. The dry run is
exercised first so the None under test is the one production carries.
Verified the test fails when the fail-closed branch is removed, rather
than merely restating it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/ai-design/2026-07-28-legacy-identity-recovery/design.md`:
- Line 708: Update the documentation sentence in the detection-task description
to replace “the ladder had just created empty” with “the ladder had just created
an empty database.”
- Around line 407-410: Update the dispatch description near
`display_task_result` to reflect the shipped render-latch behavior: dispatch
`CheckLegacyRecovery` from the render latch, while `refresh_on_arrival` only
re-reads state and re-arms the check. Preserve the existing legacy-rows gate,
result handling, refresh-on-completion, and banner lifecycle details.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1f71e77e-f408-49c6-8317-bdd3643c6f39

📥 Commits

Reviewing files that changed from the base of the PR and between fc125f4 and be5299b.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • docs/ai-design/2026-07-28-legacy-identity-recovery/design.md
  • src/backend_task/identity/recover_legacy_keys.rs
  • src/context/identity_db.rs
  • src/context/mod.rs
  • src/database/legacy_import.rs
  • src/model/legacy_recovery.rs
  • src/ui/components/legacy_recovery_section.rs
  • src/ui/identities/keys/key_info_screen.rs
  • src/ui/masternodes/list_screen.rs
  • src/ui/state/legacy_recovery.rs
  • tests/kittest/legacy_recovery_section.rs
💤 Files with no reviewable changes (1)
  • tests/kittest/legacy_recovery_section.rs
🚧 Files skipped from review as they are similar to previous changes (8)
  • CHANGELOG.md
  • src/ui/components/legacy_recovery_section.rs
  • src/ui/state/legacy_recovery.rs
  • src/ui/masternodes/list_screen.rs
  • src/database/legacy_import.rs
  • src/ui/identities/keys/key_info_screen.rs
  • src/model/legacy_recovery.rs
  • src/backend_task/identity/recover_legacy_keys.rs

lklimek added 4 commits July 29, 2026 11:42
The voter-target fix landed one half of the rule: a key on a voter or
operator identity the modern record does not link to has no witness
outside the legacy file, so it is excluded. The operator *link* itself
was offered with no gate at all, which left the same hole open one step
further out.

Restoring it writes the legacy file's own claim into the modern record.
The next preview then reads that claim back as the outside witness for
the same file's operator keys, and every one of them becomes a
candidate — self-vouching in two moves instead of one. Nothing in
production ever writes `associated_operator_identity` fresh, so an
offered operator link was always in that unverifiable state.

An operator link the modern record does not carry is now excluded as
`LinkedIdentityUnverified`, like the keys held on that identity.

Also renames M8, whose name and opening sentence claimed it proved the
whole legacy key set is offered while its own assertions exclude two of
five items.
The node page carried a second missing-voter message offering restore as
the primary remedy, chosen whenever the recovery plan held a voting-role
candidate. Since the voter-key check began reading the modern record
only, that candidate exists only when the record already carries the
voter link — and a record carrying the voter link is written in the same
branch that writes the voting key, so it is never in the missing-voter
state to begin with. The two conditions are mutually exclusive: no user,
and no test, has ever seen that message or its companion tooltip.

Gone, along with the predicate behind them. The remaining message is the
honest one and still matches what the screen offers: the in-place "Add
voting key" prompt right underneath it, which needs no re-load.

Restoring a voting key held on a separate voter identity needs an
on-chain check this flow deliberately does not make; that is issue #942,
not something this branch pretends to do.
… nothing

A plan holding only unrestorable items — now the ordinary shape for a
masternode loaded from its ProTxHash — opened with "Some keys ... haven't
been brought across", followed by no list, no button, and then a second
heading for the items it cannot bring back. A lead-in that promises an
action the section never offers reads as a broken screen.

That case gets its own lead-in, which introduces the list itself, so the
second heading appears only when there really are two lists to keep
apart.

The reason an item cannot be restored also stops being hover-only. It is
the single sentence that tells the user what to do instead, and a tooltip
reaches neither touch nor keyboard; it is now an inline line under each
item. The reason for an unverifiable linked identity is reworded to read
correctly for the operator link as well as for a key held on one.
The user story and the changelog both said restoring is offered as the
first remedy for a node with no voting key, with typing the key in as the
fallback. For the flagship case — a masternode loaded from its ProTxHash
alone — that is never true: the voting key sits on a separate voting
identity that only the previous version's data names, so it is listed as
one that cannot be brought back and entering it by hand is the only
remedy. Naming owner, voting and payout together in the same breath
carried the same implication and is dropped.

Both now describe what happens, and point at issue #942 for the on-chain
check that would let the voting-key case be closed safely later.

The design record gains the two shipped deviations behind this: §2.1's
"restore first, WIF as fallback" branch removed as unreachable, and the
operator link excluded as unverifiable for the same reason its keys are.

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/ui/masternodes/detail_screen.rs (2)

312-316: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Keep the store reload off the UI thread.

refresh_from_store() synchronously calls load_local_masternode_identities() from a UI screen method. A slow local-store read can block egui rendering; return the refreshed identity through a BackendTask instead and apply it on the UI thread.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ui/masternodes/detail_screen.rs` around lines 312 - 316, Update
refresh_from_store() so it does not synchronously call
load_local_masternode_identities() on the UI thread. Move the store reload into
a BackendTask, return the matching identity for node_id from that task, and
apply the refreshed identity when the task result is handled on the UI thread.

Source: Coding guidelines


317-320: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Refresh contest-derived state after replacing the identity.

Recovery can add the associated voter identity, but this updates only self.identity and key_presence; contest_summary and open_contests remain based on the old voter ID. The DPNS section can therefore show stale results until a manual refresh.

 self.key_presence = identity.masternode_key_presence();
 self.identity = identity;
+self.refresh_contests();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ui/masternodes/detail_screen.rs` around lines 317 - 320, After replacing
the identity in the recovery flow, refresh the contest-derived state by updating
contest_summary and open_contests using the new voter identity before completing
recovery. Keep the existing self.identity and key_presence assignments, and
ensure the DPNS section reflects the recovered identity immediately.
🧹 Nitpick comments (1)
src/ui/masternodes/detail_screen.rs (1)

1124-1160: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise the shared disambiguation branch in the test.

The active and disabled payout keys already differ by the (disabled) suffix, so this test never verifies disambiguate_role_labels appending key IDs. Add two same-role keys whose labels genuinely collide and assert the resulting #<key id> suffixes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/ui/masternodes/detail_screen.rs` around lines 1124 - 1160, Update
manage_keys_labels_disambiguate_rotated_evonode_payout_keys to include two
same-role keys whose base labels collide without relying on the disabled suffix,
then assert their labels include the expected #<key id> disambiguation suffixes.
Keep the existing uniqueness assertion and other role-label expectations intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/ui/masternodes/detail_screen.rs`:
- Around line 312-316: Update refresh_from_store() so it does not synchronously
call load_local_masternode_identities() on the UI thread. Move the store reload
into a BackendTask, return the matching identity for node_id from that task, and
apply the refreshed identity when the task result is handled on the UI thread.
- Around line 317-320: After replacing the identity in the recovery flow,
refresh the contest-derived state by updating contest_summary and open_contests
using the new voter identity before completing recovery. Keep the existing
self.identity and key_presence assignments, and ensure the DPNS section reflects
the recovered identity immediately.

---

Nitpick comments:
In `@src/ui/masternodes/detail_screen.rs`:
- Around line 1124-1160: Update
manage_keys_labels_disambiguate_rotated_evonode_payout_keys to include two
same-role keys whose base labels collide without relying on the disabled suffix,
then assert their labels include the expected #<key id> disambiguation suffixes.
Keep the existing uniqueness assertion and other role-label expectations intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e47f7168-5b84-4001-9ab5-1ddd763efb65

📥 Commits

Reviewing files that changed from the base of the PR and between be5299b and 1612fc7.

📒 Files selected for processing (7)
  • CHANGELOG.md
  • docs/ai-design/2026-07-28-legacy-identity-recovery/design.md
  • docs/user-stories.md
  • src/model/legacy_recovery.rs
  • src/ui/components/legacy_recovery_section.rs
  • src/ui/masternodes/detail_screen.rs
  • tests/kittest/legacy_recovery_section.rs
🚧 Files skipped from review as they are similar to previous changes (6)
  • tests/kittest/legacy_recovery_section.rs
  • src/ui/components/legacy_recovery_section.rs
  • docs/user-stories.md
  • docs/ai-design/2026-07-28-legacy-identity-recovery/design.md
  • CHANGELOG.md
  • src/model/legacy_recovery.rs

@Claudius-Maginificent

Copy link
Copy Markdown
Collaborator Author

Triage on the two src/ui/masternodes/detail_screen.rs findings from CodeRabbit's outside-diff-range comments (not postable as inline threads, so noting disposition here instead):

  • refresh_from_store() reloading all masternode identities synchronously on the UI thread (312-316) — confirmed real, out of scope for this PR, not fixed here.
  • Stale contest_summary/open_contests after a recovery adds a voter association (317-320) — confirmed real, out of scope for this PR, not fixed here.

The test-coverage nitpick at 1124-1160 needs no action — the suggested branch is already exercised by the adjacent manage_keys_labels_fall_back_to_key_id_on_residual_collision test.

@thepastaclaw thepastaclaw 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.

Preliminary review — Codex only

The recovery flow has four blocking correctness issues: it can accept unusable key material, lose concurrent identity updates, create mixed-password vault entries, and reset an active restore after an unrelated task error. The implementation also drops typed SQLite causes, and the design document has two minor lint/wording issues.

Validated blockers were found in the Codex precheck. Sonnet is deferred until a fresh Codex revalidation clears the blocker gate.

Review provenance

  • Codex reviewers: gpt-5.6-sol — general (completed), gpt-5.6-sol — rust-quality (completed)
  • Verifier: gpt-5.6-sol — verifier
  • Sonnet: not run (deferred by blocker gate)

🔴 4 blocking | 🟡 1 suggestion(s) | 💬 2 nitpick(s)

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `src/model/legacy_recovery.rs`:
- [BLOCKING] src/model/legacy_recovery.rs:466-481: Validate recovered keys against the exact live key slot
  The correspondence check accepts two classes of unusable keys. First, any error from `public_key_data_from_private_key_data` skips private/public validation, so malformed bytes such as an all-zero ECDSA secret can be restored when their saved public metadata matches the identity. Second, the live-key search compares only type and public bytes across every key, ignoring the approved map key's `key_id`; a legacy entry under one ID can therefore be accepted because the same material is live under another ID. The entry is still stored under the legacy `(target, key_id)`, while signing resolves private material by the requested on-chain key ID, so role-presence checks can report a key that cannot sign. Pass `key_id` into this check, require the saved map key and embedded public-key ID to agree, compare with the active current key at exactly that ID, and reject derivation failures unless a specific supported key type has an independent correspondence validator.

In `src/backend_task/identity/recover_legacy_keys.rs`:
- [BLOCKING] src/backend_task/identity/recover_legacy_keys.rs:196-242: Serialize recovery with all writers of the identity record
  Neither guard held by this read/merge/write section excludes ordinary same-identity writers. `migration_run` coordinates migration and removal, while the identity-load claim is observed only by load and recovery paths; refreshes, key edits, top-ups, transfers, DPNS registration, and other callers of `update_local_qualified_identity` do not take either guard. Because these paths persist whole `QualifiedIdentity` snapshots, another writer can update the record after the read at lines 204-206 and have its change overwritten at line 242, or write an older snapshot immediately after recovery and erase the restored keys. The existing prompt-race test only covers an update that lands before this final reread. Use a per-identity mutation lock shared by every whole-record writer, or a versioned compare-and-swap with retry, so the final read-modify-write is atomic relative to all identity updates.
- [BLOCKING] src/backend_task/identity/recover_legacy_keys.rs:229-239: Do not seal with a password verified against an obsolete vault state
  `VerifiedIdentityPassword` only proves that its password opened one protected key when the prompt completed; it is not tied to the current vault generation. Protection and unprotection tasks take neither the recovery claim nor `migration_run`. If the identity is unprotected and then protected under a new password while recovery is waiting, the second scope check still sees a protected identity, but `seal_merged_plaintext_keys` seals the recovered keys with the previously verified password. Existing and recovered keys then require different passwords, violating the one-password invariant. Serialize protection changes with recovery through the final persist, or revalidate the password against the current protected scope while holding a shared same-identity mutation guard. Add a regression test for concurrent unprotect-and-reprotect with a different password.
- [SUGGESTION] src/backend_task/identity/recover_legacy_keys.rs:284-307: Preserve SQLite causes in legacy recovery errors
  Failures to open or query the legacy database are logged and then collapsed into `LegacyIdentityUnreadable`, whose `Debug` output contains only the identity ID and has no `#[source]`. Consequently, `BannerHandle::with_details`, callers, and tests cannot inspect whether recovery failed because of permissions, I/O, schema, or another SQLite error once the process log is unavailable. Add a `TaskError` variant with the `rusqlite::Error` as a source for open/query failures, while keeping row-decoding corruption as a separate source-free outcome if no underlying error object is retained.

In `src/ui/identities/keys/key_info_screen.rs`:
- [BLOCKING] src/ui/identities/keys/key_info_screen.rs:256-269: Keep unrelated task errors from resetting an active recovery
  `display_message` is invoked for generic errors routed to the currently visible screen, so this calls `recovery.failed()` for every failing backend task, not only this identity's recovery operation. An unrelated failure while a restore is awaiting its password or running changes `Restoring` back to `Offered` and re-enables Restore even though the original task still owns the identity-load claim; pressing it again produces a misleading `IdentityLoadInProgress` error. `MasternodesScreen::display_task_error` has the same unconditional behavior through `detail.recovery_failed()`. Give recovery checks and restores distinct `BackendTaskContext` values carrying the identity and dispatch, then transition recovery state only when the failing context matches the in-flight operation.

Comment thread src/model/legacy_recovery.rs Resolved
The correspondence check accepted two classes of key that cannot sign.

A derivation this build cannot perform short-circuited the private/public
test, so an all-zero ECDSA secret — the shape a truncated legacy blob
leaves — passed on its saved public metadata alone. A derivation failure is
now a rejection: nothing else here can settle the correspondence.

The live-key search compared type and public bytes across every key on the
identity, ignoring the slot the entry occupies. An entry filed under one
key id was accepted because the same material is live under another, but it
is stored under the legacy (target, key_id) and signing resolves private
material by the id it was asked for — so a role-presence check would report
a key that resolves to nothing. The saved slot and the embedded public-key
id must now agree, and the identity must publish exactly that key, at that
id, undisabled.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
lklimek and others added 3 commits July 30, 2026 08:58
The merge's read → seal → write span was guarded by the identity-load
claim and the storage-migration mutex, and neither excludes an ordinary
writer. Refreshes, key edits, top-ups, transfers and DPNS registration all
persist a whole QualifiedIdentity snapshot through
update_local_qualified_identity without taking either, so one landing
inside the span erased the restored keys with no error anywhere.

AppContext::identity_record_lock is a per-identity guard, taken inside
insert_local_qualified_identity, update_local_qualified_identity,
set_identity_alias, delete_local_qualified_identity and both key-protection
tier migrations — coverage by construction rather than by remembering it at
~20 call sites. The write section holds it for its whole span and writes
through write_local_qualified_identity_locked. Lock order is migration_run
then the record guard, matching the delete path, and the password prompt
still runs outside both, so a UI thread that waits on the guard is never
waiting on itself.

That guard also closes the stale-password hole. VerifiedIdentityPassword
proves a password opened one protected key when the prompt closed; the tier
migrations take neither the claim nor migration_run, so an identity
unprotected and re-protected under a NEW password still read as protected
at write time and the recovered keys were sealed under the old one, leaving
one identity needing two passwords. The write section now re-proves the
password against the scope that exists then, via
SecretAccess::identity_object_password_still_opens, and refuses with
LegacyRecoveryIdentityChanged when it no longer opens.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
Errors reach whichever screen is visible when they arrive, so Key Info's
display_message and MasternodesScreen's display_task_error ended the
recovery operation on ANY failing task. An unrelated failure mid-restore
flipped Restoring back to Offered and re-enabled the button while the
original task still held the identity, so pressing it again only produced
IdentityLoadInProgress.

The check and the restore now carry identity-scoped BackendTaskContext
values, and both screens transition their recovery state from
display_backend_task_error only when the failing operation names the
identity they are showing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
Covers the key-slot validation, cross-writer serialization, stale-password
seal, and error-attribution fixes for issue #889 / PR #941.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd
@lklimek
lklimek merged commit 7607622 into v1.0-dev Jul 30, 2026
5 checks passed
@lklimek
lklimek deleted the feat/issue-889-legacy-key-recovery branch July 30, 2026 12:26
orchardpaytl pushed a commit to orchardpaytl/orchardpay that referenced this pull request Jul 30, 2026
… (dashpay#941)

* feat(model): add the legacy identity recovery plan and additive merge

Issue dashpay#889: a v0.9.3 identity that was already partially loaded before the
upgrade keeps its remaining keys stranded in `data.db`, because the migration
skips a present identity wholesale. That rule is correct — three earlier
reconcile heuristics each failed by inferring user intent from record shape.

`compute_recovery_plan` only lists what the legacy record holds and the modern
one does not, keyed on the `(target, key_id)` map slot and on `None`
associations; it never decides whether an item should come back. That decision
travels back in as an item-level allowlist, so the absence-versus-removal
ambiguity lands with the only party holding the provenance.

`apply_recovery_plan` is additive by construction, not by discipline: it starts
from the fresh modern record, inserts with `or_insert` so the modern copy wins
every collision, recomputes candidacy rather than trusting the allowlist, and
has no write path at all for alias, status, the dpp identity, DPNS names, or
the wallet link. A voting key drags its voter-identity link along, since one
without the other cannot vote.

M1-M10 from the design doc's test matrix. M2/M5/M6/M9/M10 were confirmed RED
against a naive legacy-wins merge before this implementation landed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(database): read one legacy identity row through the shared row decoder

Issue dashpay#889: the recovery flow needs one identity out of the preserved legacy
`data.db`, not the whole table. A second hand-written reader would be free to
drift from the importer's idea of which rows are readable — and then recovery
could merge from a record the migration never considered importable, or miss
one it did.

So the per-row decode moves into `decode_identity_row` and both readers call
it, along with one shared `SELECT` that binds the same pair of accepted network
spellings. `read_identity_row` adds only the `id` predicate on top.

`LegacyIdentityLookup` keeps "nothing to recover" and "the row will not decode"
apart. An absent table, an absent row, an observed-identity cache row and a
NULL blob are all `Absent` — the ordinary answer. Only a genuinely corrupt row
is `Unreadable`, so no caller can mistake corruption for an empty record and
merge against it.

`open_legacy_read_only` is hoisted next to `database/mod.rs`'s existing one, so
`SQLITE_OPEN_READ_ONLY` is a property of the one function that opens the file
rather than of each caller remembering the flag.

The importer's 12 existing row-decode tests are the regression net for the
extraction; 8 new tests cover the lookup, including one asserting both readers
decode the same row identically.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(identity): restore keys stranded in the previous version's saved data

Issue dashpay#889: an identity that was only partially loaded before the v1.0 upgrade
keeps its remaining keys in `data.db`, reachable by nothing — the load form
rejects the duplicate ProTxHash, and the per-key screen wants a WIF the user may
no longer hold. This is the way in, and it is entirely user-driven.

`CheckLegacyRecovery` lists; `RecoverLegacyIdentityData` writes. Detection is
read-only, offline and side-effect-free, so a screen can dispatch it on arrival
and hide the affordance when the plan comes back empty. Candidacy is recomputed
inside the executing task rather than trusted from the caller: only
`recomputed-candidates ∩ approved` is merged, so an approval that went stale
since the preview is reported rather than acted on, and an item the user never
approved is never restored even when it is missing. An empty allowlist is
refused, not widened into "restore everything".

The protection-downgrade trip that sank an earlier reconcile attempt is
unreachable here by branch condition, not by care: the flow branches on the same
predicate the at-rest guard evaluates. On a protected identity the password is
verified up front through the shipped prompt, the resident-plaintext preflight
runs before any vault write, and every merged key is sealed under that password
before the record is persisted — so the encoder never sees plaintext on a
protected identity. On a keyless identity there is no protected key for the
guard to protect. Cancel, wrong password and headless all fail closed with the
stored record byte-identical.

Exactly one record write, so the merge either lands whole or changes nothing.
No new persisted state: eligibility recomputes from the two existing stores, so
a re-run is a no-op and `data.db` — opened read-only — stays a repeatable
recovery source.

`reject_resident_identity_plaintext` widens to `pub(super)`; it now guards both
seal boundaries. Two test-only readers expose the at-rest blob and the wallet
link, which the hydrated record cannot show.

B1-B12 from the design doc's test matrix, on the offline wired `AppContext`
harness, plus the excluded-key and empty-allowlist cases.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* feat(masternodes): offer the previous version's stranded keys on the node page

Issue dashpay#889: the restore path exists but nothing reaches it. The node detail
page is the canonical surface — its operator is the one holding a node that
cannot vote because its voting key stayed behind in the previous version's
saved data.

The offer is passive and contextual, never a launch-time nag. On opening a
node the view dispatches the read-only detection task once, and only on an
install that actually has a previous-version database; the section renders in
the Keys area only when detection found something, and retires itself once a
restore lands, because eligibility recomputes from the two stores every time.

For a node with no voting key that becomes the primary remedy: the
missing-voter message points at restoring, which asks nothing of an operator
who no longer has the key, and the existing WIF prompt keeps its place as the
fallback for one who does.

`LegacyRecoveryState` (`ui/state/`) owns the fetch state — dispatch-once,
in-flight, offered, retryable — and `LegacyRecoverySection` (`ui/components/`)
renders it, per the placement rule's render/no-render split. A failed restore
returns to its offer so a mistyped identity password can be corrected and
retried; a failed detection does not re-ask.

A preview result is routed into the open detail view rather than triggering the
list screen's reload-and-reopen, which would rebuild the view, re-dispatch its
check and never settle. A completed restore does reload, since the store
changed, and the rebuilt view's fresh check finds nothing left.

`RecoveryItemDescriptor::is_voting_key` factors out the rule `label` already
applied, so "is this the voting key" has one definition.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* feat(identities): offer stranded legacy keys on the Key Info screen

Issue dashpay#889: the node page covers the masternode case, but a `User` identity
that was partially loaded before the upgrade has no node page. The Key Info
screen is the issue's own suggested location and the one surface every identity
type reaches — from the Identities list for a user identity, and through Manage
keys for a node.

The offer is identity-scoped rather than key-scoped, so it renders whatever the
opened key's own state is: what it lists are precisely the keys the identity
does *not* hold, which no per-key view could show. Both surfaces share
`LegacyRecoveryState` and `LegacyRecoverySection`, so detection, the allowlist
and the copy have one definition each.

Dispatch follows this screen's established queue-then-drain pattern, alongside
the protect/unprotect ones. The check and a restore can never contend for the
frame's single `AppAction`: the check goes out once on arrival, and a restore
only after a press. A completed restore re-probes the protection status, since
the restored keys have just landed in the vault.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* docs(identity): record the legacy-key recovery flow and close the migration gap

Issue dashpay#889: the migration design's §7 named this limitation and deferred it to
"a dedicated, provenance-aware flow". That flow now exists, so the limitation
gets its resolution rather than staying an open pointer to an issue — with the
one clarification a reader of that section needs: the importer itself did not
change, skip-if-present still stands, and nothing about recovery runs at
migration or launch time.

The design record moves into `docs/ai-design/` under this repo's dated-directory
convention, so the cross-reference resolves inside the repo.

U1 covers the widget from the outside: an empty plan renders nothing, items are
named by role with the voter link folded into its voting key, pressing Restore
approves exactly the previewed set, an in-flight restore has no button to press
twice, unrestorable keys are listed with no restore offered, and an install with
no previous-version data never even asks.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(model): only offer legacy keys that still correspond to the identity

The plan admitted any legacy key the modern record happened not to hold,
keyed on the map slot alone. Nothing checked that the saved private half
derived the public half it was stored with, that the public half was still
a live key of the identity, or that a wallet-derivation reference named a
wallet this install holds — the exact checks the manual "type the WIF"
path this flow replaces already enforces.

That matters because `masternode_key_presence` reports a role as held from
the record alone. Restoring a key the node rotated away from flipped the
role to "present", retiring both the recovery offer and the missing-voter
remedy, and the operator found out from a rejected transaction. The voter
link alone did the same thing with no key behind it at all.

Failing candidates now go to `excluded` with their own reason and are
never restorable. `AppliedRecovery` also reports that `excluded` list, so
an approval naming something that was never restorable is no longer also
reported as a stale approval ("already back in place" — the opposite
answer), and the caller stops recomputing the same plan to read one field
off it. Whatever plaintext the legacy record still holds after a merge is
zeroized instead of being dropped intact.

The item labels and exclusion copy move out of `model/` into the UI, where
they now delegate to the shipped `role_label_and_tip` vocabulary rather
than a second mapping that disagreed with it on the same screen ("Payout
key" next to "Payout address key"), and two rows in one role are told
apart by key id instead of rendering identically.

Test fixtures move onto genuinely derived key pairs with the chain's
public keys published on the record — a correspondence check that passes
against placeholder key material verifies nothing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(identity): stop holding the storage guard across the password prompt

`recover_legacy_identity_data` took `migration_run` for the whole async
span, prompt included. The delete path it copied that pattern from is
fully synchronous and holds the mutex for microseconds; this held it for
as long as a modal sat in front of the user. Two independent reviewers
reproduced the fallout: removing an *unrelated* identity failed with
"storage is still being updated" when no migration was running, and
`finish_unwire`'s awaiting acquire could park indefinitely.

The flow is now a preflight and one fully synchronous critical section.
The preflight reads, dry-runs the merge to see whether anything would be
restored at all, decides whether a password is needed, and prompts —
holding nothing. The write section then re-acquires the guard, re-checks
the migration state, re-reads the record, merges again and writes, all
without an await in between.

Re-reading is not just tidiness. The prompt window let any other writer
land in between — refresh, DPNS registration, transfer, none of which take
the load claim — and the write of a pre-prompt snapshot silently reverted
it. It also makes the no-resurrection guarantee explicit: a delete during
the prompt now surfaces as `IdentityNotFoundLocally` instead of being
undone by the upsert, which until now held only as a side effect of how
long the lock was kept.

The at-rest protection predicate is evaluated over the merged record, the
one the encoder's downgrade guard actually sees, rather than over the
pre-merge record. If the identity gained password protection during the
prompt the verified password no longer covers what is about to be written,
so the restore stops with a typed `LegacyRecoveryIdentityChanged` rather
than sealing under a password for a different state.

Also: the nothing-to-recover success no longer records a `Failed` load, the
preview zeroizes the stranded plaintext it decodes on every screen open
instead of releasing it intact, and the "nothing restored" banner is worded
to be true of both outcomes that produce it.

Both concurrency tests were confirmed RED against the old lock scope,
reproducing the reviewers' exact failures.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(ui): keep the restore offer and the record it wrote in step

Three ways the two shipped surfaces disagreed with the store after a
restore, and the state machine behind them had no tests at all.

The Key Info screen keeps the identity clone it opened with, and its own
add-key and remove-key paths persist that whole clone. This feature added
a second writer to the same record reachable from the same screen: restore
keys, then add or remove any key, and the pre-restore copy was written
back — the restored keys gone, right after a banner said they were back.
The completion now re-reads the record and the key on screen from it.

The node page never hears about a restore run from the Key Info screen it
pushed: the pushed screen is on top, so it takes the result. Coming back
left the page offering keys already restored and warning about a voting
key it now held. Arrival re-reads the node and re-arms its check; vote
selections and any open prompt survive, which a blanket rebuild would have
discarded. The `recovery_completed()` call in the result handler goes with
it — the reload that follows re-opens the view and re-arms the check
anyway, so it was mutating a view discarded three statements later.

Writing the state machine's tests turned up a third one: `completed()`
re-armed unconditionally, so calling it on an install with no
previous-version database armed a check that must never run. Harmless
until arrival started calling it; now `Unavailable` stays unavailable.

The Restore button loses its ellipsis: on a keyless identity — the common
case this feature exists for — it commits immediately rather than opening
anything.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* docs(identity): record what the recovery flow actually shipped

The committed design record was landed marked "implemented" with exactly
one edit — the status line — so the repo's permanent account of this
feature described a dispatch model, a progress mechanism, a module set and
a gating rule that were all deliberately changed, plus the pre-review
merge rules that the fix round replaced.

A §10 now records all nine departures with the reasoning that produced
them, rather than rewriting §1–§9 into a story nobody actually followed;
the status line says which of the two is authoritative. §7's claim that
`finish_unwire.rs` is untouched is reconciled with §4.2's hoist in the
same document: the importer's behaviour is unchanged, the file is not.

`reject_resident_identity_plaintext`'s header claimed to guard "every
boundary that seals an identity's keys". It does not — the merge-load path
seals without it. The header now says which boundaries it covers, and that
path carries a TODO describing the gap. Fixing it is a separate issue:
it is pre-existing code, unrelated to this feature.

Also: user story and CHANGELOG pick up the correspondence check and the
non-blocking prompt, the components catalog names the copy this feature's
component now owns, and three private rustdoc blocks come back inside the
internal-commentary budget.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(model): stop the legacy blob from vouching for its own voter key

The correspondence check that keeps a rotated-away key out of the offer
resolved a voter/operator-target key's identity as "the modern link, or
the legacy one if there is no modern link". In the case the check exists
for -- a masternode whose record carries no voter link -- that fallback
read the identity snapshot out of the same unauthenticated legacy blob
as the key under test, so any self-consistent pair passed. A voting key
the chain retired months before the upgrade still reads as live in that
snapshot, and restoring it flips the node's voting role to "present",
retiring the manual remedy that would actually fix the node.

reference_identity now reads the modern record only. A key on a voter or
operator identity the modern record does not link to has no admissible
witness and is excluded as LinkedIdentityUnverified, carrying the same
"load this identity again and enter the key" remedy as its neighbours.

Fetching the linked identity from Platform was rejected twice over. It
would put the network in the middle of an offline, read-only preview
that every screen arrival dispatches, and model/ is pure by contract.
More decisively, it would not establish the property: a voter identity's
id is derived from its voting key (Identifier::create_voter_identifier),
so rotating the key on-chain creates a *different* voter identity rather
than retiring a key on the existing one. Fetching the legacy-named voter
identity would confirm the stale key against its own orphaned identity.

Behaviour change worth noticing on its own: a masternode loaded from its
ProTxHash alone no longer gets its voter-identity-target voting key back
in one click. The key is listed as unverifiable, the voter link goes with
it, the node keeps reporting the role as missing, and render_missing_voter
keeps offering manual entry -- the honest outcome, since nothing available
offline can tell that key from one the chain replaced. A record that does
carry the voter link (a re-load keeps it) restores the key as before.

Grouping follows the same rule: voter_association_is_grouped now keys on
the voting role, the predicate that already decides whether the link is
worth offering, so the two cannot disagree about which key the link
belongs to.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(identity): gate the recovery offer on legacy rows, not on data.db existing

FetchState::Unavailable was documented as the state a fresh install never
leaves, but no shipped install could reach it. AppState::boot_inputs
opens an existing data.db read-only *or* creates one and runs the
fresh-install schema ladder, so db_file_path().exists() is true for every
user, and every identity or node screen dispatched a detection task
against a table the ladder had just created empty. The kittest that
claimed otherwise passed only because the `testing` feature substitutes
an in-memory database whose path is None -- a test of the substitution,
not of the gate.

AppContext::has_legacy_identities now asks whether the legacy `identity`
table holds a local row for this network: one SELECT EXISTS over the same
filter read_identities uses (so "there is something here" and "here it
is" cannot drift), false when the table does not exist at all, answered
once per context and cached. A probe that errors arms the offer instead
of retiring it -- the detection task reports its own typed error, while a
silent false would withdraw a recovery the user's data still supports.

The kittest is replaced by lib tests over a real file-backed data.db,
which assert the premise the old gate missed (the file is there and the
gate still says no) and cover the network scoping a file check could
never have. Confirmed red against the old gate before the fix.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(ui): re-read the key screen on arrival and attribute a finished restore

Two ways a restore's result reached the wrong screen state.

KeyInfoScreen had an empty refresh(), which refresh_on_arrival defaults
to, so returning to a screen that missed its result never re-read the
record. That screen persists the whole identity clone it opened with on
every key add or remove, so the clone -- predating the restore -- was
written back over the restored keys on the next edit, silently and with a
successful save to show for it. It now re-reads on arrival, re-probes the
protection line and re-arms its check, exactly as the masternode detail
view already does.

The LegacyRecoveryCompleted arm discarded identity_id, unlike the
LegacyRecoveryCandidates arm directly above it, which routes through
LegacyRecoveryState::offered's identity check. Results reach whichever
screen is visible when they arrive, not the screen that dispatched them,
so a restore dispatched from identity A's Key Info screen could land on
identity B's: B showed "your keys have been restored to this identity"
for a restore that was never B's, and B's own in-flight recovery state
was reset under it.

The attribution rule now lives once, in LegacyRecoveryState as
completed_for -- the twin of offered -- so both call sites share it
rather than each remembering to check. The masternodes list applies the
same rule through shows_node: a completion for an identity no card and no
open detail names is dropped, banner, reload and detail rebuild included.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* test(identity): pin the mid-flight protection guard against regression

TaskError::LegacyRecoveryIdentityChanged is listed in
persist_legacy_recovery's rustdoc and spelled out in design.md 10.6, but
was the only documented error branch of that function with no test --
every sibling (IdentityLoadInProgress, WalletStorageNotReady,
IdentityNotFoundLocally, LegacyIdentityUnreadable, the prompt's cancel
and unavailable errors, IdentityKeyProtectionIncomplete, the deleted
identity, the undecodable row) has one.

B13 drives the 10.6 scenario: the dry run on a keyless identity decides
no password is needed, a ProtectIdentityKeys lands before the write
section re-reads the record, and the write refuses with the typed error
and a byte-identical stored blob.

It calls persist_legacy_recovery directly with the None the dry run
produced, as B5 calls verify_recovery_password directly: a Tier-1 restore
never prompts, so there is no await point between the two where a
concurrent task could be made to land deterministically. The dry run is
exercised first so the None under test is the one production carries.
Verified the test fails when the fail-closed branch is removed, rather
than merely restating it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(model): stop the legacy blob from vouching for its own operator key

The voter-target fix landed one half of the rule: a key on a voter or
operator identity the modern record does not link to has no witness
outside the legacy file, so it is excluded. The operator *link* itself
was offered with no gate at all, which left the same hole open one step
further out.

Restoring it writes the legacy file's own claim into the modern record.
The next preview then reads that claim back as the outside witness for
the same file's operator keys, and every one of them becomes a
candidate — self-vouching in two moves instead of one. Nothing in
production ever writes `associated_operator_identity` fresh, so an
offered operator link was always in that unverifiable state.

An operator link the modern record does not carry is now excluded as
`LinkedIdentityUnverified`, like the keys held on that identity.

Also renames M8, whose name and opening sentence claimed it proved the
whole legacy key set is offered while its own assertions exclude two of
five items.

* fix(masternodes): drop the missing-voter message that can never be shown

The node page carried a second missing-voter message offering restore as
the primary remedy, chosen whenever the recovery plan held a voting-role
candidate. Since the voter-key check began reading the modern record
only, that candidate exists only when the record already carries the
voter link — and a record carrying the voter link is written in the same
branch that writes the voting key, so it is never in the missing-voter
state to begin with. The two conditions are mutually exclusive: no user,
and no test, has ever seen that message or its companion tooltip.

Gone, along with the predicate behind them. The remaining message is the
honest one and still matches what the screen offers: the in-place "Add
voting key" prompt right underneath it, which needs no re-load.

Restoring a voting key held on a separate voter identity needs an
on-chain check this flow deliberately does not make; that is issue dashpay#942,
not something this branch pretends to do.

* fix(ui): let the recovery section read as a whole when it can restore nothing

A plan holding only unrestorable items — now the ordinary shape for a
masternode loaded from its ProTxHash — opened with "Some keys ... haven't
been brought across", followed by no list, no button, and then a second
heading for the items it cannot bring back. A lead-in that promises an
action the section never offers reads as a broken screen.

That case gets its own lead-in, which introduces the list itself, so the
second heading appears only when there really are two lists to keep
apart.

The reason an item cannot be restored also stops being hover-only. It is
the single sentence that tells the user what to do instead, and a tooltip
reaches neither touch nor keyboard; it is now an inline line under each
item. The reason for an unverifiable linked identity is reworded to read
correctly for the operator link as well as for a key held on one.

* docs(identity): stop promising a voting-key restore that cannot happen

The user story and the changelog both said restoring is offered as the
first remedy for a node with no voting key, with typing the key in as the
fallback. For the flagship case — a masternode loaded from its ProTxHash
alone — that is never true: the voting key sits on a separate voting
identity that only the previous version's data names, so it is listed as
one that cannot be brought back and entering it by hand is the only
remedy. Naming owner, voting and payout together in the same breath
carried the same implication and is dropped.

Both now describe what happens, and point at issue dashpay#942 for the on-chain
check that would let the voting-key case be closed safely later.

The design record gains the two shipped deviations behind this: §2.1's
"restore first, WIF as fallback" branch removed as unreachable, and the
operator link excluded as unverifiable for the same reason its keys are.

* fix(model): validate a recovered key against the exact live key slot

The correspondence check accepted two classes of key that cannot sign.

A derivation this build cannot perform short-circuited the private/public
test, so an all-zero ECDSA secret — the shape a truncated legacy blob
leaves — passed on its saved public metadata alone. A derivation failure is
now a rejection: nothing else here can settle the correspondence.

The live-key search compared type and public bytes across every key on the
identity, ignoring the slot the entry occupies. An entry filed under one
key id was accepted because the same material is live under another, but it
is stored under the legacy (target, key_id) and signing resolves private
material by the id it was asked for — so a role-presence check would report
a key that resolves to nothing. The saved slot and the embedded public-key
id must now agree, and the identity must publish exactly that key, at that
id, undisabled.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(identity): serialize legacy recovery with every writer of the record

The merge's read → seal → write span was guarded by the identity-load
claim and the storage-migration mutex, and neither excludes an ordinary
writer. Refreshes, key edits, top-ups, transfers and DPNS registration all
persist a whole QualifiedIdentity snapshot through
update_local_qualified_identity without taking either, so one landing
inside the span erased the restored keys with no error anywhere.

AppContext::identity_record_lock is a per-identity guard, taken inside
insert_local_qualified_identity, update_local_qualified_identity,
set_identity_alias, delete_local_qualified_identity and both key-protection
tier migrations — coverage by construction rather than by remembering it at
~20 call sites. The write section holds it for its whole span and writes
through write_local_qualified_identity_locked. Lock order is migration_run
then the record guard, matching the delete path, and the password prompt
still runs outside both, so a UI thread that waits on the guard is never
waiting on itself.

That guard also closes the stale-password hole. VerifiedIdentityPassword
proves a password opened one protected key when the prompt closed; the tier
migrations take neither the claim nor migration_run, so an identity
unprotected and re-protected under a NEW password still read as protected
at write time and the recovered keys were sealed under the old one, leaving
one identity needing two passwords. The write section now re-proves the
password against the scope that exists then, via
SecretAccess::identity_object_password_still_opens, and refuses with
LegacyRecoveryIdentityChanged when it no longer opens.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* fix(ui): keep unrelated task errors from resetting an active recovery

Errors reach whichever screen is visible when they arrive, so Key Info's
display_message and MasternodesScreen's display_task_error ended the
recovery operation on ANY failing task. An unrelated failure mid-restore
flipped Restoring back to Offered and re-enabled the button while the
original task still held the identity, so pressing it again only produced
IdentityLoadInProgress.

The check and the restore now carry identity-scoped BackendTaskContext
values, and both screens transition their recovery state from
display_backend_task_error only when the failing operation names the
identity they are showing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

* docs(changelog): document round-11 legacy-recovery blocker fixes

Covers the key-slot validation, cross-writer serialization, stale-password
seal, and error-attribution fixes for issue dashpay#889 / PR dashpay#941.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M9RDy2kYvhYUdFhEYZ1QRd

---------

Co-authored-by: Lukasz Klimek <842586+lklimek@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
(cherry picked from commit 7607622)
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.

Recovery flow for legacy-only identity keys stranded by a partial pre-migration load

3 participants