Skip to content

feat(platform-wallet): record the payment intent of external asset locks - #5930

Open
romchornyi wants to merge 27 commits into
HashEngineering/platform-wallet-top-up-someone-elses-identity-frfrom
feat/platform-wallet-asset-lock-intent
Open

romchornyi wants to merge 27 commits into
HashEngineering/platform-wallet-top-up-someone-elses-identity-frfrom
feat/platform-wallet-asset-lock-intent

Conversation

@romchornyi

@romchornyi romchornyi commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Issue being fixed or feature implemented

Closes #5824. An external asset lock (fund_from_asset_lock_external, which pays Platform addresses the wallet does not own) recorded no recipients. Recovery therefore resumed it as an owned top-up and refunded the sender, and hosts had to keep the outpoint → recipients link themselves in on_asset_lock_built.

Stacked: base is #5931 (HashEngineering/platform-wallet-top-up-someone-elses-identity-fr). This PR is Rust only (wallet, storage, FFI). The host wiring is in #6272 (Swift, SwiftData) and #6273 (Kotlin, Room/JNI), both based on this PR. Landing: #6272 and #6273 are reviewed on their own, and this PR does not merge alone: it merges only once both are review-clean, and the three land back to back into #5931's branch, so no state of that branch has this PR's guard without both standard handlers declaring bit 18 (without them fundFromAssetLockExternal is refused before anything is built).

What was done?

Wallet

  • AssetLockRecipient::PlatformAddresses(PlatformAddressRecipients): the recipient map of an external funding plus its single remainder. It is validated on construction and stored as opaque bytes (at most 4096). It lives as platform_address_recipients on AssetLockEntry and TrackedAssetLock, immutable through merges like the identity recipient. Locks rebuilt from the chain carry none.
  • fund_from_asset_lock_external records the map on the lock it builds. The row, its recipients and the funding pool that indexes the credit-output key go out in one durable write before the broadcast. If that write fails, nothing is broadcast.
  • New capability ASSET_LOCK_PLATFORM_ADDRESS_RECIPIENTS (bit 18). An external funding requires the composite EXTERNAL_PLATFORM_ADDRESS_FUNDING (bits 0 ATOMIC_CHANGESETS, 2 ASSET_LOCK_FUNDING_INDICES, 7 WALLET_RESTORE, 9 TRACKED_ASSET_LOCKS and 18; a host missing any of them is refused), so a backend allowed to fund a payment can also restore it and record its completion. Resuming an external funding requires bit 9. A backend without it is refused before anything is built; there is no in-memory fallback. An owned funding records nothing.
  • Resume: only a funding to exactly the recorded addresses may consume such a lock. Anything else, the owned path included, is AssetLockPlatformAddressRecipientMismatch. resume_platform_address_funding_to_recorded_recipients resumes it without the caller naming the recipients.
  • Before any lock is built, the transition the map becomes is checked: it must be active at the SDK's protocol version, pass DPP's structure validation, and a fresh lock must cover the explicit outputs plus the admission fee.
  • A lock that records no recipients (an owned funding, or an external one tracked before V026) is not refused, as before. The wallet cannot tell the two apart, so the host resumes a legacy external payment to the payees it saved.

Storage: sqlite migration V026 adds the nullable asset_locks.platform_address_recipients BLOB (1–4096 bytes) with an immutability trigger. SqlitePersister declares bit 18.

FFI:

  • on_persist/on_load_asset_lock_platform_address_recipients_fn appended to PersistenceCallbacksExtension. Bit 18 is attested only with both slots, the row writer, the wallet restore pair, the begin/end pair and a declared ATOMIC_CHANGESETS.
  • platform_wallet_get_asset_lock_platform_address_recipients (+ free) and platform_address_wallet_resume_fund_from_asset_lock_to_recorded_recipients_signer.
  • has_platform_address_recipients on the tracked-lock structs. A mismatch maps to ErrorAssetLockRecipientMismatch (61).

Resume and FFI safety (since the merge of #5931's 7d6b70435c)

  • TrackedResumeMetadata::same_lock_as compares the Platform-address recipients, so a deferred retry never sends a replaced lock.
  • After the ChainLock fallback the row is checked again under the resume's claim (type, recipients, not consumed). A wallet or row lost by then is TransactionBroadcastUnconfirmed, not a not-found error.
  • The two external exports, the recorded-recipients resume and the recipients read refuse a call from a runtime thread, report a panic (as ErrorTransactionBroadcastUnconfirmed where a payment may be out), and release the registry before blocking.
  • The recipients loader runs whenever it is wired, so saved payees are read even by a host that cannot write new ones.
  • A ChainLock or proof wait ends when the wallet, its generation or the row is gone; every ChainLock fallback reports that as the unknown outcome.
  • Known limit, documented on AssetLockBuiltFn: the callback cannot withdraw the outpoint of a lock abandoned before it was sent.

How Has This Been Tested?

  • Rust unit tests in platform-wallet (with --features shielded), platform-wallet-storage and platform-wallet-ffi. They cover:
    • an external lock whose Platform submit fails, then a restart: an owned resume is refused and the recorded recipients resolve;
    • legacy rows loading and resuming as before;
    • a failed funding-pool write stopping each kind of recorded-recipient lock before the broadcaster;
    • the activation check;
    • V026 and its trigger;
    • the FFI capability gate and the sidecar.
  • With --all-features on the current head: platform-wallet 3042 and platform-wallet-ffi 816 lib tests pass. platform-wallet-storage: one permissions integration test (should_open_under_insecure_ancestor_reached_through_parent_symlink_and_warn) fails on the author's macOS machine; this PR changes neither it nor the code it tests. Breaking each new check fails a test, except the error mapping of the resume right after the ChainLock wait, which only the Platform-address resolver's test covers.
  • cargo fmt, clippy on the touched crates (unused-imports allowed).
  • Swift and Kotlin: see feat(swift-sdk): persist and resume the Platform addresses an external asset lock pays #6272 and feat(kotlin-sdk): persist and resume the Platform addresses an external asset lock pays #6273.

Breaking Changes

  • Rust API: a new public field on AssetLockEntry and TrackedAssetLock (struct literals outside the crate must set it), and new PlatformWalletError variants. AssetLockRecipient gains the PlatformAddresses variant and is no longer Copy: a caller that copied it must clone it.
  • C ABI: two callbacks appended to PersistenceCallbacksExtension, and a field added to the tracked-lock structs; no slot reordered.
  • Persistence: sqlite V026 (V021–V025 are taken on feat(platform-wallet): top up someone else's identity from the Core balance #5931's branch; its V025 adds identity_recipient).
  • Hosts that call fund_from_asset_lock_external must declare EXTERNAL_PLATFORM_ADDRESS_FUNDING (bits 0, 2, 7, 9 and 18). Resuming an external funding (either resume path) needs TRACKED_ASSET_LOCKS (bit 9, with the asset-lock row writer). The in-tree Swift, Kotlin and SQLite backends declare all of them.
  • FFI hosts without the asset-lock row writer: a round that carries asset-lock rows now fails instead of dropping them silently. The sync bridge no longer sends the rows it reconstructs from the chain to a backend without TRACKED_ASSET_LOCKS, so such a host's Core sync is unaffected.

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

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • 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

⛔ Final review complete — 1 blocking finding(s) (commit c22558e) · triage: critical · Phase 2 only (queue backlog)

@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 payment-intent model and strict resume comparison are generally well integrated, but external recovery still has several funds-safety gaps. In particular, recovery requires an unrelated newly selected local account, external intents may be broadcast without durable persistence, and chain reconstruction erases the distinction between unknown and owned locks. The available Kotlin check passed; the Rust and Swift checks were skipped rather than failed.

🔴 4 blocking | 🟡 4 suggestion(s)

6 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: External recovery still requires an unrelated newly selected local account
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift

The resume UI requires a selected fresh recipient and platform account even when the lock already carries a payment intent. The external branch then passes that newly selected platformAcct to resumeFundFromAssetLockExternal, although the required account is the one owning the recorded credits == nil remainder address. With multiple platform accounts, validation rejects a valid recorded payment; with no fresh unused address, recovery cannot be submitted at all. The Kotlin screen has the same issue at KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/funding/FundFromAssetLockScreen.kt:248-267. For intent-bearing locks, derive the remainder address from the recorded intent, resolve its owning account, and do not require a newly selected destination.

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

🔴 Blocking: External recovery is persisted as an owned top-up to the wrong address
packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift

After completion, this backfill unconditionally writes the UI's recipientHash and sets recipientIsExternal = false. During external recovery, that hash is the newly selected local address, not the recipients in the recorded payment-intent map. The consumed row can therefore display a third-party payment as an incoming credit to an unrelated local address, and downstream activity classification can treat it as an owned top-up. Intent-bearing rows must bypass this legacy singular-recipient backfill and use the payment intent or explicit external-recipient metadata as the source of truth.

source: gpt-6.1-sol (phase2-reviewer: general)

🟡 Suggestion: Payment-intent decoding does not enforce the exactly-one-remainder invariant
packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs

The builder rejects recipient maps unless exactly one entry has None credits, but from_bytes accepts a stored map with zero or multiple remainder entries. Such bytes pass the persistence load boundary and produce a value that cannot be resumed: a matching external call fails shape validation, while an owned resume mismatches the recorded intent. Enforce the same cardinality invariant while decoding so malformed sidecars fail the load rather than becoming loadable but unusable rows.

if !rest.is_empty() {
    return Err(AssetLockPaymentIntentDecodeError("trailing bytes"));
}
if recipients.values().filter(|amount| amount.is_none()).count() != 1 {
    return Err(AssetLockPaymentIntentDecodeError(
        "must contain exactly one remainder recipient",
    ));
}
Ok(Self::PlatformAddresses(recipients))

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

🟡 Suggestion: Resume authorization reads status and intent under separate snapshots
packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs

tracked_resume_metadata snapshots the funding role, identity index, and status under one read lock, but the new intent check then takes a second read lock through tracked_payment_intent. A concurrent consume can change the status between those reads, causing this path to report AssetLockPaymentIntentMismatch instead of AssetLockAlreadyConsumed, or to perform unnecessary work before resume_asset_lock observes the consumed state. Include the payment intent in the existing metadata snapshot so all resume authorization inputs come from one guard.

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

🟡 Suggestion: The infallible encoder silently truncates oversized recipient maps
packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs

to_bytes converts a recipient count above u16::MAX to u16::MAX and then encodes only that prefix, so encode/decode is lossy for values that the public type can represent. The normal external funding path checks fits_storage, but direct serialization and future persistence paths can bypass that gate and silently change the payment intent rather than rejecting it. Make the encoder fallible or enforce the size invariant at every public serialization boundary.

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

🟡 Suggestion: JNI getter converts intent-array allocation failure into no intent
packages/rs-unified-sdk-jni/src/wallet_manager.rs

After found is true, failure of byte_array_from_slice returns a null JNI value without throwing an exception. Kotlin interprets null as the legitimate absence of a recorded intent, so an allocation failure can route recovery as if the lock were owned or legacy. Preserve null for found == false, but clear the JNI error and throw a DashSDKException when materializing a found intent fails.

match env.byte_array_from_slice(&blob) {
    Ok(array) => array.into_raw(),
    Err(_) => {
        let _ = env.exception_clear();
        throw_sdk_exception(
            env,
            99,
            "allocating asset-lock payment intent byte array failed",
        );
        ptr::null_mut()
    }
}

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

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); 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 is a large cross-language change that alters asset-lock funding and recovery behavior affecting funds movement, while also introducing a persistent SQLite schema migration and capability-gated state.
  • 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/asset_lock/build.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1471-1487: External asset-lock payments proceed without durable intent persistence
  When `payment_intent` is present but the persistence backend does not advertise `ASSET_LOCK_PAYMENT_INTENTS`, this code only logs a warning and continues to track and broadcast the lock. A process failure after broadcast can therefore lose the recipient map; after restart, the lock has no recorded intent and the ordinary owned resume path is accepted, refunding the asset lock to the wallet instead of paying the third party. The new external-payment API should fail before building or broadcasting unless the intent can be durably persisted.

In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/reconstruction.rs:232-237: Chain reconstruction erases unknown external-payment intent
  Every chain-reconstructed asset-lock row is assigned `payment_intent: None`. For an external address-funding lock whose local sidecar was lost or unavailable, this is indistinguishable from an owned or legacy lock. `resolve_funding_with_intent` only rejects the owned resume when an intent is present, so the reconstructed lock can again be consumed through the owned path and refund the sender. Reconstruction needs an explicit unknown-intent state, or must refuse owned recovery until the caller supplies verifiable recipient metadata; `None` cannot safely represent both legacy-owned and intent-unknown rows.

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift: External recovery still requires an unrelated newly selected local account
  The resume UI requires a selected fresh recipient and platform account even when the lock already carries a payment intent. The external branch then passes that newly selected `platformAcct` to `resumeFundFromAssetLockExternal`, although the required account is the one owning the recorded `credits == nil` remainder address. With multiple platform accounts, validation rejects a valid recorded payment; with no fresh unused address, recovery cannot be submitted at all. The Kotlin screen has the same issue at `KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/funding/FundFromAssetLockScreen.kt:248-267`. For intent-bearing locks, derive the remainder address from the recorded intent, resolve its owning account, and do not require a newly selected destination.
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift: External recovery is persisted as an owned top-up to the wrong address
  After completion, this backfill unconditionally writes the UI's `recipientHash` and sets `recipientIsExternal = false`. During external recovery, that hash is the newly selected local address, not the recipients in the recorded payment-intent map. The consumed row can therefore display a third-party payment as an incoming credit to an unrelated local address, and downstream activity classification can treat it as an owned top-up. Intent-bearing rows must bypass this legacy singular-recipient backfill and use the payment intent or explicit external-recipient metadata as the source of truth.

In `packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs: Payment-intent decoding does not enforce the exactly-one-remainder invariant
  The builder rejects recipient maps unless exactly one entry has `None` credits, but `from_bytes` accepts a stored map with zero or multiple remainder entries. Such bytes pass the persistence load boundary and produce a value that cannot be resumed: a matching external call fails shape validation, while an owned resume mismatches the recorded intent. Enforce the same cardinality invariant while decoding so malformed sidecars fail the load rather than becoming loadable but unusable rows.
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs: The infallible encoder silently truncates oversized recipient maps
  `to_bytes` converts a recipient count above `u16::MAX` to `u16::MAX` and then encodes only that prefix, so encode/decode is lossy for values that the public type can represent. The normal external funding path checks `fits_storage`, but direct serialization and future persistence paths can bypass that gate and silently change the payment intent rather than rejecting it. Make the encoder fallible or enforce the size invariant at every public serialization boundary.

In `packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs: Resume authorization reads status and intent under separate snapshots
  `tracked_resume_metadata` snapshots the funding role, identity index, and status under one read lock, but the new intent check then takes a second read lock through `tracked_payment_intent`. A concurrent consume can change the status between those reads, causing this path to report `AssetLockPaymentIntentMismatch` instead of `AssetLockAlreadyConsumed`, or to perform unnecessary work before `resume_asset_lock` observes the consumed state. Include the payment intent in the existing metadata snapshot so all resume authorization inputs come from one guard.

In `packages/rs-unified-sdk-jni/src/wallet_manager.rs`:
- [SUGGESTION] packages/rs-unified-sdk-jni/src/wallet_manager.rs: JNI getter converts intent-array allocation failure into no intent
  After `found` is true, failure of `byte_array_from_slice` returns a null JNI value without throwing an exception. Kotlin interprets null as the legitimate absence of a recorded intent, so an allocation failure can route recovery as if the lock were owned or legacy. Preserve null for `found == false`, but clear the JNI error and throw a `DashSDKException` when materializing a found intent fails.

@romchornyi

Copy link
Copy Markdown
Contributor Author

Replies to the findings shown only in the review body:

  • External recovery persisted as an owned top-up — fixed in 9f3047d: the example app skips the singular-recipient backfill when the resumed lock carries a payment intent, whose recipient map is the source of truth.
  • Decode does not enforce exactly one remainder — fixed in c3dc29a: from_bytes rejects a map without exactly one None-credits entry; tests cover zero and two.
  • External recovery requires a newly selected local account — deferred: the proper fix is a Rust resume-by-outpoint that finds the account owning the recorded remainder address itself (an API change across Rust, FFI, Swift and Kotlin). Today Rust refuses a mismatched account, so the gap is a refused resume, not a wrong payment. Tracked as item 3 of platform-wallet: payment-intent follow-ups (no-capability hosts, chain reconstruction, resume by intent) #5938.
  • Infallible encoder truncates oversized maps — not changing this: every production intent comes from fund_from_asset_lock_external, which refuses an intent that does not fits_storage() before anything is built, and consensus caps a funding at far fewer outputs than u16::MAX.
  • Status and intent read under separate snapshots — not changing this: the intent is immutable after build, so a concurrent consume only changes which refusal is returned (mismatch vs. already consumed); Platform rejects a consumed lock either way.
  • JNI getter turns an allocation failure into no intent — not changing this: a failed NewByteArray leaves an OutOfMemoryError pending, so Kotlin sees a throw; and even a null would take the owned path, which Rust refuses for a lock that recorded an intent.

@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 current head correctly preserves and validates payment intent during recovery, but the new external funding path still allows recipient maps that Rust/DPP rejects only after the irreversible Core asset lock has been broadcast. The public intent encoder also remains a non-blocking truncation hazard. CI shows no failed code checks, although the Rust and Swift checks are skipped and review/hygiene checks remain pending.

🔴 1 blocking | 🟡 1 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: External funding accepts output maps that are rejected after the asset lock is broadcast
packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:758-774

The shared preflight checks only non-empty cardinality, exactly one remainder, and P2PKH address types. It does not enforce the address-funding transition's explicit-output minimum or maximum output count. Consequently, an external request with an explicit amount below DPP's min_output_amount (for example Some(1)) or with more than the configured 128 outputs passes this preflight and reaches asset-lock construction. The asset lock is then broadcast before top_up_with_signers constructs the transition and ensure_valid_state_transition_structure rejects it. Because the recorded intent blocks the owned resume path and the same invalid map fails on an exact external retry, the already-broadcast lock can be stranded. Reject every address-funding map that would fail the transition's structural validation before resolving or broadcasting a fresh asset lock.

Raised on code unchanged since the last review, and confirmed by an independent pass: An external call with a valid owned remainder and an explicit P2PKH recipient amount of Some(1) (or more than 128 recipients) passes validate_recipient_addresses and the count-based asset-lock fee floor, then broadcasts and records the lock. top_up_with_signers subsequently rejects the transition during structural validation, while the recorded intent prevents an owned resume and the exact external retry repeats the rejection, leaving the asset lock stranded.

source: gpt-6.1-sol (phase2-reviewer: general)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); 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 is a large cross-language change that alters asset-lock recovery and funds movement while introducing Rust/Swift/Kotlin persistence migrations and FFI ABI changes, including the asset-lock payment-intent paths in packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs and migration V021__asset_lock_payment_intent.rs.
  • 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 (79a61c0f): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed
  • 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/platform_addresses/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:758-774: External funding accepts output maps that are rejected after the asset lock is broadcast
  The shared preflight checks only non-empty cardinality, exactly one remainder, and P2PKH address types. It does not enforce the address-funding transition's explicit-output minimum or maximum output count. Consequently, an external request with an explicit amount below DPP's `min_output_amount` (for example `Some(1)`) or with more than the configured 128 outputs passes this preflight and reaches asset-lock construction. The asset lock is then broadcast before `top_up_with_signers` constructs the transition and `ensure_valid_state_transition_structure` rejects it. Because the recorded intent blocks the owned resume path and the same invalid map fails on an exact external retry, the already-broadcast lock can be stranded. Reject every address-funding map that would fail the transition's structural validation before resolving or broadcasting a fresh asset lock.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: An external call with a valid owned remainder and an explicit P2PKH recipient amount of `Some(1)` (or more than 128 recipients) passes `validate_recipient_addresses` and the count-based asset-lock fee floor, then broadcasts and records the lock. `top_up_with_signers` subsequently rejects the transition during structural validation, while the recorded intent prevents an owned resume and the exact external retry repeats the rejection, leaving the asset lock stranded._

