Repository navigation
feat(platform-wallet): one address top-up for any identity - #5929
romchornyi wants to merge 7 commits into
Conversation
Add `PlatformWallet::top_up_identity_from_addresses`: it fetches the identity from Platform whatever its owner, writes the proved balance back when the identity manager holds the identity, and never adds an identity to the manager. The host no longer decides whether an identity is its own; a managed identity topped up through the external route no longer keeps a stale cached balance until the next sync. The lifecycle gate, liveness check, nonce binding, balance-growth check and reconciliation at the proof's height are unchanged. The growth baseline is the balance in the fetched identity, as on the external route; the managed route read the same value through `IdentityBalance`. Exposed as `platform_wallet_top_up_identity_from_addresses_with_signer`, `ManagedPlatformWallet.topUpIdentityFromAddresses` (Swift) and `IdentityCredits.topUpIdentityFromAddresses` (Kotlin, new JNI bridge `CreditsNative.topUpIdentityFromAddresses`). The example apps use it. Deprecated, still working on top of the new operation: - `PlatformWallet::top_up_from_addresses` (`#[deprecated]`) and its export, Swift and Kotlin methods: still refuse an identity the manager does not hold with IdentityNotFound (7) before Platform is asked. - `PlatformWallet::top_up_external_identity_from_addresses` (`#[deprecated]`) and its export and Swift method: now the same call. Funding inputs are still chosen by the host (issue item 2 is later). Refs #5925 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…signing The address top-up held the wallet generation's payment gate from before the identity fetch to the end of reconciliation, across the host's signing prompt. That was agreed on #5860 to close a window in which a retained handle could broadcast after removal. It contradicts the gate's own contract (`WalletGeneration::teardown_guard`): an operation awaiting an external signer takes the gate only after the signature returns, so an open signing prompt cannot stall teardown. With the wide gate, removing a wallet waited for whatever the host's signer did, and the write-preferring lock queued every later payment of that wallet behind the removal. The top-up now signs through `GatedAddressSigner`, as the contact request send signs through its `GatedSigner`: when the last input's witness returns, it takes the gate (`payment_guard_owned`) and checks under it that the handle's generation is still the registered one. The gate is then held through the broadcast, the result wait, the managed balance write-back and the address reconciliation. The transition needs every witness before it can be broadcast, so nothing reaches the network without the gate. A wallet removed or re-created while the host signed is refused there with WalletRemovedBeforeSend and nothing is broadcast; the window #5860 closed stays closed, because the liveness check and the broadcast are still one section under the gate. A handle already stale at the start is still refused before anything is fetched or signed (an ungated point-in-time check). Replaces `should_hold_a_wallets_removal_until_its_top_up_returns` with tests of the new contract: a removal during signing completes without waiting and the top-up then abandons before broadcast (also for a wallet re-created meanwhile), and a removal after the last signature waits until the top-up lets the gate go. This reverses the #5860 agreement, so it is a separate commit that can be dropped if maintainers prefer the wide gate. Refs #5925 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the
|
|
✅ Final review complete — no blockers (commit dc11d90) · triage: critical |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
The Rust routing and lifecycle-gate changes are generally sound, and the supplied CI snapshot contains no failed code checks. One blocking Kotlin cancellation path can hide a completed native top-up and permit a duplicate retry; several lower-severity API, documentation, lifecycle-proof, and test-coverage issues also remain.
🔴 1 blocking | 🟡 6 suggestion(s) | 💬 1 nitpick(s)
2 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Add compiler deprecation annotations to the old top-up wrappers
packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:794-838
The Rust compatibility routes are marked with #[deprecated], but Swift's topUpFromAddresses and topUpExternalIdentityFromAddresses only contain a **Deprecated:** doc comment. The corresponding Kotlin IdentityCredits.topUpFromAddresses method likewise lacks @Deprecated. Consumers therefore receive no compiler warning or migration guidance even though the PR introduces topUpIdentityFromAddresses as the single replacement route. Add @available(*, deprecated, message: ...) to the Swift methods and @Deprecated(...) to the Kotlin method, updating internal dispatch-test call sites as needed.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)
💬 Nitpick: Document the new JNI top-up export
packages/rs-unified-sdk-jni/src/credits.rs:9-18
The module-level bridge list still documents only platform_wallet_top_up_from_addresses_with_signer as the ID-06 entry point, while the primary export is now platform_wallet_top_up_identity_from_addresses_with_signer. Update the list to document the new any-identity export and identify the old export as the deprecated managed-only variant.
//! - [`platform_wallet_top_up_identity_from_addresses_with_signer`] — top up any
//! identity from Platform-address inputs (ID-06).
//! - [`platform_wallet_top_up_from_addresses_with_signer`] — deprecated managed-only
//! variant of the same top-up (ID-06).
source: muse-spark-1.3-contributor (phase1-reviewer: general, 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: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to funds movement and signing/lifecycle safety in PlatformWallet::top_up_identity_from_addresses and GatedAddressSigner, including broadcast gating and balance reconciliation. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity 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; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt:238-245: Preserve a completed native top-up when the coroutine is cancelled
This new payment method uses `gate.op`, which runs the synchronous JNI call through `withContext(Dispatchers.IO)`. If cancellation occurs after `addressTopUpNative.call` has broadcast and completed but before the dispatcher handoff returns the value, `withContext` can throw `CancellationException` and discard the completed balance. The caller cannot distinguish a completed top-up from an unsent one and may retry with newly resolved address nonces, crediting the identity twice. Use `gate.opReturningCompletedResult` here, as the neighboring money-moving Kotlin APIs already do, and add a cancellation-after-native-completion regression test.
In `packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift`:
- [SUGGESTION] packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift:794-838: Add compiler deprecation annotations to the old top-up wrappers
The Rust compatibility routes are marked with `#[deprecated]`, but Swift's `topUpFromAddresses` and `topUpExternalIdentityFromAddresses` only contain a `**Deprecated:**` doc comment. The corresponding Kotlin `IdentityCredits.topUpFromAddresses` method likewise lacks `@Deprecated`. Consumers therefore receive no compiler warning or migration guidance even though the PR introduces `topUpIdentityFromAddresses` as the single replacement route. Add `@available(*, deprecated, message: ...)` to the Swift methods and `@Deprecated(...)` to the Kotlin method, updating internal dispatch-test call sites as needed.
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:717-731: Recheck wallet liveness before prompting the host signer
`top_up_identity` performs its only ungated `is_current_generation` check before the Platform identity fetch. If the wallet is removed during that fetch or the subsequent nonce lookup, the operation still reaches the host signer and only fails when the last signature acquires the lifecycle gate. No funds are broadcast, but the user receives a needless signing prompt for an operation that is already known to be stale. Repeat the cheap current-generation check after the awaited pre-signing reads, ideally immediately before invoking the host signer; retain the gated check as the decisive race-safe check.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:722-755: Make the lifecycle gate a requirement of top-up bookkeeping
The production path stores the returned guard in `_lifecycle` and relies on it remaining alive while `record_top_up` writes the managed balance and reconciles addresses, but `record_top_up` accepts no guard parameter. Because it is `pub(crate)`, a future caller can invoke it with a stale handle after the wallet id has been re-created, causing the manager lookup to write into the replacement generation. Thread a reference to the owned lifecycle guard through `record_top_up` and `record_top_up_balance` so the required gate is enforced by the API rather than by documentation and variable scope.
In `packages/rs-unified-sdk-jni/src/credits.rs`:
- [NITPICK] packages/rs-unified-sdk-jni/src/credits.rs:9-18: Document the new JNI top-up export
The module-level bridge list still documents only `platform_wallet_top_up_from_addresses_with_signer` as the ID-06 entry point, while the primary export is now `platform_wallet_top_up_identity_from_addresses_with_signer`. Update the list to document the new any-identity export and identify the old export as the deprecated managed-only variant.
In `packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:98-118: Replace the boolean top-up scope with a typed route
`top_up_identity_from_addresses` uses `managed_only: bool`, and the public methods pass literal `false` and `true` at `platform_wallet.rs:640` and `platform_wallet.rs:669`. Swapping those literals would silently invert the authorization behavior without compiler help. The FFI layer already models this distinction with `AddressTopUpRoute`; use an equivalent Rust enum such as `TopUpScope::AnyIdentity` and `TopUpScope::ManagedOnly` in the wallet core.
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:230-329: Share the lifecycle-gated signer state machine
This introduces a second lifecycle-gated signer state machine alongside `GatedSigner` in `contact_requests.rs`. Both implementations allow host signing without the teardown gate, acquire the generation read guard after the final signature, check generation identity under the manager lock, and retain the guard through publication and bookkeeping. Keeping these policies duplicated in separate network modules allows a future lock-ordering or stale-generation fix to update one payment path while leaving the other inconsistent. Extract the shared gating/finalization behavior into a common Rust wallet helper while retaining address- and identity-key-specific signing adapters.
In `packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs:684-735: Test that the returned gate spans bookkeeping
The lifecycle test holds the gate only until `gated.into_gate()` is immediately dropped, while the bookkeeping seam test calls `record_top_up` without any gate. There is no regression test proving that the production guard remains held across the manager write and address reconciliation, so dropping `_lifecycle` before bookkeeping would not be detected. Add a test that holds the returned gate while running `record_top_up` and verifies concurrent wallet removal remains blocked until bookkeeping completes.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Move account-scoped funding input selection into Rust — The Swift and Kotlin example flows still enumerate wallet addresses and greedily select funding rows in
TopUpIdentityView.buildInputsandTopUpIdentityScreen.packInputs. This leaves account selection and input-selection behavior host-specific even though the new API centralizes identity ownership and top-up orchestration in Rust.- Follow-up: Open and link a follow-up issue or PR for Rust-owned account-scoped funding selection, then route both mobile examples through that operation.
| if !self.core().is_current_generation().await { | ||
| return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( | ||
| self.wallet_id, | ||
| ))); | ||
| } | ||
| let (address_infos, new_balance, proof_height) = top_up.await?; | ||
| let (confirmed, _lifecycle) = self | ||
| .identity | ||
| .top_up_identity_from_addresses( | ||
| identity_id, | ||
| inputs, | ||
| address_signer, | ||
| settings, | ||
| managed_only, | ||
| ) | ||
| .await?; |
There was a problem hiding this comment.
✅ Resolved at
dc11d90b; see the replies below.
🟡 Suggestion: Recheck wallet liveness before prompting the host signer
top_up_identity performs its only ungated is_current_generation check before the Platform identity fetch. If the wallet is removed during that fetch or the subsequent nonce lookup, the operation still reaches the host signer and only fails when the last signature acquires the lifecycle gate. No funds are broadcast, but the user receives a needless signing prompt for an operation that is already known to be stale. Repeat the cheap current-generation check after the awaited pre-signing reads, ideally immediately before invoking the host signer; retain the gated check as the decisive race-safe check.
source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)
There was a problem hiding this comment.
Not changing this: a recheck before the host signer would still race and only narrows the window. The decisive check is the gated one after the last signature, which refuses the operation before anything is broadcast, so the cost is at most one extra signing prompt for a wallet removed mid-operation.
There was a problem hiding this comment.
Still applies (re-reviewed at 57fe772c): The post-signing gated check remains the decisive race-safe refusal, but the current code still has no liveness check after the awaited identity and nonce reads, so a wallet removed during those reads can still trigger an unnecessary host-signing prompt.
There was a problem hiding this comment.
Fixed in dc11d90: the wallet generation is rechecked after the identity and nonce reads, right before signing, so a wallet removed during those reads gets no signing prompt. The gated check after signing stays the decisive one. A test covers it.
There was a problem hiding this comment.
Resolved (re-reviewed at dc11d90b): Confirmed on this head: wallet generation is checked after the awaited identity and nonce reads and before invoking the host signer, while the gated post-signing check remains the decisive race-safe check.
| pub(crate) async fn top_up_identity_from_addresses<S, I>( | ||
| &self, | ||
| identity_id: &Identifier, | ||
| inputs: I, | ||
| address_signer: &S, | ||
| settings: Option<PutSettings>, | ||
| ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> | ||
| managed_only: bool, | ||
| ) -> Result< | ||
| ( | ||
| (AddressInfos, Credits, ResponseMetadata), | ||
| OwnedRwLockReadGuard<()>, | ||
| ), | ||
| PlatformWalletError, | ||
| > | ||
| where | ||
| S: Signer<PlatformAddress> + Send + Sync, | ||
| I: IntoIterator<Item = (PlatformAddress, Credits)> + Send, | ||
| { | ||
| let inputs = funding_inputs(inputs)?; | ||
| let identity = { | ||
| let wm = self.wallet_manager.read().await; | ||
| let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { | ||
| crate::error::PlatformWalletError::WalletNotFound( | ||
| "Wallet info not found in wallet manager".to_string(), | ||
| ) | ||
| })?; | ||
| let manager = &info.identity_manager; | ||
| manager | ||
| .identity(identity_id) | ||
| .map(|m| m.identity.clone()) | ||
| .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))? | ||
| }; | ||
| // The cached balance can sit above Platform's (credits spent from | ||
| // another device, not yet synced): growth is measured against | ||
| // Platform's own balance, read before anything is signed. | ||
| let balance_before = IdentityBalance::fetch(&self.sdk, *identity_id) | ||
| if managed_only && !self.manages_identity(identity_id).await? { | ||
| return Err(PlatformWalletError::IdentityNotFound(*identity_id)); |
There was a problem hiding this comment.
✅ Resolved at
dc11d90b; see the replies below.
🟡 Suggestion: Replace the boolean top-up scope with a typed route
top_up_identity_from_addresses uses managed_only: bool, and the public methods pass literal false and true at platform_wallet.rs:640 and platform_wallet.rs:669. Swapping those literals would silently invert the authorization behavior without compiler help. The FFI layer already models this distinction with AddressTopUpRoute; use an equivalent Rust enum such as TopUpScope::AnyIdentity and TopUpScope::ManagedOnly in the wallet core.
source: rust-quality
There was a problem hiding this comment.
Not changing this: managed_only is private to the wallet crate with two documented call sites, and the true one is the deprecated managed-only route that goes away with it, so an enum would outlive its only second user.
There was a problem hiding this comment.
Still applies (re-reviewed at 57fe772c): Both any-identity and managed-only routes remain live in this head and still select authorization with false versus true; deprecation does not make an accidental swap compiler-visible.
There was a problem hiding this comment.
Fixed in 7535c90: the scope is now a crate-private TopUpScope { AnyIdentity, ManagedOnly }, so each call site names the identities it accepts, and swapping them no longer compiles silently.
There was a problem hiding this comment.
Resolved (re-reviewed at dc11d90b): Confirmed on this head: TopUpScope::AnyIdentity and TopUpScope::ManagedOnly are explicit at the wallet call sites, so swapping authorization behavior no longer compiles silently.
…ancelled IdentityCredits.topUpIdentityFromAddresses ran under gate.op, so a top-up that finished natively after its caller was cancelled had its balance dropped and the caller could not tell the credits moved. Run it under gate.opReturningCompletedResult, like the wallet's other credit-moving calls, and pin that with a regression test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…keeping record_top_up and record_top_up_balance now take the held lifecycle guard, so the identity-manager write and the address reconciliation cannot be called without it. The test seam acquires it the way production does. Mark the managed-only address top-up wrappers deprecated in favour of topUpIdentityFromAddresses (Swift topUpFromAddresses and topUpExternalIdentityFromAddresses, Kotlin IdentityCredits and CreditsNative topUpFromAddresses), and list platform_wallet_top_up_identity_from_addresses_with_signer in the JNI credits module doc. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Replies to the findings shown only in the review body:
|
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The any-identity address top-up is consistently wired through the Rust wallet, FFI, JNI, Swift, and Kotlin layers, and the lifecycle guard is now enforced through bookkeeping. One blocking cancellation issue remains in the deprecated Kotlin managed-only route, along with two non-blocking Rust API/UX concerns. CI shows the Kotlin build and tests passing; the review check is still in progress.
🔴 1 blocking | 🟡 2 suggestion(s)
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🔴 Blocking: Deprecated Kotlin top-up still drops a completed result on cancellation
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt:266-280
The deprecated topUpFromAddresses route still uses gate.op, while the new any-identity route uses opReturningCompletedResult. If the synchronous JNI call broadcasts and completes before coroutine cancellation is observed during the withContext(Dispatchers.IO) handoff, gate.op can throw CancellationException and discard the completed balance. The caller cannot distinguish a completed top-up from an unsent one and may retry with newly resolved nonces, potentially crediting the identity twice. This route is explicitly retained and modified by this PR as the deprecated compatibility path, so it should preserve completed results under cancellation as well.
suspend fun topUpFromAddresses(
walletHandle: Long,
identityId: ByteArray,
inputs: List<FundingInput>,
signerHandle: Long,
): Long = gate.opReturningCompletedResult {
mapNativeErrors {
CreditsNative.topUpFromAddresses(
walletHandle,
identityId,
FundingInput.encode(inputs),
signerHandle,
)
}
}
source: muse-spark-1.3-contributor (phase1-reviewer: general)
Still open from earlier rounds (2)
- 🟡 Suggestion: Replace the boolean top-up scope with a typed route —
packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:98-118(thread) - 🟡 Suggestion: Recheck wallet liveness before prompting the host signer —
packages/rs-platform-wallet/src/wallet/platform_wallet.rs:714-731(thread)
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: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This is a large, intricate change to identity credit top-up transaction signing, broadcast, lifecycle gating, and balance write-back inPlatformWallet::top_up_identity_from_addressesandGatedAddressSigner, directly affecting funds movement and key-handling boundaries. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity 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; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt`:
- [BLOCKING] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt:266-280: Deprecated Kotlin top-up still drops a completed result on cancellation
The deprecated `topUpFromAddresses` route still uses `gate.op`, while the new any-identity route uses `opReturningCompletedResult`. If the synchronous JNI call broadcasts and completes before coroutine cancellation is observed during the `withContext(Dispatchers.IO)` handoff, `gate.op` can throw `CancellationException` and discard the completed balance. The caller cannot distinguish a completed top-up from an unsent one and may retry with newly resolved nonces, potentially crediting the identity twice. This route is explicitly retained and modified by this PR as the deprecated compatibility path, so it should preserve completed results under cancellation as well.
In `packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs:98-118: Replace the boolean top-up scope with a typed route
(carried; thread: https://github.com/dashpay/platform/pull/5929#discussion_r4578944933)
In `packages/rs-platform-wallet/src/wallet/platform_wallet.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/platform_wallet.rs:714-731: Recheck wallet liveness before prompting the host signer
(carried; thread: https://github.com/dashpay/platform/pull/5929#discussion_r4578944929)
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Bind address top-up completion to the exact transition — The existing nonce-and-balance heuristic can accept a result when another transition consumes the same address nonces and unrelated credits raise the target identity balance. That can make an unexecuted top-up appear complete, although this limitation predates the reviewed range and is documented in the current implementation.
- Follow-up: Create a follow-up PR adding an execution-bound proof or result binding for address-funded top-ups.
…ler is cancelled The deprecated IdentityCredits.topUpFromAddresses still ran under gate.op, so a top-up that finished natively after its caller was cancelled had its balance dropped and the caller could retry and credit the identity twice. Run it under gate.opReturningCompletedResult like topUpIdentityFromAddresses, behind an injectable bridge, and extend the cancellation regression test to both routes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The crate-private address top-up chose between any identity and only a
managed one with a `managed_only: bool`, passed as bare `true`/`false`
literals by the public routes, so swapping them would silently invert
which identities a route accepts. Replace it with a crate-private
`TopUpScope { AnyIdentity, ManagedOnly }` so the choice is named at
each call site.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…gn a top-up The address top-up checked the wallet generation once, before the identity fetch, and then again only under the lifecycle gate after the last signature. A wallet removed or replaced during the identity and nonce reads still got the host's signing prompt for a top-up that could only be refused. Recheck the generation after those reads, right before the transition is signed, and refuse with WalletRemovedBeforeSend; the gated check after signing stays the decisive one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Addressed the review at
|
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
The current head preserves the lifecycle-gated any-identity top-up behavior and correctly routes the Rust, FFI, JNI, Kotlin, and Swift layers. I found two actionable suggestions—a Kotlin input-validation gap and a Rust test-coverage gap—and one inaccurate deprecated Swift documentation comment; no blocking correctness issues were found. Kotlin and policy checks passed, with only the review check still in progress.
🟡 2 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.
1 finding(s) not shown inline (the lines are not part of this PR's diff)
🟡 Suggestion: Reject out-of-range Kotlin address types before u8 encoding
packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt:41-49
FundingInput.addressType is an Int, but FundingInput.encode writes it with DataOutputStream.writeByte, which retains only the low eight bits. For example, addressType = 256 is encoded as 0, and the JNI/Rust boundary then accepts it as P2PKH instead of rejecting the invalid caller input. Validate that the value is exactly 0 or 1 in the FundingInput initializer before it is encoded.
init {
require(addressType == 0 || addressType == 1) {
"FundingInput.addressType must be 0 (P2PKH) or 1 (P2SH), got $addressType"
}
require(hash.size == 20) { "FundingInput.hash must be 20 bytes, got ${hash.size}" }
require(credits > 0) { "FundingInput.credits must be positive, got $credits" }
}
source: gpt-6.1-sol (phase2-reviewer: ffi-engineer)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); 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: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)
- Triage:
criticalbygpt-6.1-sol(effort low) — This large, cross-language change alters identity credit top-up funds movement, signing coordination, wallet liveness, broadcasting, and balance write-back inPlatformWallet::top_up_identity_from_addressesandGatedAddressSigner. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity 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 (
57fe772c): 1 new nitpick(s) dropped - Fresh verifier:
gpt-6.1-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— general (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— architecture-layering (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— ffi-engineer (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— rust-quality (completed, effort xhigh); agentphase2-reviewer,gpt-6.1-sol— security-auditor (completed, effort xhigh); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt`:
- [SUGGESTION] packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt:41-49: Reject out-of-range Kotlin address types before u8 encoding
`FundingInput.addressType` is an `Int`, but `FundingInput.encode` writes it with `DataOutputStream.writeByte`, which retains only the low eight bits. For example, `addressType = 256` is encoded as `0`, and the JNI/Rust boundary then accepts it as P2PKH instead of rejecting the invalid caller input. Validate that the value is exactly `0` or `1` in the `FundingInput` initializer before it is encoded.
In `packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs`:
- [SUGGESTION] packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs:545-576: Make the liveness regression test remove the wallet after the reads
This test removes the wallet before invoking `IdentityWallet::top_up_identity_from_addresses`, so it does not exercise the operation after the identity and address-nonce reads have completed. It would continue to pass if the post-read liveness check were moved before either awaited read. Coordinate the mocked identity and nonce fetches, remove the wallet after both have completed, then assert that the operation refuses without invoking the signer or submitting anything.
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Rust-owned funding input selection remains a caller responsibility — The new APIs continue to accept explicit address-and-credit rows, leaving Kotlin, Swift, and other hosts responsible for selecting and packing funding inputs. This keeps input-selection policy above
rs-platform-walletand preserves the related concurrent nonce-selection limitation.- Follow-up: Implement Rust-owned funding-input selection and reservation under #5925, then reduce the mobile and FFI APIs to marshal the selected account and amount.
| /// A wallet removed after the entry check, while the identity and the | ||
| /// address nonces are read, asks the host for no signature: the top-up is | ||
| /// refused before signing, with nothing submitted. The wallet's top-up past | ||
| /// its entry check is driven directly, on the wallet already removed. | ||
| #[tokio::test(flavor = "multi_thread")] | ||
| async fn should_not_ask_the_host_to_sign_for_a_wallet_removed_during_the_reads() { | ||
| let mut fixture = Fixture::new(true).await; | ||
| let wallet_id = fixture.wallet.wallet_id(); | ||
| fixture | ||
| .manager | ||
| .remove_wallet(&wallet_id) | ||
| .await | ||
| .expect("removed"); | ||
|
|
||
| let refused = fixture | ||
| .wallet | ||
| .identity() | ||
| .top_up_identity_from_addresses( | ||
| &fixture.target, | ||
| vec![(ADDRESS, AMOUNT)], | ||
| &fixture.signer, | ||
| settings(), | ||
| TopUpScope::AnyIdentity, | ||
| ) | ||
| .await | ||
| .map(|_| ()); | ||
| assert!( | ||
| matches!( | ||
| superseded_own, | ||
| Err(PlatformWalletError::WalletRemovedBeforeSend(_)) | ||
| ), | ||
| "managed route: {superseded_own:?}" | ||
| matches!(&refused, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) | ||
| if *id == hex::encode(wallet_id)), | ||
| "{refused:?}" | ||
| ); | ||
| assert_eq!(fixture.submissions().await, (0, 0, 0)); | ||
| assert_eq!(fixture.submissions().await, (0, 0, 0), "nothing is signed"); |
There was a problem hiding this comment.
🟡 Suggestion: Make the liveness regression test remove the wallet after the reads
This test removes the wallet before invoking IdentityWallet::top_up_identity_from_addresses, so it does not exercise the operation after the identity and address-nonce reads have completed. It would continue to pass if the post-read liveness check were moved before either awaited read. Coordinate the mocked identity and nonce fetches, remove the wallet after both have completed, then assert that the operation refuses without invoking the signer or submitting anything.
source: gpt-6.1-sol (phase2-reviewer: rust-quality)
Issue being fixed or feature implemented
Refs #5925 (this PR does items 1 and 3; item 2, Rust selecting the funding inputs, stays open in that issue for a follow-up). Stacked on #5860 (base
feat/platform-wallet-external-identity-top-up).Hosts had to choose between two top-up exports (managed vs any other identity), so each app decided "is this identity mine?" on its own, and the lifecycle gate was held across the host signer, against the gate's own contract.
What was done?
Commit 1 — one address top-up for any identity
PlatformWallet::top_up_identity_from_addresses: always fetches the identity from Platform; after a confirmed proof,record_top_up_balancewrites the balance back only when the identity manager holds that id. No identity is ever added to the manager.platform_wallet_top_up_identity_from_addresses_with_signer, SwiftManagedPlatformWallet.topUpIdentityFromAddresses, KotlinIdentityCredits.topUpIdentityFromAddresses(JNICreditsNative.topUpIdentityFromAddresses).top_up_from_addresses,top_up_external_identity_from_addresses, their FFI exports, SwifttopUpFromAddresses/topUpExternalIdentityFromAddresses, KotlintopUpFromAddresses. The old managed route still refuses an identity the manager does not hold (code 7) before Platform is asked. The example apps call the new method.Commit 2 — take the lifecycle gate after signing (separate so it can be dropped)
GatedAddressSignertakespayment_guard_ownedonce the last input's signature returns, then checks under it that the wallet is still current; the gate stays held through broadcast, result wait, balance write-back and reconciliation. A handle already stale at the start is refused before anything is fetched or signed.teardown_guard's contract, an open signing prompt must not stall teardown; a wallet removed while signing is now refused at the liveness check, with nothing broadcast.How Has This Been Tested?
cargo test -p platform-wallet: 1676 passed;-p platform-wallet-ffi: 528 passed. New tests: managed identity (balance written back), unmanaged identity (nothing added), the deprecated routes unchanged; removal during signing completes without waiting and the top-up fails withWalletRemovedBeforeSend, nothing broadcast; the same with the wallet re-created during signing; with two inputs, removal after the last signature waits for the gate (driven throughGatedAddressSignerdirectly, since the mock SDK cannot pause mid-broadcast).should_hold_a_wallets_removal_until_its_top_up_returnsis replaced.cargo fmt --check, clippy clean on platform-wallet, platform-wallet-ffi, rs-unified-sdk-jni; parity manifest check passes.:sdk:testDebugUnitTest :app:testDebugUnitTestgreen, including the newIdentityAddressTopUpTest. JNI crate: clippy-D warnings --all-targets, 72 tests.packages/swift-sdk/run_tests.sh(dev framework): SwiftDashSDK 992 tests, SwiftExampleApp unit tests green.Breaking Changes
None: additions and deprecations only. Behaviour: the deprecated managed route now reads the identity from Platform instead of the manager (same errors to the caller); removing a wallet no longer waits for a top-up that is still signing.
Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull request🤖 Generated with Claude Code