Skip to content

feat(platform-wallet)!: give identity slots one wallet-owned lease - #6014

Draft
romchornyi wants to merge 72 commits into
v5.2-devfrom
feat/wallet-identity-slot-lease
Draft

romchornyi wants to merge 72 commits into
v5.2-devfrom
feat/wallet-identity-slot-lease

Conversation

@romchornyi

@romchornyi romchornyi commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Issue being fixed or feature implemented

Closes #5917.

Stacked on #5536 (feat/invitation-claim-preflight). Review only the commits after 4a6ee4f0ed. Once #5536 merges, this PR will be retargeted to v5.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 an isUsed marker 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-wallet

  • IdentityManager keeps a slot map: Free, Leased(holder, phase) or Occupied(identity). Every identity reaches its slot through place_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.
    • A registration holds a slot with a token (acquire returns index + token).
    • An invitation claim holds a slot keyed by the invitation's funding outpoint, so a retried claim gets the same slot back. The claim lease is durable: IdentitySlotLeaseChangeSet, a new persister capability (IDENTITY_SLOT_LEASES, bit 17), implemented in SwiftData and Room. A host without that capability cannot claim (Q1).
  • Registration (asset lock, Platform addresses, shielded pool), invitation claim and voucher reclaim-as-new-identity now all require a lease on the index they use.
    • A registration lease funds one operation at a time: it goes Submitted before the first await, so a second call with the same token gets 81. A definitive failure returns it to Reserved; an unconfirmed one keeps it. Tokens start at 1, so a host default of 0 never matches a live lease.
    • The asset_lock_manager_* exports refuse to fund an IdentityRegistration lock at an index the allocator would not hand out.
    • A claim lease goes Submitted durably 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.
    • Releasing a Submitted lease is refused with a typed error (83).
  • Pre-funding guard: before any funding is spent, the wallet checks whether the slot's key is already registered. If it belongs to an identity of this wallet, the wallet places that identity in the slot and returns IdentitySlotTakenOnChain; the host acquires the next slot and retries (capped at IDENTITY_SLOT_TAKEN_RETRY_LIMIT). If the lookup fails, the guard fails closed.
  • Shielded identity creates: the pending shielded spend stores its 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 84 IdentitySlotsUnresolved (fail closed). An unconfirmed create hands its registration lease over to that hold.
  • After funding the wallet never returns 82: recovery returns Ok only 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).
  • Registration lock settle (R6, 40200/40206): before a resume, and after an AlreadyConsumed / 40200 / 40206 refusal, the wallet checks what holds the slot's keys:
    • the lock's own identity → success, and the lock is consumed;
    • another identity of this wallet → 82; the lock stays and can top up the identity at its own index, which the apps now offer.
  • Startup settle (Q4), run before identity discovery:
    • Submitted claim 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.
    • Reserved claim leases are ended.
    • Only leases restored from the store and unchanged since (same index and phase) are ended; a claim of this process that takes, resubmits or releases a lease makes it non-restored.
    • An invitation whose voucher was consumed by something other than a claim (refused outpoint, and a proof-verified lookup finds no identity at the claim's id) frees the slot.
    • Unconsumed registration locks are settled as above.
    • The scan key is resolved at most once per start.

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:

    • 81 IdentitySlotNotHeld
    • 82 IdentitySlotTakenOnChain, with JSON detail
    • 83 IdentitySlotClaimSubmitted, JSON {identityIndex}
    • 84 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_point is now public.

Swift and Kotlin SDKs and example apps

  • Typed errors 81–84, the slot API, and claim-lease persistence (SwiftData model, shown in the Storage Explorer; Room migration 16→17).
  • The apps take every index from the wallet:
    • retry on 82 at the next slot;
    • keep the slot when the result may have reached Platform (TransactionBroadcastUnconfirmed, shielded unconfirmed);
    • release the lease when the claim sheet closes or the invitation changes;
    • offer a top-up when a resumed registration lock's slot is taken.
  • Removed: Swift's isUsed reservation, the coordinator-snapshot index pick, and Kotlin's free-text index field.
  • Parity manifest entry identity.slot_leases; ID-01 rows in both TEST_PLAN.md.

Known limitations

  • An address-funded registration left unconfirmed across a restart holds its index in memory only. A later registration at that index is caught by the pre-funding guard once the first one has executed; it races only while the first is still pending. A durable hold for this case is tracked in platform-wallet: identity slot lease follow-ups from #6014 #6243, with the other review follow-ups (SDK dispatch boundary for claims, startWalletSubsystems in the example apps, a wallet-side 82 retry bound).
  • A 40206 caused by a non-master key, when no identity of ours holds our master key, stays a raw error, and a further resume pays again.
  • Watch-only wallets cannot resolve a Submitted claim at startup (no scan key), so the lease stays held.
  • AlreadyClaimed / ClaimedByThisWallet refusals in the same session are settled at the next start, not right away.
  • The startup settle records a landed identity by loading it at its index. If the wallet has it only as an observed identity (looked up by name, say), it is not moved into the slot, and the lease or lock stays held. Moving it is part of claim recovery (follow-up PR).
  • Claim recovery (promotion through 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.
  • Kotlin: ./gradlew sdk + app unit tests — green.
  • Swift: xcframework + SwiftExampleApp built (iOS simulator); ErrorHandlingTests and CreateIdentityResumableTests — green.
  • Not run:
    • Kotlin instrumented tests (Room migration 16→17, FFI smoke), which need an emulator.
    • A device or simulator run of the 82 retry, the startup settle, and resume → top-up.
    • Anything against a live network.
  • No direct test (no mocked claim or refusal harness):
    • claim_invitation's wiring for the "never executed" case;
    • the settle wiring after a submit is refused;
    • the unconfirmed → hold branch of shielded create.

Breaking Changes

  • The FFI functions platform_wallet_register_identity_with_funding_signer, platform_wallet_resume_identity_with_existing_asset_lock_signer, platform_wallet_register_identity_with_signer and platform_wallet_manager_shielded_identity_create_from_pool take a slot_token after identity_index; the matching JNI functions take it too.
  • Registration, claim and reclaim fail with 81 unless the index was acquired from the wallet first.
  • A persister without the claim-lease capability cannot claim an invitation.
  • The Swift and Kotlin registration and claim APIs take the acquired slot instead of a free index.

Checklist:

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request
  • If I added or changed a system contract's document schemas, I checked the contract viewer link posted on this pull request

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

jeanpierreroma and others added 30 commits October 22, 2026 13:42
…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]>
- 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]>
…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
…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]>
@coderabbitai