In `packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs:60-63: The infallible encoder silently truncates oversized recipient maps
  `to_bytes()` converts a recipient count above `u16::MAX` to `u16::MAX` and serializes only the first `count` entries. The fresh external builder currently calls `fits_storage()` before building, but the public enum and encoder can still be used directly by persistence, serde, tests, or future callers. Such a value is silently changed into a different intent, and whether decoding later fails depends on where the single remainder entry falls. Make the encoding boundary reject oversized maps or make encoding fallible rather than silently emitting a prefix.

@romchornyi

Copy link
Copy Markdown
Contributor Author

Addressed the review at 9f3047d7b6:

  • External funding maps rejected after the lock is broadcast — fixed in 215e6c0. Before any lock is resolved, fund_from_asset_lock(_external) runs DPP's own validate_structure on the transition it will submit: our outputs, no inputs and the derived fee strategy. So an output below min_output_amount, more than max_address_outputs outputs, or any other structural rejection fails with the same SDK error, before anything is built or broadcast. Two tests check that no lock is built for each case.
  • Infallible intent encoder truncates oversized maps — fixed in f1d0052. to_bytes is now fallible and refuses more than u16::MAX recipients instead of storing a prefix. The SQLite backend then fails the row write, and the FFI persister records a fatal round. A unit test covers it.

@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 current head fixes the previously reported truncating encoder, structural preflight, strict decoding, and example-app recovery defects. Static review found one blocking ABI compatibility issue in the extended tracked-lock array and several non-blocking validation, persistence-boundary, typed-error, and release-metadata issues; the CI snapshot shows Kotlin success, no failed code checks, and the Rust/Swift checks skipped or pending.

🟡 3 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Follow-up candidates (optional) (2)

New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.

🟡 Suggestion: Breaking public Rust struct fields are not marked through the release gate
packages/rs-platform-wallet/src/changeset/changeset.rs:1633-1637

Adding the required payment_intent field to the publicly constructible AssetLockEntry, and the analogous field on TrackedAssetLock, breaks downstream Rust struct literals that use the old field set. The workspace remains on the 5.0.3 release line, the PR title does not use the breaking ! marker, and the PR checklist leaves that item unchecked despite documenting the break. Mark the change through the repository's breaking-release convention and release metadata, or preserve source compatibility with a construction API that does not require downstream literals to add the field.

source: gpt-6.1-sol (phase2-reviewer: platform-versioning)

🟡 Suggestion: Preserve the typed payment-intent mismatch in shielded FFI flows
packages/rs-platform-wallet-ffi/src/shielded_send.rs:847-852

The shared resolver returns AssetLockPaymentIntentMismatch when a lock created for external Platform-address recipients is resumed through the shielded funding path. This specialized mapper only treats the older AssetLockRecipientMismatch as typed, so the new error falls through to ErrorWalletOperation instead of the documented ErrorAssetLockRecipientMismatch code 61. The lock remains safely unsubmitted, but hosts lose the actionable destination-mismatch classification and cannot handle this refusal consistently across funding entry points.

| PlatformWalletError::AssetLockRecipientMismatch { .. }
            | PlatformWalletError::AssetLockPaymentIntentMismatch { .. }),

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

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); 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); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 12: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 13: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 14: 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 cross-language change alters asset-lock funding and recovery behavior that affects funds movement, while also introducing Rust, Swift, Kotlin, and SQLite persistence migrations.
  • 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 final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Code unchanged since the last final review (9f3047d7): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 judged invalid (dropped); 2 new suggestion(s) listed as follow-up candidates, not posted inline
  • 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, 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-ffi/src/persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:3161-3173: FFI persistence forwards payment intents larger than its advertised 4096-byte limit
  `to_bytes()` rejects only recipient counts above `u16::MAX`; it can still successfully encode a map whose serialized form exceeds `ASSET_LOCK_PAYMENT_INTENT_MAX_LEN`. The normal fresh-build path checks `fits_storage()`, but this persistence path accepts directly supplied changesets without that check and forwards the oversized blob to the host callback. A host can store it, after which the JNI load trampoline cannot fit it into its documented 4096-byte buffer and wallet restoration fails. Enforce the storage-size limit before invoking the callback and record the round as fatal.

In `packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:653-663: Preflight validation is hard-coded to the V0 transition generation
  The preflight constructs `AddressFundingFromAssetLockTransitionV0` directly, while submission goes through `AddressFundingFromAssetLockTransition::try_from_asset_lock_with_signers`, whose dispatcher selects the conversion generation from `platform_version`. The enum currently has only V0, but when a later platform version introduces a transition generation with different structure rules, this gate can accept a map, broadcast the irreversible asset lock, and then have the selected submission generation reject it. Route the preflight through a DPP-owned version-aware validation helper or construct and validate the versioned transition through the same owner path.

