Skip to content

platform-wallet: top up someone else's identity from Core, with the recipient recorded on the asset lock before broadcast #5924

Open

Description

@romchornyi

Expected Behavior

A wallet can top up someone else's identity from its Core balance (asset lock → IdentityTopUp),
and an interrupted top-up resumes to the recipient the user confirmed, never to an identity the
resuming caller happens to pass.

Current Behavior

rs-platform-wallet can only top up an identity the wallet manages, and an asset lock does not record
which identity it was meant for:

  1. IdentityWallet::top_up_identity_with_funding looks the identity up in the wallet's
    IdentityManager and returns IdentityNotFound for any other identity; the bound funding account it
    derives from is keyed by that identity's registration index
    (registration.rs#L382-L408,
    build.rs#L291-L294).
  2. TrackedAssetLock stores funding_type and identity_index, but no recipient for an identity
    top-up; only the shielded funding (Type 18) records its recipient before dispatch
    (tracked.rs#L129-L155).
  3. On resume, an unbound top-up lock is "deliberately eligible for any target"
    (orchestration.rs#L700-L725),
    and the resume entry points take the identity from the caller
    (platform_wallet_topup_identity_with_existing_asset_lock_signer,
    Swift resumeTopUpWithAssetLock).
    A host's recovery passes its own identity, so an interrupted top-up of someone else's identity would
    be paid into the holder's identity.

Because of (3), both wallets keep Core → someone else's identity unavailable (dashpay/dash-wallet#1680,
and the iOS external send in dashpay/dashwallet-ios#1406–#1409), while Shielded and Identity sources can
already pay any identity, and Platform addresses will with #5860.

Possible Solution

  1. External top-up operation in rs-platform-wallet, e.g.
    top_up_external_identity_with_funding(identity_id, funding, signer, settings): fetch the identity
    from Platform instead of the IdentityManager, touch no identity-manager state, and fund the lock
    from the unbound top-up account (IdentityTopUpNotBound, DIP-9), which needs no local registration
    index (see Option to fund identity top-ups from the unbound (legacy-compatible) top-up account #4253).
  2. Record the recipient before broadcast: a new immutable TrackedAssetLock field (e.g.
    identity_recipient: Option<Identifier>), written with the row before the lock is dispatched, as
    shielded_recipient is. This is a persistence change: changeset / serde adapters, the FFI
    asset-lock persistence callbacks and the hosts' stores.
  3. Resume pays the recorded recipient: when a lock carries identity_recipient, the resume uses it
    and refuses (or ignores) a different caller-supplied identity; validate_existing_asset_lock_role
    stops treating such a lock as eligible for any target. Locks without a record keep today's behaviour.
  4. Restore from seed: the recipient is not on chain (the credit output is the next unused address
    of the unbound account), so a reconstructed lock has no record. It must not be auto-resumed into the
    holder's identity; surface it to the host as an unassigned lock instead. The funds stay recoverable,
    since the wallet holds the lock key.
  5. Completion is decided by the recipient's proved balance, as in feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 (there is no local
    ManagedIdentity to persist), and the operation goes through the same wallet-lifecycle fence as
    the other top-ups (platform-wallet: an asset-lock build is not excluded from wallet removal, so a lock can be broadcast for a wallet that is gone #5516).
  6. FFI and Swift/Kotlin bindings: one export for the top-up and one for its resume, with the
    identity-not-found / lookup-failed codes the external top-up from addresses uses (feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860).

Alternatives Considered

  • Register the foreign identity in the wallet's IdentityManager first: no new operation, but the
    wallet would list someone else's identity as its own, and recovery would still pay it as a managed
    identity.
  • Keep the pair unavailable (today): Core-only users cannot pay an identity without first moving
    funds to Shielded or Platform.

Additional Context

Activity

  1. HashEngineering commented on Nov 13, 2026

    @HashEngineering
    Collaborator

    Plan: top up someone else's identity from Core (#5924)

    Code references are at origin/v5.2-dev a7669077c5, the commit the issue cites.

    Findings

    • The issue is accurate. IdentityWallet::top_up_identity_with_funding requires an identity the
      wallet manages (rs-platform-wallet/src/wallet/identity/network/registration.rs:382-408).
      validate_existing_asset_lock_role (wallet/asset_lock/orchestration.rs:700-725) accepts an
      unbound top-up lock for any identity.
    • The Rust side is mostly ready.
      • The builder already supports the unbound top-up account (wallet/asset_lock/build.rs:495, :609).
      • key-wallet creates that account by default (create_special_purpose_accounts, rust-dashcore c9aeac0).
      • Restore from seed already rebuilds its locks (wallet/asset_lock/sync/reconstruction.rs:202).
    • Nothing builds unbound locks today. No Rust path creates an IdentityTopUpNotBound lock; only
      the generic FFI builder can, if a host passes funding type 2. Unbound locks with no recorded
      recipient are therefore almost all rebuilt from a seed, which makes stricter handling cheap.
    • There is a pattern to copy. shielded_recipient does the same job for shielded funding:
      • storage migration V020__asset_lock_shielded_recipient;
      • wallet/apply.rs keeps the field from being overwritten;
      • FFI persist/load slots and capability bit 14 (ASSET_LOCK_SHIELDED_RECIPIENTS);
      • error 61 AssetLockRecipientMismatch.
    • The Kotlin SDK does not save the shielded recipient today. It wires neither persistence
      slot, and AssetLockEntity has no column for it, so a shielded recipient is lost on restart. A
      new identity-recipient field would be lost the same way unless Kotlin wires it.
    • Swift already saves the shielded recipient (PersistentAssetLock.shieldedRecipientRaw43,
      PlatformWalletPersistenceHandler.persistAssetLockShieldedRecipient), so its part is smaller.

    Plan

    PR A: Rust core, storage and FFI

    Target v5.2-dev, stacked on #5860 (it reuses #5860's error codes and its Platform lookup).

    1. Record the recipient on the lock.
      • Add identity_recipient: Option<Identifier> to TrackedAssetLock and AssetLockEntry.
      • Update the changeset, the serde adapters and core_bridge.
      • In apply.rs, keep the field fixed once it is set, as shielded_recipient is.
      • In the storage crate, add a SQLite migration modelled on V020.
      • In the build path, write the recipient with the row before the lock is broadcast. Refuse to
        build an unbound lock for an external top-up without a recipient.
    2. Add the external top-up:
      IdentityWallet::top_up_external_identity_with_funding(identity_id, funding, signer, settings).
      Expose it through a PlatformWallet wrapper that checks the wallet is still current (platform-wallet: an asset-lock build is not excluded from wallet removal, so a lock can be broadcast for a wallet that is gone #5516), as
      feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 does.
      • Look the identity up on Platform before building anything. If it doesn't exist, return
        IdentityNotFound (7); if the lookup fails, return IdentityLookupFailed (80). Nothing is
        spent in either case.
      • Read the identity's balance before submitting.
      • Fund the lock from the unbound account (IdentityTopUpNotBound, index 0), with the recipient
        recorded.
      • Submit with the existing submit_with_chain_lock_fallback.
      • Count the top-up as done only when the proved balance is higher than the balance read before
        submitting. Otherwise return StateTransitionResultUnconfirmed (20).
      • Mark the lock consumed. Write nothing to the identity manager.
    3. Make resume pay the recorded recipient.
      • Pass the recorded recipient into validate_existing_asset_lock_role.
      • If the lock has a recipient and the caller names a different identity, return
        AssetLockRecipientMismatch (61). This applies on the managed route too, so a host recovery
        that passes the holder's identity can no longer redirect the payment.
      • Add a resume entry point that takes no identity. It reads the recipient from the lock, then
        uses the managed path if that identity is managed and the external path if not.
    4. Treat unbound locks with no recipient as unassigned.
      • Leave them out of tracked_identity_recovery_asset_locks.
      • List them through a new accessor.
      • Refuse to resume them through the generic path, with a new error ("recipient unknown").
      • Add an explicit call that assigns a recipient when the user picks one. The lock key stays in
        the wallet, so the funds remain recoverable.
      • This replaces "locks without a record keep today's behaviour" in the issue, which conflicts
        with the issue's point 4 (restore from seed).
    5. FFI changes:
      • New exports: platform_wallet_top_up_external_identity_with_funding_signer, and a resume
        export that reads the recipient from the lock.
      • platform_wallet_topup_identity_with_existing_asset_lock_signer now returns 61 when the lock
        was recorded for a different identity.
      • Asset-lock struct (asset_lock/manager.rs): add has_identity_recipient and
        identity_recipient_32.
      • Persistence: add an on_persist_asset_lock_identity_recipient_fn /
        on_load_asset_lock_identity_recipient_fn pair and capability bit 16
        (ASSET_LOCK_IDENTITY_RECIPIENTS).
      • Error codes: add the "recipient unknown" code and record it in ERROR_CODE_REGISTRY.md.
      • Follow feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860's registry_release_tests pattern: don't call block_on_worker inside
        PLATFORM_WALLET_STORAGE.with_item.
      • PR A owns every FFI export. The Kotlin and Swift PRs only add bindings, so the two don't
        clash on symbols as gap 3b and feat(swift-sdk): shieldedShieldFromIdentityToRecipient #5863 did.
    6. Require the persistence capability. The external Core top-up refuses before building
      anything if the host hasn't declared bit 16. Without it, a restart turns the lock into an
      unassigned one: not paid to the wrong person, but stuck until someone assigns it by hand.

    PR A tests

    • An unknown identity returns 7 and builds no lock. A failed lookup returns 80.
    • The recipient is saved before the lock is broadcast.
    • Resuming with the wrong identity returns 61, on both the managed and external routes.
    • A stale snapshot can't change the recorded recipient (apply.rs).
    • A rebuilt unbound lock is left out of recovery and refused by the generic resume. Assigning a
      recipient makes it resumable.
    • The external top-up is refused when bit 16 is not declared.
    • No balance increase returns 20. Nothing is written to the identity manager.
    • A wallet removed mid-top-up is refused, and a removal waits for a running top-up.
    • Store/load round trip, plus a host that doesn't wire the new slots.
    • The resume that takes no identity uses the managed path for a managed recipient and the external
      path otherwise.

    PR B: Kotlin SDK

    • JNI bindings:
      • CreditsNative exports;
      • IdentityCredits.topUpExternalIdentityFromCore(...);
      • IdentityCredits.resumeTopUpToRecordedRecipient(lock).
    • TrackedAssetLock gets identityRecipient and shieldedRecipient.
    • Persistence:
      • a Room migration adding identityRecipientId and shieldedRecipientRaw43 to AssetLockEntity;
      • NativePersistenceBridge persist/load callbacks for both slot pairs;
      • declarations for capability bits 14 and 16.
      • This also fixes the existing gap where the Kotlin SDK loses the shielded recipient on restart.
    • Map the new error code in DashSdkError.
    • Update the parity manifest and regenerate PARITY_SUMMARY.md.
    • Tests: unit tests and an FfiSmokeTest case.
    • Example app: IdentityAssetLockRecovery and ResumableTopUps resume to the recorded recipient
      and show unassigned locks.

    PR C: Swift SDK (iOS developer's part, likely romchornyi)

    Smaller than Kotlin, because Swift already saves the shielded recipient.

    1. Wrappers in ManagedPlatformWallet.swift:
      • topUpExternalIdentityWithFunding(identityId:…), alongside topUpIdentityWithFunding
        (:5552);
      • a resume that takes no identity and pays the recorded recipient.
      • resumeTopUpWithAssetLock (:5632) stays for bound locks and now gets 61 when the lock was
        recorded for a different identity.
    2. Lock model: ManagedAssetLockManager.swift reads has_identity_recipient /
      identity_recipient_32, as it does shieldedRecipientRaw43 (:85, :138).
    3. Persistence:
      • PersistentAssetLock gets identityRecipientId: Data?.
      • PlatformWalletPersistenceHandler gets persist/load callbacks with the same "never change a
        recorded recipient" check as persistAssetLockShieldedRecipient (:707-721).
      • Add a capability constant 1 << 16 next to assetLockShieldedRecipients
        (PlatformWalletManager.swift:116), declared by the handler.
    4. Errors: map the new "recipient unknown" code in PlatformWalletResult.swift.
      7, 80, 61 and 20 are already mapped once feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 lands.
    5. Example app:
      • TransitionDetailView.swift:766 resumes to the recorded recipient instead of an identity the
        caller picks.
      • The invitation-reclaim flow (ReclaimInvitationSheet.swift:226) doesn't change.
      • Unassigned locks need somewhere to show up.

    Host wallets (e.g. dashwallet-ios #1406–#1409) need a matching recovery change: resume to the
    recorded recipient and skip unassigned locks.

    Order

    1. feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 merges (or PR A stacks on it).
    2. PR A: Rust core, storage and FFI.
    3. PR B (Kotlin SDK) and PR C (Swift SDK), in parallel on top of PR A.

    Open decisions

    1. Unbound locks with no recorded recipient: treat them as unassigned (recommended), or keep
      the issue's "locks without a record behave as today"?
  2. romchornyi commented on Nov 14, 2026

    @romchornyi
    ContributorAuthor

    Review of the plan: architecture, completeness, security

    🟡 4 high · 8 medium · no blockers to the direction. Reviewed against a7669077c5 (the commit the plan cites) and the #5860 head 2ce86e8430.

    Level Verdict
    Architecture 🟡 partly in the wrong layer The Rust-owned recipient on the lock row is the right core. Recovery eligibility, managed-vs-external routing and the "never change the recipient" check leak into SDKs and hosts.
    Completeness 🟡 untracked gaps Assign and the unassigned list have no FFI. The Kotlin list row has no recipient. Legacy unbound top-ups and sweep/reinstate are not covered. About 16 branches have no planned test.
    Security 🟡 4 high No path pays an identity other than the recorded one unless the caller picks it. The high risks are the completion rule, the role check on the external entry, the lifecycle gate scope and a missing amount floor.

    Code claims marked ✔ were checked against the code by a separate verifier. Claims marked (not verified) were not.

    High

    1. The completion rule "proved balance higher than before" can strand funds or cause a second payment. (Plan A2, A3)

    2. The external entry can pay a bound lock, or an invitation voucher, to a stranger. (Plan A2, A3)

      • ✔ validate_existing_asset_lock_role compares only funding type and index. With expected IdentityTopUp, it accepts a bound top-up lock of the same index (orchestration.rs#L704-L734).
      • ✔ Invitation reclaim accepts IdentityTopUp and bypasses the validator (#L641-L697).
      • The planned signature takes a full AssetLockFunding, including FromExistingAssetLock. Bound locks carry no recipient, so neither 61 nor the "unassigned" rule catches them. It is also a second door for unassigned locks.
      • Suggestion:
        • The external op accepts only FromWalletBalance and validates with expected IdentityTopUpNotBound (exact type match).
        • It rejects consume_invitation_voucher.
        • Resumes go only through the identity-less resume, which refuses any other funding type.
        • Read the recipient in the same snapshot as tracked_resume_metadata, not in a separate read as the shielded path does, to avoid a race with assign.
    3. Gating "as feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 does" would block wallet removal for the whole Core flow. (Plan A2 and its test "a removal waits for a running top-up")

    4. No minimum-amount floor on the new path. (Plan A2, A5)

      • ✔ The floor exists only in the managed FFI export (identity_top_up.rs#L163, MIN_TOP_UP_DUFFS = 50_500, "accepted by Core … rejected by Platform, stranding the funds"). The Rust op has none.
      • An unbound lock can only be spent by a top-up, and the plan makes its recipient immutable. A sub-floor lock is therefore stuck forever.
      • Suggestion: enforce the floor in the Rust op, before lookup and build, for both exact and drain amounts. Derive it from the platform version's minimum rather than a constant. Add a test.

    Medium

    1. Assign / unassigned is under-specified and has no FFI. (Plan A4, A5)

      • Step 5 lists two exports (top-up, resume) while "PR A owns every FFI export". Hosts can neither list nor assign, so "funds remain recoverable" is not implemented. Issue point 6 needs at least four exports.
      • Preconditions to state:
        • only IdentityTopUpNotBound, no recipient, not Consumed, never an invitation lock;
        • Platform lookup first (7/80);
        • compare-and-set under the manager write lock;
        • store + flush before returning OK;
        • a second, different assign is refused;
        • automatic recovery never calls assign.
      • Store provenance (recorded at build vs assigned later) so that a 24 after assign is never read as "paid X".
      • Restore from seed brings every completed external top-up back as unassigned, and there is no Platform query for outpoint consumption. The user has to pick a recipient just to learn the lock is spent. Consider a terminal "already used" state after a 24 for reconstructed locks.
    2. Sweep, then reinstate, can drop the recipient.

      • ✔ remove_tracked_asset_locks_for_swept removes the entries and the stores delete non-consumed rows. Reconstruction re-inserts the lock with no recovery metadata (reconstruction.rs#L392-L427, #L229-L246).
      • If both land in one changeset, the merge keeps the stored row, and only memory loses the recipient until restart. If they land separately, the store loses it too, and a confirmed external top-up becomes unassigned.
      • Suggestion: keep recipients in a record a removal doesn't delete (or a tombstone keyed by outpoint), and re-attach it on reconstruction and load. Add a test.
    3. Exports that bypass the recipient check, and other producers of recipient-less unbound locks.

      • ✔ asset_lock_manager_resume returns the proof and credit-key path with no role or recipient check. It refuses only Consumed, drain-without-persistence and over-cap rows (sync.rs#L213-L259).
      • ✔ asset_lock_manager_create_funded_proof accepts funding type 2 (build.rs#L122-L160). So does asset_lock_manager_recover with a host-supplied type-2 row (not verified).
      • Suggestion:
        • Say whether these count as "the generic path".
        • Refuse type 2 without a recipient, or accept it explicitly as unassigned.
        • Make asset_lock_manager_resume refuse recipient-carrying locks, or return the recipient and document that callers must honour it.
        • State that the recorded recipient is wallet policy, not a cryptographic binding: whoever holds the key can sign the lock to any identity.
    4. Recovery eligibility is planned in a function that is not Rust.

      • ✔ tracked_identity_recovery_asset_locks does not exist in Rust. It is Kotlin's trackedIdentityRecoveryAssetLocks (PlatformWalletManager.kt#L822).
      • The Swift and Kotlin example apps filter on fundingType 0...2 themselves. Under the plan, the "unassigned" rule would be re-derived in Rust, the Kotlin SDK, both example apps and both host wallets.
      • Suggestion: Rust computes one recovery class per lock (resumable-bound / resumable-to-recorded-recipient / unassigned / not-generic) and exposes it on the list rows. Everyone else filters on that field.
    5. The Kotlin list row has no recipient, so PR B has no source for it.

      • ✔ Kotlin lists through platform_wallet_tracked_asset_locks_list → TrackedAssetLockSnapshot, which carries no recipient, not even the shielded one (manager_diagnostics.rs#L258-L297). A5 extends only TrackedAssetLockFFI, which Swift reads.
      • Suggestion: PR A extends both rows, or moves Kotlin onto the asset-lock-manager list.
      • The JNI persistence trampolines in rs-unified-sdk-jni are Rust work that the PR A / PR B split doesn't assign (not verified that the shielded slot is absent there).
    6. Kotlin @Upsert would wipe the new column. (PR B)

      • ✔ onPersistAssetLockUpsert builds a fresh AssetLockEntity on every status upsert, keeping only createdAt (PlatformWalletPersistenceHandler.kt#L2395-L2441). Swift carries the value forward and refuses a change (PlatformWalletPersistenceHandler.swift#L707-L724).
      • Suggestion:
        • PR B preserves both recipient columns on base upserts and refuses a different value.
        • Declare bits 14 and 16 only after round-trip tests pass.
        • Call out that declaring bit 14 on Android also turns on durable-before-broadcast and 61 for shielded resumes, a behaviour change for the host.
    7. Routing managed vs external.

      • ✔ The identity manager also holds OutOfWallet identities with no index, and the managed top-up then fails with IdentityIndexNotSet (lifecycle.rs#L154-L200, registration.rs#L401-L407).
        • Route to managed only for IdentityLocation::InWallet.
      • Bound (type 1) locks carry no recipient, so the identity-less resume is not total and hosts keep a classifier.
        • Resolve type 1 through identity_index in the same entry, or record the recipient on managed top-ups too.
      • Decide in Rust what the external op does with an ID this wallet manages: refuse with a typed error, or delegate. Add a test.
    8. Capability bit 16 is already claimed, and the gate is an attestation.

    Low

    • Error 80 after build: 80 promises nothing was signed or broadcast. A failed baseline re-read after the lock is built must not map to 80, since the host would rebuild. Keep 7/80 strictly before the build.
    • Code 7 on legacy resume: the legacy resume called with an external recorded identity returns 7 from the manager lookup, which feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 defines as "nothing signed or broadcast". That is false on a resume.
    • Naming: ✔ 20 is ErrorTransactionBroadcastUnconfirmed, not StateTransitionResultUnconfirmed.
    • Privacy: ✔ AssetLockRecipientMismatch prints both recipients in full and is typed for 43-byte shielded recipients (error.rs#L662-L676). Add an identity variant that prints no IDs, and keep recipients out of above-debug logs.
    • Address pool: the unbound account's gap limit is 5 (DEFAULT_SPECIAL_GAP_LIMIT). An index is not handed back after a rejected broadcast or a failed recipient store (not verified), so 5 unlanded attempts could exhaust the pool.
    • Downgrade: an older SDK ignores the new column and treats NotBound locks as "any target" again.
    • FFI layout: append the new lock-struct fields and persistence slots at the end, gated by struct_size. Give the serde field default, as shielded_recipient has.

    Completeness

    What the plan gets right

    • The recipient is recorded on the lock row and made durable before broadcast, reusing the shielded store-and-flush branch.
    • Recipient-less unbound locks are unassigned, so the plan fails closed. This is safer than the issue's "today's behaviour", which conflicts with the issue's point 4.
    • 61 applies on the managed route too, so a host recovery that passes the holder's identity can't redirect the payment.
    • The Platform lookup (7/80) runs before anything is built, and the external top-up is refused without the persistence capability.
    • Nothing is written to the identity manager, PR A owns all FFI symbols, and the plan follows feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860's rule against block_on_worker inside with_item.
    • It fixes Kotlin's existing loss of the shielded recipient.

    Open questions

    1. Should there be an explicitly authorized "reclaim into my own identity" for a recorded lock, like consume_invitation_voucher? Without it, a sub-floor amount, an unpayable recorded ID, or a payment the user no longer wants is permanent.
    2. Is unattended launch-time resume acceptable for a third-party recipient, or must the user confirm it (with an age limit)?
    3. Same seed on two devices: device B sees device A's in-flight lock as unassigned. May assigning on B race A?
    4. Should bound top-ups record their recipient too, so that 61 and the identity-less resume are uniform?
    Review details
    • Architecture and completeness: a layered review (architecture, then completeness judged in the owning layer).
    • Security: two independent reviews on different models, given the same brief and no conclusions.
    • Verifier: a third, clean-context pass checked 13 code claims. 9 were confirmed and 4 confirmed in part; the wording above reflects its corrections, and none were refuted.
    • Read-only against a7669077c5 and the feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 head 2ce86e8430; no code was changed.

    🤖 Reviewed with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions