Repository navigation
feat(platform-wallet)!: give identity slots one wallet-owned lease - #6014
romchornyi wants to merge 72 commits into
Conversation
…re broadcasting it The claim used to broadcast blindly. When a submitted key was already registered to another identity, Platform refused it with 40207/10501 and charged the voucher on every attempt. Hosts also could not tell their own landed claim from someone else's. - rs-sdk: before signing, look up the identity at the invitation's id and under every submitted key hash, and return ClaimedByThisWallet / AlreadyClaimed / KeysAlreadyRegistered / NotReady without broadcasting. Map 40207/10501 after a broadcast to KeysAlreadyRegistered, and classify a consumed-outpoint refusal by whose identity is there. One shared identity_holds_master_key predicate. - rs-platform-wallet: typed error variants; invitation_claim_status_for_identity with a claimed_by_this_wallet tri-state, resolving the master key only when the invitation was claimed; an identity the wallet already records counts as its own. - FFI: codes 63-66 (JSON detail on 63/64), AlreadyClaimed -> 24, and platform_wallet_invitation_claim_status_for_identity. - Swift/Kotlin mirrors, example-app message for 64, parity manifest gap for the missing Kotlin status binding. Refs dashpay/dashwallet-ios#1224 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Recognize a landed claim whose master key is BLS: Platform signs BLS keys into an identity like ECDSA ones. - Check every key-hash result for the invitation's identity before reporting a taken key, whatever order the keys were submitted in. - Keep Platform's 40207/10501 refusal on KeysAlreadyRegistered and stamp its consensus code on FFI code 63. - Classify an unverifiable claim-status lookup as NotReady, as the claim does. - Release the wallet storage before the claim's network round, and the wallet-manager guard before deriving from a resolved master key. - Correct the protocol version the duplicate-key refusal changed in (v11), narrow the wallet-internal claimant API to pub(crate), fix doc placement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tered Code 63 refused after the broadcast now carries Platform's 40207/10501 consensus verdict; the typed Swift case keeps it beside the classification and `consensusError` returns it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on code 64 - Test `Sdk::claim_invitation` against a mock SDK: our identity found by id and a taken key found by the last key's hash both end the claim before signing; with nothing registered it reaches the signer. `MockDashPlatformSdk::expect_request` (test-only) answers the Core funding-transaction request. - `adopt_already_landed_claim` takes the master key from its caller, dropping an arm that could not be reached. - Both example apps continue with the identity a code 64 names: the one the wallet records, or the one loaded from Platform when its id matches; otherwise they show its id and point to the re-scan screen. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n the claim sheets On code 64 a failed load of the claimed identity is now reported as a failure to retry instead of "not listed". On code 63 both example apps load the identity at the claim's index; when it is the key owner, it is recorded and the user claims again at the next index. Kotlin gains a bridge to platform_wallet_load_identity_at_index, which the Swift app already calls, so both apps probe exactly the claim's index. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e claim shortcut to its wallet The JNI bridge and the Kotlin wrapper refuse a negative identity index instead of probing the slot the u32 cast lands on. On code 64 both example apps take a recorded identity as the claimed one only when it is recorded under the selected wallet; otherwise they load it from that wallet. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts kept both sides: the invitation-claim codes 63-66 sit next to v5.1-dev's 61 and 68-76 in the FFI enum, the registry, Swift and Kotlin; the claim submission calls the renamed submit_claim_with_chain_lock_fallback; PARITY_SUMMARY.md regenerated. The invitation test seed helper returns Zeroizing<[u8; 64]> after the rust-dashcore bump. Co-Authored-By: Claude Opus 5.5 <[email protected]>
#5845 adds the input-cap case to the claim's IS → ChainLock fallback; both conflicts were in the comments that list those cases. Also gates the mock-SDK claim tests behind the mocks feature and keeps the load error as the cause of the Kotlin example's recovery message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…stration when claiming an invitation The claim sheet picked one past the highest recorded identity index, so a normal registration still in flight for that slot (no identity row yet) could be given the same index and the same HD keys. The Kotlin sheet already counts the coordinator's slots. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…before deriving its keys The claim now marks its identity-registration slot used as soon as it picks the index, the same reservation CreateIdentityView reads, so a normal registration started while the claim is in flight skips that slot instead of deriving the same keys. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…at once The isUsed marker was left to SwiftData's autosave, so an app exit during the claim could lose it. The claim's own selector still ignores the marker on purpose: a retry after a lost result must return to the same slot to be recognized as this wallet's claim. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…idation refuses Duplicate key data, too many keys, a wrong master-key count or a disallowed security level reached Platform, which refuses them only after charging part of the voucher. The claim now runs the identity-create structural validation from DPP on its keys before anything is signed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rsion The structural key check ran before any Platform request, at the version an SDK starts with (the network minimum), so keys a newer generation refuses could still be broadcast and charged. It now runs after the preflight: its proved lookups raise the SDK's version to the one the network signed, and nothing is signed before the check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…col version A pinned SDK keeps its operation version after a verified answer shows a newer network, so the structural check of the claim's keys could run under older rules than Platform applies. The keys are now judged by the newer of the SDK's version and the network's verified one; the claim is refused before signing when no verified answer showed it, or when this build has no rules for it. A keys map larger than any known version allows is refused before the per-key lookups start. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on that started it A claim runs without the wallet manager's lock, so its wallet can be removed and re-created under the same id before it ends. The claim now records the new identity only through the generation-checked `current_wallet_info_mut`, and reads whether an identity is this wallet's (refusal classification, claim status, the claimant's master key) only from the handle's own generation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the handle's wallet generation The SDK's own "claimed by this wallet" reached the host without a generation check, and the host then loads that identity through the same handle, whose loader wrote the fetched identity and its DPNS names by wallet id alone. A claim refusal now reports this wallet's claim only while the handle's wallet is still current (else WalletNotFound), and the loader's two writes go through the generation-checked `current_wallet_info_mut`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… results to the handle's wallet generation The loader read its wallet by id alone, so a handle whose wallet was removed and re-created under the same id probed the replacement and could answer "no identity at this index" for it. It also returned the fetched identity as loaded when the DPNS lookup failed, without checking the generation that the success branch's write checks. The wallet read now goes through the generation-aware `current_wallet_and_info`, and both the empty result and the DPNS-failure result are refused as WalletNotFound once the handle is stale. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…laim-preflight # Conflicts: # packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…signing Also stop the claimed-identity check before the host resolver is asked for key material once the wallet generation is stale. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n the wallet Compare the identity a claim refusal named with the one registered at the claimed index before anything is written, and move an identity the wallet only observed into its slot instead of leaving it without an index. Exposed as platform_wallet_recover_claimed_identity, Swift recoverClaimedIdentity(atIndex:identityId:) and Kotlin recoverClaimedIdentity, which both example apps now use. The claim preflight looks the invitation's identity up first and sends no key hash when it is found, and refuses a key format that the SDK's pinned version cannot build. Document that code 63 with a consensus error means Platform refused the broadcast. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e wallet-owned slot lease Remove the automatic recovery of a refused claim's identity (platform_wallet_recover_claimed_identity, Swift/Kotlin recoverClaimedIdentity, the watched-to-slot promotion) and the Swift sheet's isUsed slot reservation. Both need one durable, wallet-owned slot operation shared with normal registration, tracked in #5917. On code 64 the example apps continue with the identity only when the wallet already lists it, and otherwise point to the identity re-scan. Count an identity as this wallet's claim only when it holds one of the wallet's registration slots: an observed identity stored under the wallet's id is not its own. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Slot state (free, leased, occupied), a lease taken at the lowest free index with an invitation claim re-entering its own slot, and one place_in_slot path every wallet-owned add goes through. An occupied slot is now refused instead of overwritten by add_identity_unstored. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A claim's lease on its identity index is a changeset of its own (IdentitySlotLeaseChangeSet, keyed by the invitation outpoint), gated by the new IDENTITY_SLOT_LEASES capability, restored through IdentityManagerStartState::claim_leases and replayed by apply. A normal registration's lease stays in memory: its tracked asset lock holds the index once anything is spent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…gh the host Three extension slots (persist, load, free) carry IdentitySlotLeaseFFI rows keyed by the invitation outpoint. A host wiring all three with wallet restore attests IDENTITY_SLOT_LEASES; leases are stored in the round's bracket after the identities and loaded into the wallet's start state only for a host the wallet trusts with them. A failed read, missing buffer or unknown phase fails the load. A test that added two identities at index 0 now uses two slots: the wallet refuses an occupied one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
PersistentIdentitySlotLease keyed by network, wallet and invitation outpoint, written in the changeset round, deleted with the wallet, and handed back through the three extension callbacks. The handler declares IDENTITY_SLOT_LEASES. Co-Authored-By: Claude Opus 5.5 <[email protected]>
JNI trampolines for the three lease slots, wired only when the bridge overrides both lease methods; identity_slot_leases table (Room 17, MIGRATION_16_17), written in the changeset round, deleted with the wallet. A lease the handler cannot store (no round, no wallet row) fails the callback instead of being acknowledged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng it `IdentityManager::place_in_slot` places an identity through the one slot path, layers its keys with their derivation breadcrumbs, and stores the identity, the keys and the released claim lease as one durable write. A failed store undoes the placement in memory (the identity, an observed row it moved from, the lease and a retained private-payment hold), so no caller reports an identity as placed that a restart would not find. Registration and invitation claim land their identity through it instead of `add_identity` plus one buffered write per key. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…vitation After a refused claim the URI stays editable; a claim of another invitation replaced the only reference to the first one's lease, which then had no owner. The sheet now releases the lease it held for a different invitation before holding the new one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
|
🕓 Review not started yet because this PR is a draft.
Commit fc946d7. Normal review starts when eligible; priority review starts as soon as a slot is available. |
Every ownership verdict on an invitation's identity now counts a match only through an ECDSA or BLS key the claim submitted, which Platform admits only with a signature. An equal hash-only key proves nothing. - claimed_by (both preflight lookups and the adoption fall-through) accepts any submitted full key, so a retried claim with a hash-only master is recognized by the full key beside it (64, not 24). - identity_carries_keys requires at least one full key, so a set of hash-only keys a front-runner copied is never adopted. - AlreadyClaimed / code 24 now read "not shown to be the claimant's". - Swift claimInvitation doc again tells the two KeysAlreadyRegistered cases apart: with a consensus error the voucher may have been charged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…laim-preflight # Conflicts: # packages/kotlin-sdk/PARITY_SUMMARY.md # packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md
… into feat/wallet-identity-slot-lease The base brought v5.2-dev, where result codes 77-80 and persistence capability bit 16 are taken (#5865's shielded spend plan proposes 77-79, the external identity top-up 80, outpoint locks bit 16). The identity slot codes move to 81-83 (Rust, FFI registry, Swift, Kotlin, tests) and IDENTITY_SLOT_LEASES to bit 17 (Rust, FFI, Swift, Kotlin). The lease callbacks stay after the outpoint-lock ones in the persistence extension, so the shipped layout keeps its offsets. The parity manifest is merged by entry and its summary regenerated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lorer PersistentIdentitySlotLease had no list or detail view, which the storage explorer check requires of every model in DashModelContainer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r attests Co-Authored-By: Claude Opus 5.5 <[email protected]>
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
Changes requested: 10 blockers
- Two operations can fund registrations at the same leased index —
packages/rs-platform-wallet/src/wallet/identity/network/slots.rs:203-215(new)
Impact: A wallet client that submits twice or abandons a registration during preflight can fund two creates with the same keys and pay for a duplicate-key refusal. - A refused claim can free a still-pending slot or strand an unused one —
packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs:620-635(new)
Impact: An invitee retrying after a lost acknowledgement can make the original claim's index reusable, while a first attempt that never broadcasts can leave its index permanently held. - Shielded create slots can be reused while pending and stay blocked after expiry —
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1392-1396(new)
Impact: An app restart or upgrade can expose a pending shielded create's index to another funded operation, while a create that definitively expires can keep its unused index blocked in the running wallet. - Startup settlement can delete live claim leases and miss abandoned ones —
packages/rs-platform-wallet/src/wallet/identity/network/slots.rs:427-456(new)
Impact: A claim overlapping subsystem startup can lose its protection during submission, while users reopening either example app can keep unresolved leases because neither app runs the settlement pass. - Core registration can mutate a slot without checking its lock or wallet generation —
packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:202-216(new)
Impact: A client resuming a stale lock can change a slot the lock does not authorize, and an old registration completing after wallet replacement can end a lease in the newly loaded wallet. - Core registration recovery misses real duplicate-key refusals and can trigger a second funding —
packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:335-345(new)
Impact: A user's already-funded registration can return an unrecovered rejection or prompt the mobile apps to build another asset lock without a new funding decision. - Settlement against a lagging node can re-enable a disabled wallet key —
packages/rs-platform-wallet/src/wallet/identity/state/manager/slots.rs:380-389(new)
Impact: A user resuming a funded lock against a node behind the wallet's cached revision can persist an obsolete key and have it selected for signing. - Claim leases and the identities that replace them can disagree after a restart —
packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs:90-97(new)
Impact: An identity discovery, partial host persister, or transient flush can leave a wallet with an obsolete lease, missing identity data, or no protection for a submitted claim after restart. - An unconfirmed address-funded create or voucher reclaim can lose its slot —
packages/rs-platform-wallet/src/wallet/identity/network/register_from_addresses.rs:135-149(new; not shown inline, see below)
Impact: A user who loses confirmation of an address-funded registration can reuse its index immediately, and restarting can also expose the index of a still-pending voucher reclaim. - Shielded registration reports a generic failure when its slot is taken —
packages/rs-platform-wallet-ffi/src/shielded_send.rs:1087-1090(new; not shown inline, see below)
Impact: Swift and Kotlin users whose shielded registration slot is already occupied see a generic wallet error instead of the typed result that drives the next-slot retry.
This PR moves identity-slot allocation into the Rust wallet, adds durable invitation-claim leases, and updates the Swift and Kotlin registration flows to use wallet-issued slots. The Kotlin SDK build and emulator tests and the SwiftData explorer check passed; no code check was failing, and the automated review check was pending. This was a static review; three lower-priority suggestions did not fit the inline comment budget.
🔴 10 blocking
2 finding(s) not shown inline (the lines are not part of this PR's diff)
🔴 Blocking: An unconfirmed address-funded create or voucher reclaim can lose its slot
Impact: A user who loses confirmation of an address-funded registration can reuse its index immediately, and restarting can also expose the index of a still-pending voucher reclaim.
packages/rs-platform-wallet/src/wallet/identity/network/register_from_addresses.rs:135-149
The address SDK's broadcast_and_wait_with_metadata distinguishes an unconfirmed result, but this fallback converts it to InvalidIdentityData. The FFI no longer sees the SDK's unconfirmed variant, so Kotlin's runReleasingOnFailure and Swift's address-funded catch release the token while the transition can still land. Keeping the token in the apps would not fix restart: it is memory-only, and funded_registration_indices restores neither address-funded creates nor voucher reclaims, whose tracked lock is an IdentityInvitation at a funding-key index. Preserve submission provenance and persist a wallet-owned hold for both operations before dispatch, keyed to the leased index and the pending operation. Reconcile that hold on a proven outcome rather than asking hosts to infer delivery from an exception.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
🔴 Blocking: Shielded registration reports a generic failure when its slot is taken
Impact: Swift and Kotlin users whose shielded registration slot is already occupied see a generic wallet error instead of the typed result that drives the next-slot retry.
packages/rs-platform-wallet-ffi/src/shielded_send.rs:1087-1090
The wallet returns IdentitySlotTakenOnChain and IdentitySlotNotHeld before spending a note, but this fallback maps both to code 6 and drops the structured detail. Neither Swift nor JNI can decode codes 81 or 82 from that result. Pass these variants through the existing wallet-error conversion and keep the special unconfirmed branch that returns the prospective identity ID.
Err(e @ (PlatformWalletError::IdentitySlotNotHeld { .. }
| PlatformWalletError::IdentitySlotTakenOnChain { .. })) => e.into(),
Err(e) => PlatformWalletFFIResult::err(
PlatformWalletFFIResultCode::ErrorWalletOperation,
format!("shielded identity-create-from-pool failed: {e}"),
),
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
Review provenance
Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 7: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); reviewer 8: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.2-sol(effort low) — The diff intricately changes when wallet funding can be spent or reused inrs-platform-wallet/src/wallet/identity/network/registration.rsand changes persisted recovery state through the SQLite schema inrs-platform-wallet/src/wallet/shielded/file_store.rsand the Room migration inDashDatabase.kt. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity below 15% reserve: models 0% left),glm-5.3-flash(not used above high effort; tier asks max) - Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-astra— general (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— ffi-engineer (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-astra— security-auditor (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-platform-wallet/src/wallet/identity/network/slots.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/slots.rs:203-215: Two operations can fund registrations at the same leased index
Impact: A wallet client that submits twice or abandons a registration during preflight can fund two creates with the same keys and pay for a duplicate-key refusal.
The lease excludes a second acquisition, but not a second spend. `require_slot_lease` drops its read lock without changing the lease, so two submissions with the same token can pass, or release can give the index to another operation while the first awaits its on-chain lookup. There are two other gaps at the same authorization boundary: the exported `asset_lock_manager_create_funded_proof` can create a tracked `IdentityRegistration` lock at a caller-supplied index without consulting the allocator, and Swift voucher reclaim defaults its token to `0`, which matches the first live registration token. Atomically claim the lease for one in-flight operation before the first await and refuse release or duplicate use; enforce that authorization on new registration funding, require an explicit slot for voucher reclaim, and hand the hold off to the tracked or pending operation.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/slots.rs:427-456: Startup settlement can delete live claim leases and miss abandoned ones
Impact: A claim overlapping subsystem startup can lose its protection during submission, while users reopening either example app can keep unresolved leases because neither app runs the settlement pass.
The cleanup assumes `Reserved` means a previous process abandoned the lease. It snapshots the live map instead, and later removes by outpoint regardless of phase, so a current claim can persist `Submitted` between the snapshot and deletion and still lose its slot. The Swift and Kotlin example apps take the opposite path: `loadFromPersistor` and `loadPersistedWallets` restore the rows but never call the optional `startWalletSubsystems` that settles them. Move abandoned-reservation cleanup to exclusive restore or compare the exact restored lease and phase when deleting, and wire live settlement into the actual mobile startup lifecycle. Settlement also needs a path for a voucher already consumed by a top-up: the SDK can return a consumed-outpoint refusal with no prospective identity, and the current identity-only lookup leaves that empty index held indefinitely. Release it only on authenticated evidence of consumption, not on absence or a node's refusal alone.
In `packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/invitation.rs:620-635: A refused claim can free a still-pending slot or strand an unused one
Impact: An invitee retrying after a lost acknowledgement can make the original claim's index reusable, while a first attempt that never broadcasts can leave its index permanently held.
The wallet persists `Submitted` before SDK preflight, and uses the final error family to decide whether to undo it. On a retry, `submit_claim_lease` is a no-op for an existing `Submitted` lease; a later `NotReady` downgrades that earlier hold to `Reserved` anyway. Even on the first attempt, `NotChainLocked` can come from the SDK's post-submission InstantSend fallback, not just a local check. Conversely, an ordinary preflight transport failure or `KeysAlreadyRegistered { identity_id: Some(_), rejection: None }` can occur without dispatch but leave the lease submitted; a non-master collision bypasses the master-key placement that would end it. Serialize attempts per outpoint and have the SDK expose the dispatch boundary so only the current attempt's fresh marker can be unwound on verified non-delivery. Test lost acknowledgement followed by a refused retry, and first-attempt refusals that never dispatch.
In `packages/rs-platform-wallet/src/wallet/identity/network/register_from_addresses.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/register_from_addresses.rs:135-149: An unconfirmed address-funded create or voucher reclaim can lose its slot
Impact: A user who loses confirmation of an address-funded registration can reuse its index immediately, and restarting can also expose the index of a still-pending voucher reclaim.
The address SDK's `broadcast_and_wait_with_metadata` distinguishes an unconfirmed result, but this fallback converts it to `InvalidIdentityData`. The FFI no longer sees the SDK's unconfirmed variant, so Kotlin's `runReleasingOnFailure` and Swift's address-funded catch release the token while the transition can still land. Keeping the token in the apps would not fix restart: it is memory-only, and `funded_registration_indices` restores neither address-funded creates nor voucher reclaims, whose tracked lock is an `IdentityInvitation` at a funding-key index. Preserve submission provenance and persist a wallet-owned hold for both operations before dispatch, keyed to the leased index and the pending operation. Reconcile that hold on a proven outcome rather than asking hosts to infer delivery from an exception.
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:1392-1396: Shielded create slots can be reused while pending and stay blocked after expiry
Impact: An app restart or upgrade can expose a pending shielded create's index to another funded operation, while a create that definitively expires can keep its unused index blocked in the running wallet.
Wallet load publishes the allocator with an empty shielded hold set; only lazy shielded binding fills it. A registration before bind can therefore get the pending index, and a failed journal read leaves hydration marked successful so an identical bind can skip the retry. Even after binding, legacy create rows have a NULL index (the old Swift `isUsed` reservation is no longer consulted), and `file_store.rs:631–635` silently maps malformed non-NULL indices to the same absence. In the other direction, when the journal retires an expired create, the live hold is only ever set to `true`, and the original token can remain too. Make journal state authoritative before allocation: gate on unread or unresolved-index creates, distinguish legacy creates from other spends using the saved transition, reject malformed indices, and reconcile the hold and token when the record retires. Cover acquisition before bind, a legacy pending-create row, and expiry followed by same-session reacquisition.
In `packages/rs-platform-wallet/src/wallet/identity/network/registration.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:202-216: Core registration can mutate a slot without checking its lock or wallet generation
Impact: A client resuming a stale lock can change a slot the lock does not authorize, and an old registration completing after wallet replacement can end a lease in the newly loaded wallet.
The resume fast path calls `settle_registration_lock` before fetching the tracked lock's metadata. A successful key lookup can place an identity, end a lease, and attempt to consume the supplied outpoint before the funding resolver checks the lock's existence, role, and index. Separately, the success path at lines 363–373 looks up wallet info by ID alone after the network await; the new placement operation ends whatever lease is there, including a claim lease belonging to a replacement generation. Validate tracked role and index before settlement without starting proof resolution, preserving idempotent success for a matching consumed lock. Use the generation-checked placement path for completion and fence asset-lock bookkeeping to that same generation.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:335-345: Core registration recovery misses real duplicate-key refusals and can trigger a second funding
Impact: A user's already-funded registration can return an unrecovered rejection or prompt the mobile apps to build another asset lock without a new funding decision.
The duplicate-state-key validator emits 40207 today (10501 in the older generation), but `settles_by_the_slot` matches 40206 and its test constructs that variant directly. Fixing that classification alone would expose another defect: when post-submit settlement does find an identity from a different outpoint, it returns the same code 82 as the pre-funding guard, without the funded outpoint. Both mobile retry paths treat that code on a fresh registration as permission to rerun wallet-balance funding. Use the SDK's typed duplicate-key classification where applicable, without treating an unconfirmed result as a refusal. Return a distinct funded-recovery outcome carrying the tracked outpoint, and put the bounded pre-funding retry decision in the wallet rather than duplicating the limit in C, Kotlin, and the app loops. Test a real duplicate-key refusal through the funded path and assert that it does not start another funding call.
In `packages/rs-platform-wallet/src/wallet/identity/state/manager/slots.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/state/manager/slots.rs:380-389: Settlement against a lagging node can re-enable a disabled wallet key
Impact: A user resuming a funded lock against a node behind the wallet's cached revision can persist an obsolete key and have it selected for signing.
When the identity already occupies the slot, `place_in_slot_unstored` retains the cached identity, but `place_in_slot` still calls `layer_keys`, which replaces each fetched key by ID. An older proved answer can therefore overwrite a disable or raised limit while leaving the cached revision unchanged. Promotion of an observed identity has the same merge issue. Use the revision-aware fetched-key fold already used by loading and discovery, and persist the folded identity, key breadcrumbs, and lease removal together. Test placement with an older proof whose key is still enabled.
In `packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs:90-97: Claim leases and the identities that replace them can disagree after a restart
Impact: An identity discovery, partial host persister, or transient flush can leave a wallet with an obsolete lease, missing identity data, or no protection for a submitted claim after restart.
Three paths break the durable slot invariant. Loading and discovery call `add_identity_unstored`, which ends the lease in memory, then persist identity and key records without the lease tombstone or placement rollback; startup can write the tombstone separately. In the nominal atomic path, the FFI capability gate lets a custom host supply lease callbacks but omit either identity writer, and JNI can wire trampolines backed by inherited no-ops, so the host can commit just the deletion. Finally, `acquire_resolved_slot` frees a reservation on any `store_durably` error, even when a transient flush or `OtherFlushUnsettled` leaves its upsert buffered. Another outpoint can then lease the same index, and replay keeps whichever row comes last, not necessarily the submitted one. Use the wallet manager's durable placement transaction for discovery, loading, and settlement; require real identity and key writers when attesting the lease capability; and keep an uncertain reservation unavailable until its write or a compensating tombstone is durably settled.
In `packages/rs-platform-wallet-ffi/src/shielded_send.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/shielded_send.rs:1087-1090: Shielded registration reports a generic failure when its slot is taken
Impact: Swift and Kotlin users whose shielded registration slot is already occupied see a generic wallet error instead of the typed result that drives the next-slot retry.
The wallet returns `IdentitySlotTakenOnChain` and `IdentitySlotNotHeld` before spending a note, but this fallback maps both to code 6 and drops the structured detail. Neither Swift nor JNI can decode codes 81 or 82 from that result. Pass these variants through the existing wallet-error conversion and keep the special unconfirmed branch that returns the prospective identity ID.
| pub(crate) async fn require_slot_lease( | ||
| &self, | ||
| identity_index: RegistrationIndex, | ||
| holder: &SlotHolder, | ||
| ) -> Result<(), PlatformWalletError> { | ||
| let wm = self.wallet_manager.read().await; | ||
| let info = self.current_wallet_info(&wm)?; | ||
| match info | ||
| .identity_manager | ||
| .slot_state(&self.wallet_id, identity_index) | ||
| { | ||
| SlotState::Leased(lease) if lease.holder == *holder => Ok(()), | ||
| SlotState::Leased(_) | SlotState::Occupied(_) | SlotState::Free => { |
There was a problem hiding this comment.
🔴 Blocking: Two operations can fund registrations at the same leased index
Impact: A wallet client that submits twice or abandons a registration during preflight can fund two creates with the same keys and pay for a duplicate-key refusal.
The lease excludes a second acquisition, but not a second spend. require_slot_lease drops its read lock without changing the lease, so two submissions with the same token can pass, or release can give the index to another operation while the first awaits its on-chain lookup. There are two other gaps at the same authorization boundary: the exported asset_lock_manager_create_funded_proof can create a tracked IdentityRegistration lock at a caller-supplied index without consulting the allocator, and Swift voucher reclaim defaults its token to 0, which matches the first live registration token. Atomically claim the lease for one in-flight operation before the first await and refuse release or duplicate use; enforce that authorization on new registration funding, require an explicit slot for voucher reclaim, and hand the hold off to the tracked or pending operation.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 539f6e2: a registration lease funds one operation at a time, and no registration asset lock is funded at an index the allocator would not hand out. Applied at register_identity_with_funding, register_from_addresses and shielded_identity_create_from_pool (each moves its lease Reserved → Submitted before the first await via begin_registration, so a second call with the same token gets 81 and release_identity_slot refuses an in-flight lease with 83; a definitive failure returns it to Reserved, an unconfirmed one keeps it), at both asset_lock_manager_* exports for IdentityRegistration funding (ensure_registration_index_unallocated), and at the registration token counter, which now starts at 1 so a host default of 0 never matches a live lease.
Left deliberately: the Rust-level AssetLockManager::build_asset_lock_transaction / create_funded_asset_lock_proof do not check the allocator, because the registration flows call them with the index their own lease holds. The check sits at the FFI exports, where funding happens outside a lease.
| let out_point = self.invitation_funding_out_point(&invitation).await?; | ||
| self.submit_claim_lease(identity_index, out_point).await?; | ||
|
|
||
| let our_keys = keys_map.clone(); | ||
| let identity = match self | ||
| .sdk | ||
| .claim_invitation(invitation, keys_map, identity_signer, settings) | ||
| .await | ||
| { | ||
| Ok(identity) => identity, | ||
| Err(error) => return Err(self.claim_refusal(error).await), | ||
| Err(error) => { | ||
| // A claim that can never execute gives its slot back to the | ||
| // host; a failed store keeps it held, as before. | ||
| if claim_never_executes(&error) { | ||
| if let Err(e) = self.unsubmit_claim_lease(identity_index, out_point).await { | ||
| tracing::warn!( |
There was a problem hiding this comment.
🔴 Blocking: A refused claim can free a still-pending slot or strand an unused one
Impact: An invitee retrying after a lost acknowledgement can make the original claim's index reusable, while a first attempt that never broadcasts can leave its index permanently held.
The wallet persists Submitted before SDK preflight, and uses the final error family to decide whether to undo it. On a retry, submit_claim_lease is a no-op for an existing Submitted lease; a later NotReady downgrades that earlier hold to Reserved anyway. Even on the first attempt, NotChainLocked can come from the SDK's post-submission InstantSend fallback, not just a local check. Conversely, an ordinary preflight transport failure or KeysAlreadyRegistered { identity_id: Some(_), rejection: None } can occur without dispatch but leave the lease submitted; a non-master collision bypasses the master-key placement that would end it. Serialize attempts per outpoint and have the SDK expose the dispatch boundary so only the current attempt's fresh marker can be unwound on verified non-delivery. Test lost acknowledgement followed by a refused retry, and first-attempt refusals that never dispatch.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 14448fc: only the attempt that moved a claim's lease to Submitted may give it back, and only on a refusal that proves its claim never executes. submit_claim_lease now reports whether this call made the move. Refusals about the invitation itself (Invalid, NetworkMismatch, and the new VoucherConsumed) free the slot for any attempt. Refusals of one attempt (NotReady, NotChainLocked, and KeysAlreadyRegistered { rejection: None } from the preflight, which covers the non-master collision) free it only for the attempt that submitted it. Tests: a retry after a lost acknowledgement keeps the earlier hold, and each first-attempt preflight refusal frees the slot.
Not changed:
NotChainLockedafter the InstantSend fallback: rs-sdk returns it only after Platform refused the primary proof (stale islock, too many inputs, too large). That transition did not execute, and the islock only gets staler.- A preflight transport
Sdkerror keeps the leaseSubmitted. The wallet cannot tell it from a post-broadcast failure without an SDK dispatch boundary. It fails safe: the release is refused, a retry of the claim recovers the slot, and startup settles it from Platform. - The SDK dispatch boundary and per-outpoint serialization are moved to platform-wallet: identity slot lease follow-ups from #6014 #6243.
| match install.restore(&start.shielded).await { | ||
| Ok(()) => install.mark_hydrated(true).await, | ||
| Ok(()) => { | ||
| install.mark_hydrated(true).await; | ||
| self.hold_shielded_create_slots(coordinator).await; | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Shielded create slots can be reused while pending and stay blocked after expiry
Impact: An app restart or upgrade can expose a pending shielded create's index to another funded operation, while a create that definitively expires can keep its unused index blocked in the running wallet.
Wallet load publishes the allocator with an empty shielded hold set; only lazy shielded binding fills it. A registration before bind can therefore get the pending index, and a failed journal read leaves hydration marked successful so an identical bind can skip the retry. Even after binding, legacy create rows have a NULL index (the old Swift isUsed reservation is no longer consulted), and file_store.rs:631–635 silently maps malformed non-NULL indices to the same absence. In the other direction, when the journal retires an expired create, the live hold is only ever set to true, and the original token can remain too. Make journal state authoritative before allocation: gate on unread or unresolved-index creates, distinguish legacy creates from other spends using the saved transition, reject malformed indices, and reconcile the hold and token when the record retires. Cover acquisition before bind, a legacy pending-create row, and expiry followed by same-session reacquisition.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in fc946d7: the store's saved identity creates from the shielded pool are authoritative for the slots they hold, and a wallet leases no slot while they are unknown. Applied at:
- Wallet load (
load_from_persistor, for a wallet that bound shielded before or declares the private scan state) and wallet creation (hold_or_restore_private_payments): slots are held until a read. - The reads: first
configure_shielded, a repeat configure or a load with a store, a create with a store,bind_shielded, and the end of every shielded sync pass (ShieldedSyncManager::sync_nowandsync_wallet). A read replaces the held set, so a create that resolved or expired frees its slot in the same process. FileBackedShieldedStore::identity_create_slots_for_wallet, which fails the read (fail closed: every slot held, new code 84ErrorIdentitySlotsUnresolved) for a create whose index is NULL or damaged, a damaged create row retained without being loaded, or a transition that does not decode. The legacy NULL-index rows therefore block allocation until they resolve.- The unconfirmed create: its registration lease is handed over to the hold (
hand_off_to_shielded_create), so no stale token remains. - The readers:
acquire_identity_slot,slot_allocatableandensure_registration_index_unallocated.
A failed read no longer looks like a successful hold: it blocks the wallet until a later read succeeds, which also closes the hydration point.
Left deliberately:
- An explicit wipe (Clear, wallet removal, a re-bind that drops an account) deletes the saved records with everything else, so the next read frees their slots. Keeping create records through a wipe would change what the store promises to delete. The pre-funding check (82) still finds the identity if that create lands.
- A wallet loaded without a bound shielded account and without a persister that keeps the private scan state is not held before the read. It cannot have made a shielded create unless its persister dropped the viewing keys.
| let leases = { | ||
| let wm = self.wallet_manager.read().await; | ||
| self.current_wallet_info(&wm)? | ||
| .identity_manager | ||
| .claim_leases(&self.wallet_id) | ||
| }; | ||
| let mut resolution = ClaimLeaseResolution::default(); | ||
| for lease in leases { | ||
| if lease.slot_occupied { | ||
| if self.end_claim_lease(lease.invitation).await { | ||
| resolution.ended += 1; | ||
| } | ||
| continue; | ||
| } | ||
| // Nothing was sent for a `Reserved` claim, and the operation | ||
| // that leased it ended with the process that ran it: no claim | ||
| // can land there, and nothing else would release the lease. | ||
| if lease.phase != SlotLeasePhase::Submitted { | ||
| if self.end_claim_lease(lease.invitation).await { | ||
| resolution.ended += 1; | ||
| } | ||
| continue; | ||
| } | ||
| let identity_id = identity_id_for_out_point(lease.invitation); | ||
| let found = match Identity::fetch(&self.sdk, identity_id).await { | ||
| Ok(Some(found)) => found, | ||
| Ok(None) => { | ||
| resolution.held += 1; | ||
| continue; | ||
| } |
There was a problem hiding this comment.
🔴 Blocking: Startup settlement can delete live claim leases and miss abandoned ones
Impact: A claim overlapping subsystem startup can lose its protection during submission, while users reopening either example app can keep unresolved leases because neither app runs the settlement pass.
The cleanup assumes Reserved means a previous process abandoned the lease. It snapshots the live map instead, and later removes by outpoint regardless of phase, so a current claim can persist Submitted between the snapshot and deletion and still lose its slot. The Swift and Kotlin example apps take the opposite path: loadFromPersistor and loadPersistedWallets restore the rows but never call the optional startWalletSubsystems that settles them. Move abandoned-reservation cleanup to exclusive restore or compare the exact restored lease and phase when deleting, and wire live settlement into the actual mobile startup lifecycle. Settlement also needs a path for a voucher already consumed by a top-up: the SDK can return a consumed-outpoint refusal with no prospective identity, and the current identity-only lookup leaves that empty index held indefinitely. Release it only on authenticated evidence of consumption, not on absence or a node's refusal alone.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in ede4db7 and 14448fc: startup settlement ends only a claim lease that was restored from the store and is unchanged since. The wallet ends a Reserved lease only if it was restored, and every end requires the lease to match the snapshot (index and phase). A claim of this process that takes the lease, resubmits it or releases it makes it non-restored. Applied at IdentityWallet::settle_claim_leases / end_claim_lease and IdentityManager::end_claim_lease. A voucher consumed by something other than a claim now returns InvitationError::VoucherConsumed from adopt_already_landed_claim, which counts as a never-executes refusal and frees the slot. It takes Platform's consumed-outpoint refusal together with a proof-verified lookup that finds no identity at the claim's id. The refusal itself is not authenticated. If a node lies about it, the worst case is a freed slot whose identity appears later, and the pre-funding check of the next registration at that index finds it (82).
Not changed: wiring startWalletSubsystems into the example apps. The SDK contract already requires the host to call it, and neither app called it before this PR (it also runs drain, discovery and the gate for SPV start), so this is moved to #6243.
| if let AssetLockFunding::FromExistingAssetLock { | ||
| out_point, | ||
| consume_invitation_voucher: false, | ||
| } = funding | ||
| { | ||
| // A resumed registration lock: before anything is resolved or | ||
| // submitted (a refusal for keys already registered costs a | ||
| // penalty from the lock each time), see whether the keys derived | ||
| // at its index are an identity's already: this lock's own (an | ||
| // earlier submit landed) or another of this wallet's. | ||
| if let Some(settled) = self | ||
| .settle_registration_lock(identity_index, &keys_map, out_point) | ||
| .await? | ||
| { | ||
| return settled; |
There was a problem hiding this comment.
🔴 Blocking: Core registration can mutate a slot without checking its lock or wallet generation
Impact: A client resuming a stale lock can change a slot the lock does not authorize, and an old registration completing after wallet replacement can end a lease in the newly loaded wallet.
The resume fast path calls settle_registration_lock before fetching the tracked lock's metadata. A successful key lookup can place an identity, end a lease, and attempt to consume the supplied outpoint before the funding resolver checks the lock's existence, role, and index. Separately, the success path at lines 363–373 looks up wallet info by ID alone after the network await; the new placement operation ends whatever lease is there, including a claim lease belonging to a replacement generation. Validate tracked role and index before settlement without starting proof resolution, preserving idempotent success for a matching consumed lock. Use the generation-checked placement path for completion and fence asset-lock bookkeeping to that same generation.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 4048530: a resume touches a slot only for a tracked IdentityRegistration lock at that index, and completion is generation-checked. Applied at the resume fast path (authorize_registration_lock, which validates the tracked role and index before settle_registration_lock without starting proof resolution) and the success path (record_registered_identity through current_wallet_info_mut). consume_asset_lock has no generation check, but that predates this PR.
| Err(refusal) if settles_by_the_slot(&refusal, &proof_out_point) => { | ||
| match self | ||
| .settle_registration_lock( | ||
| identity_index, | ||
| placeholder.public_keys(), | ||
| proof_out_point, | ||
| ) | ||
| .await | ||
| { | ||
| Ok(Some(settled)) => return settled, | ||
| Ok(None) | Err(_) => return Err(refusal), |
There was a problem hiding this comment.
🔴 Blocking: Core registration recovery misses real duplicate-key refusals and can trigger a second funding
Impact: A user's already-funded registration can return an unrecovered rejection or prompt the mobile apps to build another asset lock without a new funding decision.
The duplicate-state-key validator emits 40207 today (10501 in the older generation), but settles_by_the_slot matches 40206 and its test constructs that variant directly. Fixing that classification alone would expose another defect: when post-submit settlement does find an identity from a different outpoint, it returns the same code 82 as the pre-funding guard, without the funded outpoint. Both mobile retry paths treat that code on a fresh registration as permission to rerun wallet-balance funding. Use the SDK's typed duplicate-key classification where applicable, without treating an unconfirmed result as a refusal. Return a distinct funded-recovery outcome carrying the tracked outpoint, and put the bounded pre-funding retry decision in the wallet rather than duplicating the limit in C, Kotlin, and the app loops. Test a real duplicate-key refusal through the funded path and assert that it does not start another funding call.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in e92f9b3: post-funding recovery matches the duplicate-key codes Platform actually emits, and never returns 82 after funding. settles_by_the_slot matches 40207 DuplicatedIdentityPublicKeyIdStateError and 10501 DuplicatedIdentityPublicKeyIdBasicError. After funding, settled_after_funding returns Ok only for the landed identity and otherwise returns Platform's refusal, never IdentitySlotTakenOnChain, so the apps' 82 retry cannot start a second funding. Test: a real duplicate-key refusal through the funded path. A wallet-side retry limit is outside this PR's scope.
| let placement = self.place_in_slot_unstored(identity, identity_index, wallet_id)?; | ||
|
|
||
| let managed = self | ||
| .managed_identity_mut(&identity_id) | ||
| .ok_or(PlatformWalletError::IdentityNotFound(identity_id))?; | ||
| let keys_cs = managed.layer_keys(keys); | ||
| let mut changeset = PlatformWalletChangeSet { | ||
| identities: Some(managed.snapshot_changeset()), | ||
| identity_keys: Some(keys_cs), | ||
| ..Default::default() |
There was a problem hiding this comment.
🔴 Blocking: Settlement against a lagging node can re-enable a disabled wallet key
Impact: A user resuming a funded lock against a node behind the wallet's cached revision can persist an obsolete key and have it selected for signing.
When the identity already occupies the slot, place_in_slot_unstored retains the cached identity, but place_in_slot still calls layer_keys, which replaces each fetched key by ID. An older proved answer can therefore overwrite a disable or raised limit while leaving the cached revision unchanged. Promotion of an observed identity has the same merge issue. Use the revision-aware fetched-key fold already used by loading and discovery, and persist the folded identity, key breadcrumbs, and lease removal together. Test placement with an older proof whose key is still enabled.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
Fixed in 6f44876: placing an identity in its slot folds fetched keys by revision, as loading and discovery do. Applied at place_in_slot (key_decisions_for_fetch before layer_keys), the shared choke point for settlement, registration completion and promotion. Test: placement with an older proof whose key is still enabled keeps the cached disable.
| return Err(PlatformWalletError::IdentityAlreadyExists(identity_id)); | ||
| } | ||
|
|
||
| let mut managed_identity = ManagedIdentity::new(identity, identity_index); | ||
| // Denormalize the bucket keys onto the value so callers that | ||
| // iterate values know which wallet + slot they came from | ||
| // without re-threading the keys. | ||
| managed_identity.wallet_id = Some(wallet_id); | ||
| // Held before anything can send or accept for it, when a persister | ||
| // kept its record marked. | ||
| if self.retained_private_payment_markers.remove(&identity_id) { | ||
| managed_identity.hold_for_retained_private_payment_marker(); | ||
| } | ||
|
|
||
| self.wallet_identities | ||
| .entry(wallet_id) | ||
| .or_default() | ||
| .insert(identity_index, managed_identity); | ||
| // Keep the side-index invariant in lockstep with the bucket | ||
| // insert above. | ||
| self.location_index_insert( | ||
| identity_id, | ||
| IdentityLocation::InWallet { | ||
| wallet_id, | ||
| registration_index: identity_index, | ||
| }, | ||
| ); | ||
|
|
||
| Ok(()) | ||
| // Through the one slot path, so an occupied slot is refused here as | ||
| // everywhere else instead of being overwritten. | ||
| self.place_in_slot_unstored(identity, identity_index, wallet_id) | ||
| .map(|_| ()) |
There was a problem hiding this comment.
🔴 Blocking: Claim leases and the identities that replace them can disagree after a restart
Impact: An identity discovery, partial host persister, or transient flush can leave a wallet with an obsolete lease, missing identity data, or no protection for a submitted claim after restart.
Three paths break the durable slot invariant. Loading and discovery call add_identity_unstored, which ends the lease in memory, then persist identity and key records without the lease tombstone or placement rollback; startup can write the tombstone separately. In the nominal atomic path, the FFI capability gate lets a custom host supply lease callbacks but omit either identity writer, and JNI can wire trampolines backed by inherited no-ops, so the host can commit just the deletion. Finally, acquire_resolved_slot frees a reservation on any store_durably error, even when a transient flush or OtherFlushUnsettled leaves its upsert buffered. Another outpoint can then lease the same index, and replay keeps whichever row comes last, not necessarily the submitted one. Use the wallet manager's durable placement transaction for discovery, loading, and settlement; require real identity and key writers when attesting the lease capability; and keep an uncertain reservation unavailable until its write or a compensating tombstone is durably settled.
source: gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)
There was a problem hiding this comment.
- Rollback. A slot change in memory is rolled back only when no later flush can still write it (
NotDurable::may_still_be_written). Applied at claim acquisition, release,set_claim_lease_phase,end_claim_leaseand theplace_in_slotundo. - Capability gate. The lease bit is attested only with real identity and key writers. Applied at the FFI gate (
on_persist_identities_fn+on_persist_identity_keys_fn) and the JNI bridge (onPersistIdentityUpsert/onPersistIdentityKeyUpsertoverrides).
Not changed: load and discovery ending the lease in memory before the identity is stored. An occupant wins over a lease in slot_state, and startup ends the leases of occupied slots. If the store fails, the lease row stays and the identity is rediscovered, so the slot is never handed out twice.
…d identity create A shielded create refused for its slot (not held, or taken on chain) fell into the generic wallet-operation code, so Swift and Kotlin could not decode codes 81/82 and take the next slot. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ey code Platform emits Platform refuses an identity create whose key is already registered with DuplicatedIdentityPublicKeyIdStateError (40207), or the basic error 10501 before protocol version 7; the settle matched only 40206, which identity create never emits. After funding, a settle that finds another identity now returns Platform's refusal instead of the pre-funding slot-taken code 82, on which both apps fund the next slot again. The lock stays tracked, so a resume reaches the settle and the top-up offer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
place_in_slot layered the fetched keys over an identity the wallet already held, so a proof from a node behind the cache could re-enable a key the cache holds disabled. The keys now go through the same revision-aware fold as loading and discovery; every placement (registration, claim, slot settlement, discovery by slot) passes through it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tracked lock A resume settled the slot by what holds its keys before the funding resolver checked the lock, so an untracked lock or one tracked for another index could place an identity and end a claim's lease there. The resume now requires a tracked registration lock of that index first, spent or not, so a landed resume stays idempotent. A registration that lands now records its identity through the generation-checked placement, so a wallet replaced during the submit keeps its own slots and leases. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h may write it Every slot store (claim lease acquire, release, phase change, end, and an identity's placement) rolled memory back on any failed durable store. After a transient flush failure, or with another flush unsettled, the row stays buffered and a later flush writes it: memory then disagreed with what a restart loads, and another claim could lease the same index. Memory now rolls back only when the store failed or the buffer was dropped. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and key writers A placement ends a claim's lease in the same write as the identity and its keys. The FFI gate attested the lease bit without the identity and identity-key callbacks, and JNI without overridden identity and key upserts, so a host could commit just the lease's end and lose the identity on restart. Both now require them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… proves it A claim moved its lease to Submitted and undid that on any refusal of its family, whichever attempt had submitted it. A retry after a lost acknowledgement could therefore free the slot of an earlier claim that may still land, while a preflight refusal for a key registered to another identity kept the lease Submitted for good. Refusals are now split: one about the invitation (invalid, other network, or a voucher spent without a claim) frees the slot for every attempt; one about the attempt (not ready, not chain-locked, a key the claim's own lookup found registered) frees it only when this attempt submitted the lease. The SDK reports a voucher spent without a claim (Platform's consumed-outpoint refusal with a proved absence of the invitation's identity, as after an inviter's top-up reclaim) as InvitationError::VoucherConsumed instead of a plain SDK error, so that claim's slot is no longer held forever. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ous process left The startup settlement ended every Reserved claim lease, and ended a lease by its invitation whatever its phase. A claim this process leased during startup, or moved to Submitted between the read and the end, lost its slot while it ran. A Reserved lease is now ended only when it was restored from the store and no operation of this process took it up since, and every end requires the lease to stand as it was read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a time A registration's lease was only checked, so two submissions with the same token could both fund a create at one index, and its release could give the index away while the first awaited its pre-funding lookup. Each of the three registration entry points (asset lock, addresses, shielded pool) now takes the lease for its operation (Reserved to Submitted, in memory) before its first await and refuses one already in flight; its release is refused meanwhile, and the operation's end gives it back unless its outcome is unknown. The generic asset-lock exports funded a registration lock at any index; a registration lock there now needs an index the allocator would hand out. Registration tokens start at 1, so a host's zero or default token never names a live lease. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ates The slots identity creates from the shielded pool hold were filled only at a lazy bind and never released, so a registration before bind could take a pending create's index, a legacy create with no saved index held nothing, and an expired create kept its slot blocked for the session. The store's saved creates are now authoritative. A read replaces the wallet's held slots, so a create that resolved or expired frees its slot in the same process. It runs at configure, at a load or creation with a store, at bind, and after every shielded sync pass. A wallet that may have saved creates leases no slot until a read succeeds, and a read that fails, or finds a create whose slot is NULL, damaged or not decodable, keeps every slot held (new code 84, ErrorIdentitySlotsUnresolved, typed in Swift and Kotlin). An unconfirmed create hands its registration lease over to the hold. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Replies to the review body: 9. Not changed: since #5556, 10. Fixed in 6947478: a refused shielded identity create keeps the typed slot codes (81/82) at the FFI instead of the generic shielded failure. Applied at |
Issue being fixed or feature implemented
Closes #5917.
Stacked on #5536 (
feat/invitation-claim-preflight). Review only the commits after4a6ee4f0ed. Once #5536 merges, this PR will be retargeted tov5.2-dev.A normal registration and an invitation claim could both pick the same
(wallet, identity_index). Both would then derive the same keys, and Platform refused the second one (40200 identity exists, or 40206 duplicated key) only after its funding was spent. Each host chose the index itself: Swift used anisUsedmarker plus coordinator snapshots, and Kotlin used a free text field. #5536 cut claim recovery and the Swift slot reservation because the wallet had no single operation that owns a slot. This PR adds that operation. Claim recovery comes back in a follow-up PR on top of it.What was done?
One slot owner in
rs-platform-walletIdentityManagerkeeps a slot map:Free,Leased(holder, phase)orOccupied(identity). Every identity reaches its slot throughplace_in_slot, which stores durably before it publishes. An occupied slot holds no lease: placing an identity ends any lease on that slot.IdentityWallet::acquire_identity_slot/release_identity_slot. The wallet picks the lowest free index; hosts never choose one.index + token).IdentitySlotLeaseChangeSet, a new persister capability (IDENTITY_SLOT_LEASES, bit 17), implemented in SwiftData and Room. A host without that capability cannot claim (Q1).Submittedbefore the first await, so a second call with the same token gets 81. A definitive failure returns it toReserved; an unconfirmed one keeps it. Tokens start at 1, so a host default of0never matches a live lease.asset_lock_manager_*exports refuse to fund anIdentityRegistrationlock at an index the allocator would not hand out.Submitteddurably before the claim is sent. Only the attempt that made that move may give it back, and only on a refusal that proves the claim never executes: refusals about the invitation (Invalid, NetworkMismatch, VoucherConsumed) free the slot for any attempt; refusals of one attempt (NotReady, NotChainLocked, a preflight key collision) only for the attempt that submitted it.Submittedlease is refused with a typed error (83).IdentitySlotTakenOnChain; the host acquires the next slot and retries (capped atIDENTITY_SLOT_TAKEN_RETRY_LIMIT). If the lookup fails, the guard fails closed.identity_index(new nullable SQLite column), and the store's saved creates are authoritative for the slots they hold. The wallet re-reads them at configure, bind and the end of every shielded sync pass, so a create that resolves or expires frees its slot in the same process. Until a read succeeds (at load, or when a saved create has no index or does not decode) the wallet leases no slot and returns 84IdentitySlotsUnresolved(fail closed). An unconfirmed create hands its registration lease over to that hold.Okonly for the landed identity and otherwise Platform's refusal, so the apps' 82 retry cannot start a second funding. Duplicate-key refusals are matched by Platform's real codes (40207, 10501).Submittedclaim leases are resolved against Platform: the claim's identity id is derived from the outpoint, then fetched. If it landed, it is placed; if the invitation was consumed by someone else, the lease ends; otherwise the lease is kept.Reservedclaim leases are ended.FFI / JNI (marshal only)
New exports:
platform_wallet_identity_slot_{acquire,release}_{registration,invitation_claim}.Register, resume, address-funded and shielded create FFI and JNI take
slot_token.New result codes:
IdentitySlotNotHeldIdentitySlotTakenOnChain, with JSON detailIdentitySlotClaimSubmitted, JSON{identityIndex}IdentitySlotsUnresolved(retryable: the saved shielded creates are not read yet)All four are listed in
ERROR_CODE_REGISTRY.md.rs-sdk:identity_id_for_out_pointis now public.Swift and Kotlin SDKs and example apps
TransactionBroadcastUnconfirmed, shielded unconfirmed);isUsedreservation, the coordinator-snapshot index pick, and Kotlin's free-text index field.identity.slot_leases; ID-01 rows in bothTEST_PLAN.md.Known limitations
startWalletSubsystemsin the example apps, a wallet-side 82 retry bound).Submittedclaim at startup (no scan key), so the lease stays held.AlreadyClaimed/ClaimedByThisWalletrefusals in the same session are settled at the next start, not right away.place_in_slot,recover_claimed_identity) is not here; it is the follow-up PR.How Has This Been Tested?
cargo test -p platform-wallet --all-features,cargo test -p platform-wallet-ffi,cargo test -p rs-unified-sdk-jni, clippy and fmt — green. Covered by unit tests: slot model, leases, placement, guard, claim-lease resolver, registration-lock settle, startup settle, shielded hold. Mutation checks on the resolver, settle and hold paths were all caught by tests../gradlewsdk + app unit tests — green.ErrorHandlingTestsandCreateIdentityResumableTests— green.claim_invitation's wiring for the "never executed" case;Breaking Changes
platform_wallet_register_identity_with_funding_signer,platform_wallet_resume_identity_with_existing_asset_lock_signer,platform_wallet_register_identity_with_signerandplatform_wallet_manager_shielded_identity_create_from_pooltake aslot_tokenafteridentity_index; the matching JNI functions take it too.Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code