In `packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs:63-81: The payment-intent encoder can emit bytes that its decoder will always reject
  `to_bytes()` now protects the encoded count width, but it does not enforce the semantic invariant that `from_bytes()` requires: a non-empty map with exactly one `None` remainder recipient. Public callers can construct an empty map or a map with zero or multiple remainder entries, persist the resulting bytes through SQLite or FFI, and then make the wallet reject the row during restoration as malformed. Enforce the canonical recipient shape at the encoding boundary or require construction through a validating constructor.

Comment on lines +3161 to +3173
for entry in al_cs.asset_locks.values() {
let Some(intent) = entry.payment_intent.as_ref() else {
continue;
};
let out_point = outpoint_to_bytes(&entry.out_point);
let bytes = match intent.to_bytes() {
Ok(bytes) => bytes,
Err(e) => {
tracing::error!("failed to encode asset-lock payment intent: {e}");
outcome.record_fatal();
continue;
}
};

@thepastaclaw thepastaclaw Nov 16, 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 c41628d3; see the replies below.

🟡 Suggestion: FFI persistence forwards payment intents larger than its advertised 4096-byte limit

to_bytes() rejects only recipient counts above u16::MAX; it can still successfully encode a map whose serialized form exceeds ASSET_LOCK_PAYMENT_INTENT_MAX_LEN. The normal fresh-build path checks fits_storage(), but this persistence path accepts directly supplied changesets without that check and forwards the oversized blob to the host callback. A host can store it, after which the JNI load trampoline cannot fit it into its documented 4096-byte buffer and wallet restoration fails. Enforce the storage-size limit before invoking the callback and record the round as fatal.

Suggested change
for entry in al_cs.asset_locks.values() {
let Some(intent) = entry.payment_intent.as_ref() else {
continue;
};
let out_point = outpoint_to_bytes(&entry.out_point);
let bytes = match intent.to_bytes() {
Ok(bytes) => bytes,
Err(e) => {
tracing::error!("failed to encode asset-lock payment intent: {e}");
outcome.record_fatal();
continue;
}
};
let bytes = if !intent.fits_storage() {
tracing::error!("asset-lock payment intent exceeds persistence size limit");
outcome.record_fatal();
continue;
} else {
match intent.to_bytes() {
Ok(bytes) => bytes,
Err(e) => {
tracing::error!("failed to encode asset-lock payment intent: {e}");
outcome.record_fatal();
continue;
}
}
};

source: gpt-6.1-sol (phase2-reviewer: general)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 1b9330e, at the encoding boundary rather than only in this callback: to_bytes now refuses an intent over the 4096-byte stored form (and one its decoder would reject), so this path takes its existing Err arm and records the round as fatal, and the SQLite write fails the same way. should_refuse_to_encode_an_intent_over_the_stored_size_limit pins it.

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 c41628d3): Verified that the encoding boundary now rejects stored forms over 4096 bytes, so the existing FFI error path records the persistence round as fatal instead of forwarding an oversized blob.

Comment on lines +653 to +663
fn validate_funding_transition_structure(
addresses: &BTreeMap<PlatformAddress, Option<Credits>>,
fee_strategy: &AddressFundsFeeStrategy,
platform_version: &PlatformVersion,
) -> Result<(), PlatformWalletError> {
let transition = AddressFundingFromAssetLockTransitionV0 {
outputs: addresses.clone(),
fee_strategy: fee_strategy.clone(),
..Default::default()
};
let result = transition.validate_structure(platform_version);

@thepastaclaw thepastaclaw Nov 16, 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 c41628d3; see the replies below.

🟡 Suggestion: Preflight validation is hard-coded to the V0 transition generation

The preflight constructs AddressFundingFromAssetLockTransitionV0 directly, while submission goes through AddressFundingFromAssetLockTransition::try_from_asset_lock_with_signers, whose dispatcher selects the conversion generation from platform_version. The enum currently has only V0, but when a later platform version introduces a transition generation with different structure rules, this gate can accept a map, broadcast the irreversible asset lock, and then have the selected submission generation reject it. Route the preflight through a DPP-owned version-aware validation helper or construct and validate the versioned transition through the same owner path.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.1-sol (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c41628d: the preflight selects the generation by the same state_transition_conversion_versions.address_funding_from_asset_lock_transition the submission's conversion dispatches on, validates the AddressFundingFromAssetLockTransition enum, and refuses a generation it cannot build with UnknownVersionMismatch before the asset lock exists. should_refuse_a_funding_transition_generation_the_preflight_cannot_build pins it.

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 c41628d3): Verified that the preflight now selects the generation from the same platform-version conversion slot used by submission and refuses unsupported generations before any asset lock is created.

Comment on lines +63 to +81
pub fn to_bytes(&self) -> Result<Vec<u8>, AssetLockPaymentIntentEncodeError> {
match self {
Self::PlatformAddresses(recipients) => {
let count = u16::try_from(recipients.len())
.map_err(|_| AssetLockPaymentIntentEncodeError(recipients.len()))?;
let mut bytes = Vec::with_capacity(3 + recipients.len() * 30);
bytes.push(KIND_PLATFORM_ADDRESSES);
bytes.extend_from_slice(&count.to_be_bytes());
for (address, amount) in recipients {
bytes.extend_from_slice(&address.to_bytes());
match amount {
Some(credits) => {
bytes.push(1);
bytes.extend_from_slice(&credits.to_be_bytes());
}
None => bytes.push(0),
}
}
Ok(bytes)

@thepastaclaw thepastaclaw Nov 16, 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 c41628d3; see the replies below.

🟡 Suggestion: The payment-intent encoder can emit bytes that its decoder will always reject

to_bytes() now protects the encoded count width, but it does not enforce the semantic invariant that from_bytes() requires: a non-empty map with exactly one None remainder recipient. Public callers can construct an empty map or a map with zero or multiple remainder entries, persist the resulting bytes through SQLite or FFI, and then make the wallet reject the row during restoration as malformed. Enforce the canonical recipient shape at the encoding boundary or require construction through a validating constructor.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 1b9330e: to_bytes refuses any map without exactly one remainder (None) recipient, the empty map included, so nothing it encodes fails restoration. should_refuse_to_encode_an_intent_its_decoder_would_reject pins the empty, no-remainder and two-remainder shapes; the decoder tests now write those bytes by hand.

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 c41628d3): Verified that to_bytes now rejects empty maps and every map without exactly one remainder recipient before persistence, matching the decoder's canonical-shape requirement.

@romchornyi
romchornyi marked this pull request as ready for review November 16, 2026 00:12
@romchornyi
romchornyi marked this pull request as ready for review November 16, 2026 00:12
@github-actions

Copy link
Copy Markdown
Contributor

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-self-review Waiting for the author to post /self-reviewed label Nov 16, 2026
@romchornyi

Copy link
Copy Markdown
Contributor Author

Merged v5.2-dev (cc2ea51). It took migration V021, so the payment-intent migration is renumbered to V022 (SCHEMA.md lists both, the schema-pinning fingerprints are re-pinned for the added file, and the test-only rewind_v021 undoes V022 too so a replay applies both). The three suggestions are answered on their threads (1b9330e, c41628d). The previous Swift CI failure was the runner's simulator launch, not the code. CI clippy set (--all-features), cargo test -p platform-wallet -p platform-wallet-storage -p platform-wallet-ffi --all-features and fmt pass on the merged tree.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 18, 2026

@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 current head still has one in-scope blocking defect: external funding validates only a count-based fee floor, so explicit recipient amounts can exceed the asset-lock value and fail after the irreversible lock is broadcast. The reported tracked-lock ABI stride issue is a false positive because the appended bool occupies existing trailing padding and leaves the repr(C) array element size unchanged; relevant Rust, Swift, and Kotlin CI checks passed.

🔴 1 blocking

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — This large, cross-language change alters asset-lock recovery and recipient-directed funds movement while introducing persistent SQLite/Room/SwiftData migrations, making it critical on both funds-movement and storage-migration surfaces.
  • 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.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:342-346: External funding accepts output maps that are rejected after the asset lock is broadcast
  The added structure validation covers static shape rules, but `enforce_asset_lock_amount_covers_address_funding_floor` checks only the count-based fee floor. For `FromWalletBalance`, a caller can provide explicit `Some` outputs whose total exceeds `amount_duffs * CREDITS_PER_DUFF`; the map passes preflight, the asset lock is built and broadcast, and Drive's state-dependent validation then returns `AddressesNotEnoughFunds` while applying the insufficient-funds penalty. Because the payment intent has already been recorded and the lock is single-use, the requested payment cannot be completed by retrying and the lock can be stranded after the penalty. Preflight the explicit-output sum against the available asset-lock credits, including the applicable fee margin, before resolving or building the lock.

Comment on lines 345 to 346
self.sdk.version(),
)?;

@thepastaclaw thepastaclaw Nov 18, 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 a2ed9e10; see the replies below.

🔴 Blocking: External funding accepts output maps that are rejected after the asset lock is broadcast

The added structure validation covers static shape rules, but enforce_asset_lock_amount_covers_address_funding_floor checks only the count-based fee floor. For FromWalletBalance, a caller can provide explicit Some outputs whose total exceeds amount_duffs * CREDITS_PER_DUFF; the map passes preflight, the asset lock is built and broadcast, and Drive's state-dependent validation then returns AddressesNotEnoughFunds while applying the insufficient-funds penalty. Because the payment intent has already been recorded and the lock is single-use, the requested payment cannot be completed by retrying and the lock can be stranded after the penalty. Preflight the explicit-output sum against the available asset-lock credits, including the applicable fee margin, before resolving or building the lock.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: rust-quality)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a2ed9e1, as a class: the funding floor now covers the explicit outputs plus the admission fee, so a wallet-balance funding the lock cannot cover is refused (AssetLockInsufficientFunds) before anything is built, and a drain that cannot cover it is abandoned after the build and before the broadcast. Four tests pin it and fail without the fix. A metered fee above the admission minimum still can't be known before the lock.

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 a2ed9e10): Your new floor adds the explicit credits to the static admission fee before rounding up to duffs. The fixed-amount check runs before lock resolution, and the drain checks the built value and releases the reservation before tracking or broadcast, addressing the reported shortfall without assuming the metered fee is known.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 18, 2026
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@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 new funding floor rejects locks that cannot cover the explicit outputs plus the admission fee. Four blockers remain: the FFI can advertise durable recovery without atomic writes, and the example apps can reuse another lock’s success, submit an external payment under a local top-up label, or report a balance the result does not establish. Rust workspace tests, Kotlin emulator checks, and Swift SDK build/tests and frozen-schema checks passed on this head.

🔴 4 blocking

Follow-up candidates (optional) (5)

New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.

🟡 Suggestion: Qualify the restart recovery guarantee
packages/rs-platform-wallet-ffi/src/platform_addresses/fund_from_asset_lock.rs:473-477

The new docs tell hosts to stop keeping the outpoint-to-recipients association and name only pre-upgrade locks as an exception. A current host without effective ASSET_LOCK_PAYMENT_INTENTS can still broadcast a lock and lose its intent on restart. Swift and Kotlin repeat the unconditional promise; Swift can even configure the manager without a persistence container. State that hosts can rely on recovery of SDK-recorded recipients only when the effective backend supports the capability and its store is retained. Otherwise hosts that need restart recovery must keep the association themselves. This documents the existing policy without reopening #5938.

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

🟡 Suggestion: Check the JVM intent array length before copying it
packages/rs-unified-sdk-jni/src/persistence.rs:2272-2282

convert_byte_array allocates a Rust vector and copies the entire Java array before this trampoline checks intent_capacity. An oversized array returned by a custom bridge or corrupt store therefore incurs a second allocation during restore even though the destination is bounded to 4096 bytes. Read the Java array length first and reject empty or oversized arrays before copying. Preserve null as the distinct, successful no-intent case.

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

🟡 Suggestion: Reject oversized stored intents at the public decoder
packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs:111-125

The decoder checks shape but not size. An ordered map with 136 explicit outputs and one remainder occupies 4,105 bytes, so from_bytes and serde accept it, but to_bytes rejects it on the next save. SQLite and the FFI restore buffer enforce the limit for their own inputs, not for callers of the public decoder. Reject blobs larger than ASSET_LOCK_PAYMENT_INTENT_MAX_SIZE before parsing the recipients, and test an otherwise valid oversized blob.

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

🟡 Suggestion: Append paymentIntent after the existing Kotlin timestamps
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/AssetLockEntity.kt:73-76

Inserting the new field before createdAt breaks existing positional constructor and copy calls that pass a Date there. It also silently changes component13() from updatedAt to createdAt, both of which have type Date. Append the defaulted field after updatedAt to preserve positional source calls and destructuring. JVM signatures still change, so document the rebuild requirement for Kotlin consumers in the PR’s breaking-changes section.

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

🟡 Suggestion: Pin the persisted payment-intent format with a literal fixture
packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs:215-222

The positive round-trip test decodes bytes produced by the current encoder. Changing the kind tag or amount endianness in both directions could keep the test green while breaking existing SQLite, SwiftData, and Room records. Add a literal kind-1 fixture with a multi-byte explicit amount and a remainder. Assert that the decoder reads the expected recipients and that the encoder reproduces those bytes exactly.

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

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — The diff changes who can receive funds when an external asset lock is resumed in wallet/platform_addresses/fund_from_asset_lock.rs, and enforcing that behavior across restarts requires coordinated persistence changes across SQLite, SwiftData, and Room.
  • 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 (c41628d3): 4 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 4 confirmed; 5 new suggestion(s) listed as follow-up candidates, not posted inline
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:1994-2005: Require atomic changesets before advertising durable payment intents
  The bridge reports `ASSET_LOCK_PAYMENT_INTENTS` when the host declares it and supplies the row and sidecar callbacks, even if it neither declares `ATOMIC_CHANGESETS` nor provides begin/end callbacks. `store()` delivers the signed `Built` row before the intent. If those callbacks commit independently and the process stops between them, restore loads a signed, resumable lock with no intent. An owned resume can then broadcast and consume it without paying the intended recipients; the flush after `store()` cannot close that window. Require declared atomicity and both transaction callbacks, as `CORE_SWEEP_REMOVAL` already does for another split write. Test that the bit is withheld when either requirement is missing. This is distinct from the deferred policy for hosts that do not advertise the capability.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: An FFI host that declares payment-intent support and commits each callback independently can crash after saving the signed Built row but before saving its intent. After restart, an owned resume can broadcast and consume that lock into the sender's wallet without paying the recorded payees._

In `packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/funding/FundFromAssetLockScreen.kt`:
- [BLOCKING] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/funding/FundFromAssetLockScreen.kt:248-254: Do not reuse a different lock’s completed payment
  The coordinator and progress route identify a resume by wallet, account, and the picked address, not by the lock being resumed. If external lock A pays its recorded recipients without crediting the picked address, that address stays eligible for the next resume. Selecting lock B on the same account during A’s completion-retention window therefore returns A’s `Completed` controller without running B’s submission. The screen shows success while B is still pending. Swift uses the same key and completion shortcut. Key resumes and their progress routes by wallet and outpoint. Test that two distinct outpoints submit independently while a duplicate tap for the same outpoint still coalesces.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: Resume external lock A with unused address X displayed and a different recorded change address on the same account. If the user returns to the pending list and resumes lock B while A's completed controller is retained, X is still eligible and B shows A's success without submitting B._
- [BLOCKING] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/funding/FundFromAssetLockScreen.kt:270-271: Do not turn a wallet changeset into an external payment balance
  The external resume returns address-tagged updates for wallet-owned addresses, not a balance for the displayed destination or the external payee. Taking the first update drops its address: it can be the recorded remainder or another owned output, even though the progress UI identifies the operation by the picked address. If sync already applied the balances, reconciliation can return no updates, which this code reports as zero. Swift does the same at `FundFromAssetLockPlatformAddressView.swift:581`. Report payment completion without a singular balance, or show only address-labelled updates and leave missing balances unknown.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: If a resumed payment pays a third party and sends change to wallet address R while the form displays address X, the completion UI reports R's balance as the funding result even though X was not credited. If sync has already applied R's update, the UI can report zero despite a successful payment and a nonzero balance on R._

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift:566-581: Show the recorded payees before confirming an external payment
  The form shows a wallet-owned “Destination Address” and asks the user to “Resume Top Up,” but the submission closure ignores that address and loads the recorded external recipients only after the tap. With the correct account, the operation succeeds and pays recipients the confirmation screen never showed. A user who settled the original bill another way can approve what looks like a top-up and pay that bill again. Kotlin has the same behavior. Load the recorded intent before enabling submission, show its payees, explicit amounts, and wallet remainder, and label the action as completing an external payment. This does not require changing how the account is selected.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: A user can open a pending external lock, see their own address as the destination, and tap Resume Top Up with the correct account selected. The submission instead makes an irreversible payment to the undisclosed recorded payees, potentially paying a bill the user already settled another way._

Comment on lines +1994 to +2005
if wallet_restore
&& self.callbacks.on_persist_asset_locks_fn.is_some()
&& self
.tracked_masternodes_callbacks
.persist_asset_lock_payment_intent
.is_some()
&& self
.tracked_masternodes_callbacks
.load_asset_lock_payment_intent
.is_some()
{
capabilities = capabilities.union(PersistenceCapabilities::ASSET_LOCK_PAYMENT_INTENTS);

@thepastaclaw thepastaclaw Nov 18, 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 eddb2649; see the replies below.

🔴 Blocking: Require atomic changesets before advertising durable payment intents

The bridge reports ASSET_LOCK_PAYMENT_INTENTS when the host declares it and supplies the row and sidecar callbacks, even if it neither declares ATOMIC_CHANGESETS nor provides begin/end callbacks. store() delivers the signed Built row before the intent. If those callbacks commit independently and the process stops between them, restore loads a signed, resumable lock with no intent. An owned resume can then broadcast and consume it without paying the intended recipients; the flush after store() cannot close that window. Require declared atomicity and both transaction callbacks, as CORE_SWEEP_REMOVAL already does for another split write. Test that the bit is withheld when either requirement is missing. This is distinct from the deferred policy for hosts that do not advertise the capability.

Raised on code unchanged since the last review, and confirmed by an independent pass: An FFI host that declares payment-intent support and commits each callback independently can crash after saving the signed Built row but before saving its intent. After restart, an owned resume can broadcast and consume that lock into the sender's wallet without paying the recorded payees.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deferred, tracked in #5986: attest ASSET_LOCK_PAYMENT_INTENTS only with ATOMIC_CHANGESETS and both changeset callbacks, as CORE_SWEEP_REMOVAL does. Meanwhile 8dcf289 qualifies the capability's doc: the row and its intent commit as one unit only on a host that also attests atomic changesets.

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 8dcf289e): Thanks for documenting the limitation and opening #5986. The documentation does not change the runtime gate: this PR's new capability still selects the durable path for a host that can commit the signed row without its intent, so the split-write case needs to be addressed here.

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 aa38a356): The current bridge implements the gate you tracked in #5986: it requires declared atomicity, both transaction callbacks, both recipient callbacks, the row writer, and the wallet restore pair before it attests recipient support.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3bfa624 + aa38a35 (closing #5986 here rather than later): a persistence capability whose row and sidecar must commit as one unit is attested only when the host declares ATOMIC_CHANGESETS and supplies both changeset callbacks, as CORE_SWEEP_REMOVAL already is. Applied at the FFI bridge capability gate (persistence.rs) for ASSET_LOCK_PLATFORM_ADDRESS_RECIPIENTS (bit 18), and at the wallet, which funds external Platform addresses only under the composite EXTERNAL_PLATFORM_ADDRESS_FUNDING (bit 18 together with atomic changesets), so a host that commits the signed Built row and the recipients separately is refused before any Core funds move. The Swift and Kotlin persisters wire bit 18 only next to their atomic rounds (#6272, #6273).

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 eddb2649): I verified the two layers of your fix: FFI checks declared atomicity and both transaction brackets before it attests bit 18, and the wallet refuses to build without the composite.

Comment on lines +251 to +254
recipientHash = recipientHash,
recipientType = recipientType,
) {
if (lock.paymentIntent != null) {

@thepastaclaw thepastaclaw Nov 18, 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.

✅ No longer applies at aa38a356; see the replies below.

🔴 Blocking: Do not reuse a different lock’s completed payment

The coordinator and progress route identify a resume by wallet, account, and the picked address, not by the lock being resumed. If external lock A pays its recorded recipients without crediting the picked address, that address stays eligible for the next resume. Selecting lock B on the same account during A’s completion-retention window therefore returns A’s Completed controller without running B’s submission. The screen shows success while B is still pending. Swift uses the same key and completion shortcut. Key resumes and their progress routes by wallet and outpoint. Test that two distinct outpoints submit independently while a duplicate tap for the same outpoint still coalesces.

Raised on code unchanged since the last review, and confirmed by an independent pass: Resume external lock A with unused address X displayed and a different recorded change address on the same account. If the user returns to the pending list and resumes lock B while A's completed controller is retained, X is still eligible and B shows A's success without submitting B.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4409c61 on both platforms: the resumed outpoint is part of the slot key (coordinator, controller, progress route, row id, dismiss), so lock B no longer gets lock A's completed controller. Kotlin test resumes of two distinct locks on one address submit independently.

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 8dcf289e): Confirmed: the resumed outpoint is carried through slot selection, progress lookup, row identity, and dismissal on both platforms. The Kotlin test exercises two different outpoints on the same address.

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.

No longer applies (re-reviewed at aa38a356): Your outpoint-keyed controller changes are no longer in this range, but neither is the recorded-payment route that could reuse another lock’s completed controller.

Comment on lines +566 to +581
body = {
guard case .platformAddresses(let recipients)? = try managedHolder.assetLockPaymentIntent(
txid: parsed.txid, vout: parsed.vout
) else {
throw PlatformWalletError.invalidParameter(
"The asset lock no longer carries its recorded recipients."
)
],
signer: signer
)
return updates
.first(where: { $0.hash == recipientHash })?.balance ?? 0
}
let updates = try await addressWallet.resumeFundFromAssetLockExternal(
outPointTxid: parsed.txid,
outPointVout: parsed.vout,
platformAccountIndex: platformAcct,
recipients: recipients,
signer: signer
)
return updates.first?.balance ?? 0

@thepastaclaw thepastaclaw Nov 18, 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.

✅ No longer applies at aa38a356; see the replies below.

🔴 Blocking: Show the recorded payees before confirming an external payment

The form shows a wallet-owned “Destination Address” and asks the user to “Resume Top Up,” but the submission closure ignores that address and loads the recorded external recipients only after the tap. With the correct account, the operation succeeds and pays recipients the confirmation screen never showed. A user who settled the original bill another way can approve what looks like a top-up and pay that bill again. Kotlin has the same behavior. Load the recorded intent before enabling submission, show its payees, explicit amounts, and wallet remainder, and label the action as completing an external payment. This does not require changing how the account is selected.

Raised on code unchanged since the last review, and confirmed by an independent pass: A user can open a pending external lock, see their own address as the destination, and tap Resume Top Up with the correct account selected. The submission instead makes an irreversible payment to the undisclosed recorded payees, potentially paying a bill the user already settled another way.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4409c61 on both platforms: for an external lock the recorded intent is loaded before submit is enabled, a Recorded Payees section (address prefix with credits, or remainder to this wallet) replaces the destination picker, and submit sends exactly that list. Kotlin test RecordedPayeeLinesTest; the Swift example has no tests for this screen.

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 8dcf289e): Confirmed: both forms display the recorded payees, explicit amounts, and remainder before enabling confirmation, and the submission uses that same list.

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.

No longer applies (re-reviewed at aa38a356): The rewrite removed both your Recorded Payees UI and the submission path it confirmed. The remaining owned submission is refused for a lock with recorded external recipients.

Comment on lines +270 to +271
)
return@startFunding updates.firstOrNull()?.balance ?: 0L

@thepastaclaw thepastaclaw Nov 18, 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.

✅ No longer applies at aa38a356; see the replies below.

🔴 Blocking: Do not turn a wallet changeset into an external payment balance

The external resume returns address-tagged updates for wallet-owned addresses, not a balance for the displayed destination or the external payee. Taking the first update drops its address: it can be the recorded remainder or another owned output, even though the progress UI identifies the operation by the picked address. If sync already applied the balances, reconciliation can return no updates, which this code reports as zero. Swift does the same at FundFromAssetLockPlatformAddressView.swift:581. Report payment completion without a singular balance, or show only address-labelled updates and leave missing balances unknown.

Raised on code unchanged since the last review, and confirmed by an independent pass: If a resumed payment pays a third party and sends change to wallet address R while the form displays address X, the completion UI reports R's balance as the funding result even though X was not credited. If sync has already applied R's update, the UI can report zero despite a successful payment and a nonzero balance on R.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4409c61 on both platforms: Completed takes an optional balance, an external resume reports none, and the screen says the payment completed without a balance line. Test a funding that reports no balance completes without one.

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 8dcf289e): Confirmed: both external resume closures return no singular balance, and the completion screens render payment success without a balance line.

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.

No longer applies (re-reviewed at aa38a356): Your earlier optional-balance fix belonged to the external completion branch, which is no longer in either example. Neither example now displays a balance from recorded-recipient recovery.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR Hygiene is not checking this pull request: it targets HashEngineering/platform-wallet-top-up-someone-elses-identity-fr, outside the policy. What was said about its diffs is kept for when it returns; it will queue for a review slot again.

@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

At 8dcf289, both example apps now show the recorded payees before confirmation, but neither offers recovery for a saved external lock that never reached broadcast, and a competing SQLite flush can still let a payment broadcast without a durable recipient record. Rust workspace, Swift SDK, and Kotlin emulator checks passed; PastaClaw review and PR Hygiene were pending. One verified SQLite error-reporting suggestion was omitted under the 10-comment budget.

A pattern across this PR's review rounds

This is review round 6, and the PR has drawn 14 blocking findings so far. 14 of them share 4 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.

1. No guaranteed payment checkpoint (1 new in this round, 3 earlier finding(s))

broadcast_funded_asset_lock_tracked treats ASSET_LOCK_PAYMENT_INTENTS and a successful store followed by flush as proof that the signed lock and its payees committed together. The FFI bridge can advertise that capability without atomic callbacks, and the buffered path does not use WalletPersister::store_durably to verify that this write survived a competing flush. Whenever intent is absent, including after chain reconstruction, resolve_funding_with_intent cannot distinguish an external payment whose payees were lost from an owned or legacy lock.

Already tracked: #5986

In this round: Verify that the payment-intent write committed before broadcast

2. Preflight and submission check different rules (1 new in this round, 2 earlier finding(s))

fund_from_asset_lock_inner builds a preview before committing Core funds, then builds the real transition later through top_up_with_signers. Reusing DPP's structure checks and matching the conversion generation closed the output-validation gap, but neither checks DPP's active_version_range: protocol 10 can construct the transition without accepting it.

In this round: Check transition activation before committing Core funds

3. External recovery still runs through the owned top-up form (2 new in this round, 4 earlier finding(s))

Swift and Kotlin still assemble recovery from a post-broadcast top-up list, a locally selected account and address, and a separate lookup of recordedPayees. Keying progress by outpoint and showing the saved payees correct parts of that flow, but there is still no single recovery record the apps can use to discover a restored Built lock, resolve its remainder account, and tell whether its payees are ready to confirm.

Already tracked: #5938

In this round: Offer recovery for an external payment saved before broadcast; Distinguish a failed payee lookup from a missing intent

4. Wallet changes are not a payment receipt (1 new in this round, 1 earlier finding(s))

PlatformAddressChangeSet contains wallet address updates, not a receipt or a balance lookup. The apps now allow external completion without a balance, but the owned paths still turn a missing update into zero even when sync already applied the confirmed balance.

In this round: Do not report a zero balance when an owned funding returns no update

Suggested decision (land the prerequisite first): Land a wallet-owned external-payment checkpoint first: the signed Built lock and exact payees must be confirmed committed together before broadcast and recoverable by wallet and outpoint without a new destination selection. Limit that guarantee to restoring the checkpoint; Core history alone cannot supply the payees. If that prerequisite does not land first, leave external-payment resume and its restart guarantee out of this PR.

🔴 6 blocking

2 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Offer recovery for an external payment saved before broadcast
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt:100-105

If the process stops after the pre-broadcast write commits but before the broadcaster runs, storage contains the signed transaction and its payees at status Built (0). IdentitiesHomeScreen uses this query, which selects only statuses 1–3 and 5. Swift's PendingPlatformFundFromAssetLocksList.isResumableTopUp also excludes status 0. For a transaction that was never sent, no network event will advance the row. Rust's resume_asset_lock already handles (Built, None) by sending the saved transaction. Expose that recovery path for restored, intent-bearing address-funding locks in both apps, keep the in-flight guard, and test that restart resumes the saved outpoint without building a second lock.

Raised on code unchanged since the last review, and confirmed by an independent pass: A Kotlin SDK host using the shipped resumable-top-ups query can start an external payment and be killed after the signed lock and payees commit but before broadcast. On restart the query omits the saved lock, so the host offers no way to complete that payment and Core has no transaction to report.

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

🔴 Blocking: Verify that the payment-intent write committed before broadcast
packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1542-1548

With SQLite in manual-flush mode, store() only stages the Built row and intent in the wallet's shared buffer. An independent flush_persist() for that wallet can take the changeset and discard it on a non-transient error. This call's flush() then finds an empty buffer and returns Ok(()), allowing the wallet to broadcast. If the process stops before a later status write, the live lock has no durable payee record. This can happen even when SQLite writes the row and intent in one transaction. Use WalletPersister::store_durably, which checks the shared flush ledger, and test that a competing flush that loses the write prevents broadcast.

Raised on code unchanged since the last review, and confirmed by an independent pass: With manual-flush SQLite, a concurrent flush_persist() can take the staged lock and intent and discard them on a non-transient error, such as a foreign-key violation in another write in the same batch. The funding call then flushes an empty buffer and broadcasts; if the process dies before a later status write, the live Core lock has no durable payee record.

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

Still open from earlier rounds (1)

  • 🔴 Blocking: Require atomic changesets before advertising durable payment intents — packages/rs-platform-wallet-ffi/src/persistence.rs:1996-2007 (thread)
Follow-up candidates (optional) (4)

New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.

🟡 Suggestion: State when hosts can rely on the SDK alone for payment recovery
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformAddressWallet.swift:863-872

The Swift, Kotlin, and C API docs tell callers they no longer need their own outpoint-to-payees association. But Swift supports modelContainer: nil, which installs empty persistence callbacks and zero capabilities, and C and Kotlin hosts can also omit the relevant persistence support. Rust still allows those payments, so after a restart the recipient map can be gone and the absence of an intent does not establish that the lock was an owned top-up. Qualify the promise in all three APIs: relying on SDK-only crash recovery requires durable intent storage and an atomic row-and-intent commit. Otherwise, retain a durable association or decline the payment. This documents the supported fallback without changing it.

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

🟡 Suggestion: Verify that Kotlin bridges implement the base asset-lock callbacks
packages/rs-unified-sdk-jni/src/persistence.rs:268-278

JNI checks that both intent methods are overridden, but its vtable always installs the asset-lock upsert and wallet-list trampolines. A bridge can declare bit 16 and override both sidecar methods while inheriting onPersistAssetLockUpsert, which returns success without writing, or onLoadWalletList, which returns an empty array. The FFI capability check sees non-null pointers in either case, but restore has no base lock row on which to invoke the intent loader. Require both base overrides before wiring the intent extension, and test the partial bridges. The bundled Room handler already implements both; this check is separate from transaction atomicity.

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

🟡 Suggestion: Enforce the stored-size limit when decoding an intent
packages/rs-platform-wallet/src/changeset/asset_lock_payment_intent.rs:111-114

from_bytes accepts 137 sorted recipients with one remainder: 136 explicit entries at 30 bytes, one remainder at 22 bytes, and a 3-byte header total 4,105 bytes. to_bytes refuses the resulting value, so a serde-backed host can accept an intent on restore and fail the next time it saves. SQLite's column constraint and the FFI load buffer do not protect the public decoder or serde. Reject inputs above the shared limit before parsing and add a decode-boundary test.

    pub fn from_bytes(bytes: &[u8]) -> Result<Self, AssetLockPaymentIntentDecodeError> {
        if bytes.len() > ASSET_LOCK_PAYMENT_INTENT_MAX_SIZE {
            return Err(AssetLockPaymentIntentDecodeError(
                "larger than the stored-form limit",
            ));
        }
        let (&kind, body) = bytes
            .split_first()
            .ok_or(AssetLockPaymentIntentDecodeError("empty"))?;

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: rust-quality)

🟡 Suggestion: Check the stored-intent array length before copying it into Rust
packages/rs-unified-sdk-jni/src/persistence.rs:2272-2282

convert_byte_array allocates and copies the entire host-provided ByteArray before the trampoline checks it against intent_capacity. An oversized value can therefore cause a large native allocation during restore just to be rejected. Check the JNI array length first and reject empty or oversized arrays before allocating or copying. Keep Java null as the distinct, successful “no intent” result.

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

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — The diff changes funds movement in rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs by requiring a resumed external asset lock to use its recorded recipients, with correctness depending on durable writes before broadcast and compatible recovery across SQLite, SwiftData, and Room migrations.
  • 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 (a2ed9e10): 3 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 3 confirmed; 4 new suggestion(s) listed as follow-up candidates, not posted inline
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): No guaranteed payment checkpoint; Preflight and submission check different rules; External recovery still runs through the owned top-up form; Wallet changes are not a payment receipt. When you fix the findings below, fix the cause, not only the reported case. The review suggests (land the prerequisite first): Land a wallet-owned external-payment checkpoint first: the signed `Built` lock and exact payees must be confirmed committed together before broadcast and recoverable by wallet and outpoint without a new destination selection. Limit that guarantee to restoring the checkpoint; Core history alone cannot supply the payees. If that prerequisite does not land first, leave external-payment resume and its restart guarantee out of this PR. If that decision is not yours to make, say so to the PR's author or maintainer.

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/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt:100-105: Offer recovery for an external payment saved before broadcast
  If the process stops after the pre-broadcast write commits but before the broadcaster runs, storage contains the signed transaction and its payees at status `Built` (0). `IdentitiesHomeScreen` uses this query, which selects only statuses 1–3 and 5. Swift's `PendingPlatformFundFromAssetLocksList.isResumableTopUp` also excludes status 0. For a transaction that was never sent, no network event will advance the row. Rust's `resume_asset_lock` already handles `(Built, None)` by sending the saved transaction. Expose that recovery path for restored, intent-bearing address-funding locks in both apps, keep the in-flight guard, and test that restart resumes the saved outpoint without building a second lock.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: A Kotlin SDK host using the shipped resumable-top-ups query can start an external payment and be killed after the signed lock and payees commit but before broadcast. On restart the query omits the saved lock, so the host offers no way to complete that payment and Core has no transaction to report._

In `packages/rs-platform-wallet/src/wallet/asset_lock/build.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1542-1548: Verify that the payment-intent write committed before broadcast
  With SQLite in manual-flush mode, `store()` only stages the `Built` row and intent in the wallet's shared buffer. An independent `flush_persist()` for that wallet can take the changeset and discard it on a non-transient error. This call's `flush()` then finds an empty buffer and returns `Ok(())`, allowing the wallet to broadcast. If the process stops before a later status write, the live lock has no durable payee record. This can happen even when SQLite writes the row and intent in one transaction. Use `WalletPersister::store_durably`, which checks the shared flush ledger, and test that a competing flush that loses the write prevents broadcast.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: With manual-flush SQLite, a concurrent `flush_persist()` can take the staged lock and intent and discard them on a non-transient error, such as a foreign-key violation in another write in the same batch. The funding call then flushes an empty buffer and broadcasts; if the process dies before a later status write, the live Core lock has no durable payee record._

