Skip to content

feat(platform-wallet): top up someone else's identity from the Core balance - #5931

Draft
HashEngineering wants to merge 10 commits into
v5.2-devfrom
HashEngineering/platform-wallet-top-up-someone-elses-identity-fr
Draft

HashEngineering wants to merge 10 commits into
v5.2-devfrom
HashEngineering/platform-wallet-top-up-someone-elses-identity-fr

Conversation

@HashEngineering

@HashEngineering HashEngineering commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Basic explanation

What this does: A wallet can now pay Dash from its Core balance into an identity it does not own (someone else's identity). It builds an asset lock (a Core transaction that turns Dash into Platform credits) from the wallet's shared "unbound" top-up account, and saves on the lock's row which identity it is meant for before the lock is sent. If the app is killed mid-way, the top-up resumes to that saved identity, and to no other.

Value: Wallets can enable Core → any identity ID in their send flows (dash-wallet#1680, dashwallet-ios#1406–#1409). Today that pair is disabled, so Core-only users must first move funds to Shielded or Platform to pay an identity. It also closes a gap where a resume of an unbound top-up lock accepted any identity, so a host's recovery could pay an interrupted top-up of someone else's identity into the holder's own.

Risks: Low to medium. No consensus change: the IdentityTopUp transition is unchanged. Top-ups of the wallet's own identities (bound locks) behave as before. Unbound top-up locks are stricter now (see Breaking Changes): one with no recorded identity, such as one rebuilt from the seed, is no longer resumed into any identity until the user assigns one. No test shows a confirmed external top-up end to end; the mock SDK cannot produce one for this transition, so that needs a testnet send.

Issue being fixed or feature implemented

Fixes #5924.

IdentityWallet::top_up_identity_with_funding only tops up identities in the wallet's IdentityManager, and a tracked asset lock recorded no recipient for an identity top-up. On resume, an unbound top-up lock (IdentityTopUpNotBound) was "deliberately eligible for any target", so the identity came from the caller. A host recovery passes its own identity, so both wallets kept Core → someone else's identity disabled.

What was done?

Recipient recorded on the lock (rs-platform-wallet)

  • TrackedAssetLock / AssetLockEntry gain identity_recipient: Option<Identifier>, kept immutable through AssetLockChangeSet::merge and apply.rs, like shielded_recipient.
  • The build path takes AssetLockRecipient (Shielded(raw) or Identity(id)) instead of shielded_recipient; recorded_recipients decides what a lock records. An unbound top-up lock must name its identity, and is built only for a persister declaring the new PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS (bit 17; bit 16 is reserved for OUTPOINT_LOCKS from feat(platform-wallet): keep masternode collateral out of coin selection #5890). Its row is flushed before the broadcast, and removed durably if the broadcast is rejected, so a lost removal cannot bring back a lock resumable to that recipient after the user re-sent. If the row's store or flush fails, its removal is stored behind it; if that removal is refused too, the inputs stay reserved, because the row may survive (a host without atomic changesets can write it and fail on the recipient). The build-only API (build_asset_lock_transaction) refuses unbound top-up locks, since it tracks nothing.
  • Wallet removal and re-creation (shared build path, all funding types):
    • AssetLockManager keeps the generation of the wallet it was registered with. A build through a handle whose wallet was since replaced is refused (WalletRemovedBeforeSend) before anything is selected, reserved or signed, and a lock is tracked only on the generation that built it.
    • The broadcast runs under the generation's lifecycle gate, after checking that generation is still the wallet's. A wallet replaced while the build awaited sends nothing: the unsent row is removed durably and its inputs released (WalletRemovedBeforeSend). If a resume has claimed the row's dispatch, or the wallet now under the id tracks the row, the row and inputs stay and the outcome is TransactionBroadcastUnconfirmed.
  • Every abandoned-lock removal (rejected broadcast, wallet replaced before send, recipient row not made durable) is stored and flushed through one helper; a failed flush is tolerated only on a backend that commits inline. Inputs are released only once the removal is durable, otherwise they stay reserved.
  • validate_existing_asset_lock_role: an unbound lock serves a top-up only of the identity it recorded. Another identity is AssetLockIdentityRecipientMismatch; no recorded identity is AssetLockRecipientUnknown.
  • IdentityWallet::assign_identity_top_up_recipient records an identity the user picks for an unassigned lock (TrackedAssetLock::is_unassigned_identity_top_up).
    • It first checks that Platform knows the identity, because an assignment is permanent. An unknown identity is IdentityNotFound and nothing is assigned.
    • It holds the handle's generation gate and refuses a wallet since replaced (WalletRemovedBeforeSend).
    • The identity is recorded in memory, then stored and flushed. If the store fails, the error is returned and the assignment holds for the session, so another identity is refused (61) rather than silently dropped when the queued row flushes later. Assigning the same identity again retries the store.
    • The asset-lock manager's own method is crate-private, so no caller skips the lookup.

External top-up and resume (wallet/identity/network/registration.rs)

  • top_up_external_identity_with_funding: fetches the identity from Platform (unknown → IdentityNotFound, nothing built), funds an unbound lock recording it, submits with the managed top-up's IS→CL fallbacks, consumes the lock. Writes nothing to the identity manager.
  • resume_identity_top_up_to_recorded_recipient: takes no identity and resumes any identity top-up lock, so hosts need no classifier. A bound lock pays the wallet's identity at its index (AssetLockIdentityNotLoaded, FFI 7, if that identity is not loaded yet); an unbound lock pays the identity it recorded. An identity the wallet holds goes through the managed path, any other through the external path.
  • An external top-up of an identity the wallet happens to hold updates its local balance, through a helper shared with the managed route, and returns the proved post-transition balance.
  • The managed and external top-ups share submit_top_up_with_funding (funding, submit, reconcile, lock cleanup). The external top-up and the assignment share one Platform lookup.
  • The top-up minimum moves from the FFI into the wallet as min_top_up_duffs(): the largest IdentityTopUpTransition::calculate_min_required_fee across every supported protocol version (50,500 duffs today), instead of a literal. It does not depend on the SDK's current version, which can change during the identity fetch. It applies to both Core top-ups. A smaller amount is refused. A drain gets the minimum as its floor, which the builder enforces before anything is tracked or broadcast.
  • Resuming a consumed unbound lock reports AssetLockAlreadyConsumed (24) before a missing recipient, as the unassigned listing and the assignment do.

FFI (rs-platform-wallet-ffi)

  • New exports: platform_wallet_top_up_external_identity_with_funding_signer, platform_wallet_resume_identity_top_up_to_recorded_recipient_signer, platform_wallet_assign_identity_top_up_recipient (returns 7 for an identity Platform doesn't know). All three read the wallet out of the registry and release it before awaiting, and convert a panic to a result code instead of unwinding through the C ABI (20 for the two paying exports, 6 for the assignment).
  • Persistence: on_persist_asset_lock_identity_recipient_fn / on_load_asset_lock_identity_recipient_fn appended to PersistenceCallbacksExtension; PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS (bit 17) attested when both slots, the asset-lock persist callback and the wallet-list restore pair are wired.
  • TrackedAssetLockFFI and TrackedAssetLockEntryFFI gain has_identity_recipient, the 32-byte recipient and identity_recipient_unassigned.
  • Error codes: new ErrorAssetLockRecipientUnknown = 81; ErrorAssetLockRecipientMismatch (61) now also covers identity recipients. ERROR_CODE_REGISTRY.md updated (77–79 feat(platform-wallet): plan a shielded spend with its exact fee and spend against the plan #5865, 80 feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860, 81 here).

SQLite storage (rs-platform-wallet-storage)

  • V021__asset_lock_identity_recipient.rs: nullable 32-byte asset_locks.identity_recipient column plus an immutability trigger; SqlitePersister declares bit 17; SCHEMA.md and the migration fingerprints updated.

How Has This Been Tested?

cargo test -p platform-wallet --lib --all-features (2056 passed), cargo test -p platform-wallet-ffi --lib --all-features (582 passed, 1 ignored), cargo test -p platform-wallet-storage --all-features (unchanged since the earlier run), and cargo clippy -p platform-wallet -p platform-wallet-ffi -p platform-wallet-storage -p rs-unified-sdk-jni --all-features --all-targets -- -D warnings (clean). New tests:

  • asset_lock/build.rs: a build through a handle of a replaced wallet is refused with nothing reserved; a lock built on a wallet replaced before the send is removed durably with its inputs released, kept when a resume or the replacement may still send it, and kept fenced when the removal is not durable; an abandoned row's removal that cannot be flushed keeps the inputs reserved, and one removed inline survives a failed flush notification; an assignment on a replaced wallet is refused; an unbound lock is refused without a recipient, with a non-identity recipient, or on a persister without bit 17, with nothing stored or broadcast; the recipient is flushed before the broadcast and a failed flush stops it; a rejected lock's removal is flushed, and a failed one is reported; the build-only API refuses unbound locks; assigning a recipient once and refusals; a failed assignment store keeps the identity, refuses another and is retried by assigning it again.
  • asset_lock/orchestration.rs: the validator and the funding resolver refuse another identity (61) and an unrecorded lock (81).
  • identity/network/registration.rs: both Core top-ups refuse an amount below the minimum, and a drain gets the minimum as its floor; an assignment to an identity Platform doesn't know is refused and the lock stays unassigned; the external top-up refuses an unknown identity and a persister that cannot record, building nothing; the resume refuses untracked, registration and unassigned locks, resolves a bound lock to the wallet's identity at its index (or refuses it when none is loaded), and sends a foreign recorded identity down the external path; a top-up balance lands on an identity the wallet holds.
  • changeset.rs, apply.rs: the recipient survives stale snapshots and a conflicting one is dropped.
  • rs-platform-wallet-ffi: panic-to-code mapping for the new exports; persistence round trip and capability attestation, error mapping (61, 81), null-pointer and handle guards on the new exports, extension layout pins.
  • sqlite_asset_locks_filter.rs: column round trip, immutability, fail-closed load of a malformed recipient, capability advertised.

The plan review on #5924 was checked against this PR; six of its gaps are fixed here (capability bit, durable removal of a rejected recipient lock, bound locks in the identity-less resume, build-only refusal, balance of a held identity, docs) and the rest are handled or listed under Known limitations. Local pre-reviews with the review bot's prompts: every finding is fixed except one, which the last round (on 93c61ac126, before the dispatch-claim fix in 4cb8c71387) still lists: an unbound lock with no recorded identity gets 81 on mobile until PR B/C bind the assignment and persistence. That is deliberate; see "Release order" under Breaking Changes.

The review bot's round on 3b30b1e4b0 is addressed in 282c6df764: fixed the broadcast after wallet removal (in the shared build path), the inputs released after a refused row store, the protocol-versioned minimum, the consumed-lock error order and the assignment doc. Declined, with replies on the threads: the tracked-lock array layout (same decision as #5762; the bot withdrew it) and the cached balance a top-up returns. The bot's round on 282c6df764 is addressed in 6c3548a227, 93c61ac126 and 4cb8c71387: the unsent lock of a replaced wallet is removed (or kept when it may still be sent), the assignment is generation-gated, the minimum no longer depends on the SDK's current version, the external top-up returns the proved balance (conceding that thread), and the new exports catch panics.

Not covered: a confirmed external top-up end to end (mock SDK limitation, as in #5860); to be checked with a testnet send. Locally, four sqlite_identity_key_restore tests fail only because /tmp is group-writable here (InsecureParentDir); they do not touch this change.

Breaking Changes

No consensus change, so no !. Wallet/FFI behaviour that changes for hosts:

  • Building an unbound top-up lock (funding type 2) without a recipient is refused (InvalidParameter), including through asset_lock_manager_create_funded_proof. A host using that builder for type 2 gets the error before anything is broadcast.
  • Resuming an unbound top-up lock into an identity other than the recorded one now returns 61, on the managed route too (platform_wallet_topup_identity_with_existing_asset_lock_signer); a lock with no recorded identity returns the new code 81 until a recipient is assigned. Before, any identity was accepted.
    • Release order: this PR must ship in the same SDK release as PR B (Kotlin) and PR C (Swift).
      • Why: an unbound lock's credit output names no identity on chain, so a lock rebuilt from the seed, or one built before this PR, has no recorded recipient.
      • What happens: this PR refuses such a lock with 81 rather than guess an identity. Guessing was the platform-wallet: top up someone else's identity from Core, with the recipient recorded on the asset lock before broadcast #5924 bug, where recovery paid the holder's own identity.
      • The gap: the user unblocks the lock with platform_wallet_assign_identity_top_up_recipient, which the mobile SDKs don't bind until PR B/C. On this Rust alone, a mobile app can't move such a lock past 81.
      • No funds are lost: the lock key stays in the wallet.
      • Few users are affected: today's apps build no unbound locks, and they can't build new ones until they declare bit 17.
  • TrackedAssetLockFFI, TrackedAssetLockEntryFFI and PersistenceCallbacksExtension gain appended fields; hosts rebuild against the new header. Older hosts' smaller struct_size keeps the extension slots absent.
  • New FFI code 81 ErrorAssetLockRecipientUnknown; Swift and Kotlin map it in their follow-up PRs, and until then report it as unknown / generic.
  • Other behaviour changes (not breaking):
    • An asset-lock build whose wallet was removed or re-created before the broadcast now returns WalletRemovedBeforeSend instead of sending the transaction.
    • IdentityWallet::top_up_identity_with_funding now refuses a new lock below the protocol's top-up minimum with InvalidParameter, and holds a drained top-up (DrainAccountBalance) to that floor. Before, only the FFI checked, and only an exact amount, so a Rust caller or a drain could broadcast a lock Platform then rejects, stranding the funds.
    • platform_wallet_top_up_identity_with_funding_signer checks the amount after the wallet lookup: an invalid handle with a too-small amount now returns NotFound instead of ErrorInvalidParameter. With a valid handle the result is unchanged.
  • Internal Rust API: resolve_funding_with_is_timeout_fallback and the create_*_asset_lock_proof* helpers take Option<AssetLockRecipient> instead of Option<ShieldedRecipientRaw>; preserve_recovery_metadata takes the recorded identity; tracked_resume_metadata returns TrackedResumeMetadata.

Known limitations

  • Sweep, then reinstate: when a lock's funding transaction is swept, its row is deleted. If the transaction comes back, the rebuilt lock has no recorded recipient, so an unbound lock becomes unassigned (81), not mis-paid. The shielded recipient already has the same gap. Bound top-ups to the wallet's own identities are unaffected: their identity index comes back from the derivation path. Keeping recipients across row deletion is a follow-up.
  • Old dashj/DashSync top-ups: they were derived on the unbound path (Option to fund identity top-ups from the unbound (legacy-compatible) top-up account #4253), so on a migrated seed every past top-up is rebuilt as an unassigned unbound lock, almost all of them long consumed. Before this PR they were offered for resume into any identity and returned 24; now they are listed as unassigned. Hosts should list rebuilt unassigned locks separately.
  • Wallet removal during a resume: a new build checks the wallet's generation, but a resume's re-broadcast of an already built lock (sync/recovery.rs) does not yet, although the asset-lock manager now holds its generation. It sends the same transaction again, never a new one. Gating it is a follow-up (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).

Follow-ups

  • When feat(platform-wallet)!: top up an identity the wallet does not manage from Platform addresses #5860 merges: report a failed identity lookup (fetch_identity_to_pay, used by the external top-up and the assignment) as IdentityLookupFailed (FFI 80) instead of the plain SDK error (marked TODO(dashpay/platform#5860)), and update both exports' docs.
  • Kotlin SDK (PR B): one Room migration adding the identity recipient, the shielded recipient and the operation id, which Kotlin does not store yet; declare bits 13, 14 and 17; bind the three new exports; map code 81.
  • Swift SDK (PR C): the same for SwiftData, including the three Swift error-code edits for 81.

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

HashEngineering and others added 4 commits November 13, 2026 16:14
An unbound identity top-up lock (`IdentityTopUpNotBound`) names no identity
on chain, and a resume accepted any identity the caller passed, so a host
recovery passing its own identity would pay an interrupted top-up of someone
else's identity into the holder's. First part of #5924.

- `TrackedAssetLock`/`AssetLockEntry` carry `identity_recipient`, recorded
  with the row and flushed before the lock is broadcast, immutable once set
  (merge, apply, SQLite V021 column and trigger).
- The build path takes `AssetLockRecipient` (shielded address or identity).
  An unbound top-up lock must name its identity and is built only for a
  backend declaring `ASSET_LOCK_IDENTITY_RECIPIENTS` (bit 16).
- A resume of an unbound lock pays only the recorded identity: another is
  `AssetLockIdentityRecipientMismatch` (FFI 61), none recorded is
  `AssetLockRecipientUnknown` (new FFI 81).
- `assign_identity_top_up_recipient` / FFI
  `platform_wallet_assign_identity_top_up_recipient` records a recipient the
  user chooses for an unassigned lock (one rebuilt from the chain).
- FFI: identity-recipient persistence slots appended to the extension
  struct; both tracked-lock lists expose the recipient and an unassigned flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…alance

Second part of #5924: a wallet can now pay an identity it
does not manage from its Core balance, and resume an interrupted one to the
identity its lock recorded.

- `IdentityWallet::top_up_external_identity_with_funding` fetches the
  identity from Platform (an unknown one is refused before anything is
  built), funds the lock from the unbound top-up account with the identity
  recorded on its row before the broadcast, submits with the managed
  top-up's IS→CL fallbacks, and writes nothing to the identity manager.
- `resume_identity_top_up_to_recorded_recipient` takes no identity: it pays
  the one the lock recorded, through the managed path when the wallet
  manages it and the external path otherwise.
- The managed and external top-ups share one funding/submit helper.
- FFI: `platform_wallet_top_up_external_identity_with_funding_signer` and
  `platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`,
  both releasing the wallet registry before awaiting.

A failed identity lookup surfaces as the SDK error until #5860 adds
`IdentityLookupFailed` (FFI 80); a TODO marks the switch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cleanups from review of the #5924 change, no change to what is paid:

- `submit_top_up_with_funding` consumes the tracked lock itself, so both
  top-ups drop their copy of that cleanup.
- The top-up minimum (`MIN_TOP_UP_DUFFS`) moves from the FFI into
  rs-platform-wallet and applies to both Core top-ups, so Rust callers can
  no longer build a lock below it; the FFI copies are removed.
- `tracked_resume_metadata` returns `TrackedResumeMetadata` instead of a
  tuple; one `not_an_unbound_top_up` builds the funding-mismatch error.
- FFI: the new exports use `OutPoint::from(&OutPointFFI)`; the shielded and
  identity recipient loaders share `load_asset_lock_recipient_sidecar`.
- Storage decodes `identity_recipient` with `id32`.
- Tests share one mock-SDK helper and one test module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…oor drained top-ups

- Record an assigned identity recipient in memory before storing it, so a
  failed flush that leaves the row queued cannot be overridden by a later
  assignment of another identity; assigning the same identity again retries
  the store.
- Look the identity up on Platform before assigning it (an assignment is
  permanent); the FFI export goes through IdentityWallet, and the manager's
  method is now crate-private. The lookup is shared with the external top-up.
- Hold drained top-up fundings to MIN_TOP_UP_DUFFS as their floor, which the
  builder enforces before anything is tracked or broadcast.

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

coderabbitai Bot commented Nov 14, 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

@github-actions github-actions Bot added this to the v5.2.0 milestone Nov 14, 2026
@thepastaclaw

thepastaclaw commented Nov 14, 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 4cb8c71. Normal review starts when eligible; priority review starts as soon as a slot is available.

@HashEngineering HashEngineering self-assigned this Nov 14, 2026
HashEngineering and others added 2 commits November 13, 2026 20:59
…p to any identity

- Move ASSET_LOCK_IDENTITY_RECIPIENTS to capability bit 17 and reserve bit 16,
  which #5890 claims for OUTPOINT_LOCKS.
- Remove a rejected lock's row durably when it records a recipient, as drains
  already do, so a lost removal cannot bring back a Built row resumable to
  that recipient while its inputs fund the next attempt.
- The resume that takes no identity also resumes bound top-up locks, paying
  the wallet's identity at the lock's index (AssetLockIdentityNotLoaded, FFI 7,
  when that identity is not loaded yet), so hosts need no classifier.
- Refuse unbound top-up locks in the build-only API, which tracks nothing and
  so cannot record a recipient.
- An external top-up of an identity the wallet holds updates its local
  balance, through a helper shared with the managed route.
- Document that the generic resume's recorded recipient is wallet policy, that
  a failed external top-up is resumed rather than rebuilt, and what the legacy
  resume returns for identities outside the wallet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… may survive

A lock row stored but not flushed before the broadcast has its removal stored
behind it before the inputs are released, as before. If the store refuses that
removal, the row may survive a restart and be re-broadcast after the user's
retry, paying its recipient twice, so the reservation and the in-broadcast
fence now stay held and the error says the inputs stay reserved. A row the
store refused outright needs no removal, and its inputs are still released.

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

@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

The PR contains three blocking issues: wallet-generation teardown is not excluded during the new top-up flows, tracked-lock FFI array element strides change incompatibly, and a failed non-atomic persistence store can still leave a recipient row behind before inputs are released. The remaining findings are non-blocking correctness and documentation issues involving versioned fee floors, consumed-lock error precedence, stale balance reporting, and the assignment API contract.

🔴 3 blocking | 🟡 4 suggestion(s)

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large, intricate change to wallet asset-lock orchestration and persistence that directly affects funds movement and includes a storage migration.
  • 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 quota lookup failed), 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.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); 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/registration.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:469-481: Top-up operations can broadcast after wallet-generation removal
  The new external top-up calls `submit_top_up_with_funding` without acquiring this wallet generation's payment guard or checking that the generation is still current. The FFI path clones the `IdentityWallet` and releases the registry read lock before awaiting, so wallet removal can complete while the build or broadcast is in flight. The stale operation can then broadcast its already-signed asset-lock transaction after reservations from the removed generation were discarded; re-registering the same wallet ID can also cause subsequent state mutations to target replacement state. The same generation protection is needed on the new recorded-recipient resume and assignment paths, and it belongs in the Rust wallet layer rather than by retaining the FFI registry lock.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:768-806: Top-up minimum does not follow the active protocol version
  `MIN_TOP_UP_DUFFS` hard-codes the v1 minimum of 50,500 duffs, while `IdentityTopUpTransition::calculate_min_required_fee` is version-dispatched. Protocol versions selecting fee v0 require only 50,000 duffs, so an SDK configured for an older supported `PlatformVersion` rejects a funding amount that Platform accepts. Conversely, a future fee-table change could make this client-side floor stale. Derive the minimum from the SDK's effective `PlatformVersion` and the DPP fee calculation instead of maintaining a second literal in the wallet crate.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:583-603: Consumed unassigned locks report the wrong recovery error
  `resume_identity_top_up_to_recorded_recipient` checks `identity_recipient` before checking the tracked lock status. A consumed unbound lock with no recorded recipient therefore returns `AssetLockRecipientUnknown`, even though `is_unassigned_identity_top_up` excludes consumed locks and `check_identity_recipient_assignable` returns `AssetLockAlreadyConsumed`. Recovery and listing consequently disagree about the state of the same lock, and the caller is directed toward assignment even though assignment is rejected. Check the consumed status first so terminal locks consistently report `AssetLockAlreadyConsumed`.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:636-647: Top-up result can report a stale cached balance
  `record_top_up_balance` returns the value returned by `persist_confirmed_balance`, which is the managed identity's cached balance. If the response metadata height ties the existing watermark, `take_fetched_balance` treats the proved snapshot as a duplicate and leaves the cache unchanged. The top-up can therefore succeed with Platform returning a new balance while the FFI output reports the old balance. Persistence should remain best-effort, but the caller's result must always be the proved `new_balance`; the watermark should only control what is cached.

In `packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/asset_lock/manager.rs:41-53: Tracked-lock array element strides changed without ABI negotiation
  `TrackedAssetLockFFI` is returned as a contiguous bare-pointer array by `asset_lock_manager_list_tracked_locks`, and `TrackedAssetLockEntryFFI` is returned the same way by `platform_wallet_tracked_asset_locks_list`. Appending the identity-recipient fields changes `sizeof` and therefore the element stride. A host compiled against the previous header will index the second and later elements using the old stride, reading fields from the middle of the newer elements and potentially displaying or resuming the wrong lock. The paired free functions receive only the pointer and count, so they cannot recover the stride. The size-gated persistence extension does not protect these arrays. Preserve the existing V1 element types and add V2 list functions, or add explicit element-size/ABI negotiation.

In `packages/rs-platform-wallet/src/wallet/asset_lock/build.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1550-1555: A failed recipient-row store can still leave a resumable row
  The `Err(false, error)` branch assumes that a failed `persister.store` means the asset-lock row was not written, then releases the input reservation after the follow-up removal succeeds. The FFI persistence contract does not provide that guarantee unless the host declares atomic changesets: a non-atomic host can write the base asset-lock row and fail while writing the recipient sidecar, and an atomic host can also leave the outcome unknown if rollback fails. The identity-recipient capability only proves that the callbacks exist; it does not prove atomicity. If the row survives while the reservation is released, a retry can spend the inputs again and later recovery can resume the surviving row, paying the recipient twice. Treat an error from the initial store as an unknown/potentially stored outcome and retain the reservation unless durable removal is confirmed.

In `packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs:434-454: Assignment documentation selects an incompatible resume export
  The assignment API accepts any identity known to Platform, including an identity not managed by this wallet. Its documentation directs hosts to `platform_wallet_topup_identity_with_existing_asset_lock_signer`, whose implementation requires the identity to exist in the local `IdentityManager`; an externally assigned identity therefore fails with `ErrorIdentityNotFound`. The documented recovery entry point must be the recorded-recipient resume export, which dispatches to the managed or external route without requiring the host to classify the identity.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Legacy FFI top-up exports hold the registry read lock across network waits — The managed top-up export, and the analogous registration export, still execute block_on_worker inside PLATFORM_WALLET_STORAGE.with_item, holding the global registry read guard across signer, persistence, retry, and network waits. The new exports correctly clone the wallet data and release the registry guard first. This is a real teardown and contention issue, but the locking shape predates this PR and the diff does not introduce it; it should be corrected in a follow-up rather than blocking this feature.
    • Follow-up: A follow-up FFI cleanup should clone the identity wallet, wallet ID, and network from the registry, drop the registry guard, and only then call block_on_worker in the managed top-up and registration exports.

Comment on lines +469 to +481
let funding = apply_top_up_minimum(funding)?;
let identity = self.fetch_identity_to_pay(identity_id).await?;

let (new_balance, metadata) = self
.submit_top_up_with_funding(
&identity,
funding,
AssetLockFundingType::IdentityTopUpNotBound,
0,
asset_lock_signer,
settings,
)
.await?;

@thepastaclaw thepastaclaw Nov 14, 2026 •

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.

✅ Resolved at 282c6df7; see the replies below.

🔴 Blocking: Top-up operations can broadcast after wallet-generation removal

The new external top-up calls submit_top_up_with_funding without acquiring this wallet generation's payment guard or checking that the generation is still current. The FFI path clones the IdentityWallet and releases the registry read lock before awaiting, so wallet removal can complete while the build or broadcast is in flight. The stale operation can then broadcast its already-signed asset-lock transaction after reservations from the removed generation were discarded; re-registering the same wallet ID can also cause subsequent state mutations to target replacement state. The same generation protection is needed on the new recorded-recipient resume and assignment paths, and it belongs in the Rust wallet layer rather than by retaining the FFI registry lock.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

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.

Resolved (re-reviewed at 282c6df7): The shared build path now acquires the build generation's payment guard and checks generation identity immediately before calling the broadcaster, so removal or same-ID recreation returns WalletRemovedBeforeSend without broadcasting. The current cleanup leak after that check is reported separately as a new finding.

Comment on lines +41 to +53
/// Whether `identity_recipient_32` carries the identity an unbound
/// identity top-up (funding type 2) pays. A resume of the lock pays that
/// identity and refuses any other.
pub has_identity_recipient: bool,
/// The identity a resume of this lock pays, valid only when
/// `has_identity_recipient` is true (all zero otherwise).
pub identity_recipient_32: [u8; 32],
/// An unbound identity top-up, not consumed, that records no identity
/// (rebuilt from the chain, for example after a restore from the seed):
/// no resume pays it until the user assigns it a recipient with
/// `platform_wallet_assign_identity_top_up_recipient`. Hosts list it
/// for the user rather than resuming it into one of their identities.
pub identity_recipient_unassigned: bool,

@thepastaclaw thepastaclaw Nov 14, 2026 •

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.

✅ Withdrawn at 282c6df7; see the replies below.

🔴 Blocking: Tracked-lock array element strides changed without ABI negotiation

TrackedAssetLockFFI is returned as a contiguous bare-pointer array by asset_lock_manager_list_tracked_locks, and TrackedAssetLockEntryFFI is returned the same way by platform_wallet_tracked_asset_locks_list. Appending the identity-recipient fields changes sizeof and therefore the element stride. A host compiled against the previous header will index the second and later elements using the old stride, reading fields from the middle of the newer elements and potentially displaying or resuming the wrong lock. The paired free functions receive only the pointer and count, so they cannot recover the stride. The size-gated persistence extension does not protect these arrays. Preserve the existing V1 element types and add V2 list functions, or add explicit element-size/ABI negotiation.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Declining, as on #5762 (#5762 (comment), withdrawn there): TrackedAssetLockFFI and TrackedAssetLockEntryFFI have no layout freeze or size negotiation, they are not part of the published persistence ABI, and their only consumers are the Swift and Kotlin SDKs built from this tree against the generated header. The appended fields are listed under Breaking Changes in the PR description.

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.

Withdrawn (re-reviewed at 282c6df7): The stated release model is sufficient for this diagnostic surface: it is not a frozen published persistence ABI, its supported Swift and Kotlin consumers rebuild against the new header, and the appended fields are explicitly called out as a host-breaking change. The separate persistence row remains size-gated.

Comment on lines +1550 to +1555
let durable = match self.persister.store(PlatformWalletChangeSet {
asset_locks: Some(changeset),
..Default::default()
}) {
Ok(()) => self.persister.flush().map_err(|error| (true, error)),
Err(error) => Err((false, error)),

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 failed recipient-row store can still leave a resumable row

The Err(false, error) branch assumes that a failed persister.store means the asset-lock row was not written, then releases the input reservation after the follow-up removal succeeds. The FFI persistence contract does not provide that guarantee unless the host declares atomic changesets: a non-atomic host can write the base asset-lock row and fail while writing the recipient sidecar, and an atomic host can also leave the outcome unknown if rollback fails. The identity-recipient capability only proves that the callbacks exist; it does not prove atomicity. If the row survives while the reservation is released, a retry can spend the inputs again and later recovery can resume the surviving row, paying the recipient twice. Treat an error from the initial store as an unknown/potentially stored outcome and retain the reservation unless durable removal is confirmed.

Suggested change
let durable = match self.persister.store(PlatformWalletChangeSet {
asset_locks: Some(changeset),
..Default::default()
}) {
Ok(()) => self.persister.flush().map_err(|error| (true, error)),
Err(error) => Err((false, error)),
let durable = match self.persister.store(PlatformWalletChangeSet {
asset_locks: Some(changeset),
..Default::default()
}) {
Ok(()) => self.persister.flush().map_err(|error| (true, error)),
Err(error) => Err((true, error)),
};

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Comment on lines +768 to +806
/// Minimum asset-lock funding for a Core-funded identity top-up, in duffs.
///
/// Platform rejects an `IdentityTopUp` whose asset-lock output value (in
/// credits) is below `IdentityTopUpTransition::calculate_min_required_fee`.
/// Under the active fee version (v1) that minimum is
/// `identity_topup_base_cost` (500_000 credits = 500 duffs) **plus**
/// `required_asset_lock_duff_balance_for_processing_start_for_identity_top_up`
/// (50_000 duffs) — i.e. 50_500 duffs. Below that, a lock built and broadcast
/// is accepted by Core (spending real UTXOs) but rejected by Platform,
/// stranding the funds in a lock that can never complete the top-up.
///
/// (The bare 50_000 asset-lock floor alone was the fee-v0 minimum; the active
/// v1 calc — `STATE_TRANSITION_VERSIONS_V3`, protocol v11+ — adds the base
/// cost, so this constant must include it.)
pub const MIN_TOP_UP_DUFFS: u64 = 50_500;

/// Hold a new top-up lock to [`MIN_TOP_UP_DUFFS`] before anything is looked
/// up, built or broadcast. An amount below it is refused; a drain gets it as
/// its floor, which the builder enforces on the built lock before tracking or
/// broadcasting it. An existing lock's amount is already fixed.
fn apply_top_up_minimum(
funding: AssetLockFunding,
) -> Result<AssetLockFunding, PlatformWalletError> {
let floor = |minimum: Option<u64>| Some(minimum.unwrap_or(0).max(MIN_TOP_UP_DUFFS));
match funding {
AssetLockFunding::FromWalletBalance { amount_duffs, .. }
if amount_duffs < MIN_TOP_UP_DUFFS =>
{
Err(PlatformWalletError::InvalidParameter(format!(
"a top-up of {amount_duffs} duffs is below the minimum top-up asset-lock \
balance of {MIN_TOP_UP_DUFFS} duffs"
)))
}
AssetLockFunding::DrainAccountBalance {
account,
minimum_lock_duffs,
} => Ok(AssetLockFunding::DrainAccountBalance {
account,
minimum_lock_duffs: floor(minimum_lock_duffs),

@thepastaclaw thepastaclaw Nov 14, 2026 •

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.

✅ Resolved at 282c6df7; see the replies below.

🟡 Suggestion: Top-up minimum does not follow the active protocol version

MIN_TOP_UP_DUFFS hard-codes the v1 minimum of 50,500 duffs, while IdentityTopUpTransition::calculate_min_required_fee is version-dispatched. Protocol versions selecting fee v0 require only 50,000 duffs, so an SDK configured for an older supported PlatformVersion rejects a funding amount that Platform accepts. Conversely, a future fee-table change could make this client-side floor stale. Derive the minimum from the SDK's effective PlatformVersion and the DPP fee calculation instead of maintaining a second literal in the wallet crate.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

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.

Resolved (re-reviewed at 282c6df7): The literal minimum was replaced with IdentityTopUpTransition::calculate_min_required_fee through min_top_up_duffs, and the floor is applied to both exact and drain funding. The remaining pre-fetch version race is a separate current-head issue.

Comment on lines +583 to +603
AssetLockFundingType::IdentityTopUpNotBound => {
let identity_id = lock
.identity_recipient
.ok_or(PlatformWalletError::AssetLockRecipientUnknown(out_point))?;
// Only a signing-capable identity of this wallet takes
// the managed route: an observed one has no index.
let managed = identities.is_some_and(|manager| {
manager
.wallet_identity(&self.wallet_id, &identity_id)
.is_some()
});
(identity_id, managed)
}
_ => {
return Err(not_an_unbound_top_up(
out_point,
lock.funding_type,
lock.identity_index,
))
}
}

@thepastaclaw thepastaclaw Nov 14, 2026 •

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.

✅ Resolved at 282c6df7; see the replies below.

🟡 Suggestion: Consumed unassigned locks report the wrong recovery error

resume_identity_top_up_to_recorded_recipient checks identity_recipient before checking the tracked lock status. A consumed unbound lock with no recorded recipient therefore returns AssetLockRecipientUnknown, even though is_unassigned_identity_top_up excludes consumed locks and check_identity_recipient_assignable returns AssetLockAlreadyConsumed. Recovery and listing consequently disagree about the state of the same lock, and the caller is directed toward assignment even though assignment is rejected. Check the consumed status first so terminal locks consistently report AssetLockAlreadyConsumed.

Suggested change
AssetLockFundingType::IdentityTopUpNotBound => {
let identity_id = lock
.identity_recipient
.ok_or(PlatformWalletError::AssetLockRecipientUnknown(out_point))?;
// Only a signing-capable identity of this wallet takes
// the managed route: an observed one has no index.
let managed = identities.is_some_and(|manager| {
manager
.wallet_identity(&self.wallet_id, &identity_id)
.is_some()
});
(identity_id, managed)
}
_ => {
return Err(not_an_unbound_top_up(
out_point,
lock.funding_type,
lock.identity_index,
))
}
}
AssetLockFundingType::IdentityTopUpNotBound => {
if lock.status.is_consumed() {
return Err(PlatformWalletError::AssetLockAlreadyConsumed(out_point));
}
let identity_id = lock
.identity_recipient
.ok_or(PlatformWalletError::AssetLockRecipientUnknown(out_point))?;
let managed = identities.is_some_and(|manager| {
manager.wallet_identity(&self.wallet_id, &identity_id).is_some()
});
(identity_id, managed)
}

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

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.

Resolved (re-reviewed at 282c6df7): The current resume implementation checks lock.status.is_consumed() before reading identity_recipient, so a consumed unassigned lock returns AssetLockAlreadyConsumed before AssetLockRecipientUnknown.

Comment on lines +636 to +647
let mut wm = self.wallet_manager.write().await;
match wm.get_wallet_info_mut(&self.wallet_id) {
Some(info) => info
.identity_manager
.managed_identity_mut(identity_id)
.map_or(new_balance, |managed| {
managed.persist_confirmed_balance(
new_balance,
BlockTime::from(metadata),
&self.persister,
)
}),

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.

🟡 Suggestion: Top-up result can report a stale cached balance

record_top_up_balance returns the value returned by persist_confirmed_balance, which is the managed identity's cached balance. If the response metadata height ties the existing watermark, take_fetched_balance treats the proved snapshot as a duplicate and leaves the cache unchanged. The top-up can therefore succeed with Platform returning a new balance while the FFI output reports the old balance. Persistence should remain best-effort, but the caller's result must always be the proved new_balance; the watermark should only control what is cached.

Suggested change
let mut wm = self.wallet_manager.write().await;
match wm.get_wallet_info_mut(&self.wallet_id) {
Some(info) => info
.identity_manager
.managed_identity_mut(identity_id)
.map_or(new_balance, |managed| {
managed.persist_confirmed_balance(
new_balance,
BlockTime::from(metadata),
&self.persister,
)
}),
let mut wm = self.wallet_manager.write().await;
if let Some(info) = wm.get_wallet_info_mut(&self.wallet_id) {
if let Some(managed) = info.identity_manager.managed_identity_mut(identity_id) {
managed.persist_confirmed_balance(
new_balance,
BlockTime::from(metadata),
&self.persister,
);
}
} else {
tracing::warn!(
identity = %identity_id,
"identity top-up accepted on Platform but wallet info was not found locally; skipping balance persistence"
);
}
new_balance

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Declining for this PR: returning the cached balance from persist_confirmed_balance predates it. top_up_identity_with_funding on v5.2-dev already returns that value, and record_top_up_balance only moves the same code into a helper the external route shares. Changing what a top-up reports belongs in its own change.

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.

Still applies (re-reviewed at 282c6df7): Although the managed route inherited this behavior, this PR introduced the shared helper and exposes it through the new external route, whose documented and FFI result is the proved post-transition balance. Equal-height metadata still causes the helper to return the old managed cache, so returning new_balance remains the targeted fix for the new API surface.

Comment on lines +434 to +454
/// Assign the identity an unassigned unbound identity top-up lock pays, as
/// the user chose it. A lock is unassigned when it records no identity
/// (`identity_recipient_unassigned` on the tracked-lock lists): it was rebuilt
/// from the chain, for example after a restore from the seed, and its credit
/// output names none, so no resume pays it. Afterwards
/// [`platform_wallet_topup_identity_with_existing_asset_lock_signer`] pays
/// this identity from the lock and refuses any other.
///
/// The identity is looked up on Platform first, because an assignment is
/// permanent: an identity Platform does not know is `ErrorIdentityNotFound`
/// (7) and nothing is assigned; a failed lookup is the SDK's error.
///
/// Errors: `ErrorAssetLockNotTracked` (23) for an unknown outpoint,
/// `ErrorAssetLockAlreadyConsumed` (24) for a consumed lock,
/// `ErrorAssetLockRecipientMismatch` (61) when the lock already records a
/// different identity (assigning the recorded one again is a no-op), and a
/// persistence error when the host's persister does not keep identity
/// recipients (`ASSET_LOCK_IDENTITY_RECIPIENTS`) or the store fails. After a
/// failed store the assignment still holds for this session and another
/// identity is refused (61); calling again with the same identity retries
/// the store. A lock

@thepastaclaw thepastaclaw Nov 14, 2026 •

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.

✅ Resolved at 282c6df7; see the replies below.

🟡 Suggestion: Assignment documentation selects an incompatible resume export

The assignment API accepts any identity known to Platform, including an identity not managed by this wallet. Its documentation directs hosts to platform_wallet_topup_identity_with_existing_asset_lock_signer, whose implementation requires the identity to exist in the local IdentityManager; an externally assigned identity therefore fails with ErrorIdentityNotFound. The documented recovery entry point must be the recorded-recipient resume export, which dispatches to the managed or external route without requiring the host to classify the identity.

Suggested change
/// Assign the identity an unassigned unbound identity top-up lock pays, as
/// the user chose it. A lock is unassigned when it records no identity
/// (`identity_recipient_unassigned` on the tracked-lock lists): it was rebuilt
/// from the chain, for example after a restore from the seed, and its credit
/// output names none, so no resume pays it. Afterwards
/// [`platform_wallet_topup_identity_with_existing_asset_lock_signer`] pays
/// this identity from the lock and refuses any other.
///
/// The identity is looked up on Platform first, because an assignment is
/// permanent: an identity Platform does not know is `ErrorIdentityNotFound`
/// (7) and nothing is assigned; a failed lookup is the SDK's error.
///
/// Errors: `ErrorAssetLockNotTracked` (23) for an unknown outpoint,
/// `ErrorAssetLockAlreadyConsumed` (24) for a consumed lock,
/// `ErrorAssetLockRecipientMismatch` (61) when the lock already records a
/// different identity (assigning the recorded one again is a no-op), and a
/// persistence error when the host's persister does not keep identity
/// recipients (`ASSET_LOCK_IDENTITY_RECIPIENTS`) or the store fails. After a
/// failed store the assignment still holds for this session and another
/// identity is refused (61); calling again with the same identity retries
/// the store. A lock
/// Afterwards, resume it with
/// [`platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`].
/// That entry point dispatches to the managed or external top-up path based on
/// whether the recorded identity is held by this wallet.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

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.

Resolved (re-reviewed at 282c6df7): The assignment documentation now points to platform_wallet_resume_identity_top_up_to_recorded_recipient_signer, which is the identity-less recovery export that pays the recorded recipient for both managed and external top-ups.

…a refused row's inputs

- Asset-lock builds broadcast under the build generation's lifecycle gate,
  after checking that generation is still the wallet's; a wallet removed or
  re-created mid-build sends nothing (WalletRemovedBeforeSend). This covers
  every new asset-lock funding, not only the top-ups.
- A recipient-carrying row whose store is refused may still be written by a
  host without atomic changesets, so it is handled like a failed flush: its
  removal is stored, and if that is refused the inputs stay reserved.
- The top-up minimum comes from IdentityTopUpTransition's fee calculation
  for the SDK's protocol version (min_top_up_duffs) instead of a literal.
- Resuming a consumed unbound lock reports AssetLockAlreadyConsumed before a
  missing recipient.
- The assignment doc points at the recorded-recipient resume.

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

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

Re-review — Final validation — Phase 1 + Phase 2

The recipient-binding implementation is present, but the current head still has four in-scope blocking lifecycle and durability defects: failed cleanup can release inputs before removal is durable, generation-mismatch aborts leave a durable unsent lock fenced, assignment can mutate a replacement wallet generation, and the minimum can be checked against a stale SDK protocol version. The new external route also exposes the pre-existing stale balance return, and the new FFI exports do not contain the established panic boundary. CI shows no failed code check, but the wallet tests and most package checks are skipped while PR hygiene remains pending.

🔴 4 blocking | 🟡 2 suggestion(s)

Still open from earlier rounds (2)

  • 🔴 Blocking: A failed recipient-row store can still leave a resumable row — packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1572-1605 (thread)
  • 🟡 Suggestion: Top-up result can report a stale cached balance — packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:640-657 (thread)
Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This large, intricate diff changes funds movement and coin-selection behavior for Core-to-identity top-ups, including asset-lock lifecycle and recipient authorization, while also introducing persistent storage schema changes.
  • 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 quota lookup failed), 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)
  • Code unchanged since the last final review (3b30b1e4): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed; 1 new nitpick(s) dropped
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — ffi-engineer (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort xhigh); 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/asset_lock/build.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1668-1678: WalletRemovedBeforeSend leaves a durable Built lock fenced as pending
  The generation check correctly prevents the broadcaster from being called, but this early return performs no cleanup. The recipient-bearing row was flushed earlier at lines 1546–1554, so it remains a durable `Built` lock. Returning drops `InBroadcastPin` with its default pending verdict and skips `abandon_unsent_build`, leaving the shared generation fence pending and not explicitly settling the old reservation. A recreated wallet inherits the shared fence, while a caller that treats `WalletRemovedBeforeSend` as retryable can build another lock even though the original signed row remains resumable and may later be recovered. Treat this as a definitive pre-send abort by durably removing the row before release, or retain an explicit operation-level hold and require recovery of this row rather than permitting a new build.
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1572-1605: A failed recipient-row store can still leave a resumable row
  (carried; thread: https://github.com/dashpay/platform/pull/5931#discussion_r4572750252)

In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/tracking.rs:171-200: Identity-recipient assignment can mutate a replacement wallet generation
  The assignment path acquires the wallet manager by `wallet_id` only. The FFI export clones the `IdentityWallet`, releases the registry, awaits the Platform identity lookup, and then calls this method. During that await the wallet can be removed and recreated under the same ID; the stale handle already contains a generation, but this method does not compare it with the current `PlatformWalletInfo.generation`. It can therefore assign and persist the recipient on the replacement generation's tracked lock. Perform the mutation through the handle's generation-checked accessor, under the appropriate lifecycle guard, before persisting.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: After the FFI export clones an `IdentityWallet` and awaits `fetch_identity_to_pay`, the wallet can be removed and recreated with the same ID. The stale handle then calls `AssetLockManager::assign_identity_top_up_recipient`, which mutates the entry returned by `get_wallet_info_mut(&self.wallet_id)` without checking the handle's generation, so it can assign and persist a recipient on the replacement wallet's tracked lock; a subsequent resume can pay that replacement lock to the stale call's identity._

In `packages/rs-platform-wallet/src/wallet/identity/network/registration.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:474-475: External top-up minimum is checked against a stale SDK protocol version
  `apply_top_up_minimum` reads `self.sdk.version()` before `fetch_identity_to_pay` performs its proved network fetch. An unpinned SDK can ratchet its protocol version during that fetch, so the amount may pass the v0 floor and then be used by transition construction at v1, whose active minimum is higher. A pinned SDK can likewise remain below the network's active version. The lock can therefore be built and broadcast from real Core funds before Platform rejects the top-up. Resolve the network version before applying the floor and keep the same stable version for the floor and transition construction, or conservatively enforce a floor valid for every supported active version.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/registration.rs:640-657: Top-up result can report a stale cached balance
  (carried; thread: https://github.com/dashpay/platform/pull/5931#discussion_r4572750273)

In `packages/rs-platform-wallet-ffi/src/identity_top_up.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/identity_top_up.rs:307-328: New top-up exports can unwind through the C ABI
  The new external top-up export calls `block_on_worker`, whose worker join path uses `expect("tokio worker panicked")`. A panic in the async wallet operation therefore re-panics inside this `extern "C"` function instead of returning a `PlatformWalletFFIResult`. The recorded-recipient resume and assignment exports use the same pattern. The crate already provides `catch_panic_to_code` because a panic cannot safely unwind through the C boundary and the JNI guard is outside the Rust export. Wrap each complete new export body with the operation-appropriate panic conversion, using an ambiguous-failure result for operations that may already have caused side effects.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Resume re-broadcast is not generation-gated — The existing recovery path can re-broadcast a tracked lock after its wallet generation has been removed or replaced because it does not hold the lifecycle gate used by new asset-lock builds. This is an important lifecycle gap, but it predates this change and is already tracked separately.

Comment on lines +1668 to +1678
let lifecycle = in_broadcast_pin.generation().payment_guard().await;
let is_current = self
.wallet_manager
.read()
.await
.get_wallet_info(&self.wallet_id)
.is_some_and(|info| in_broadcast_pin.is_on(&info.generation));
if !is_current {
return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode(
self.wallet_id,
)));

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: WalletRemovedBeforeSend leaves a durable Built lock fenced as pending

The generation check correctly prevents the broadcaster from being called, but this early return performs no cleanup. The recipient-bearing row was flushed earlier at lines 1546–1554, so it remains a durable Built lock. Returning drops InBroadcastPin with its default pending verdict and skips abandon_unsent_build, leaving the shared generation fence pending and not explicitly settling the old reservation. A recreated wallet inherits the shared fence, while a caller that treats WalletRemovedBeforeSend as retryable can build another lock even though the original signed row remains resumable and may later be recovered. Treat this as a definitive pre-send abort by durably removing the row before release, or retain an explicit operation-level hold and require recovery of this row rather than permitting a new build.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Comment on lines +171 to +200
self.require_identity_recipient_persistence()?;
let entry = {
let mut wm = self.wallet_manager.write().await;
let lock = wm
.get_wallet_info_mut(&self.wallet_id)
.ok_or_else(|| {
PlatformWalletError::WalletNotFound(
"Wallet info not found in wallet manager".to_string(),
)
})?
.tracked_asset_locks
.get_mut(out_point)
.ok_or(PlatformWalletError::AssetLockNotTracked(*out_point))?;
check_identity_recipient_assignable(lock, identity)?;
lock.identity_recipient = Some(identity);
AssetLockEntry::from(&*lock)
};
self.persister
.store(PlatformWalletChangeSet {
asset_locks: Some(AssetLockChangeSet {
asset_locks: [(*out_point, entry)].into(),
..Default::default()
}),
..Default::default()
})
.and_then(|()| self.persister.flush())
.map_err(|error| {
PlatformWalletError::Persistence(format!(
"asset-lock identity recipient was not made durable: {error}"
))

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: Identity-recipient assignment can mutate a replacement wallet generation

The assignment path acquires the wallet manager by wallet_id only. The FFI export clones the IdentityWallet, releases the registry, awaits the Platform identity lookup, and then calls this method. During that await the wallet can be removed and recreated under the same ID; the stale handle already contains a generation, but this method does not compare it with the current PlatformWalletInfo.generation. It can therefore assign and persist the recipient on the replacement generation's tracked lock. Perform the mutation through the handle's generation-checked accessor, under the appropriate lifecycle guard, before persisting.

Raised on code unchanged since the last review, and confirmed by an independent pass: After the FFI export clones an IdentityWallet and awaits fetch_identity_to_pay, the wallet can be removed and recreated with the same ID. The stale handle then calls AssetLockManager::assign_identity_top_up_recipient, which mutates the entry returned by get_wallet_info_mut(&self.wallet_id) without checking the handle's generation, so it can assign and persist a recipient on the replacement wallet's tracked lock; a subsequent resume can pay that replacement lock to the stale call's identity.

source: gpt-6.1-sol (phase2-reviewer: rust-quality)

Comment on lines +474 to +475
let funding = apply_top_up_minimum(funding, self.sdk.version())?;
let identity = self.fetch_identity_to_pay(identity_id).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: External top-up minimum is checked against a stale SDK protocol version

apply_top_up_minimum reads self.sdk.version() before fetch_identity_to_pay performs its proved network fetch. An unpinned SDK can ratchet its protocol version during that fetch, so the amount may pass the v0 floor and then be used by transition construction at v1, whose active minimum is higher. A pinned SDK can likewise remain below the network's active version. The lock can therefore be built and broadcast from real Core funds before Platform rejects the top-up. Resolve the network version before applying the floor and keep the same stable version for the floor and transition construction, or conservatively enforce a floor valid for every supported active version.

source: gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Comment on lines +307 to +328
let result = block_on_worker(async move {
// SAFETY: see the fn-level safety doc — the handle is pinned alive
// for the duration of this FFI call.
let asset_lock_signer = unsafe {
MnemonicResolverCoreSigner::new(
core_signer_addr as *mut MnemonicResolverHandle,
wallet_id,
network,
)
};
identity_wallet
.top_up_external_identity_with_funding(
&identity_id,
AssetLockFunding::FromWalletBalance {
amount_duffs,
account_index,
},
&asset_lock_signer,
None,
)
.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.

🟡 Suggestion: New top-up exports can unwind through the C ABI

The new external top-up export calls block_on_worker, whose worker join path uses expect("tokio worker panicked"). A panic in the async wallet operation therefore re-panics inside this extern "C" function instead of returning a PlatformWalletFFIResult. The recorded-recipient resume and assignment exports use the same pattern. The crate already provides catch_panic_to_code because a panic cannot safely unwind through the C boundary and the JNI guard is outside the Rust export. Wrap each complete new export body with the operation-appropriate panic conversion, using an ambiguous-failure result for operations that may already have caused side effects.

source: gpt-6.1-sol (phase2-reviewer: ffi-engineer)

@romchornyi romchornyi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 4 major (inline) · 12 non-blocking recommendations · no blockers — reviewed at 282c6df764

Level Verdict
1 · Idea ✅ valid The recipient lives on the lock row and is enforced in the one resolver every existing-lock resume goes through, which fixes #5924 at the root.
2 · Architecture 🟡 right layer, one cross-PR overlap Open draft #5930 models "who a lock pays" differently (payment_intent, also V021, bit 16, also reuses 61). Two models for one fact on the same base, and neither PR mentions the other. Please settle one model, or the rule that splits them, before either lands.
3 · Completeness 🟡 untracked gaps Swift PR C, sweep/reinstate, legacy unbound locks on a restored seed, the testnet e2e send and the host recovery changes have no tracking issue. Fixes #5924 will close the issue while its points 5–6 are partly open.
4 · Code 🟡 4 major Phantom unassigned locks, one error code for opposite retry contracts, no outpoint from the external top-up, V021 taken three times.

Major (inline)

  • tracked.rs#L173 — a consumed or restored unbound lock comes back as "unassigned, recoverable"; an irreversible assignment then binds it, and a conflicting one breaks that wallet's persistence for the session.
  • build.rs#L1593 — three exits with opposite retry contracts all return Persistence (FFI 99), and the rejected-broadcast flush arm ignores store_commits_inline.
  • identity_top_up.rs#L288 — the external top-up returns no outpoint, and a pre-build lookup failure and a post-broadcast transport failure share code 99.
  • V021__asset_lock_identity_recipient.rs#L4 — V021 is also claimed by #5890 (ready for review) and #5930; bit 16 by both of them.

On the open thread "WalletRemovedBeforeSend leaves a durable Built lock fenced as pending" — three of our lanes reached it independently, with a concrete double payment (build.rs#L1668-L1679):

  1. The wallet is removed and re-created under the same id while the build awaits the signer or the persister.
  2. The row with recipient X is stored, flushed and tracked into the new generation (track_asset_lock is keyed by wallet_id only).
  3. The gate fails and the host is told nothing was sent.
  4. The user re-sends from other coins (the old ones stay fenced), and host recovery later resumes the leftover Built row through the ungated re-broadcast, so X is paid twice.

Taking the gate and liveness check right after the build returns, before persist_asset_lock_account_pools and the row store, and holding it through track and broadcast (as #5516 prescribes) leaves nothing published on !is_current, so abandon_unsent_build can release the inputs cleanly.

12 non-blocking recommendations
  1. The gate checks the build's generation, not the caller's handle — build.rs#L448, registration.rs#L475. IdentityWallet carries generation, and contact requests refuse a replaced generation with it (contact_requests.rs#L868-L872). The top-up path doesn't: a removal and re-import during fetch_identity_to_pay lets a payment started on the removed wallet run on its replacement. The open assign thread covers only assign_identity_top_up_recipient.
  2. mark_asset_lock_consumption_unknown has no consumed guard — tracking.rs#L430-L441. With two overlapping resumes of one outpoint, the later 24 reverts an in-memory Consumed to RecoveredFromChain, so the lock lists as resumable again until restart. The function predates this PR; the new resume export makes the overlap easier to hit.
  3. Code 7 means "retry after sync" and "never" — error.rs#L1085. AssetLockIdentityNotLoaded and "Platform doesn't know the identity" share 7 on the same resume export, and the bound branch returns 7 before checking consumed (registration.rs#L577-L593). Consider a separate code, or at least document both in the registry row and the enum doc. Both triggers are hard to hit.
  4. Assignment writes memory first and stores a snapshot after releasing the lock — tracking.rs#L166-L203. A refused conflicting value (see major 1) stays in memory, and a sweep tombstone or rejected-lock removal stored in between is resurrected by the assignment's upsert. Roll memory back on a constraint refusal; refuse assignment of a Built lock.
  5. asset_lock_manager_resume still bypasses the recipient check — sync.rs#L225. The change is doc-only. A host recovery loop that still uses it and then tops up its own identity reproduces #5924. Refusing locks that carry, or lack, an identity recipient (61/81) would close it at the root.
  6. Sweep then reinstate drops the recipient — reconstruction.rs#L393-L424, reconstruction.rs#L236. Listed under Known limitations, but untracked. Please file an issue.
  7. Identity index 0 doubles as a sentinel on unbound locks — it is exposed as registration_index / identity_index on the tracked-lock lists (accessors.rs#L1068). Hosts that filter recovery rows by identityIndexRaw == 0 without the funding type (dashwallet-ios does, in its registration coordinator) will mix an in-flight external top-up into identity #0's progress. Exposing it as optional, or a doc note for hosts, would help.
  8. Code 81 and the 61 registry row — Swift maps 81 to errorUnknown and loses the number (Kotlin keeps it as Generic), and this already affects the existing managed resume. ERROR_CODE_REGISTRY.md row 61 still says rows without a recipient "accept the caller's", which is no longer true for unbound top-ups.
  9. A host that wires only the identity load slot stalls persistence — persistence.rs#L3136-L3146. Loaded rows carry recipients, and every later round with them fails. Run the load sidecar only when bit 17 is attested, or document that the slots go in pairs.
  10. Positional column reads in SQLite — asset_locks.rs#L341-L345. #5930 edits the same SELECTs; a merge that adds its column but keeps index 8 would decode one 32-byte blob as the other with no error. A shared column list, or reading by name, removes the hazard.
  11. top_up_identity_with_funding with an observed identity — registration.rs#L411-L418. It returns IdentityIndexNotSet (99), while the export doc names 7 for "one the wallet does not hold".
  12. Tests:
    • recorded_recipients has no test for (IdentityTopUp, Some(Identity)) → (None, None), the arm every managed Core top-up now takes (build.rs#L1917), nor for the catch-all refusal.
    • The first half of should_durably_remove_a_rejected_lock_that_records_its_recipient passes on the old code, because with commits_inline: true the queued removal also counts as stored. Re-run it with commits_inline: false.
    • Not covered:
      • the removed-wallet (None) arm of !is_current, and the row, pin and reservation it leaves;
      • assign on a consumed lock, and assign with the wallet missing;
      • resume of an unbound lock whose recorded identity the wallet holds (the managed route);
      • the FFI persist callback returning non-zero, and the load sidecar through FFIPersister::load;
      • the new list-row fields;
      • V021 on a populated V020 database;
      • the DrainWalletBalance floor.
    • sqlite_advertises_asset_lock_identity_recipients doesn't follow the repo's should_… naming rule.
Review details
  • Layered review: idea, architecture and completeness, then code.
  • Code lanes: a general correctness pass, plus specialist lanes for funds, security, concurrency, FFI and persistence, and edge-case lanes for failure injection, ordering/crash/restart, ownership and legacy data, and tests.
  • Verifier: every major was re-checked against the code by a separate clean-context pass. The migration and bit collisions were checked against the heads of #5890 (6ca3b7eede) and #5930 (9f3047d7b6).
  • Not repeated: findings already open from the review bot's round on this commit, for example the replacement-generation assignment, the stale protocol version and the C-ABI unwind.
  • Dropped: one candidate, create_funded_proof type 2 as an undocumented break, because it is in Breaking Changes.

🤖 Reviewed with Claude Code

/// consumed: its funds are recoverable (the wallet holds the credit
/// output's key), but the identity it was meant to pay is unknown, so no
/// resume pays it until the user assigns one.
pub fn is_unassigned_identity_top_up(&self) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major — phantom "unassigned" locks, and assigning one doesn't heal it. Verified in code, normal use.

  1. A completed external top-up comes back unassigned after a restart.
    • The top-up completes on the IS proof, and consume_asset_lock stores the row consumed with recipient X and no operation_id.
    • The app is closed before the funding tx is mined.
    • On relaunch, load_unconsumed skips consumed rows without operation_id (asset_locks.rs#L490).
    • The block then arrives as BlockProcessed, and reconstruction re-inserts the absent outpoint with identity_recipient: None (reconstruction.rs#L229-L236).
    • This predicate turns it into an unassigned lock "whose funds are recoverable".
  2. After a restore from seed, every past unbound top-up lists the same way. That includes ones Platform consumed long ago: RecoveredFromChain means "consumption unknown", and this flag reads it as "recoverable". The FFI doc tells hosts to list them for the user (manager.rs#L48-L53).
  3. Assigning is irreversible. Nothing checks consumption first. A resume then gets 24, and the lock stays bound to whoever was picked.
  4. A conflicting assignment breaks persistence for the session. In case 1, assigning Y ≠ X sets memory first (tracking.rs#L185). The SQLite apply then refuses the change before the consumed guard (asset_locks.rs#L208-L219) with a non-transient BlobDecode, which drops the buffered changeset (the whole wallet buffer in Manual mode). Y stays in memory, and every later snapshot of that row fails the same way until restart.

No funds move (the outpoint is one-shot), but the user is asked to act on spent locks, and persistence breaks.

Suggestion:

  • Load consumed rows that carry an identity recipient, as rows with an operation_id are kept, so reconstruction doesn't resurrect them.
  • Don't present a recipient-less RecoveredFromChain lock as recoverable: a separate "consumption unknown" state, or a consumption probe before the irreversible assignment.
  • Skip the recipient-conflict check when the stored row is consumed.
  • Roll the in-memory assignment back on a constraint refusal.

"abandoned asset lock's row may survive; keeping its inputs reserved"
);
in_broadcast_pin.settle_pending_spend();
return Err(PlatformWalletError::Persistence(format!(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major — three exits with opposite retry contracts return the same Persistence error (FFI 99). Verified in code; the trigger needs a persister failure, so it is rare, but the outcome is a double payment.

Exit State Host should
here (L1585-1598) row may survive, inputs kept not retry; resume later
L1599-1608 row removed, inputs released retry
L1719-1745 removal of a rejected lock failed not retry

The message text is the only signal.

Failure sequence:

  1. The host retries on 99 after this exit.
  2. The fence only blocks these exact inputs for this session, so the retry is funded from other coins and pays X.
  3. After a restart, the surviving Built row with recipient X loads, and recovery resumes it: X is paid twice.

A second problem in the same area: the flush-failure arm at build.rs#L1739 checks only operation.is_some(), not store_commits_inline(). On an FFI host whose store commits inline (with on_changeset_end_fn), the removal is already durable and flush is only a notification. Yet the call reports "could not durably remove" and keeps the inputs fenced with nothing left to resume. Precedent: advance_asset_lock_status_if (tracking.rs#L444-L452) and the drain arm.

Suggestion:

  • Give the "row may survive" exits a typed unknown-outcome error that carries the outpoint, as the sibling TransactionBroadcastUnconfirmed arm does, distinct from the released case.
  • Treat a flush failure on an inline-committing backend as a notification failure.

amount_duffs: u64,
account_index: u32,
core_signer_handle: *mut MnemonicResolverHandle,
out_new_balance: *mut u64,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major — the external top-up gives the host no outpoint, and "nothing built" and "built and broadcast" can share a code. Verified in code.

  • Same code for both cases. A failed fetch_identity_to_pay before any build is PlatformWalletError::Sdk, which maps to 99 (registration.rs#L522-L537). A transport failure of the Platform submit after the lock is on Core is also a plain Sdk, and also 99. The unconfirmed shape gets 20 and already-consumed gets 24, but this one doesn't.
  • No outpoint and no observer. on_built is None (registration.rs#L698-L708), and the export has no outpoint out-parameter.
  • The doc's remedy is ambiguous. The doc asks the host to look for a tracked lock "recording identity_id", but two sends to the same identity cannot be told apart that way.

Failure sequence:

  1. The lock is broadcast, and the submit fails on transport.
  2. The host sees the same code as a lookup failure and offers "try again".
  3. The re-send builds lock B and pays X.
  4. Recovery later resumes lock A to its recorded recipient: X is paid twice.

Suggestion: add an out-parameter for the built outpoint, zero when nothing was built, fed from on_built as the registration and shielded flows do. Optionally type the pre-build lookup failure now, rather than waiting for #5860's 80.

//! The identity an unbound identity top-up was built (or later assigned) to
//! pay, so a resume after restart pays that identity and refuses another.
//! Legacy blobs stay byte-identical; old rows receive NULL.
pub fn migration() -> String {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major — migration V021 is claimed three times on v5.2-dev, and capability bit 16 twice. Checked against the PR heads.

PR State Migration Bit
#5890 (6ca3b7eede) ready for review V021__core_locked_outpoints.rs 16 (OUTPOINT_LOCKS)
#5930 (9f3047d7b6) draft V021__asset_lock_payment_intent.rs 16 (ASSET_LOCK_PAYMENT_INTENTS)
this PR draft V021 17

Suggestion:

HashEngineering and others added 3 commits November 15, 2026 19:32
…e assignment, version-proof top-up floor

- A lock built on a wallet removed or re-created before the broadcast is
  aborted: its durable row is removed and its fence released, or, if that
  removal is refused, its inputs stay fenced. Tracking inserts only on the
  build's generation, so a replacement wallet is never handed the lock.
- Assigning a top-up recipient holds the handle's generation gate and refuses
  a wallet since replaced (WalletRemovedBeforeSend).
- min_top_up_duffs() is the largest minimum across every supported protocol
  version, so an SDK version change during the identity fetch cannot let a
  lock below the active floor be built.
- The external top-up returns the proved post-transition balance.
- The three new top-up FFI exports convert a panic to a result code instead
  of unwinding through the C ABI.
- The typed-amount drain test now expects inputs to stay reserved when the
  backend also refuses the abandoned row's removal (from 282c6df).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…remove abandoned rows durably

- AssetLockManager keeps the generation of the wallet it was registered
  with, and the funded build refuses (WalletRemovedBeforeSend) when the
  wallet under its id is a replacement, before selecting, reserving or
  signing: a stale handle can no longer spend a re-created wallet's funds.
- Every abandoned-lock removal (rejected broadcast, wallet replaced before
  send, recipient row not made durable) goes through one helper that stores
  and flushes it, tolerating a failed flush notification only on a backend
  that commits inline. Inputs are released only once the removal is durable;
  otherwise they stay reserved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… resume may still send

The pre-send abort for a wallet removed or re-created since the build now
checks, under the wallet write guard, whether a resume has claimed the row's
dispatch, as the rejected-broadcast cleanup does. When a resume or the wallet
now under the id may still send the lock, its row and inputs stay and the
outcome is reported as TransactionBroadcastUnconfirmed, so the caller does
not rebuild from other inputs and pay the recipient twice.

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

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