coderabbitai Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@thepastaclaw

thepastaclaw commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Review not started yet because this PR is a draft.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit fc946d7. Normal review starts when eligible; priority review starts as soon as a slot is available.

romchornyi and others added 5 commits November 23, 2026 12:36
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]>

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

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: critical by gpt-6.2-sol (effort low) — The diff intricately changes when wallet funding can be spent or reused in rs-platform-wallet/src/wallet/identity/network/registration.rs and changes persisted recovery state through the SQLite schema in rs-platform-wallet/src/wallet/shielded/file_store.rs and the Room migration in DashDatabase.kt.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-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; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-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.

Comment on lines +203 to +215
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 => {

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +620 to +635
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!(

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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:

  • NotChainLocked after 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 Sdk error keeps the lease Submitted. 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.

Comment on lines 1392 to +1396
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;
}

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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_now and sync_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 84 ErrorIdentitySlotsUnresolved) 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_allocatable and ensure_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.

Comment on lines +427 to +456
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;
}

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +202 to +216
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;

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +335 to +345
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),

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +380 to +389
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()

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines 91 to +97
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(|_| ())

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.

🔴 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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 6755490 and 855d898:

  • 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_lease and the place_in_slot undo.
  • 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 / onPersistIdentityKeyUpsert overrides).

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.

romchornyi and others added 10 commits November 24, 2026 11:26
…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]>
@romchornyi

Copy link
Copy Markdown
Contributor Author

Replies to the review body:

9. Not changed: since #5556, preserve_signer_key_unavailable_or keeps an unconfirmed register_from_addresses result as Sdk(unconfirmed), and the FFI maps it to code 20. It is not reported as a refusal.

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 shielded_identity_create_result.

This branch has not been deployed

No deployments
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.

3 participants