In `packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:685-688: Check transition activation before committing Core funds
  The preflight verifies that it can construct the transition and that the outputs satisfy its structural rules, not that Platform accepts that transition at the SDK's effective protocol version. `PLATFORM_V10` selects conversion generation 0 and permits 128 address outputs, so a valid two-recipient map can pass this gate and the funding floor. DPP's active range for `AddressFundingFromAssetLock` starts at 11, and its version-aware decoder rejects the transition at 10. A wallet configured for a v10 network can therefore broadcast the Core lock before the Platform payment is rejected. Consult the DPP-owned activation rule before resolving fresh funding, and test that a v10 request never reaches the Core builder.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: On a v10 network, a funded wallet pinned to `PLATFORM_V10` can submit a fresh external payment with a 500,000-credit P2PKH payee, an owned remainder, and enough Core funds to clear the floor. The wallet broadcasts the Core lock, but Platform rejects the inactive address-funding transition, leaving the funds locked and the payee unpaid._

In `packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift`:
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift:566-575: Distinguish a failed payee lookup from a missing intent
  Swift calls this only on appearance. If the persisted row is visible before the managed wallet is published, or the getter throws, `recordedPayees` stays nil and the view says the lock no longer carries its recipients. Submission stays disabled even if the wallet finishes restoring while the sheet is open. Kotlin re-runs the lookup when the wallet or row changes, but `runCatching(...).getOrNull()` leaves a completed failed read labelled “Loading” with no retry for unchanged keys. Keep confirmation disabled until the recorded payees load, but distinguish waiting for the wallet, not found, and a failed read. Reload when the wallet becomes available and offer a retry after an error.
- [BLOCKING] packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/FundFromAssetLockPlatformAddressView.swift:674-675: Do not report a zero balance when an owned funding returns no update
  The revised completion type can represent success without a balance, but the owned resume branch carried into the new flow still substitutes zero for a missing update. `reconcile_address_infos_with_persistence` can return an empty changeset when sync has already applied the same proof-confirmed balance. This screen then reports zero for an address with a positive balance. Preserve the optional result of the address lookup in the owned resume and fresh funding closures on both platforms; Kotlin has the same `?: 0L` fallback.

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:1996-2007: Require atomic changesets before advertising durable payment intents
  (carried; thread: https://github.com/dashpay/platform/pull/5930#discussion_r4621252039)

Comment on lines +685 to +688
};
let result = transition.validate_structure(platform_version);
if result.is_valid() {
Ok(())

@thepastaclaw thepastaclaw Nov 18, 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 eddb2649; see the replies below.

🔴 Blocking: Check transition activation before committing Core funds

The preflight verifies that it can construct the transition and that the outputs satisfy its structural rules, not that Platform accepts that transition at the SDK's effective protocol version. PLATFORM_V10 selects conversion generation 0 and permits 128 address outputs, so a valid two-recipient map can pass this gate and the funding floor. DPP's active range for AddressFundingFromAssetLock starts at 11, and its version-aware decoder rejects the transition at 10. A wallet configured for a v10 network can therefore broadcast the Core lock before the Platform payment is rejected. Consult the DPP-owned activation rule before resolving fresh funding, and test that a v10 request never reaches the Core builder.

Raised on code unchanged since the last review, and confirmed by an independent pass: On a v10 network, a funded wallet pinned to PLATFORM_V10 can submit a fresh external payment with a 500,000-credit P2PKH payee, an owned remainder, and enough Core funds to clear the floor. The wallet broadcasts the Core lock, but Platform rejects the inactive address-funding transition, leaving the funds locked and the payee unpaid.

source: gpt-6.2-astra (phase2-reviewer: architecture-layering)

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 aa38a356): validate_funding_transition now checks DPP’s active version range before funding resolution, with tests for refusal below activation and acceptance at the boundary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 67a88a4: every fresh external Platform-address funding checks, before any Core funds are committed, that AddressFundingFromAssetLock is active at the SDK's effective protocol version, through DPP's own active-version range rather than a wallet copy of it. Applied at validate_funding_transition (platform_addresses/fund_from_asset_lock.rs), the one preflight that fresh fundings and resumes both pass through; a v10 network now gets a not-sent refusal and no lock is built.

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 eddb2649): Your DPP-owned activation check still runs before funding resolution, so a v10 request cannot reach the Core builder through this path.

Comment on lines +566 to +575
private func loadRecordedPayees() {
guard isExternalResume, recordedPayees == nil,
let lock = resumeFromLock,
let parsed = parseOutPoint(lock.outPointHex),
let managed = walletManager.wallet(for: wallet.walletId),
case .platformAddresses(let recipients)? = try? managed.assetLockPaymentIntent(
txid: parsed.txid, vout: parsed.vout
)
else { return }
recordedPayees = recipients

@thepastaclaw thepastaclaw Nov 18, 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.

✅ No longer applies at eddb2649; see the replies below.

🔴 Blocking: Distinguish a failed payee lookup from a missing intent

Swift calls this only on appearance. If the persisted row is visible before the managed wallet is published, or the getter throws, recordedPayees stays nil and the view says the lock no longer carries its recipients. Submission stays disabled even if the wallet finishes restoring while the sheet is open. Kotlin re-runs the lookup when the wallet or row changes, but runCatching(...).getOrNull() leaves a completed failed read labelled “Loading” with no retry for unchanged keys. Keep confirmation disabled until the recorded payees load, but distinguish waiting for the wallet, not found, and a failed read. Reload when the wallet becomes available and offer a retry after an error.

source: gpt-6.2-astra (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.

No longer applies (re-reviewed at aa38a356): The rewrite removed loadRecordedPayees from the example, along with the lookup whose failure was at issue. The Rust restore paths return an error for an unreadable record.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This example code moved out of #5930 (now Rust-only) into the host PRs, and the defect is fixed there on both platforms: the recorded-payee read distinguishes waiting for the wallet, loading, loaded, not found and failed; it re-runs once the wallet is available; a failure offers Retry; and confirmation (and on Kotlin, submit) stays disabled until the payees are loaded. Swift: c924430 in #6272. Kotlin: 4682bc3 in #6273 (RecordedPayeesLoad, 6 tests).

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.

No longer applies (re-reviewed at eddb2649): The payee lookup and its loading and retry UI are in the companion patches, not this diff. This head does not introduce the example lookup that conflated an error with a missing record.

Comment on lines +674 to +675
return updates
.first(where: { $0.hash == recipientHash })?.balance ?? 0

@thepastaclaw thepastaclaw Nov 18, 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.

✅ No longer applies at eddb2649; see the replies below.

🔴 Blocking: Do not report a zero balance when an owned funding returns no update

The revised completion type can represent success without a balance, but the owned resume branch carried into the new flow still substitutes zero for a missing update. reconcile_address_infos_with_persistence can return an empty changeset when sync has already applied the same proof-confirmed balance. This screen then reports zero for an address with a positive balance. Preserve the optional result of the address lookup in the owned resume and fresh funding closures on both platforms; Kotlin has the same ?: 0L fallback.

source: gpt-6.2-astra (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.

No longer applies (re-reviewed at aa38a356): The rewritten range no longer changes either example’s owned completion result; the remaining zero fallback is identical to the target branch.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This example code moved out of #5930 into the host PRs, and is fixed there on both platforms: every funding completion keeps a missing balance update as absent instead of substituting 0, through one AddressFundFromAssetLockController.reportedBalance used by both the owned resume and the fresh funding closures, and Completed shows no balance line when there is none. Swift: 5512794 in #6272. Kotlin: 595bba8 in #6273.

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.

No longer applies (re-reviewed at eddb2649): The completion closures are unchanged from the target branch here. The optional-balance handling you describe is in the companion host patches.

romchornyi and others added 3 commits November 24, 2026 23:13
Add `AssetLockRecipient::PlatformAddresses` next to the shielded and
identity recipients, carrying `PlatformAddressRecipients`: the recipient
map of an external Platform-address funding with its single remainder,
validated on construction and stored as opaque bytes (at most 4096; the
decoder refuses longer input before parsing it).

`AssetLockEntry` and `TrackedAssetLock` gain
`platform_address_recipients`, kept immutable through changeset merges
and stale-snapshot apply exactly like the identity recipient. Locks
rebuilt from the chain carry none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ble before it is sent

`fund_from_asset_lock_external` now records its recipient map on the
lock it builds. The row goes through the recipient path of
`broadcast_funded_asset_lock_tracked`: durable before the broadcast,
removed durably when the broadcast is rejected or the wallet was
replaced, with the same `TransactionBroadcastUnconfirmed` and
`WalletRemovedBeforeSend` outcomes as the other recorded recipients.

Add `PersistenceCapabilities::ASSET_LOCK_PLATFORM_ADDRESS_RECIPIENTS`
(1 << 18). It is required: an external funding is refused before
anything is built on a backend that does not declare it, as an unbound
identity top-up is without bit 17. An owned funding records nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ly to its recorded recipients

`validate_existing_asset_lock_role` now checks a Platform-address lock
that recorded its recipients: only a funding to exactly those addresses
may consume it, anything else (an owned funding included) is
`AssetLockPlatformAddressRecipientMismatch`. A lock that records none is
the wallet's own, as before.

`resume_platform_address_funding_to_recorded_recipients` resumes such a
lock without the caller naming recipients, crediting the platform
payment account that holds the recorded remainder address.

Before any lock is built, the address-funding transition the recipient
map becomes is checked: that it is active at the SDK's protocol version
(`StateTransition::active_version_range`), DPP's structure validation,
and that a fresh lock covers the explicit outputs on top of the
admission fee. A map Platform would refuse only after the lock is on
chain no longer strands Core funds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…till records them

A resume to the Platform-address recipients read from a lock's row now requires the row it
claims to record exactly those recipients. A row recreated at the outpoint by an owned
funding records none, and its funds no longer go to the old payees: it is refused before
anything is sent. A caller naming its own payees for a row without recipients (a legacy
external payment) still resumes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Nothing blocks: no blocking finding stands on this head.
Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: Recorded-recipient recovery now requires the tracked lock to contain the same payee map both during resolution and under the guard that protects the dispatch claim. Callers that explicitly supply saved legacy payees can still resume a lock with no recorded map. The Kotlin SDK build and emulator tests passed, the review check is pending, and no code checks failed; no tests were run locally.

🟡 1 suggestion(s)

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — The diff changes which recipients can receive funds when an asset lock is resumed in wallet/platform_addresses/fund_from_asset_lock.rs and ties that behavior to a pre-broadcast persistence guarantee across the wallet, the V025 SQLite migration, and FFI-backed storage.
  • 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.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:2783-2799: The replacement-row test misses a swap after the first recipient check
  Impact: A regression in the dispatch-time check could let a wallet recovery pay the old recipients from a replacement owned lock while this test still passes.
  This test would stay green if the claim-time check stopped requiring recorded payees. It installs the recipient-less row before calling `resolve_funding_to_recorded_recipients`, so the first metadata check returns `InvalidParameter` and the guarded authorization closure never runs. Setting `platform_addresses_must_be_recorded` to `false` only in that closure would leave both the refusal and legacy-success assertions unchanged. Keep the legacy case and add an orchestration test that starts with matching payees, swaps in a recipient-less `Built` row through the `on_out_point` callback between the two checks, and verifies that recovery refuses the row without calling the broadcaster.

Not approved: 1 blocking finding(s) are disputed and left to the maintainers.

Comment on lines +2783 to +2799
row.platform_address_recipients = None;
restart_with_failed_submit(&wallet, &chain_locked(row.clone())).await;
let resume = || AssetLockFunding::FromExistingAssetLock {
out_point: row.out_point,
consume_invitation_voucher: false,
};

let Err(refused) = wallet
.platform()
.asset_locks
.resolve_funding_to_recorded_recipients(
resume(),
AssetLockFundingType::AssetLockAddressTopUp,
Some(AssetLockRecipient::PlatformAddresses(old_payees.clone())),
&signer,
)
.await

@thepastaclaw thepastaclaw Nov 26, 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 79e4276e; see the replies below.

🟡 Suggestion: The replacement-row test misses a swap after the first recipient check
Impact: A regression in the dispatch-time check could let a wallet recovery pay the old recipients from a replacement owned lock while this test still passes.

This test would stay green if the claim-time check stopped requiring recorded payees. It installs the recipient-less row before calling resolve_funding_to_recorded_recipients, so the first metadata check returns InvalidParameter and the guarded authorization closure never runs. Setting platform_addresses_must_be_recorded to false only in that closure would leave both the refusal and legacy-success assertions unchanged. Keep the legacy case and add an orchestration test that starts with matching payees, swaps in a recipient-less Built row through the on_out_point callback between the two checks, and verifies that recovery refuses the row without calling the broadcaster.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 79e4276: should_refuse_old_payees_for_a_row_recreated_after_the_first_check starts from a row that records the payees, so the first check passes. It then recreates the row without recipients through on_out_point, between the first check and the claim, and expects the claim to refuse it with the lock unconsumed. Verified by mutation: with platform_addresses_must_be_recorded: false in the claim-time check only, this test fails and the earlier one still passes. The earlier test stays for the legacy caller-supplied-payees case.

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 79e4276e): Your callback runs only after the initial check succeeds, and the test requires both InvalidParameter and a tracked row whose recipients were cleared. The chain-locked fixture reaches the same guarded authorization as a Built row, before the status-specific paths diverge.

Comment on lines +860 to +864
if actual_funding_type == AssetLockFundingType::AssetLockAddressTopUp {
return match recorded_platform_addresses {
None => Ok(()),
Some(recorded) if requested_platform_addresses == Some(recorded) => Ok(()),
Some(recorded) => Err(

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 0db8d1a7): I verified your fix in 0db8d1a7e5: both checks require the stored map to be present and equal, and the second check runs on the current row under the dispatch-claim guard. Explicit legacy payees still take the non-strict path.

…the two checks

The replacement-row test installed the recipient-less row before the first
check, so the claim-time check never ran. The new test starts with a row that
records the payees, recreates it without recipients through on_out_point
between the first check and the claim, and expects the claim to refuse it with
nothing sent. It fails when only the claim-time check stops requiring recorded
recipients.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Nothing blocks: no blocking finding stands on this head.
Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This revision adds a wallet regression test that clears the recorded payees between the initial lookup and guarded authorization, then verifies that recovery refuses the changed row. The resolver becomes crate-visible for the test; its behavior is unchanged. Kotlin SDK build and tests and policy checks passed, PastaClaw review is pending, and CI does not list a dedicated Rust test run for this head.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — The diff makes intricate changes to funds movement in wallet/platform_addresses/fund_from_asset_lock.rs and wallet/asset_lock/build.rs, binding resumed payments to recorded recipients and requiring durable persistence of the lock and its funding index before broadcast.
  • 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.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

Not approved: 1 blocking finding(s) are disputed and left to the maintainers.

Comment on lines +2783 to +2799
row.platform_address_recipients = None;
restart_with_failed_submit(&wallet, &chain_locked(row.clone())).await;
let resume = || AssetLockFunding::FromExistingAssetLock {
out_point: row.out_point,
consume_invitation_voucher: false,
};

let Err(refused) = wallet
.platform()
.asset_locks
.resolve_funding_to_recorded_recipients(
resume(),
AssetLockFundingType::AssetLockAddressTopUp,
Some(AssetLockRecipient::PlatformAddresses(old_payees.clone())),
&signer,
)
.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.

Resolved (re-reviewed at 79e4276e): Your callback runs only after the initial check succeeds, and the test requires both InvalidParameter and a tracked row whose recipients were cleared. The chain-locked fixture reaches the same guarded authorization as a Built row, before the status-specific paths diverge.

romchornyi added a commit to dashpay/dashwallet-ios that referenced this pull request Nov 27, 2026
…tform address

Core now pays the two destinations it refused until the SDK could record who
an asset lock pays:

- Someone else's identity: the unbound top-up (`topUpExternalIdentityWithFunding`,
  dashpay/platform#5931) records the identity on the lock before it is
  broadcast. The Current identity keeps the bound top-up.
- Someone else's key-form Platform address: `fundFromAssetLockExternal`
  (dashpay/platform#5930, Swift in #6272) pays the amount to it and the rest of
  the lock to one of this wallet's addresses, recording both before the
  broadcast. Its fee is the two-output address-funding fee in the lock plus the
  lock's L1 miner fee. A script-form address stays unavailable ("Core can't pay
  this kind of Platform address"): the SDK takes P2PKH recipients only.

A failure after the lock is built reports the lock as held, so Send offers to
finish it. Every resume of such a lock pays the recorded recipient and never
names one: an unbound top-up resumes with `resumeTopUpToRecordedRecipient`, and
a Platform-address funding that recorded recipients with
`resumeFundFromAssetLockToRecordedRecipients`, at the one resume entry point
(`resumeFundFromCore`) that Send, Internal Transfer and the recovery list share.

The unused `coreToOtherIdentity` reason is gone. Tests that used Core and
someone else's identity to exercise a replaced source now use a script-form
Platform address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi added a commit to dashpay/dashwallet-ios that referenced this pull request Nov 27, 2026
…tform address

Core now pays the two destinations it refused until the SDK could record who
an asset lock pays:

- Someone else's identity: the unbound top-up (`topUpExternalIdentityWithFunding`,
  dashpay/platform#5931) records the identity on the lock before it is
  broadcast. The Current identity keeps the bound top-up.
- Someone else's key-form Platform address: `fundFromAssetLockExternal`
  (dashpay/platform#5930, Swift in #6272) pays the amount to it and the rest of
  the lock to one of this wallet's addresses, recording both before the
  broadcast. Its fee is the two-output address-funding fee in the lock plus the
  lock's L1 miner fee. A script-form address stays unavailable ("Core can't pay
  this kind of Platform address"): the SDK takes P2PKH recipients only.

A failure after the lock is built reports the lock as held, so Send offers to
finish it. Every resume of such a lock pays the recorded recipient and never
names one: an unbound top-up resumes with `resumeTopUpToRecordedRecipient`, and
a Platform-address funding that recorded recipients with
`resumeFundFromAssetLockToRecordedRecipients`, at the one resume entry point
(`resumeFundFromCore`) that Send, Internal Transfer and the recovery list share.

The unused `coreToOtherIdentity` reason is gone. Tests that used Core and
someone else's identity to exercise a replaced source now use a script-form
Platform address.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
romchornyi and others added 2 commits December 1, 2026 12:38
…ntity-fr (7d6b704)

TrackedResumeMetadata::same_lock_as compares the Platform-address recipients too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…thorized, and guard its FFI exports

After the ChainLock fallback the row is checked again (recipients, type, not
consumed), and a wallet or row lost by then is the unknown outcome. The
external funding and resume exports and the recipients read refuse a runtime
thread, catch panics, copy their inputs before clearing outputs and release
the registry before blocking. The recipients loader runs only for a host that
attests the capability.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Changes requested: 2 blockers

  • Reopening a wallet without the external-payment writer can hide saved payees and allow an owned top-up — packages/rs-platform-wallet-ffi/src/persistence.rs:4435-4439 (new)
    Impact: An FFI host that can still read an existing payment store but reopens it without fresh external-payment write support can redirect a pending third-party payment into the sender's wallet.
  • Removing the wallet during the ChainLock wait can leave external funding blocked forever — packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs:529-532 (new)
    Impact: A caller whose asset lock was broadcast can remove the wallet while InstantSend-to-ChainLock recovery is polling and remain blocked indefinitely instead of receiving the promised unknown-outcome result.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: The latest commit adds claim-time reauthorization for Platform-address ChainLock recovery and hardens the related FFI exports and recipient loading. The Kotlin SDK build/tests and policy checks pass on this head; the PastaClaw review remains in progress, and no local builds or tests were run.

A pattern across this PR's review rounds

This is review round 13, and the PR has drawn 19 blocking findings so far. 2 of them share one underlying cause. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.

1. An unread checkpoint looks like a legacy lock (2 new in this round, 2 earlier finding(s))

FFIPersister::load uses the host's current write capability to decide whether to read saved payees, so TrackedAssetLock::platform_address_recipients can be None even when the payees are still on disk. validate_existing_asset_lock_role treats that the same as a lock with no saved payees and lets the caller choose where to pay. The panic handler makes the opposite assumption: it tells even legacy callers to resume to recorded payees the wallet does not have.

Already tracked: #5938

In this round: Reopening a wallet without the external-payment writer can hide saved payees and allow an owned top-up; Panic recovery for legacy external locks points callers to an unavailable recorded-recipient path

Suggested decision (land the prerequisite first): Make fail-closed checkpoint restore a prerequisite for recorded-payment recovery. The signed Built lock, payees and funding-key index now commit together, and the standard mobile adapters are set to land with this PR, but a store containing those checkpoints must still restore them by wallet and outpoint or refuse to make the affected locks spendable when reopened with fewer callbacks. Keep legacy and Core-only recovery outside that guarantee, as already agreed. If that restore contract cannot land first, leave recorded-payment recovery out of this PR.

🔴 2 blocking | 🟡 1 suggestion(s)

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — The large, intricate diff changes asset-lock funding and resume behavior that controls funds movement, adds persistent storage migration and recovery semantics, and introduces new FFI capability gates.
  • 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)
  • New since the last final review (79e4276e): 2 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 2 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): An unread checkpoint looks like a legacy lock. When you fix the findings below, fix the cause, not only the reported case. The review suggests (land the prerequisite first): Make fail-closed checkpoint restore a prerequisite for recorded-payment recovery. The signed `Built` lock, payees and funding-key index now commit together, and the standard mobile adapters are set to land with this PR, but a store containing those checkpoints must still restore them by wallet and outpoint or refuse to make the affected locks spendable when reopened with fewer callbacks. Keep legacy and Core-only recovery outside that guarantee, as already agreed. If that restore contract cannot land first, leave recorded-payment recovery out of this PR. If that decision is not yours to make, say so to the PR's author or maintainer.

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-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:4435-4439: Reopening a wallet without the external-payment writer can hide saved payees and allow an owned top-up
  Impact: An FFI host that can still read an existing payment store but reopens it without fresh external-payment write support can redirect a pending third-party payment into the sender's wallet.
  A pending external payment can be consumed as an owned top-up even though its payees remain intact on disk. A host can create the lock with the full callback set, restart before Platform submission, and reopen the same store with the recipient loader installed but the recipient writer or atomic-round callbacks omitted. Because this filter tests the full `ASSET_LOCK_PLATFORM_ADDRESS_RECIPIENTS` capability, the loader is skipped; `build_wallet_start_state` leaves `platform_address_recipients` as `None`, and `validate_existing_asset_lock_role` therefore accepts the owned resume through its legacy `None => Ok(())` branch. The fresh-build capability guard does not protect an existing-lock resume. Reading an existing sidecar must be negotiated separately from permission to create new payments; if the host cannot establish the saved intent, the row must remain unknown and refuse owned recovery rather than being treated as recipient-less.

  _Confirmed by an independent pass: An FFI host can broadcast an external funding lock, restart before Platform consumes it, and reopen the same store with the recipient loader and funding indices intact but the optional recipient writer omitted. Restore succeeds without reading the saved payees, so the owned-resume API can consume the one-shot lock into the sender's own Platform address, leaving the intended recipients unpaid._

In `packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/orchestration.rs:529-532: Removing the wallet during the ChainLock wait can leave external funding blocked forever
  Impact: A caller whose asset lock was broadcast can remove the wallet while InstantSend-to-ChainLock recovery is polling and remain blocked indefinitely instead of receiving the promised unknown-outcome result.
  The `after_acceptance` mapping only runs after the awaited proof operation returns, so it cannot handle a ChainLock wait that never returns. After the 300-second InstantSend window, the public Platform-address flow passes `cl_wait = None` into `upgrade_to_persisted_chain_lock_proof`, which enters `wait_for_chain_lock`. If the wallet is removed after polling begins, `tracked_chain_proof_height` and the in-memory record lookup find nothing, and `wallet_chain_lock_state` returns `(None, false)`. A mined-height lookup therefore cannot produce a usable proof, while the no-deadline loop continues waking and retrying forever. The lifecycle guard has already been released after broadcast, so `remove_wallet` can occur during this interval and leave the FFI caller pinned. The polling loop needs to detect disappearance of the wallet or tracked row and return an error that `after_acceptance` converts to `TransactionBroadcastUnconfirmed`, while retaining the unbounded wait for a live wallet.

  _Confirmed by an independent pass: A host using the new recorded-recipient resume can remove the wallet through the public manager API while a broadcast lock is in the ChainLock fallback after the 300-second InstantSend window. If no finalized transaction record is available from persistence, the removed wallet can no longer supply either a tracked proof or the wallet ChainLock height needed to use a mined-height result, so the synchronous FFI call never returns._

In `packages/rs-platform-wallet-ffi/src/platform_addresses/fund_from_asset_lock.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/platform_addresses/fund_from_asset_lock.rs:733-744: Panic recovery for legacy external locks points callers to an unavailable recorded-recipient path
  Impact: A host recovering a legacy external payment after a panic can follow the returned guidance to the recorded-recipient API, which refuses the row because it has no recorded recipients.
  The shared panic message tells every external funding operation to resume the tracked lock to its recorded recipients. That is valid for a V025 intent-bearing row, but `platform_address_wallet_resume_fund_from_asset_lock_external_signer` also supports legacy external rows whose recipients were saved by the host rather than in the wallet row. Those rows have no recorded recipients, so following the message with the recorded-recipient export returns `ErrorInvalidParameter` instead of providing a recovery path. Keep the warning not to create another lock, but make the guidance operation- or row-specific: use the recorded-recipient resume when an intent is present, and use the external resume with the host's original payees for a legacy row.

… and end a proof wait whose wallet or row is gone

The recipients loader runs whenever it is wired, so a host that cannot write
new payees still reads the saved ones. The ChainLock and proof waits end when
the wallet, its generation or the row is gone, and every ChainLock fallback
reports that as the unknown outcome. The panic guidance covers a legacy lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Changes requested: 2 blockers

  • A reader-only recipient host reports payment success but restores the lock as pending — packages/rs-platform-wallet-ffi/src/persistence.rs:3565-3570 (new)
    Impact: An FFI host that can load saved recipients and persist ordinary rows, but lacks the recipient writer, can complete a recorded external payment while leaving its pre-completion status on disk.
  • Removing a wallet after a resume rebroadcast loses the do-not-retry result — packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs:1226 (new)
    Impact: A caller resuming a pending external lock can receive a generic wallet or proof-wait error even though Core accepted a rebroadcast and the original lock may still confirm.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This head decouples saved Platform-address recipient loading from write capability, adds termination checks to proof waits, and updates panic-recovery guidance for legacy rows. The Kotlin SDK build and tests pass; no Rust test check is listed, and the PastaClaw review check remains queued.

A pattern across this PR's review rounds

This is review round 14, and the PR has drawn 21 blocking findings so far. 4 of them share 2 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.

1. The intent checkpoint is not a complete recovery contract (1 new in this round, 1 earlier finding(s))

External-payment intent is split between the tracked row and a sidecar, while FFIPersister negotiates read, write, and atomic capabilities separately. The latest change always loads the sidecar, so a reader-only reopen can authorize a payment, but store() later treats that same sidecar as mandatory and cannot commit the consumed or proof-bearing row; the API has no state in which the payment is both safely resumable and safely finalizable. Fixes therefore move the failure window from initial restore to completion.

Already tracked: #5938

In this round: A reader-only recipient host reports payment success but restores the lock as pending

2. Proof waits have no stable lifecycle claim (2 new in this round, 1 earlier finding(s))

ensure_lock_still_tracked only samples the wallet generation and outpoint before record, locator, and persister operations that suspend; it does not bind those operations to the same generation and row until they finish. A wallet can be replaced after the check, and a removed row can surface as WalletNotFound or AssetLockProofWait, while resume handling translates only FinalityTimeout after a broadcast. The new liveness checks stop some hangs but do not provide a stable claim or a consistent unknown-outcome guarantee.

In this round: Removing a wallet after a resume rebroadcast loses the do-not-retry result; A proof lookup can update a replacement wallet generation after the liveness check passes

Suggested decision (land the prerequisite first): Land a complete fail-closed asset-lock recovery contract before this feature. An intent-bearing resume must be authorized only when the host can restore the row and intent and atomically persist every later proof and consumed-state update; otherwise Rust must refuse that row and this PR must drop the external recovery path. A reader-only callback is not sufficient, and the recovery contract must also keep the resumed row tied to the same wallet generation for the full proof wait.

🔴 2 blocking | 🟡 1 suggestion(s)

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — This large, intricate diff changes external asset-lock funding and recovery behavior, payment intent persistence, and a storage migration on a funds-movement surface, particularly in packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs and packages/rs-platform-wallet-storage/migrations/V025__asset_lock_platform_address_recipients.rs.
  • 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)
  • New since the last final review (968dc95d): 2 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 2 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): The intent checkpoint is not a complete recovery contract; Proof waits have no stable lifecycle claim. When you fix the findings below, fix the cause, not only the reported case. The review suggests (land the prerequisite first): Land a complete fail-closed asset-lock recovery contract before this feature. An intent-bearing resume must be authorized only when the host can restore the row and intent and atomically persist every later proof and consumed-state update; otherwise Rust must refuse that row and this PR must drop the external recovery path. A reader-only callback is not sufficient, and the recovery contract must also keep the resumed row tied to the same wallet generation for the full proof wait. If that decision is not yours to make, say so to the PR's author or maintainer.

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-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:3565-3570: A reader-only recipient host reports payment success but restores the lock as pending
  Impact: An FFI host that can load saved recipients and persist ordinary rows, but lacks the recipient writer, can complete a recorded external payment while leaving its pre-completion status on disk.
  The payment can succeed on Platform, yet the durable wallet state remains resumable after restart. After reopening with the loader wired but `persist_asset_lock_platform_address_recipients` absent, the loader restores `Some(recipients)`, so the recorded-recipient resume is authorized without the fresh-build capability. When proof advancement or `consume_asset_lock` writes the resulting `AssetLockEntry`, the unchanged recipient map is included; this branch records a fatal round error because the writer is missing. An atomic host consequently rolls back the whole row update, while `queue_asset_lock_changeset` only logs the persistence failure and the caller still receives success. The next restore therefore sees the old `Broadcast`/`ChainLocked` row and may offer the already-paid lock again. Either support a status-only update that preserves the already-stored immutable sidecar, or reject the resume before dispatch when the terminal status cannot be durably committed; cover the loader-without-writer path through completion and a second restore.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: An FFI host can reopen a wallet with a pending external payment saved by an earlier writer, keeping the recipient loader and atomic row updates wired but omitting the recipient writer, then call the recorded-recipient resume API. If Platform accepts the payment, the missing writer still forces the atomic update to roll back; the resume returns success, but the next restart restores the already-paid lock as pending._

In `packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs:1226: Removing a wallet after a resume rebroadcast loses the do-not-retry result
  Impact: A caller resuming a pending external lock can receive a generic wallet or proof-wait error even though Core accepted a rebroadcast and the original lock may still confirm.
  The post-broadcast proof wait can now terminate with `WalletNotFound` or `AssetLockProofWait`, but both resumed `Built` and `Broadcast` arms propagate every non-`FinalityTimeout` error unchanged. A normal resume can start from a persisted `Broadcast` row with no local proof, successfully rebroadcast the transaction, release its dispatch claim, and then enter `wait_for_resumed_proof`; removing the wallet or its tracked row before the next poll makes the new check at this line return one of those errors. The existing-lock orchestration only converts `FinalityTimeout` into the ChainLock fallback, so the disappearance exits before `after_acceptance` can classify it as `TransactionBroadcastUnconfirmed`. The FFI caller consequently loses the typed instruction not to build another lock, despite Core having accepted a transaction that may still confirm. Preserve raw lookup errors before dispatch, but map wallet/row disappearance from the `Built` and `Broadcast` waits after a send was dispatched or may have been dispatched to `TransactionBroadcastUnconfirmed`.

  _Confirmed by an independent pass: A host resuming a persisted Broadcast lock with no local proof can successfully rebroadcast it, then remove the wallet through the public manager API while the resume is waiting for finality. The next proof poll returns a generic FFI error instead of ErrorTransactionBroadcastUnconfirmed, so the caller cannot distinguish the already-dispatched lock from a failure before dispatch and loses the instruction not to fund a replacement._
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/asset_lock/sync/proof.rs:1226: A proof lookup can update a replacement wallet generation after the liveness check passes
  Impact: If a wallet is removed and the same wallet ID is reloaded while a proof lookup is suspended, the old operation can attach its result to the replacement row instead of reporting that its generation disappeared.
  The new generation and row check is only a point-in-time check. After it succeeds, `record_chain_proof_height`, `located_chain_proof_height`, or the record/persister lookup can suspend; the wallet can then be removed and recreated with the same ID and outpoint. A successful lookup returns to the resume path, whose `advance_asset_lock_status` mutation looks up only wallet ID and outpoint and does not verify the captured generation, so it can update the replacement row. The already-chain-locked fast path has the same gap because it can return without another poll check. Bind the generation check to the guard that mutates the row, or make the status update reject a different generation, so a stale proof operation cannot advance replacement state.

Comment on lines +3565 to +3570
let Some(cb) = self
.tracked_masternodes_callbacks
.persist_asset_lock_platform_address_recipients
else {
outcome.record(1);
continue;

@thepastaclaw thepastaclaw Dec 1, 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 9de8e69d; see the replies below.

🔴 Blocking: A reader-only recipient host reports payment success but restores the lock as pending
Impact: An FFI host that can load saved recipients and persist ordinary rows, but lacks the recipient writer, can complete a recorded external payment while leaving its pre-completion status on disk.

The payment can succeed on Platform, yet the durable wallet state remains resumable after restart. After reopening with the loader wired but persist_asset_lock_platform_address_recipients absent, the loader restores Some(recipients), so the recorded-recipient resume is authorized without the fresh-build capability. When proof advancement or consume_asset_lock writes the resulting AssetLockEntry, the unchanged recipient map is included; this branch records a fatal round error because the writer is missing. An atomic host consequently rolls back the whole row update, while queue_asset_lock_changeset only logs the persistence failure and the caller still receives success. The next restore therefore sees the old Broadcast/ChainLocked row and may offer the already-paid lock again. Either support a status-only update that preserves the already-stored immutable sidecar, or reject the resume before dispatch when the terminal status cannot be durably committed; cover the loader-without-writer path through completion and a second restore.

Raised on code unchanged since the last review, and confirmed by an independent pass: An FFI host can reopen a wallet with a pending external payment saved by an earlier writer, keeping the recipient loader and atomic row updates wired but omitting the recipient writer, then call the recorded-recipient resume API. If Platform accepts the payment, the missing writer still forces the atomic update to roll back; the resume returns success, but the next restart restores the already-paid lock as pending.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 2cf38fb: every write of a row that carries Platform-address recipients commits on a host that can read them back but not write them, as a status-only update. FFIPersister remembers the recipients each load returned per (wallet, outpoint). A write carrying exactly those skips the sidecar, because the column is immutable and the host already holds it. A write carrying any other recipients (a different set, another wallet, or nothing read back) still fails the round. This is the single store choke point, so it covers the recorded-recipient resume, the external resume, the ChainLock fallback, background proof advances and consume_asset_lock. A fresh external funding still requires EXTERNAL_PLATFORM_ADDRESS_FUNDING, which needs the writer. Test: should_load_saved_platform_address_recipients_without_the_write_capability now also stores a Consumed write of the loaded row on a loader-only host, both before the load (refused) and after it (committed), and with other recipients or another wallet (refused).

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 9de8e69d): Confirmed for the configuration you addressed: with a working row writer and recipient loader, exact read-back bytes let the intact row's Consumed update commit without the sidecar writer. The case with no base-row writer is separate.

tokio::pin!(notified);
notified.as_mut().enable();

self.ensure_lock_still_tracked(out_point).await?;

@thepastaclaw thepastaclaw Dec 1, 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 9de8e69d; see the replies below.

🔴 Blocking: Removing a wallet after a resume rebroadcast loses the do-not-retry result
Impact: A caller resuming a pending external lock can receive a generic wallet or proof-wait error even though Core accepted a rebroadcast and the original lock may still confirm.

The post-broadcast proof wait can now terminate with WalletNotFound or AssetLockProofWait, but both resumed Built and Broadcast arms propagate every non-FinalityTimeout error unchanged. A normal resume can start from a persisted Broadcast row with no local proof, successfully rebroadcast the transaction, release its dispatch claim, and then enter wait_for_resumed_proof; removing the wallet or its tracked row before the next poll makes the new check at this line return one of those errors. The existing-lock orchestration only converts FinalityTimeout into the ChainLock fallback, so the disappearance exits before after_acceptance can classify it as TransactionBroadcastUnconfirmed. The FFI caller consequently loses the typed instruction not to build another lock, despite Core having accepted a transaction that may still confirm. Preserve raw lookup errors before dispatch, but map wallet/row disappearance from the Built and Broadcast waits after a send was dispatched or may have been dispatched to TransactionBroadcastUnconfirmed.

Confirmed by an independent pass: A host resuming a persisted Broadcast lock with no local proof can successfully rebroadcast it, then remove the wallet through the public manager API while the resume is waiting for finality. The next proof poll returns a generic FFI error instead of ErrorTransactionBroadcastUnconfirmed, so the caller cannot distinguish the already-dispatched lock from a failure before dispatch and loses the instruction not to fund a replacement.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bd1d040: once a resume has approved a row whose lock may be on the network (Built, Broadcast, InstantSendLocked, ChainLocked), the wallet, its generation or the row disappearing before the resume ends is TransactionBroadcastUnconfirmed. A refusal before the row is approved keeps its raw error. The conversion happens at one choke point, resume_authorized_asset_lock, which every resume entry point goes through (resume_asset_lock, the authorized top-up and Platform-address resumes, and the FFI asset_lock_manager_resume / catch-up). after_acceptance now treats a replaced wallet generation as gone (tracks_own_lock), so the identity top-up and Platform-address ChainLock fallbacks no longer leak a raw WalletNotFound either. Test: should_report_a_resume_whose_wallet_or_row_is_removed_during_its_wait_as_unknown covers Built and Broadcast × row, wallet and generation. offline_broadcast_resume_preserves_wallet_removal_during_refresh now expects the unknown outcome: a Broadcast row may have been sent by an earlier attempt.

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 9de8e69d): Confirmed that after a Built or Broadcast row is approved, a disappearance error goes through after_acceptance, whose tracking check is generation-aware. A failed wait after the rebroadcast now preserves the unconfirmed outcome.

tokio::pin!(notified);
notified.as_mut().enable();

self.ensure_lock_still_tracked(out_point).await?;

@thepastaclaw thepastaclaw Dec 1, 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 9de8e69d; see the replies below.

🟡 Suggestion: A proof lookup can update a replacement wallet generation after the liveness check passes
Impact: If a wallet is removed and the same wallet ID is reloaded while a proof lookup is suspended, the old operation can attach its result to the replacement row instead of reporting that its generation disappeared.

The new generation and row check is only a point-in-time check. After it succeeds, record_chain_proof_height, located_chain_proof_height, or the record/persister lookup can suspend; the wallet can then be removed and recreated with the same ID and outpoint. A successful lookup returns to the resume path, whose advance_asset_lock_status mutation looks up only wallet ID and outpoint and does not verify the captured generation, so it can update the replacement row. The already-chain-locked fast path has the same gap because it can return without another poll check. Bind the generation check to the guard that mutates the row, or make the status update reject a different generation, so a stale proof operation cannot advance replacement state.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bd1d040: every row mutation of an AssetLockManager checks the manager's generation under the same write guard. That covers advance_asset_lock_status(_if), advance_asset_lock_status_clearing_proof_if, consume_asset_lock, mark_asset_lock_consumption_unknown, untrack_asset_lock, complete_wallet_drain, hydrate_wallet_drain and recover_asset_lock_blocking. A stale proof operation therefore cannot advance the replacement's row, including through the already-chain-locked fast path. Test: should_not_advance_the_row_of_a_replacement_wallet_generation.

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 9de8e69d): Confirmed that advance_asset_lock_status_if compares the captured generation under the write guard before accessing the row. A proof lookup that finishes after replacement can no longer advance that replacement row through this path.

romchornyi and others added 3 commits December 3, 2026 18:43
…ntity-fr (45f4b64)

The base took V025 for the identity recipient, so the Platform-address
recipients migration moves to V026 (SCHEMA.md, the rewind and the pinned
fingerprints follow). The recipient mismatch joins the payment classes the
base added (LockHeld, as the identity mismatch), its panic guard carries the
panicked payment class, and the accepted-lock error conversion counts a
replaced wallet generation as a removed row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… own wallet generation

A resume that approved a Built, Broadcast, InstantSendLocked or ChainLocked
row reports its wallet, generation or row disappearing before it ends as
TransactionBroadcastUnconfirmed: the lock may be out, so the caller must not
fund another. A refusal before the row was approved keeps its own error.

Every row mutation of an AssetLockManager (status advances, consume,
consumption-unknown, untrack, drain completion and hydration, recovery
insert) now checks the manager's generation under the guard that writes, so
a proof lookup that outlived a wallet re-created under the same id cannot
advance the replacement's row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… host that only reads its recipients

A host that wires the recipients loader but not the writer can resume a
recorded external payment, and every later write of that row (proof,
consumed) carries the recipients it read back. The store used to fail that
round for the missing writer, so an atomic host rolled the completion back
while the caller saw success, and the next restore offered the paid lock
again. The persister now remembers the recipients each load returned and
commits a write carrying exactly those as a status-only update: the column
is immutable and the host already holds it. Recipients it did not read back
still fail the round, so none are silently dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@romchornyi

Copy link
Copy Markdown
Contributor Author

Round 14 is pushed in 08d77e9 (merge of the base 45f4b64: the Platform-address recipients migration moves to V026), bd1d040 and 2cf38fb; the threads name the sites.

On the suggested decision (land a fail-closed recovery contract first and drop the external recovery path here): the external recovery path stays, because the dashwallet-ios Core → someone else's Platform address route resumes through it. This round closes both gaps the bot named inside that path. The full recovery contract stays tracked in #5938.

…ntity-fr (529c41c)

The base moved the identity top-up's IS-timeout ChainLock fallback under
`with_funded_lock`; the Platform-address fallback now runs under the same
seam, both keeping the unknown outcome for a wallet or row gone after the
broadcast. Registry row 61 keeps the base's wording plus the
Platform-address recipient mismatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Changes requested: 3 blockers

  • Fresh external funding reports “maybe sent” when the request is refused before build — packages/rs-platform-wallet/src/wallet/asset_lock/build.rs:1458-1460 (new)
    Impact: A host that follows MaybeSent waits for a payment with no outpoint when recipient persistence is unavailable or local preflight rejects the request.
  • A host with no asset-lock row writer can report a successful status write — packages/rs-platform-wallet-ffi/src/persistence.rs:3583-3591 (new)
    Impact: A host that reopens a saved external payment with the restore callbacks but neither asset-lock writer can complete it and see the already-paid lock listed as pending after restart.
  • Resuming with the wrong account reports “not sent” for an already-broadcast lock — packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:443-445 (new; not shown inline, see below)
    Impact: A host restoring a pending external payment in a multi-account wallet gets NotSent and no held outpoint if it selects the wrong account, even though the payment still holds Core funds.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This round ties asset-lock resume and live status writes to the original wallet generation, allows hosts that can read payees and write the base row to save status without rewriting the payees, and applies the funded-lock error handling to the Platform-address ChainLock fallback. Kotlin SDK build and emulator tests passed; the review check is pending, and no standalone Rust test result is listed for this head.

A pattern across this PR's review rounds

This is review round 15, and the PR has drawn 24 blocking findings so far. 8 of them share 3 underlying causes. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.

1. Reading payees does not guarantee a durable resume (2 new in this round, 2 earlier finding(s))

Fresh funding commits the row, payees, and signing pool together before broadcast, but recorded-recipient recovery has no corresponding guarantee that the host can durably advance that same row. FFIPersister now uses a cached payee match to skip the sidecar write without establishing that the host still has the row or can update it. The fixes have moved the failure from restoring the payment to recording its proof or completion.

Already tracked: #5938

In this round: A host with no asset-lock row writer can report a successful status write; Cached payees can let a deleted asset-lock row be recreated without them

2. The wallet generation is checked at individual steps (1 new in this round, 3 earlier finding(s))

AssetLockManager checks the wallet generation and tracked row at individual steps rather than tying the operation and its writes to the row it authorized. The checks added to stop proof waits or protect live state do not cover a separate durable write: hydrate_wallet_drain can call persist_drain_lock_snapshot before checking the generation for live publication.

In this round: A drain retry can save an old checkpoint before rejecting the wallet generation

3. Early errors lose dispatch context (2 new in this round, 1 earlier finding(s))

The wallet adds dispatch context at selected steps, but fund_from_asset_lock_inner can return a validation or persistence error before reaching with_funded_lock, leaving PaymentDelivery to classify the error by its type alone. That is why a fresh request refused before build can look possibly sent, while a wrong-account resume can look unsent even though its lock is already Broadcast.

Already tracked: #6286

In this round: Fresh external funding reports “maybe sent” when the request is refused before build; Resuming with the wrong account reports “not sent” for an already-broadcast lock

Suggested decision (land the prerequisite first): Land a fail-closed asset-lock recovery contract before enabling the new external funding path. A resume with recorded payees must be tied to the exact row and wallet generation it authorized, on a backend that can preserve the payees and durably advance the row; the wallet must report delivery from the payment's dispatch state, not the error type. If that prerequisite does not land first, keep saved payees readable but leave the new funding and resume paths that depend on it disabled.

🔴 3 blocking | 🟡 3 suggestion(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

🔴 Blocking: Resuming with the wrong account reports “not sent” for an already-broadcast lock
Impact: A host restoring a pending external payment in a multi-account wallet gets NotSent and no held outpoint if it selects the wrong account, even though the payment still holds Core funds.
packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:443-445

The failure tells the host nothing is held for this payment, so it can offer fresh funding instead of directing the caller back to the original lock. A lock broadcast before restart can restore as Broadcast; the public platform_address_wallet_resume_fund_from_asset_lock_external_signer accepts that outpoint, the original payees and a caller-selected account index. If the caller selects another valid account, the remainder membership check correctly returns AddressNotFound, but this ? returns before the resolver or with_funded_lock runs. The newly merged delivery API exposes that error as NotSent with no held outpoint. Use the supplied funding and current tracked status to classify this refusal, as the base now does in pre_submit_top_up_error: keep the account diagnostic, and report the original outpoint as held when it is a matching, tracked, resumable lock. Cover the two-account case through the public resume path.

Raised on code unchanged since the last review, and confirmed by an independent pass: After restoring a broadcast external-payment lock, a caller can pass its outpoint and original payees to platform_address_wallet_resume_fund_from_asset_lock_external_signer but select a different valid Platform account from the one holding the remainder address. The wallet correctly refuses the account mismatch, but reports NotSent with no held outpoint even though the same payment still has Core funds in its resumable lock. A host following that result can offer fresh funding instead of directing the caller back to the existing lock.

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

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — This is a large, intricate change that alters funds movement and coin-selection behavior in asset-lock construction and recovery, while also introducing a storage migration and persistence semantics.
  • 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)
  • New since the last final review (39c7f656): 3 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 3 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): Reading payees does not guarantee a durable resume; The wallet generation is checked at individual steps; Early errors lose dispatch context. When you fix the findings below, fix the cause, not only the reported case. The review suggests (land the prerequisite first): Land a fail-closed asset-lock recovery contract before enabling the new external funding path. A resume with recorded payees must be tied to the exact row and wallet generation it authorized, on a backend that can preserve the payees and durably advance the row; the wallet must report delivery from the payment's dispatch state, not the error type. If that prerequisite does not land first, keep saved payees readable but leave the new funding and resume paths that depend on it disabled. If that decision is not yours to make, say so to the PR's author or maintainer.

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:1458-1460: Fresh external funding reports “maybe sent” when the request is refused before build
  Impact: A host that follows `MaybeSent` waits for a payment with no outpoint when recipient persistence is unavailable or local preflight rejects the request.
  A fresh payment that never produced a transaction can leave the host waiting for reconciliation instead of letting it correct the request. Calling the external funding export with valid payees, an owned remainder and a persister missing bit 18 reaches this gate and returns `Persistence` before coin selection, the built callback or either broadcast. The resolver forwards the error unchanged, and the payment-delivery API merged since the last review exposes it through FFI as `MaybeSent`. The same happens at `fund_from_asset_lock.rs:460` when DPP rejects an output below the minimum, or when the SDK protocol version does not activate the transition: both are returned as wrapped SDK protocol errors before funding resolution. Apply `before_dispatch()` where fresh funding is known not to have dispatched, as `529c41c9446` does for external identity top-ups. Keep the original diagnostic and the global error classifications, and assert `NotSent` with no built outpoint.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: A caller of `platform_address_wallet_fund_from_asset_lock_external_signer` can supply valid payees and an owned remainder but use a backend without bit 18. The wallet refuses before coin selection, the built callback, or either broadcast, yet FFI returns `MaybeSent`, directing the host to wait for a payment that cannot appear. The same false result occurs when preflight rejects an explicit output below the DPP minimum or finds the transition inactive at the SDK's protocol version._

In `packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:443-445: Resuming with the wrong account reports “not sent” for an already-broadcast lock
  Impact: A host restoring a pending external payment in a multi-account wallet gets `NotSent` and no held outpoint if it selects the wrong account, even though the payment still holds Core funds.
  The failure tells the host nothing is held for this payment, so it can offer fresh funding instead of directing the caller back to the original lock. A lock broadcast before restart can restore as `Broadcast`; the public `platform_address_wallet_resume_fund_from_asset_lock_external_signer` accepts that outpoint, the original payees and a caller-selected account index. If the caller selects another valid account, the remainder membership check correctly returns `AddressNotFound`, but this `?` returns before the resolver or `with_funded_lock` runs. The newly merged delivery API exposes that error as `NotSent` with no held outpoint. Use the supplied funding and current tracked status to classify this refusal, as the base now does in `pre_submit_top_up_error`: keep the account diagnostic, and report the original outpoint as held when it is a matching, tracked, resumable lock. Cover the two-account case through the public resume path.

  _Raised on code unchanged since the last review, and confirmed by an independent pass: After restoring a broadcast external-payment lock, a caller can pass its outpoint and original payees to `platform_address_wallet_resume_fund_from_asset_lock_external_signer` but select a different valid Platform account from the one holding the remainder address. The wallet correctly refuses the account mismatch, but reports `NotSent` with no held outpoint even though the same payment still has Core funds in its resumable lock. A host following that result can offer fresh funding instead of directing the caller back to the existing lock._

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:3583-3591: A host with no asset-lock row writer can report a successful status write
  Impact: A host that reopens a saved external payment with the restore callbacks but neither asset-lock writer can complete it and see the already-paid lock listed as pending after restart.
  The payment can succeed on Platform without any callback receiving its `Consumed` status. A host can reopen a store containing a `ChainLocked` payment with its proof, funding pool and payees; those load callbacks do not require the optional row writer, and the recorded-recipient resume does not check for that writer before submission. In `consume_asset_lock`, the FFI store skips the base-row upsert at line 3437. The new cache match then skips the missing sidecar writer as well, so the round can report success without writing the status. Keep the payees readable and the status-only path available to hosts with a row writer. Reject the upsert in the FFI adapter when the row writer is missing, and have the wallet refuse recorded-payment submission when the backend cannot persist the lifecycle row: a store error alone is only logged by `queue_asset_lock_changeset`.

  _Confirmed by an independent pass: An FFI host can reopen a store containing an interrupted `ChainLocked` payment with its proof, funding pool, and recorded payees, wiring the restore callbacks but neither asset-lock write callback. The recorded-recipient resume can succeed on Platform, but the persistence adapter acknowledges the `Consumed` update without sending it to any row writer. On the next restart, the paid lock still loads as `ChainLocked` and is offered for resume even though Platform has already consumed it._
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:4469-4477: Cached payees can let a deleted asset-lock row be recreated without them
  Impact: A host with a row writer and a recipient loader but no recipient writer can accept a delayed upsert and later restore the recreated row without its original payees.
  The adapter can report a successful write that drops the payees carried by the snapshot. `load()` only inserts into the cache, a committed `AssetLockChangeSet::removed` does not evict the entry, and a later successful load that omits the row or its payees leaves the same entry behind. If an older snapshot is applied after deletion, the base callback can recreate the row, and the byte match at lines 3583–3590 skips the sidecar write. Immutability protects an existing row, not one recreated after deletion. Invalidate entries on committed removals and replace the cache on a complete successful load, or verify that the sidecar still exists in the current write round. Hosts with a recipient writer do not need this cache. A stateful load–remove–late upsert check would distinguish this case from a valid update to an intact row.

In `packages/rs-platform-wallet/src/wallet/asset_lock/operation.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/asset_lock/operation.rs:408-415: A drain retry can save an old checkpoint before rejecting the wallet generation
  Impact: If a retry of a failed drain checkpoint overlaps same-ID wallet replacement, the retry can return `WalletNotFound` after writing the old signed lock into the replacement wallet’s store.
  The new check from `bd1d040a38` protects live publication but runs after the durable write. A failed initial store leaves the signed checkpoint in the retained operation context, as exercised by `should_retry_rolled_back_drain_checkpoint_without_rebuilding`. On a same-UUID retry with no live or durable row, `hydrate_wallet_drain` takes the retained candidate and calls `persist_drain_lock_snapshot` before comparing generations. That write uses the wallet ID, so replacement between the snapshot read and the write does not stop it, and the later error cannot undo it. Verify the current generation before writing and hold its lifecycle guard through both checkpoint persistence and live publication.

In `packages/rs-platform-wallet-storage/SCHEMA.md`:
- [SUGGESTION] packages/rs-platform-wallet-storage/SCHEMA.md:973-974: The PR upgrade notes name the wrong migration and capability and promise a fallback that no longer exists
  Impact: An integrator following the PR description can mistake a V025 database for one that already preserves Platform-address payees.
  Only the migration number is stale on this head. The capability and no-fallback wording is correct, and V025 was the right number before the last base merge. Now V025 adds `identity_recipient`, and V026 adds `platform_address_recipients`, as both the migration files and your round-14 update show. The PR description still uses V025 for the storage change, legacy cutoff, test list and breaking-change notes. Update those references to V026; the schema does not need to change.

Comment on lines +1458 to +1460
if platform_address_recipients.is_some() {
self.require_platform_address_recipient_persistence()?;
}

@thepastaclaw thepastaclaw Dec 3, 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 0bf8ce13; see the replies below.

🔴 Blocking: Fresh external funding reports “maybe sent” when the request is refused before build
Impact: A host that follows MaybeSent waits for a payment with no outpoint when recipient persistence is unavailable or local preflight rejects the request.

A fresh payment that never produced a transaction can leave the host waiting for reconciliation instead of letting it correct the request. Calling the external funding export with valid payees, an owned remainder and a persister missing bit 18 reaches this gate and returns Persistence before coin selection, the built callback or either broadcast. The resolver forwards the error unchanged, and the payment-delivery API merged since the last review exposes it through FFI as MaybeSent. The same happens at fund_from_asset_lock.rs:460 when DPP rejects an output below the minimum, or when the SDK protocol version does not activate the transition: both are returned as wrapped SDK protocol errors before funding resolution. Apply before_dispatch() where fresh funding is known not to have dispatched, as 529c41c9446 does for external identity top-ups. Keep the original diagnostic and the global error classifications, and assert NotSent with no built outpoint.

Raised on code unchanged since the last review, and confirmed by an independent pass: A caller of platform_address_wallet_fund_from_asset_lock_external_signer can supply valid payees and an owned remainder but use a backend without bit 18. The wallet refuses before coin selection, the built callback, or either broadcast, yet FFI returns MaybeSent, directing the host to wait for a payment that cannot appear. The same false result occurs when preflight rejects an explicit output below the DPP minimum or finds the transition inactive at the SDK's protocol version.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in ac9d848: every fresh Platform-address funding refused before its lock is built is before_dispatch() (NotSent, no outpoint, diagnostic kept), using the built flag of top_up_external_identity_with_funding. Applied at the bit-18 gate (require_platform_address_recipient_persistence) and every resolver error before on_asset_lock_built, and at the one pre-flight preflight_funding: validate_recipient_addresses, remainder_fee_strategy, validate_funding_transition (inactive transition, output below minimum, too many outputs), the funding floor and PlatformAddressRecipients::new. Tests assert NotSent for each refusal kind.

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 0bf8ce13): Your fresh-funding preflight and resolver errors before the built callback now go through before_dispatch(). Missing persistence and DPP validation refusals return NotSent without an outpoint.

Comment on lines +3583 to +3591
let loaded = self
.loaded_platform_address_recipients
.lock()
.get(&(wallet_id, entry.out_point))
.is_some_and(|stored| *stored == bytes);
if !loaded {
outcome.record(1);
}
continue;

@thepastaclaw thepastaclaw Dec 3, 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 0bf8ce13; see the replies below.

🔴 Blocking: A host with no asset-lock row writer can report a successful status write
Impact: A host that reopens a saved external payment with the restore callbacks but neither asset-lock writer can complete it and see the already-paid lock listed as pending after restart.

The payment can succeed on Platform without any callback receiving its Consumed status. A host can reopen a store containing a ChainLocked payment with its proof, funding pool and payees; those load callbacks do not require the optional row writer, and the recorded-recipient resume does not check for that writer before submission. In consume_asset_lock, the FFI store skips the base-row upsert at line 3437. The new cache match then skips the missing sidecar writer as well, so the round can report success without writing the status. Keep the payees readable and the status-only path available to hosts with a row writer. Reject the upsert in the FFI adapter when the row writer is missing, and have the wallet refuse recorded-payment submission when the backend cannot persist the lifecycle row: a store error alone is only logged by queue_asset_lock_changeset.

Confirmed by an independent pass: An FFI host can reopen a store containing an interrupted ChainLocked payment with its proof, funding pool, and recorded payees, wiring the restore callbacks but neither asset-lock write callback. The recorded-recipient resume can succeed on Platform, but the persistence adapter acknowledges the Consumed update without sending it to any row writer. On the next restart, the paid lock still loads as ChainLocked and is offered for resume even though Platform has already consumed it.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d770179: the FFI persister never acknowledges an asset-lock row write, or a recipient record, that no host writer took, and the wallet never submits a resumed external payment on a backend that cannot write its row. Applied at FFI store (a round with asset-lock upserts or removals fails without on_persist_asset_locks_fn; the cached-recipients skip requires that the row writer took the row in the same round) and at a new TRACKED_ASSET_LOCKS gate in the pre-flight of every external resume (the recorded-recipient resume and fund_from_asset_lock_external with an existing lock), refused before submission with the lock held. Hosts with a row writer and a recipient loader keep the status-only path.

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 0bf8ce13): Your FFI adapter now rejects nonempty lock writes without a row callback, and both external resume routes check tracked-row capability before submission. Restoring the payees alone no longer authorizes submission on a backend that cannot acknowledge the row write.

Comment on lines +4469 to +4477
let mut loaded = self.loaded_platform_address_recipients.lock();
for lock in wallet_state
.unused_asset_locks
.values()
.flat_map(|locks| locks.values())
{
if let Some(recipients) = &lock.platform_address_recipients {
loaded.insert((entry.wallet_id, lock.out_point), recipients.to_bytes());
}

@thepastaclaw thepastaclaw Dec 3, 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 0bf8ce13; see the replies below.

🟡 Suggestion: Cached payees can let a deleted asset-lock row be recreated without them
Impact: A host with a row writer and a recipient loader but no recipient writer can accept a delayed upsert and later restore the recreated row without its original payees.

The adapter can report a successful write that drops the payees carried by the snapshot. load() only inserts into the cache, a committed AssetLockChangeSet::removed does not evict the entry, and a later successful load that omits the row or its payees leaves the same entry behind. If an older snapshot is applied after deletion, the base callback can recreate the row, and the byte match at lines 3583–3590 skips the sidecar write. Immutability protects an existing row, not one recreated after deletion. Invalidate entries on committed removals and replace the cache on a complete successful load, or verify that the sidecar still exists in the current write round. Hosts with a recipient writer do not need this cache. A stateful load–remove–late upsert check would distinguish this case from a valid update to an intact row.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-astra (phase2-reviewer: general, architecture-layering, ffi-engineer, platform-versioning, rust-quality, security-auditor)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in d770179: the loaded-recipients cache holds only what the host still holds. It is replaced as a whole by each complete, successful load (a failed load keeps nothing), and an entry is forgotten once the row writer takes its removal. Wallet removal: re-registering a wallet under the same id always runs a complete load first (wallet_lifecycle.rs), which replaces the cache, so no separate hook was added.

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 0bf8ce13): Your removal path now evicts the cached bytes, and a complete successful load replaces the cache under the round lock. A delayed upsert no longer gets a successful acknowledgement from a deleted row's cached payees.

Comment on lines 411 to 415
let mut manager = self.wallet_manager.write().await;
let info = manager
.get_wallet_info_mut(&self.wallet_id)
.filter(|info| Arc::ptr_eq(&info.generation, &self.generation))
.ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id)))?;

@thepastaclaw thepastaclaw Dec 3, 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 0bf8ce13; see the replies below.

🟡 Suggestion: A drain retry can save an old checkpoint before rejecting the wallet generation
Impact: If a retry of a failed drain checkpoint overlaps same-ID wallet replacement, the retry can return WalletNotFound after writing the old signed lock into the replacement wallet’s store.

The new check from bd1d040a38 protects live publication but runs after the durable write. A failed initial store leaves the signed checkpoint in the retained operation context, as exercised by should_retry_rolled_back_drain_checkpoint_without_rebuilding. On a same-UUID retry with no live or durable row, hydrate_wallet_drain takes the retained candidate and calls persist_drain_lock_snapshot before comparing generations. That write uses the wallet ID, so replacement between the snapshot read and the write does not stop it, and the later error cannot undo it. Verify the current generation before writing and hold its lifecycle guard through both checkpoint persistence and live publication.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 0bf8ce1: a durable asset-lock write that follows a generation check is made under the generation's lifecycle gate, with the check first. Applied at hydrate_wallet_drain (gate taken without waiting, as the build does under shield_guard; generation checked before the "already tracked" check and before persist_drain_lock_snapshot, held through the publication) and at mark_asset_lock_consumption_unknown; both tested with teardown in progress and with a replaced generation.

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 0bf8ce13): Your drain retry now acquires the lifecycle guard without waiting and checks the generation before either accepting a tracked row or saving the checkpoint. The guard stays held through publication.

Comment on lines 973 to +974
| V025 | `V025__asset_lock_identity_recipient.rs` | Adds the nullable `asset_locks.identity_recipient BLOB` column (CHECK: NULL or exactly 32 bytes, the identity id) recording the identity an unbound identity top-up (`IdentityTopUpNotBound`) was built, or later assigned, to pay, so a resume after restart pays that identity and refuses another; the lifecycle blob is untouched. Adds the `asset_locks_identity_recipient_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `identity_recipient`. Purely additive; existing rows read back NULL, and an unbound top-up row without a recipient is unassigned until one is assigned. |
| V026 | `V026__asset_lock_platform_address_recipients.rs` | Adds the nullable `asset_locks.platform_address_recipients BLOB` column (CHECK: NULL or 1–4096 bytes, the wallet's opaque `PlatformAddressRecipients::to_bytes` form) recording the Platform addresses an external Platform-address funding (`fund_from_asset_lock_external`) was built to pay, so a resume after restart pays those recipients and refuses anything else, an owned funding included; the lifecycle blob is untouched. Adds the `asset_locks_platform_address_recipients_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `platform_address_recipients`. A stored value that cannot be read fails the load. Consumed rows that record recipients stay in the unconsumed feed as tombstones, like consumed identity-recipient rows. Purely additive; existing rows read back NULL: an owned funding, or an external funding tracked before V026 whose payees only the host recorded. |

@thepastaclaw thepastaclaw Dec 3, 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 0bf8ce13; see the replies below.

🟡 Suggestion: The PR upgrade notes name the wrong migration and capability and promise a fallback that no longer exists
Impact: An integrator following the PR description can mistake a V025 database for one that already preserves Platform-address payees.

Only the migration number is stale on this head. The capability and no-fallback wording is correct, and V025 was the right number before the last base merge. Now V025 adds identity_recipient, and V026 adds platform_address_recipients, as both the migration files and your round-14 update show. The PR description still uses V025 for the storage change, legacy cutoff, test list and breaking-change notes. Update those references to V026; the schema does not need to change.

source: gpt-6.2-astra (phase2-reviewer: general, ffi-engineer)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: the PR description now says V026 for the storage change, the legacy cutoff, the test list and the breaking-change notes (V025 on #5931's branch adds identity_recipient).

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 0bf8ce13): Your description now uses V026 for the storage change, legacy cutoff, test list, and breaking notes. That matches the migration files: V025 adds the identity recipient and V026 adds the Platform-address recipients.

Comment on lines +3565 to +3570
let Some(cb) = self
.tracked_masternodes_callbacks
.persist_asset_lock_platform_address_recipients
else {
outcome.record(1);
continue;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Resolved (re-reviewed at 9de8e69d): Confirmed for the configuration you addressed: with a working row writer and recipient loader, exact read-back bytes let the intact row's Consumed update commit without the sidecar writer. The case with no base-row writer is separate.

tokio::pin!(notified);
notified.as_mut().enable();

self.ensure_lock_still_tracked(out_point).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.

Resolved (re-reviewed at 9de8e69d): Confirmed that after a Built or Broadcast row is approved, a disappearance error goes through after_acceptance, whose tracking check is generation-aware. A failed wait after the rebroadcast now preserves the unconfirmed outcome.

tokio::pin!(notified);
notified.as_mut().enable();

self.ensure_lock_still_tracked(out_point).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.

Resolved (re-reviewed at 9de8e69d): Confirmed that advance_asset_lock_status_if compares the captured generation under the write guard before accessing the row. A proof lookup that finishes after replacement can no longer advance that replacement row through this path.

Comment on lines +173 to +180
/// The Platform addresses an external Platform-address funding
/// (`fund_from_asset_lock_external`) was built to pay survive store/load
/// with its row, so a resume after restart pays those recipients or is
/// refused, and never consumes the lock as an owned top-up. Required, as
/// [`Self::ASSET_LOCK_IDENTITY_RECIPIENTS`] is: nothing on chain names the
/// payee, and a backend that lost the record would reload the lock as an
/// owned one, so the wallet builds no external funding for it.
pub const ASSET_LOCK_PLATFORM_ADDRESS_RECIPIENTS: Self = Self(1 << 18);

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 9de8e69d): Your V025 correction matched the earlier head, and the capability and no-fallback wording still matches the code. The round-14 update correctly says V026 after the merge, but the current PR description still uses V025 for both the storage change and the legacy cutoff.

romchornyi and others added 3 commits December 3, 2026 23:51
… its lock from the funding

A fresh Platform-address funding refused before its lock is built (the
recipient-persistence capability gate, an inactive or structurally invalid
transition, an output below the minimum) is now `before_dispatch()`:
NotSent with no outpoint, keeping its diagnostic. The `built` flag mirrors
`top_up_external_identity_with_funding`: only an error before the
`on_asset_lock_built` report is classed so.

A resume refused before submission (the pre-flight with a wrong account, a
recorded-recipient resume of a lock that records no recipients or whose
remainder no account holds, the resolver's first check of a row that no
longer records the recipients) names a tracked, resumable
Platform-address lock as held, keeping its diagnostic, as
`pre_submit_top_up_error` does for top-ups. Applied to all three resume
entry points.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…st writer took

The FFI persister now fails a round that carries asset-lock upserts or
removals when the host wired no asset-lock row writer, instead of dropping
the rows and reporting success. The recipients a load read back stand in for
a missing recipient writer only when the row itself reached the host's
writer in the same round, and only while the host still holds them: the
cache is replaced by each complete, successful load (a failed load keeps
nothing of it), and an entry is forgotten once the row writer takes the
row's removal. A wallet registered again under an id runs a complete load
first, which replaces its entries.

The wallet refuses to resume an external Platform-address funding (the
recorded-recipient resume and `fund_from_asset_lock_external` with an
existing lock) on a backend without `TRACKED_ASSET_LOCKS`, before anything
is submitted, naming the lock as held. Hosts with a row writer and a
recipient loader keep the status-only path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…kpoint or consumption marker is stored

`hydrate_wallet_drain` wrote a retained drain checkpoint under the wallet id
before comparing generations, so a retry overlapping a same-id wallet
replacement could write the old signed lock into the replacement's store.
It now takes the generation's lifecycle gate (without waiting, as the build
does: a drain arrives holding `shield_guard`) and checks the generation
first, including the early "already tracked" check, and holds the gate
through the checkpoint write and the live publication.

`mark_asset_lock_consumption_unknown` stored its marker after the
generation-checked publication with no gate held; it now holds the same
gate from the check through the store.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@romchornyi

Copy link
Copy Markdown
Contributor Author

Re: Resuming with the wrong account reports “not sent” for an already-broadcast lock (fund_from_asset_lock.rs:443-445, not inline)

Fixed in ac9d848: every refusal before submission of a resume of a tracked, resumable Platform-address lock names the outpoint as held and keeps its diagnostic, as pre_submit_top_up_error does (pre_submit_funding_error). Applied at the pre-flight of owned and external FromExistingAssetLock, the "records no recipients" and account_holding_remainder refusals of resume_platform_address_funding_to_recorded_recipients, and the resolver's first-pass "no longer records" check, which now uses hold_resumable_lock like the claim's re-check. A two-account wrong-account resume is tested through the public resume paths (should_hold_the_lock_when_a_resume_names_the_wrong_account); consumed and untracked locks name no lock.

@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

Changes requested: 2 blockers

  • A host can broadcast an external payment that neither wallet resume API will accept — packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:441-445 (new)
    Impact: A custom FFI host declaring the documented fresh-funding composite can leave the user's Core funds locked and the recipient unpaid after a restart, even though the host restores the payment correctly.
  • Restoring a wallet with historical asset locks can freeze durable Core sync — packages/rs-platform-wallet-ffi/src/persistence.rs:3468-3472 (new)
    Impact: A supported FFI host that persists Core history but does not install the optional asset-lock row writer can lose the affected Core batch and stop saving sync progress.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This round distinguishes fresh funding refusals from refusals that leave a tracked lock held, tightens FFI asset-lock write acknowledgements, and guards drain checkpoints and consumption markers against wallet replacement. The Kotlin SDK emulator build and tests passed; the review check is pending, and no standalone Rust check is listed for this head. The head does not merge cleanly with the current stacked base: asset_lock/sync/proof.rs conflicts with d52d22c6e42.

A pattern across this PR's review rounds

This is review round 16, and the PR has drawn 26 blocking findings so far. 5 of them share one underlying cause. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.

1. Saving a payment does not guarantee it can be resumed (3 new in this round, 4 earlier finding(s))

Fresh funding checks EXTERNAL_PLATFORM_ADDRESS_FUNDING, but both external resume paths separately require TRACKED_ASSET_LOCKS, so a backend can accept a payment it cannot resume after restart. FFIPersister::store receives the same AssetLockChangeSet for required payment writes and optional Core scan rows, and uses a callback result and cached payees to decide whether it updated the saved payment. Making missing writes fail closed at that shared boundary moved the problem: a historical scan can now lose its durable checkpoint, and a retryable row write can be reported as fatal even after rollback.

Already tracked: #5938

In this round: A host can broadcast an external payment that neither wallet resume API will accept; Restoring a wallet with historical asset locks can freeze durable Core sync; Retryable asset-lock writes become fatal, while rejected writes can still change the row

Suggested decision (land the prerequisite first): Land a persistence contract for external asset-lock payments before enabling them in this PR. A backend admitted before broadcast must also support restart and durable updates to the exact saved payment row, preserving its payees and reporting whether the update committed or rolled back; optional Core scan rows must not depend on that guarantee. If that contract does not land first, keep saved payees readable but gate fresh external funding and the new recorded-payment submission paths.

🔴 2 blocking | 🟡 1 suggestion(s)

Follow-up candidates (optional) (1)

New non-blocking observations on code unchanged since the last full review. No inline threads are opened for them and later reviews do not repeat them: fix forward or track separately if they are worth it.

🟡 Suggestion: Rust callers lose the typed reason for a rejected funding map
Impact: A Rust caller submitting a below-minimum output or too many outputs now gets None from PlatformWalletError::consensus_error() instead of the specific DPP rejection.
packages/rs-platform-wallet/src/error.rs:1860

Callers using the public accessor can no longer tell which validation rule refused the request. Commit ac9d8487008 correctly changes fresh preflight failures to NotSent, but before_dispatch() wraps the SDK error in RefusedBeforeDispatch and the accessor matches only the outer variant. The two updated tests now unwrap with dispatched_source() themselves; FFI already does the equivalent in its conversion. Have the accessor look through delivery wrappers and keep the direct diagnostic assertions alongside the new NotSent assertions.

        match self.dispatched_source() {

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

Review provenance

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

  • Triage: critical by gpt-6.2-sol (effort low) — This is a large, intricate change that directly alters wallet funds movement, asset-lock recovery and resume behavior, durable storage, and FFI safety in functions such as fund_from_asset_lock_external and resume_platform_address_funding_to_recorded_recipients.
  • 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)
  • New since the last final review (9de8e69d): 2 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 2 confirmed; 1 suggestion(s) on unchanged code listed as follow-up candidates
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): Saving a payment does not guarantee it can be resumed. When you fix the findings below, fix the cause, not only the reported case. The review suggests (land the prerequisite first): Land a persistence contract for external asset-lock payments before enabling them in this PR. A backend admitted before broadcast must also support restart and durable updates to the exact saved payment row, preserving its payees and reporting whether the update committed or rolled back; optional Core scan rows must not depend on that guarantee. If that contract does not land first, keep saved payees readable but gate fresh external funding and the new recorded-payment submission paths. If that decision is not yours to make, say so to the PR's author or maintainer.

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/platform_addresses/fund_from_asset_lock.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs:441-445: A host can broadcast an external payment that neither wallet resume API will accept
  Impact: A custom FFI host declaring the documented fresh-funding composite can leave the user's Core funds locked and the recipient unpaid after a restart, even though the host restores the payment correctly.
  An interrupted payment cannot be completed through either wallet resume API on the same backend that was allowed to fund it. A host can wire the row writer, restore and recipient callbacks, funding-pool callbacks, and transaction brackets, then declare the documented fresh-funding bits 0, 2, and 18. FFI intersects callback support with that declaration, so the host passes the fresh-build gate without bit 9. If the app exits after Core broadcast but before Platform submission, both `resume_platform_address_funding_to_recorded_recipients` and `fund_from_asset_lock_external(FromExistingAssetLock, …)` reach the new bit-9 check and refuse before submission; owned resume correctly rejects the recorded payees. The new refusal test creates its payment row under that same mask. Include `TRACKED_ASSET_LOCKS` in the fresh-funding composite so the incomplete configuration is refused before build, and retain the narrower resume requirement for hosts that can update a row but cannot write new payees.

  _Confirmed by an independent pass: An FFI host with working persistence callbacks that declares the documented fresh-funding bits 0, 2, and 18 can call `fund_from_asset_lock_external` and broadcast a Core asset lock. If the app exits after Core broadcast but before Platform submission, both external resume APIs reject the restored lock on the same backend because bit 9 is absent. The owned resume also rejects the recorded recipients, leaving the recipient unpaid and the funds locked until the host changes its capability declaration._

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [BLOCKING] packages/rs-platform-wallet-ffi/src/persistence.rs:3468-3472: Restoring a wallet with historical asset locks can freeze durable Core sync
  Impact: A supported FFI host that persists Core history but does not install the optional asset-lock row writer can lose the affected Core batch and stop saving sync progress.
  Restoring a seed and scanning a historical asset-lock funding transaction can freeze the wallet's durable Core sync height for the session. The scan emits a `BlockProcessed` record for the funding account; the wallet bridge reconstructs a tracked lock and attaches it to the same changeset as the Core records without checking whether the backend maintains that mirror. The new missing-writer branch fails the whole round, so an atomic host rolls back the Core writes too. `commit_wallet` then latches the wallet's persistence fault and strips subsequent `synced_height` advances. No funding or resume call is needed to trigger this. Distinguish optional sync-mirror rows from required payment writes when the wallet prepares its changesets, so a Core-only host can commit its history and watermark without weakening the durable payment-row requirement.

  _Confirmed by an independent pass: A user can restore a seed and start Core sync on an FFI host that persists Core history atomically but does not wire the optional asset-lock row writer. When the scan finds a historical asset lock paying one of the restored wallet's funding accounts, the bridge adds the reconstructed lock to the same changeset as the Core records, and the missing writer now causes the entire round to roll back. The bridge then freezes that wallet's durable sync height for the rest of the session._
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:3622-3630: Retryable asset-lock writes become fatal, while rejected writes can still change the row
  Impact: A host that can read but not write payees can lose the retry verdict on a temporary database error or, without rollback, persist a row from an upsert Rust rejects.
  A status update whose saved payees match can return `Fatal` after a successful rollback of ordinary database contention. When the row callback returns `PLATFORM_WALLET_PERSIST_RC_TRANSIENT`, the new `asset_lock_rows_written` check skips the cache match and adds `outcome.record(1)`, which outranks the host's transient result. The reverse ordering also matters: after a removal evicts the cached payees, a delayed upsert reaches the base-row callback before Rust checks the cache miss. A supported non-atomic host that commits each callback independently can recreate the row without payees even though `store()` returns `Err`; the current no-op row writer test observes only the return value. Check whether each status-only upsert has matching saved payees before sending it to the row writer, and let the row callback's actual result determine the error class for eligible writes.

Comment on lines +441 to +445
if ownership == RecipientOwnership::ExternalExplicitOutputs
&& matches!(funding, AssetLockFunding::FromExistingAssetLock { .. })
{
self.asset_locks.require_tracked_asset_lock_persistence()?;
}

@thepastaclaw thepastaclaw Dec 3, 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 c22558e6; see the replies below.

🔴 Blocking: A host can broadcast an external payment that neither wallet resume API will accept
Impact: A custom FFI host declaring the documented fresh-funding composite can leave the user's Core funds locked and the recipient unpaid after a restart, even though the host restores the payment correctly.

An interrupted payment cannot be completed through either wallet resume API on the same backend that was allowed to fund it. A host can wire the row writer, restore and recipient callbacks, funding-pool callbacks, and transaction brackets, then declare the documented fresh-funding bits 0, 2, and 18. FFI intersects callback support with that declaration, so the host passes the fresh-build gate without bit 9. If the app exits after Core broadcast but before Platform submission, both resume_platform_address_funding_to_recorded_recipients and fund_from_asset_lock_external(FromExistingAssetLock, …) reach the new bit-9 check and refuse before submission; owned resume correctly rejects the recorded payees. The new refusal test creates its payment row under that same mask. Include TRACKED_ASSET_LOCKS in the fresh-funding composite so the incomplete configuration is refused before build, and retain the narrower resume requirement for hosts that can update a row but cannot write new payees.

Confirmed by an independent pass: An FFI host with working persistence callbacks that declares the documented fresh-funding bits 0, 2, and 18 can call fund_from_asset_lock_external and broadcast a Core asset lock. If the app exits after Core broadcast but before Platform submission, both external resume APIs reject the restored lock on the same backend because bit 9 is absent. The owned resume also rejects the recorded recipients, leaving the recipient unpaid and the funds locked until the host changes its capability declaration.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 4dc5dc9: every backend admitted to a fresh external funding can also finish and resume it. EXTERNAL_PLATFORM_ADDRESS_FUNDING now includes TRACKED_ASSET_LOCKS (and WALLET_RESTORE, which a resume after a restart needs), so a host declaring only bits 0, 2 and 18 is refused before build (NotSent), while resume keeps the narrower bit-9 requirement. Bit 9 in the composite also covers the fresh call's own writes (mark_asset_lock_consumption_unknown, the Consumed row). Applied at the composite in persistence_capabilities.rs (the only fresh gate, require_platform_address_recipient_persistence) and the FFI bit-18 doc; the refusal test covers the missing bit 9 and bit 7, and the resume-gate test now builds under the full composite before the host drops bit 9. SQLite, Swift (#6272) and Kotlin (#6273) declare all of them.

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 c22558e6): Your fresh-funding composite now requires both TRACKED_ASSET_LOCKS and WALLET_RESTORE, so the old three-bit mask cannot reach the builder. Both external resume routes still require only the narrower row-update capability at their persistence gate.

Comment on lines 3468 to +3472
if let Some(ref al_cs) = changeset.asset_locks {
let has_rows = !al_cs.asset_locks.is_empty() || !al_cs.removed.is_empty();
if has_rows && self.callbacks.on_persist_asset_locks_fn.is_none() {
outcome.record(1);
}

@thepastaclaw thepastaclaw Dec 3, 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 c22558e6; see the replies below.

🔴 Blocking: Restoring a wallet with historical asset locks can freeze durable Core sync
Impact: A supported FFI host that persists Core history but does not install the optional asset-lock row writer can lose the affected Core batch and stop saving sync progress.

Restoring a seed and scanning a historical asset-lock funding transaction can freeze the wallet's durable Core sync height for the session. The scan emits a BlockProcessed record for the funding account; the wallet bridge reconstructs a tracked lock and attaches it to the same changeset as the Core records without checking whether the backend maintains that mirror. The new missing-writer branch fails the whole round, so an atomic host rolls back the Core writes too. commit_wallet then latches the wallet's persistence fault and strips subsequent synced_height advances. No funding or resume call is needed to trigger this. Distinguish optional sync-mirror rows from required payment writes when the wallet prepares its changesets, so a Core-only host can commit its history and watermark without weakening the durable payment-row requirement.

Confirmed by an independent pass: A user can restore a seed and start Core sync on an FFI host that persists Core history atomically but does not wire the optional asset-lock row writer. When the scan finds a historical asset lock paying one of the restored wallet's funding accounts, the bridge adds the reconstructed lock to the same changeset as the Core records, and the missing writer now causes the entire round to roll back. The bridge then freezes that wallet's durable sync height for the rest of the session.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f1d7378: optional sync-mirror asset-lock rows never reach a backend that does not keep them, so they cannot fail a Core round; payment rows still fail a round without the writer, and every payment path requires a capability implying the writer before it writes one. Applied at commit_wallet, the one place drain rows join Core records (reconstruction, ChainLock enrichment, sweep removals), which now withholds them without TRACKED_ASSET_LOCKS, as it withholds payment verdicts without DASHPAY_PAYMENTS. Tested with an atomic Core-only backend whose drains reconstruct a lock: the Core rounds commit, synced_height advances, no fault.

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 c22558e6): A host with no row writer now receives the Core changes without the reconstructed rows, so this missing callback cannot freeze the scan height. Hosts that do have a writer but lack the declaration are a separate case.

Comment on lines +3622 to +3630
let loaded = asset_lock_rows_written
&& self
.loaded_platform_address_recipients
.lock()
.get(&(wallet_id, entry.out_point))
.is_some_and(|stored| *stored == bytes);
if !loaded {
outcome.record(1);
}

@thepastaclaw thepastaclaw Dec 3, 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 c22558e6; see the replies below.

🟡 Suggestion: Retryable asset-lock writes become fatal, while rejected writes can still change the row
Impact: A host that can read but not write payees can lose the retry verdict on a temporary database error or, without rollback, persist a row from an upsert Rust rejects.

A status update whose saved payees match can return Fatal after a successful rollback of ordinary database contention. When the row callback returns PLATFORM_WALLET_PERSIST_RC_TRANSIENT, the new asset_lock_rows_written check skips the cache match and adds outcome.record(1), which outranks the host's transient result. The reverse ordering also matters: after a removal evicts the cached payees, a delayed upsert reaches the base-row callback before Rust checks the cache miss. A supported non-atomic host that commits each callback independently can recreate the row without payees even though store() returns Err; the current no-op row writer test observes only the return value. Check whether each status-only upsert has matching saved payees before sending it to the row writer, and let the row callback's actual result determine the error class for eligible writes.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in c22558e: on a host without a recipient writer, whether an upsert carrying recipients may be sent is decided before the row writer sees it, and an ineligible upsert is never sent; for an eligible status-only update the row writer's own return code classes the round. Applied in the FFI store asset-lock section: the round's removals evict cached recipients first (removal plus re-upsert in one round counts as a recreate), and the eligibility filter feeds the row writer and every sidecar. Tested with a recording row writer: no call for the ineligible upsert, and a transient refusal stays transient.

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 c22558e6): Your filter now runs before the row callback and passes only eligible upserts to the sidecars. With matching saved payees and no recipient writer, the row callback's transient refusal is no longer overridden by a missing-sidecar error.

Comment on lines +173 to +180
/// The Platform addresses an external Platform-address funding
/// (`fund_from_asset_lock_external`) was built to pay survive store/load
/// with its row, so a resume after restart pays those recipients or is
/// refused, and never consumes the lock as an owned top-up. Required, as
/// [`Self::ASSET_LOCK_IDENTITY_RECIPIENTS`] is: nothing on chain names the
/// payee, and a backend that lost the record would reload the lock as an
/// owned one, so the wallet builds no external funding for it.
pub const ASSET_LOCK_PLATFORM_ADDRESS_RECIPIENTS: Self = Self(1 << 18);

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 0bf8ce13): Your latest description uses V026 for both the storage change and legacy cutoff, names the implemented capability bits, and records the loss of Copy. It no longer promises an in-memory fallback.

Comment on lines +1458 to +1460
if platform_address_recipients.is_some() {
self.require_platform_address_recipient_persistence()?;
}

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 0bf8ce13): Your fresh-funding preflight and resolver errors before the built callback now go through before_dispatch(). Missing persistence and DPP validation refusals return NotSent without an outpoint.

Comment on lines +3583 to +3591
let loaded = self
.loaded_platform_address_recipients
.lock()
.get(&(wallet_id, entry.out_point))
.is_some_and(|stored| *stored == bytes);
if !loaded {
outcome.record(1);
}
continue;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Resolved (re-reviewed at 0bf8ce13): Your FFI adapter now rejects nonempty lock writes without a row callback, and both external resume routes check tracked-row capability before submission. Restoring the payees alone no longer authorizes submission on a backend that cannot acknowledge the row write.

Comment on lines +4469 to +4477
let mut loaded = self.loaded_platform_address_recipients.lock();
for lock in wallet_state
.unused_asset_locks
.values()
.flat_map(|locks| locks.values())
{
if let Some(recipients) = &lock.platform_address_recipients {
loaded.insert((entry.wallet_id, lock.out_point), recipients.to_bytes());
}

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 0bf8ce13): Your removal path now evicts the cached bytes, and a complete successful load replaces the cache under the round lock. A delayed upsert no longer gets a successful acknowledgement from a deleted row's cached payees.

Comment on lines 411 to 415
let mut manager = self.wallet_manager.write().await;
let info = manager
.get_wallet_info_mut(&self.wallet_id)
.filter(|info| Arc::ptr_eq(&info.generation, &self.generation))
.ok_or_else(|| PlatformWalletError::WalletNotFound(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.

Resolved (re-reviewed at 0bf8ce13): Your drain retry now acquires the lifecycle guard without waiting and checks the generation before either accepting a tracked row or saving the checkpoint. The guard stays held through publication.

Comment on lines 973 to +974
| V025 | `V025__asset_lock_identity_recipient.rs` | Adds the nullable `asset_locks.identity_recipient BLOB` column (CHECK: NULL or exactly 32 bytes, the identity id) recording the identity an unbound identity top-up (`IdentityTopUpNotBound`) was built, or later assigned, to pay, so a resume after restart pays that identity and refuses another; the lifecycle blob is untouched. Adds the `asset_locks_identity_recipient_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `identity_recipient`. Purely additive; existing rows read back NULL, and an unbound top-up row without a recipient is unassigned until one is assigned. |
| V026 | `V026__asset_lock_platform_address_recipients.rs` | Adds the nullable `asset_locks.platform_address_recipients BLOB` column (CHECK: NULL or 1–4096 bytes, the wallet's opaque `PlatformAddressRecipients::to_bytes` form) recording the Platform addresses an external Platform-address funding (`fund_from_asset_lock_external`) was built to pay, so a resume after restart pays those recipients and refuses anything else, an owned funding included; the lifecycle blob is untouched. Adds the `asset_locks_platform_address_recipients_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `platform_address_recipients`. A stored value that cannot be read fails the load. Consumed rows that record recipients stay in the unconsumed feed as tombstones, like consumed identity-recipient rows. Purely additive; existing rows read back NULL: an owned funding, or an external funding tracked before V026 whose payees only the host recorded. |

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 0bf8ce13): Your description now uses V026 for the storage change, legacy cutoff, test list, and breaking notes. That matches the migration files: V025 adds the identity recipient and V026 adds the Platform-address recipients.

romchornyi and others added 4 commits December 4, 2026 01:31
…ntity-fr (d52d22c)

proof.rs `upgrade_to_persisted_chain_lock_proof`: keeps the base's
RecoveredFromChain-preserving advance (three generation-checked
`advance_asset_lock_status_if` steps) and runs the whole advance through
this branch's `after_acceptance` classification, so a refusal after the
lock's acceptance is still classed as the proof wait's is.
tracking.rs: the base's new assignment test sets the
`platform_address_recipients` field this branch adds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nly a backend that can finish it

`EXTERNAL_PLATFORM_ADDRESS_FUNDING` now also requires `TRACKED_ASSET_LOCKS`
(bit 9) and `WALLET_RESTORE` (bit 7). A backend declaring only bits 0, 2
and 18 could broadcast an external payment that both external resume APIs
then refuse for the missing bit 9, and lose its `Consumed` status; such a
backend is now refused before anything is built (NotSent). Resuming still
needs only bit 9. The in-tree SQLite, Swift (#6272) and Kotlin (#6273)
backends declare bits 7, 9 and 18.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…end that keeps them

The wallet-event bridge attached the tracked-asset-lock rows a drain
reconstructs, enriches or sweeps to the same round as its Core records,
whatever the backend. An FFI host without the optional asset-lock row
writer now refuses such rows, so the atomic round rolled back its Core
records and `commit_wallet` latched the wallet's persistence fault,
freezing its durable sync height. `commit_wallet` now withholds those
mirror rows from a backend without `TRACKED_ASSET_LOCKS`, as it withholds
payment verdicts from one without `DASHPAY_PAYMENTS`. The rows a payment
needs never travel this way: each payment path requires the capability
before it writes one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…re the row writer sees it

On a host that reads Platform-address recipients back but cannot write
them, whether an upsert carrying recipients may be sent is now decided
before the asset-lock row writer is called: only a status-only update of a
row the host still holds with exactly those recipients (read back by the
last load, its removal not taken since, this round's removals included) is
sent. Any other is never sent, so a host committing each callback on its
own cannot recreate the row without its payees, and the round fails. For an
eligible update the row writer's own result classes the round, so a
transient refusal stays transient instead of becoming fatal.

Also documents that bit 18 is attested to the wallet only within the
`EXTERNAL_PLATFORM_ADDRESS_FUNDING` composite, and that the sync bridge
sends mirror rows only to a backend with a row writer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 2 only (queue backlog)

Changes requested: 1 blocker

  • Asset locks disappear or reappear after restart on hosts with an undeclared row writer — packages/rs-platform-wallet/src/changeset/core_bridge.rs:1184-1191 (new)
    Impact: Hosts that save and restore tracked rows without declaring bit 9 can lose locks found during a seed scan or see swept locks return as pending after restart.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This head tightens the persistence requirements for fresh external funding, filters sync-derived asset-lock changes by backend capability, and checks status-only upserts before calling the host row writer. GitHub reports the review check pending and no build, test, or lint checks for this SHA; verification was static. The stacked base is 48 commits ahead and has a confirmed merge conflict in packages/rs-platform-wallet/src/error.rs.

A pattern across this PR's review rounds

This is review round 17, and the PR has drawn 27 blocking findings so far. 5 of them share one underlying cause. They are listed with the other findings as usual; fixing the cause is likely to be cheaper than fixing each case.

1. Core scan rows and payment updates share one write contract (1 new in this round, 6 earlier finding(s))

EXTERNAL_PLATFORM_ADDRESS_FUNDING now requires restore and tracked-row writes, but AssetLockChangeSet still uses the same upsert for a Core scan row and for updating an existing payment without changing its payees. FFIPersister::store infers the latter from cached payees, and rejecting writes without a row callback to protect payment status also caused Core scan batches to roll back. commit_wallet now filters scan rows on TRACKED_ASSET_LOCKS, so it can skip them even for legacy FFI hosts with a working writer; restart trusts the saved rows and scan height rather than replaying the skipped changes.

Already tracked: #5938

In this round: Asset locks disappear or reappear after restart on hosts with an undeclared row writer

Suggested decision (land the prerequisite first): Land a separate persistence contract for external asset-lock payments before enabling their submission in this PR. It must let a backend restore the payment and durably update that exact row without changing its payees, with a clear commit or rollback result. Core sync must keep delivering scan rows to hosts that already store them and advance normally on hosts without a row writer. Until that contract lands, keep saved payees readable but gate fresh external funding and submission to recorded payees.

🔴 1 blocking | 🟡 1 suggestion(s)

Review provenance

Source: reviewer 1: gpt-6.2-astra (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-astra (agent: phase2-reviewer, role: ffi-engineer); reviewer 4: gpt-6.2-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.2-astra (agent: phase2-reviewer, role: rust-quality); reviewer 6: gpt-6.2-astra (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.2-sol (effort low) — This large, intricate diff changes funds movement and recovery behavior in asset-lock wallet code, adds a storage migration, and extends persistence and FFI contracts, including functions such as fund_from_asset_lock_external and resume_platform_address_funding_to_recorded_recipients.
  • Phase 1 reviewers: not run (skipped for throughput: 12 PRs queued, above the 10 limit)
  • New since the last final review (0bf8ce13): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-astra — general (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-astra — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
Several findings on this PR share an underlying cause (the review's "pattern" section): Core scan rows and payment updates share one write contract. When you fix the findings below, fix the cause, not only the reported case. The review suggests (land the prerequisite first): Land a separate persistence contract for external asset-lock payments before enabling their submission in this PR. It must let a backend restore the payment and durably update that exact row without changing its payees, with a clear commit or rollback result. Core sync must keep delivering scan rows to hosts that already store them and advance normally on hosts without a row writer. Until that contract lands, keep saved payees readable but gate fresh external funding and submission to recorded payees. If that decision is not yours to make, say so to the PR's author or maintainer.

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/changeset/core_bridge.rs`:
- [BLOCKING] packages/rs-platform-wallet/src/changeset/core_bridge.rs:1184-1191: Asset locks disappear or reappear after restart on hosts with an undeclared row writer
  Impact: Hosts that save and restore tracked rows without declaring bit 9 can lose locks found during a seed scan or see swept locks return as pending after restart.
  The durable tracked-lock list can disagree with Core history even though the host has a working row writer. For a seed restore, `platform_wallet_manager_create` accepts the row writer and restore callbacks but always passes `PersistenceCapabilities::NONE`. When `BlockProcessed` finds a historical funding transaction, the bridge adds the lock to the live map. Before `f1d7378676` the upsert reached the installed writer; now the bit-9 filter drops it while allowing Core history and the scan height to commit. On restart, `build_unused_asset_locks` and `load_from_persistor` restore the tracked list from saved rows, not Core history, and forward sync need not revisit that block. The same filter drops deletions: an extended FFI host can attest atomic `CORE_SWEEP_REMOVAL` without bit 9, and the public owned-funding signer can still save a lock through `queue_asset_lock_changeset` on that host. If a competing spend confirms first, `TransactionsSwept` removes the pending lock from memory, but the filter drops its deletion while the Core sweep and scan height can commit. The saved row then returns in the tracked list on restart. Route sync mutations by actual row-writer support without granting payment capabilities, and keep truly writer-less hosts free of optional upserts. Do not let the durable height advance past a sweep whose deletion of a persisted lock cannot be committed.

  _Confirmed by an independent pass: A host using `platform_wallet_manager_create` with working Core and tracked-lock persistence can restore a seed and discover an unspent historical asset lock during sync. The bridge saves the Core record and advances the scan height but drops the tracked-lock upsert, so after `platform_wallet_manager_load_from_persistor` the lock is missing from the tracked list and cannot be resumed through it. An extended host that declares atomic Core sweep support but omits bit 9 can also save an owned funding lock; if a competing spend causes Core to sweep that transaction, the bridge saves the Core sweep but drops the tracked-lock deletion, so the dead lock reappears on restart._

In `packages/rs-platform-wallet-ffi/src/persistence.rs`:
- [SUGGESTION] packages/rs-platform-wallet-ffi/src/persistence.rs:3521-3522: Asset-lock upsert batches allocate a second copy of the filtered reference list
  Impact: A host persisting asset-lock upserts, including during restore scans, pays an extra allocation and pointer copy for each nonempty filtered batch.
  The row writer can use the filtered list without copying it. `rows` stays in scope for the sidecar callbacks, and `build_asset_lock_entries` only borrows the reference slice. The returned `_storage`, not the cloned reference vector, owns the buffers that must stay alive through the callback.

Comment on lines +1184 to +1191
let asset_locks = if persister
.persistence_capabilities()
.contains(PersistenceCapabilities::TRACKED_ASSET_LOCKS)
{
asset_locks
} else {
AssetLockChangeSet::default()
};

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔴 Blocking: Asset locks disappear or reappear after restart on hosts with an undeclared row writer
Impact: Hosts that save and restore tracked rows without declaring bit 9 can lose locks found during a seed scan or see swept locks return as pending after restart.

The durable tracked-lock list can disagree with Core history even though the host has a working row writer. For a seed restore, platform_wallet_manager_create accepts the row writer and restore callbacks but always passes PersistenceCapabilities::NONE. When BlockProcessed finds a historical funding transaction, the bridge adds the lock to the live map. Before f1d7378676 the upsert reached the installed writer; now the bit-9 filter drops it while allowing Core history and the scan height to commit. On restart, build_unused_asset_locks and load_from_persistor restore the tracked list from saved rows, not Core history, and forward sync need not revisit that block. The same filter drops deletions: an extended FFI host can attest atomic CORE_SWEEP_REMOVAL without bit 9, and the public owned-funding signer can still save a lock through queue_asset_lock_changeset on that host. If a competing spend confirms first, TransactionsSwept removes the pending lock from memory, but the filter drops its deletion while the Core sweep and scan height can commit. The saved row then returns in the tracked list on restart. Route sync mutations by actual row-writer support without granting payment capabilities, and keep truly writer-less hosts free of optional upserts. Do not let the durable height advance past a sweep whose deletion of a persisted lock cannot be committed.

Confirmed by an independent pass: A host using platform_wallet_manager_create with working Core and tracked-lock persistence can restore a seed and discover an unspent historical asset lock during sync. The bridge saves the Core record and advances the scan height but drops the tracked-lock upsert, so after platform_wallet_manager_load_from_persistor the lock is missing from the tracked list and cannot be resumed through it. An extended host that declares atomic Core sweep support but omits bit 9 can also save an owned funding lock; if a competing spend causes Core to sweep that transaction, the bridge saves the Core sweep but drops the tracked-lock deletion, so the dead lock reappears on restart.

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

Comment on lines +3521 to 3522
let upsert_refs: Vec<&platform_wallet::changeset::AssetLockEntry> = rows.clone();
let (upserts, _storage) = build_asset_lock_entries(&upsert_refs);

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: Asset-lock upsert batches allocate a second copy of the filtered reference list
Impact: A host persisting asset-lock upserts, including during restore scans, pays an extra allocation and pointer copy for each nonempty filtered batch.

The row writer can use the filtered list without copying it. rows stays in scope for the sidecar callbacks, and build_asset_lock_entries only borrows the reference slice. The returned _storage, not the cloned reference vector, owns the buffers that must stay alive through the callback.

Suggested change
let upsert_refs: Vec<&platform_wallet::changeset::AssetLockEntry> = rows.clone();
let (upserts, _storage) = build_asset_lock_entries(&upsert_refs);
let (upserts, _storage) = build_asset_lock_entries(&rows);

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

Comment on lines +441 to +445
if ownership == RecipientOwnership::ExternalExplicitOutputs
&& matches!(funding, AssetLockFunding::FromExistingAssetLock { .. })
{
self.asset_locks.require_tracked_asset_lock_persistence()?;
}

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 c22558e6): Your fresh-funding composite now requires both TRACKED_ASSET_LOCKS and WALLET_RESTORE, so the old three-bit mask cannot reach the builder. Both external resume routes still require only the narrower row-update capability at their persistence gate.

Comment on lines 3468 to +3472
if let Some(ref al_cs) = changeset.asset_locks {
let has_rows = !al_cs.asset_locks.is_empty() || !al_cs.removed.is_empty();
if has_rows && self.callbacks.on_persist_asset_locks_fn.is_none() {
outcome.record(1);
}

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 c22558e6): A host with no row writer now receives the Core changes without the reconstructed rows, so this missing callback cannot freeze the scan height. Hosts that do have a writer but lack the declaration are a separate case.

Comment on lines +3622 to +3630
let loaded = asset_lock_rows_written
&& self
.loaded_platform_address_recipients
.lock()
.get(&(wallet_id, entry.out_point))
.is_some_and(|stored| *stored == bytes);
if !loaded {
outcome.record(1);
}

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 c22558e6): Your filter now runs before the row callback and passes only eligible upserts to the sidecars. With matching saved payees and no recipient writer, the row callback's transient refusal is no longer overridden by a missing-sidecar error.

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.

2 participants