From 376fecccef37e5b024cd81bcb4a864f1481cfec8 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 14 Nov 2026 04:26:51 +0200 Subject: [PATCH 1/7] feat(platform-wallet): one address top-up for any identity 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 --- docs/sdk/sdk-parity-manifest.json | 21 +- .../kotlin-sdk/KotlinExampleApp/TEST_PLAN.md | 2 +- .../example/ui/credits/TopUpIdentityScreen.kt | 6 +- packages/kotlin-sdk/PARITY_SUMMARY.md | 4 +- .../dashsdk/credits/IdentityCredits.kt | 46 +- .../dashsdk/ffi/CreditsNative.kt | 26 +- .../credits/IdentityAddressTopUpTest.kt | 45 ++ .../ERROR_CODE_REGISTRY.md | 2 +- .../src/identity_top_up.rs | 339 +++++++++------ .../external_identity_tests.rs | 233 ++++++----- .../identity_top_up/registry_release_tests.rs | 15 +- .../submission_result_tests.rs | 33 +- .../identity/network/top_up_from_addresses.rs | 221 ++++------ .../external_identity_tests.rs | 395 ++++++++++++------ .../src/wallet/platform_wallet.rs | 163 +++++--- packages/rs-unified-sdk-jni/src/credits.rs | 72 +++- .../ManagedPlatformWallet.swift | 46 +- .../Views/TopUpIdentityView.swift | 2 +- .../ExternalIdentityTopUpTests.swift | 16 +- 19 files changed, 1096 insertions(+), 591 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index a59a25072e7..ce18afaa829 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -73,6 +73,7 @@ "platform_wallet_token_update_config": "packages/rs-platform-wallet-ffi/src/tokens/update_config.rs", "platform_wallet_top_up_external_identity_from_addresses_with_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", "platform_wallet_top_up_from_addresses_with_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", + "platform_wallet_top_up_identity_from_addresses_with_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", "platform_wallet_topup_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_tracked_asset_locks_free": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", "platform_wallet_tracked_asset_locks_list": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", @@ -1435,7 +1436,8 @@ "area": "shared_policy", "shared_apis": [ "platform_address_wallet_addresses_with_balances", - "platform_wallet_top_up_from_addresses_with_signer" + "platform_wallet_top_up_from_addresses_with_signer", + "platform_wallet_top_up_identity_from_addresses_with_signer" ], "required_persistence_capabilities": [], "hosts": { @@ -1474,7 +1476,8 @@ "title": "Top up an identity the wallet does not manage from Platform addresses", "area": "correctness", "shared_apis": [ - "platform_wallet_top_up_external_identity_from_addresses_with_signer" + "platform_wallet_top_up_external_identity_from_addresses_with_signer", + "platform_wallet_top_up_identity_from_addresses_with_signer" ], "required_persistence_capabilities": [], "hosts": { @@ -1482,13 +1485,13 @@ "sdk": "supported", "example_app": "unsupported", "restart": "not_applicable", - "reason": "ManagedPlatformWallet.topUpExternalIdentityFromAddresses bridges the export; the example app has no screen that pays to someone else's identity." + "reason": "ManagedPlatformWallet.topUpIdentityFromAddresses (and the deprecated topUpExternalIdentityFromAddresses) bridges the export; the example app has no screen that pays to someone else's identity." }, "kotlin": { - "sdk": "unsupported", + "sdk": "supported", "example_app": "unsupported", "restart": "not_applicable", - "reason": "No JNI bridge or Kotlin wrapper for the external identity top-up yet." + "reason": "IdentityCredits.topUpIdentityFromAddresses bridges the export through JNI; the example app has no screen that pays to someone else's identity." } }, "verification": [ @@ -1499,6 +1502,14 @@ "id": "testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites", "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:SwiftDashSDKTests/ExternalIdentityTopUpTests", "covers_restart": false + }, + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt", + "id": "top up of any identity marshals to its own bridge and returns its balance", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:testDebugUnitTest", + "covers_restart": false } ] }, diff --git a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md index 76c3b3c359e..dda7ea0d7b6 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md +++ b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md @@ -126,7 +126,7 @@ Most Platform actions have hard preconditions. Establish these fixtures before s | ID-03 | View identity (info / balance / revision / keys) | Platform | Essential | ✅ | | `IdentityDetailScreen`, `KeysListScreen`, `KeyDetailScreen`. | | ID-04 | Transfer credits identity → identity | Platform | Essential | ✅ | | `IdentityDetailScreen` → **Transfer Credits** (dialog, `TransferCreditsScreen`) → `platform_wallet_transfer_credits_with_signer` (Keystore-signed). Recipient entered via `RecipientPicker` (local identity / paste base58 id / DPNS name). | | ID-05 | Top up identity (asset lock) | Cross | Common | ✅ | | `IdentityDetailScreen` → **Top Up from Core** (`TopUpIdentityFromCoreScreen`) → `platform_wallet_top_up_identity_with_funding_signer`. Builds + broadcasts a new Core asset lock (same mechanism as ID-01), signed by the asset lock's Core key. | -| ID-06 | Top up identity (from Platform addresses) | Cross | Common | ✅ | | `IdentityDetailScreen` → **Top Up from Platform addresses** (`TopUpIdentityScreen`) → `platform_wallet_top_up_from_addresses_with_signer`. Requires the wallet's Platform-payment addresses to hold credits first — fund them via `WalletDetailScreen` → Platform Balance → **Top Up from Core** (`FundFromAssetLockScreen`). | +| ID-06 | Top up identity (from Platform addresses) | Cross | Common | ✅ | | `IdentityDetailScreen` → **Top Up from Platform addresses** (`TopUpIdentityScreen`) → `IdentityCredits.topUpIdentityFromAddresses` → `platform_wallet_top_up_identity_from_addresses_with_signer`. Requires the wallet's Platform-payment addresses to hold credits first — fund them via `WalletDetailScreen` → Platform Balance → **Top Up from Core** (`FundFromAssetLockScreen`). | | ID-07 | Update identity — add public key | Platform | Common | ✅ | | `AddIdentityKeyScreen` (from `KeysListScreen`) → `updateIdentity(addPublicKeys:)`. | | ID-08 | Create identity (from Platform addresses) | Cross | Common | ✅ | | `CreateIdentityScreen` → funding source **Platform address** → `IdentityRegistration.registerFromAddresses` → `platform_wallet_register_identity_with_signer` (Keystore-signed; one signer drives both the identity-key and platform-address roles). Derives + persists the canonical key set (as ID-01), then greedily packs the wallet's balance-carrying Platform-payment addresses; nonces auto-fetched Rust-side. Requires funded Platform addresses first (fund via `WalletDetailScreen` → Platform Balance → **Top Up from Core**). | | ID-09 | Set / edit local alias | Platform | Common | ✅ | | `IdentityDetailScreen` (Add Alias). Local only — persists across relaunch; no broadcast. | diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityScreen.kt index f9b36c262e8..3de99b76ea3 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityScreen.kt @@ -49,8 +49,8 @@ import org.dashfoundation.example.util.hexToBytes * ([org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet.addressesWithBalances]), * greedily packs them up to the requested amount (largest-balance-first, * matching Swift's `buildInputs`), then credits the identity through - * `platform_wallet_top_up_from_addresses_with_signer` - * ([org.dashfoundation.dashsdk.credits.IdentityCredits.topUpFromAddresses]). + * `platform_wallet_top_up_identity_from_addresses_with_signer` + * ([org.dashfoundation.dashsdk.credits.IdentityCredits.topUpIdentityFromAddresses]). */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -139,7 +139,7 @@ fun TopUpIdentityScreen(identityIdHex: String, navController: NavHostController) "$amt credits." return@launch } - mgr.identityCredits.topUpFromAddresses( + mgr.identityCredits.topUpIdentityFromAddresses( walletHandle = w.handle, identityId = idBytes, inputs = inputs, diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index a62b3e0e164..ca40353d7a2 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -10,7 +10,7 @@ Capabilities tracked: **31** | --- | --- | ---: | ---: | ---: | ---: | | Swift | SDK | 18 | 11 | 1 | 1 | | Swift | Example app | 5 | 14 | 3 | 9 | -| Kotlin | SDK | 14 | 14 | 2 | 1 | +| Kotlin | SDK | 15 | 14 | 1 | 1 | | Kotlin | Example app | 6 | 13 | 2 | 10 | ## Restart coverage @@ -42,7 +42,7 @@ Capabilities tracked: **31** | `persistence.dashpay_payment_history` | partial / not-applicable / required | not-applicable / not-applicable / not_applicable | | `network.masternode_discovery` | partial / not-applicable / not_applicable | partial / not-applicable / not_applicable | | `identity.platform_address_auto_funding` | partial / partial / not_applicable | partial / partial / not_applicable | -| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | unsupported / unsupported / not_applicable | +| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | supported / unsupported / not_applicable | | `tokens.authorization_decisions` | partial / partial / not_applicable | partial / partial / not_applicable | | `tokens.direct_purchase_quote` | partial / partial / not_applicable | partial / partial / not_applicable | | `protocol.address_validation` | supported / supported / not_applicable | partial / partial / not_applicable | diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index d03f3de82c8..996e65eaa10 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -19,10 +19,19 @@ internal fun interface ResumeTopUpNativeCall { ): Long } +internal fun interface AddressTopUpNativeCall { + fun call( + walletHandle: Long, + identityId: ByteArray, + inputsBlob: ByteArray, + signerHandle: Long, + ): Long +} + /** * One Platform-address funding input for an identity top-up — port of the * `IdentityAddressInput` tuple the Swift `TopUpIdentityView` packs. Encodes - * to the flat blob [CreditsNative.topUpFromAddresses] consumes. + * to the flat blob [CreditsNative.topUpIdentityFromAddresses] consumes. * * @property addressType 0 = P2PKH, 1 = P2SH. * @property hash the 20-byte address hash. @@ -81,6 +90,8 @@ class IdentityCredits internal constructor( private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, private val resumeTopUpNative: ResumeTopUpNativeCall = ResumeTopUpNativeCall(CreditsNative::topUpIdentityWithExistingAssetLock), + private val addressTopUpNative: AddressTopUpNativeCall = + AddressTopUpNativeCall(CreditsNative::topUpIdentityFromAddresses), ) { /** @@ -212,8 +223,37 @@ class IdentityCredits internal constructor( } /** - * Top up [identityId] (32 bytes) from Platform-address [inputs], - * signed via [signerHandle]. Returns the post-transition balance. + * Top up [identityId] (32 bytes) from Platform-address [inputs], whoever + * owns the identity (one of the wallet's or someone else's), signed via + * [signerHandle]. Rust fetches the identity from Platform, never adds it + * to the wallet, and updates the balance of an identity the wallet + * manages, so the caller does not decide whether it is its own. Returns + * the identity's post-transition balance. + */ + suspend fun topUpIdentityFromAddresses( + walletHandle: Long, + identityId: ByteArray, + inputs: List, + signerHandle: Long, + ): Long = gate.op { + mapNativeErrors { + addressTopUpNative.call( + walletHandle, + identityId, + FundingInput.encode(inputs), + signerHandle, + ) + } + } + + /** + * Top up [identityId] (32 bytes), an identity the wallet manages, from + * Platform-address [inputs], signed via [signerHandle]. Returns the + * post-transition balance. + * + * **Deprecated:** use [topUpIdentityFromAddresses], which tops up any + * identity and updates a managed one's balance the same way; this one + * differs only in refusing an identity the wallet does not manage. */ suspend fun topUpFromAddresses( walletHandle: Long, diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt index 395cf3ddd21..a197d41a4d3 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt @@ -69,14 +69,34 @@ internal object CreditsNative { ) /** - * Top up [identityId] (32 bytes) from Platform-address inputs, signed - * per-address via [signerHandle] (the platform-address signer). - * Returns the post-transition credit balance. + * Top up [identityId] (32 bytes), whoever owns the identity, from + * Platform-address inputs, signed per-address via [signerHandle] (the + * platform-address signer). Rust fetches the identity from Platform, + * never adds it to the wallet, and updates the balance of an identity + * the wallet manages. Returns the identity's post-transition credit + * balance. * * @param inputsBlob big-endian: `u32 rowCount` then per row * `u8 addressType (0 P2PKH / 1 P2SH), u8[20] hash, u64 credits`. * Built by [org.dashfoundation.dashsdk.credits.FundingInput.encode]. */ + external fun topUpIdentityFromAddresses( + walletHandle: Long, + identityId: ByteArray, + inputsBlob: ByteArray, + signerHandle: Long, + ): Long + + /** + * Top up [identityId] (32 bytes), an identity the wallet manages, from + * Platform-address inputs, signed per-address via [signerHandle] (the + * platform-address signer). Returns the post-transition credit balance. + * + * **Deprecated:** use [topUpIdentityFromAddresses], which tops up any + * identity; this one refuses an identity the wallet does not manage. + * + * @param inputsBlob as for [topUpIdentityFromAddresses]. + */ external fun topUpFromAddresses( walletHandle: Long, identityId: ByteArray, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt new file mode 100644 index 00000000000..c86902b9602 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt @@ -0,0 +1,45 @@ +package org.dashfoundation.dashsdk.credits + +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test + +class IdentityAddressTopUpTest { + + /** + * The top-up of any identity hands its arguments, the funding rows + * encoded, to its own JNI bridge and returns the balance it reports; + * whether the identity is the wallet's own is not decided here. + */ + @Test + fun `top up of any identity marshals to its own bridge and returns its balance`() = runTest { + val calls = mutableListOf>() + val credits = IdentityCredits( + addressTopUpNative = AddressTopUpNativeCall { wallet, identity, blob, signer -> + calls += listOf(wallet, identity, blob, signer) + 777L + }, + ) + val identityId = ByteArray(32) { 9 } + val inputs = listOf( + FundingInput(addressType = 0, hash = ByteArray(20) { 7 }, credits = 1_000), + FundingInput(addressType = 1, hash = ByteArray(20) { 8 }, credits = 7), + ) + + val balance = credits.topUpIdentityFromAddresses( + walletHandle = 42, + identityId = identityId, + inputs = inputs, + signerHandle = 5, + ) + + assertEquals(777L, balance) + assertEquals(1, calls.size) + val (wallet, identity, blob, signer) = calls.single() + assertEquals(42L, wallet) + assertArrayEquals(identityId, identity as ByteArray) + assertArrayEquals(FundingInput.encode(inputs), blob as ByteArray) + assertEquals(5L, signer) + } +} diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index 7757bbbc2bf..e5d962cab48 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -192,7 +192,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 74 | `ErrorPrivateContactStoreNotRead` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactStoreNotRead`: DashPay's private contact request store was not read to its end for the identity, with the keys Platform proves it holds, before a contact request or acceptance, public or private, was decided (every one reads it from the identity's cursor first). Nothing was reserved, sealed, paid or broadcast; calling again continues the read from where it stopped. A node behind the store already seen, or keys that kept changing, stop it. It was reported as 71 before, which says not to submit again. Mapped by the blanket conversion and kept by the shielded spend contract (`map_spend_result`). Swift types it (`PlatformWalletError.privateContactStoreNotRead`, `ErrorHandlingTests` pin) and SwiftExampleApp offers a retry with no pending row; Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactStoreNotRead`, `DashSdkErrorTest` pin) and KotlinExampleApp offers a retry with no pending row | | 75 | `ErrorSdkPinnedBelowProtocolVersion` | DashPay private contact requests | Proposed. The SDK refused a request without sending it because the SDK itself is pinned below the protocol version the request needs (`dash_sdk::Error::ProtocolVersionNotActive` with `pinned`), whatever the network runs: for example every contact request's private store read with the SDK pinned below protocol version 15 on a network at 15. A network upgrade does not lift it; only raising or removing the pin does. Before, it shared 70 with a network proven below the version, which lifts by itself. Mapped by the blanket conversion. Swift types it (`PlatformWalletError.sdkPinnedBelowProtocolVersion`, `ErrorHandlingTests` pin) and SwiftExampleApp shows a developer-facing message; Kotlin types it (`DashSdkError.PlatformWallet.SdkPinnedBelowProtocolVersion`, `DashSdkErrorTest` pin) and KotlinExampleApp shows a developer-facing message | | 76 | `ErrorPublicContactRequestUnconfirmed` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PublicContactRequestUnconfirmed`: a public contact request to that identity was broadcast and may have been delivered, and no proof settled its outcome yet, so the wallet holds the pair and signs nothing new to it, public or private. The send or accept that broadcast it reported 20; every later one is refused with 76 until a public contact request sync settles it (its document proved on Platform: recorded as sent; its transition proved unable to write it: the pair freed), broadcasting the same signed bytes again meanwhile. Not a private request pending (71). Mapped by the blanket conversion and by `map_spend_result`. `platform_wallet_get_public_contact_request_unconfirmed` reads the hold per pair (`DashPayView::public_contact_request_unconfirmed`; 7 for a sender the wallet does not hold). Swift types it (`PlatformWalletError.publicContactRequestUnconfirmed`, `ErrorHandlingTests` pin) and wraps the read (`ManagedPlatformWallet.publicContactRequestUnconfirmed`); SwiftExampleApp shows the pair as being checked, with no request or accept offered, until the read says settled, and its refreshes run the DashPay sync that settles it; Kotlin types it (`DashSdkError.PlatformWallet.PublicContactRequestUnconfirmed`, `DashSdkErrorTest` pin), bridges the read (`DashpayNative.publicContactRequestUnconfirmed`, `Dashpay.publicContactRequestsUnconfirmed`), and KotlinExampleApp shows the pair as SwiftExampleApp does | -| 80 | `ErrorIdentityLookupFailed` | External identity top-up from Platform addresses | Proposed. Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be asked for the identity the operation names (the lookup failed in transport or proof, not Platform's answer that it does not exist, which stays 7). Nothing was signed, reserved or broadcast, so the call may be retried as it is; no existing code meant "refused before anything was sent" for a Platform state transition (16 is the shielded broadcast refusal), so it takes the next free number after 77–79, which the shielded spend plan PR (#5865) holds. Returned by `platform_wallet_top_up_external_identity_from_addresses_with_signer`; before, such a failure reached a host as an unmapped SDK error. Swift types it (`PlatformWalletError.identityLookupFailed`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.IdentityLookupFailed`, `DashSdkErrorTest` pin) | +| 80 | `ErrorIdentityLookupFailed` | External identity top-up from Platform addresses | Proposed. Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be asked for the identity the operation names (the lookup failed in transport or proof, not Platform's answer that it does not exist, which stays 7). Nothing was signed, reserved or broadcast, so the call may be retried as it is; no existing code meant "refused before anything was sent" for a Platform state transition (16 is the shielded broadcast refusal), so it takes the next free number after 77–79, which the shielded spend plan PR (#5865) holds. Returned by `platform_wallet_top_up_identity_from_addresses_with_signer` and by the deprecated `platform_wallet_top_up_external_identity_from_addresses_with_signer` and `platform_wallet_top_up_from_addresses_with_signer`; before, such a failure reached a host as an unmapped SDK error. Swift types it (`PlatformWalletError.identityLookupFailed`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.IdentityLookupFailed`, `DashSdkErrorTest` pin) | **Code 31 left this table on 2026-08-04.** `ErrorSigningKeyUnavailable` sat here as #4183's proposal until #4183 merged (`189a3abb1c`); it is now in the merged diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index e5642be3990..dbd3434baaf 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -1,12 +1,16 @@ //! Identity top-up for an *existing* identity — two funding sources: //! -//! - [`platform_wallet_top_up_from_addresses_with_signer`] wraps the -//! composite -//! [`PlatformWallet::top_up_from_addresses`](platform_wallet::PlatformWallet::top_up_from_addresses), +//! - [`platform_wallet_top_up_identity_from_addresses_with_signer`] wraps +//! the composite +//! [`PlatformWallet::top_up_identity_from_addresses`](platform_wallet::PlatformWallet::top_up_identity_from_addresses), //! spending already-funded Platform-payment addresses (driven by an -//! external `Signer` handle) and reusing the same -//! address-input shape (`IdentityFundingInputFFI`) the registration FFI -//! exposes. +//! external `Signer` handle) for any identity, the +//! wallet's own or someone else's, and reusing the same address-input +//! shape (`IdentityFundingInputFFI`) the registration FFI exposes. The +//! deprecated [`platform_wallet_top_up_from_addresses_with_signer`] (the +//! wallet's own identities only) and +//! [`platform_wallet_top_up_external_identity_from_addresses_with_signer`] +//! remain for existing hosts. //! - [`platform_wallet_top_up_identity_with_funding_signer`] wraps //! `IdentityWallet::top_up_identity_with_funding`, building and //! broadcasting a **new Core asset lock** (same mechanism as identity @@ -21,11 +25,10 @@ //! signed by the lock's Core-side key via the `MnemonicResolver`. //! //! On success the function writes the post-transition credit balance -//! back through `out_new_balance`. The local `ManagedIdentity` -//! manager is updated and the spent platform-address balances are -//! reconciled synchronously inside the composite library call; -//! callers can re-read the balance via `ManagedIdentity` once this -//! returns. +//! back through `out_new_balance`. When the wallet manages the identity its +//! `ManagedIdentity` is updated, and the spent platform-address balances are +//! reconciled, synchronously inside the composite library call; callers can +//! re-read the balance via `ManagedIdentity` once this returns. use std::slice; @@ -71,29 +74,35 @@ fn catch_address_top_up_panic( ) } -/// Top up an existing identity's credit balance from one or more -/// Platform addresses, using an external `SignerHandle` for the -/// per-address funding signatures. +/// Top up an identity's credit balance from one or more Platform +/// addresses, whoever owns the identity, using an external `SignerHandle` +/// for the per-address funding signatures. /// -/// On success `out_new_balance` is populated with the post-transition -/// credit balance returned by Platform. The Rust-side -/// `ManagedIdentity` for `identity_id` has its balance updated and -/// queued for persistence inside the library call, so a subsequent -/// `ManagedIdentity::balance` read on the same handle reflects the -/// new value without an extra round trip. +/// Wraps the composite +/// [`PlatformWallet::top_up_identity_from_addresses`](platform_wallet::PlatformWallet::top_up_identity_from_addresses): +/// the identity is fetched from Platform and never added to the wallet's +/// identity manager; when the wallet manages it, its `ManagedIdentity` +/// balance is updated and queued for persistence inside the library call, +/// so a subsequent `ManagedIdentity::balance` read reflects the new value. +/// The spent platform-address balances are reconciled either way. The host +/// does not decide whether the identity is its own. /// -/// The identity's balance is read from Platform before anything is signed: -/// a failed read is `ErrorIdentityLookupFailed` (80) and an identity -/// Platform does not know `ErrorIdentityNotFound` (7), nothing sent. +/// On success `out_new_balance` is populated with the identity's +/// post-transition credit balance. +/// +/// Before anything is signed or broadcast: an identity Platform does not +/// know is `ErrorIdentityNotFound` (7), a failed lookup +/// `ErrorIdentityLookupFailed` (80), and empty or overflowing funding rows +/// `ErrorInvalidParameter`. /// /// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have /// executed or may still execute: its result was not proved, or the call /// panicked, possibly after signing or broadcast. A result proof counts only /// when it shows every input address at or past the nonce this top-up was /// signed with AND the identity balance above the balance the top-up started -/// from, a fresh read from Platform taken before signing; any other proof is -/// 20 and nothing is reconciled from it. The host must not submit it again; -/// the next sync settles the outcome. +/// from, the one in the identity fetched from Platform before signing; any +/// other proof is 20 and nothing is reconciled from it. The host must not +/// submit it again; the next sync settles the outcome. /// /// # Safety /// - `wallet_handle` must come from the platform-wallet handle registry. @@ -107,8 +116,7 @@ fn catch_address_top_up_panic( /// The caller retains ownership; this function does NOT destroy it. /// - `out_new_balance` must be writable for the duration of the call. #[no_mangle] -#[allow(clippy::too_many_arguments)] -pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( +pub unsafe extern "C" fn platform_wallet_top_up_identity_from_addresses_with_signer( wallet_handle: Handle, identity_id: *const [u8; 32], inputs: *const IdentityFundingInputFFI, @@ -116,85 +124,98 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( signer_address_handle: *mut SignerHandle, out_new_balance: *mut u64, ) -> PlatformWalletFFIResult { - catch_address_top_up_panic("platform_wallet_top_up_from_addresses_with_signer", || { - check_ptr!(identity_id); - check_ptr!(inputs); - check_ptr!(signer_address_handle); - check_ptr!(out_new_balance); - let identity_id_bytes: [u8; 32] = *identity_id; - let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let rows = match funding_rows(inputs, inputs_count) { - Ok(rows) => rows, - Err(error) => return error, - }; - - // Round-trip the signer pointer through `usize` so the spawned - // future's capture is `Send + 'static` (the raw pointer is `!Send`, - // but `usize` is). The underlying `Inner::Callback { ctx, vtable }` - // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. - let signer_addr = signer_address_handle as usize; - - // Take the wallet out of the registry in a short read, so the registry - // is not locked while the host signs. - let wallet = unwrap_option_or_return!( - PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone()) - ); - let result = block_on_worker(async move { - let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - // The composite tops up the identity AND reconciles the spent - // platform-address balances from the proof, so the wallet's - // displayed balance and next input selection reflect the spend - // (covering addresses restored from disk that are no longer in - // a live derived pool). - wallet - .top_up_from_addresses(&identity_id, rows, address_signer, None) - .await - }); - let new_balance = unwrap_result_or_return!(result); - *out_new_balance = new_balance; - PlatformWalletFFIResult::ok() - }) + catch_address_top_up_panic( + "platform_wallet_top_up_identity_from_addresses_with_signer", + || { + address_top_up( + wallet_handle, + identity_id, + inputs, + inputs_count, + signer_address_handle, + out_new_balance, + AddressTopUpRoute::AnyIdentity, + ) + }, + ) } -/// Marshal the address-input rows of an address-funded top-up into the -/// funding rows the library takes; the library sums rows naming the same -/// address and refuses what it cannot act on. +/// Top up an identity the wallet manages from one or more Platform +/// addresses, using an external `SignerHandle` for the per-address funding +/// signatures. +/// +/// **Deprecated:** use +/// [`platform_wallet_top_up_identity_from_addresses_with_signer`], which +/// tops up any identity and updates a managed one's balance the same way. +/// This export differs only in refusing an identity the wallet does not +/// manage with `ErrorIdentityNotFound` (7) before Platform is asked. It +/// wraps the deprecated +/// [`PlatformWallet::top_up_from_addresses`](platform_wallet::PlatformWallet::top_up_from_addresses), +/// itself built on the top-up of any identity. +/// +/// On success `out_new_balance` is populated with the post-transition +/// credit balance returned by Platform. The Rust-side +/// `ManagedIdentity` for `identity_id` has its balance updated and +/// queued for persistence inside the library call, so a subsequent +/// `ManagedIdentity::balance` read on the same handle reflects the +/// new value without an extra round trip. +/// +/// The identity is read from Platform before anything is signed: a failed +/// read is `ErrorIdentityLookupFailed` (80) and an identity Platform does +/// not know `ErrorIdentityNotFound` (7), nothing sent. +/// +/// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have +/// executed or may still execute: its result was not proved, or the call +/// panicked, possibly after signing or broadcast. A result proof counts only +/// when it shows every input address at or past the nonce this top-up was +/// signed with AND the identity balance above the balance the top-up started +/// from, a fresh read from Platform taken before signing; any other proof is +/// 20 and nothing is reconciled from it. The host must not submit it again; +/// the next sync settles the outcome. /// /// # Safety -/// `inputs` must point at a valid `[IdentityFundingInputFFI; inputs_count]` -/// array. -unsafe fn funding_rows( +/// Same contract as +/// [`platform_wallet_top_up_identity_from_addresses_with_signer`]. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( + wallet_handle: Handle, + identity_id: *const [u8; 32], inputs: *const IdentityFundingInputFFI, inputs_count: usize, -) -> Result, PlatformWalletFFIResult> { - slice::from_raw_parts(inputs, inputs_count) - .iter() - .map(|entry| match entry.address_type { - 0 => Ok((PlatformAddress::P2pkh(entry.hash), entry.credits)), - 1 => Ok((PlatformAddress::P2sh(entry.hash), entry.credits)), - _ => Err(PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "invalid address_type (expected 0 or 1)", - )), - }) - .collect() + signer_address_handle: *mut SignerHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + catch_address_top_up_panic("platform_wallet_top_up_from_addresses_with_signer", || { + address_top_up( + wallet_handle, + identity_id, + inputs, + inputs_count, + signer_address_handle, + out_new_balance, + AddressTopUpRoute::ManagedOnly, + ) + }) } /// Top up an identity this wallet does **not** manage (someone else's) /// from one or more Platform addresses, using an external `SignerHandle` /// for the per-address funding signatures. /// -/// Wraps the composite -/// [`PlatformWallet::top_up_external_identity_from_addresses`](platform_wallet::PlatformWallet::top_up_external_identity_from_addresses): -/// the identity is fetched from Platform rather than read from the wallet, +/// **Deprecated:** now the same call as +/// [`platform_wallet_top_up_identity_from_addresses_with_signer`], which +/// tops up any identity; use that instead. +/// +/// The identity is fetched from Platform rather than read from the wallet, /// is never added to the wallet's identity manager, and the spent -/// platform-address balances are reconciled as for -/// [`platform_wallet_top_up_from_addresses_with_signer`]. +/// platform-address balances are reconciled. Should the wallet manage the +/// identity after all, its balance is updated as well. /// /// On success `out_new_balance` is populated with the identity's /// post-transition credit balance returned by Platform. An identity -/// Platform does not know returns `ErrorIdentityNotFound` before anything -/// is signed or broadcast. +/// Platform does not know returns `ErrorIdentityNotFound` (7) and a failed +/// lookup `ErrorIdentityLookupFailed` (80), before anything is signed or +/// broadcast. /// /// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have /// executed or may still execute: its result was not proved, or the call @@ -206,7 +227,8 @@ unsafe fn funding_rows( /// the next sync settles the outcome. /// /// # Safety -/// Same contract as [`platform_wallet_top_up_from_addresses_with_signer`]. +/// Same contract as +/// [`platform_wallet_top_up_identity_from_addresses_with_signer`]. #[no_mangle] pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses_with_signer( wallet_handle: Handle, @@ -219,41 +241,112 @@ pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses catch_address_top_up_panic( "platform_wallet_top_up_external_identity_from_addresses_with_signer", || { - check_ptr!(identity_id); - check_ptr!(inputs); - check_ptr!(signer_address_handle); - check_ptr!(out_new_balance); - let identity_id_bytes: [u8; 32] = *identity_id; - let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let rows = match funding_rows(inputs, inputs_count) { - Ok(rows) => rows, - Err(error) => return error, - }; + address_top_up( + wallet_handle, + identity_id, + inputs, + inputs_count, + signer_address_handle, + out_new_balance, + AddressTopUpRoute::AnyIdentity, + ) + }, + ) +} + +/// Which library operation an address top-up export hands its arguments to. +#[derive(Clone, Copy)] +enum AddressTopUpRoute { + /// [`PlatformWallet::top_up_identity_from_addresses`](platform_wallet::PlatformWallet::top_up_identity_from_addresses). + AnyIdentity, + /// The deprecated + /// [`PlatformWallet::top_up_from_addresses`](platform_wallet::PlatformWallet::top_up_from_addresses). + ManagedOnly, +} + +/// The body every address top-up export shares: marshal the arguments, hand +/// them to `route`'s library operation and write its balance out. +/// +/// # Safety +/// The safety contract of +/// [`platform_wallet_top_up_identity_from_addresses_with_signer`]. +unsafe fn address_top_up( + wallet_handle: Handle, + identity_id: *const [u8; 32], + inputs: *const IdentityFundingInputFFI, + inputs_count: usize, + signer_address_handle: *mut SignerHandle, + out_new_balance: *mut u64, + route: AddressTopUpRoute, +) -> PlatformWalletFFIResult { + check_ptr!(identity_id); + check_ptr!(inputs); + check_ptr!(signer_address_handle); + check_ptr!(out_new_balance); + let identity_id_bytes: [u8; 32] = *identity_id; + let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); + let rows = match funding_rows(inputs, inputs_count) { + Ok(rows) => rows, + Err(error) => return error, + }; - // `usize` round-trip keeps the spawned future `Send + 'static`; see - // `platform_wallet_top_up_from_addresses_with_signer`. - let signer_addr = signer_address_handle as usize; + // Round-trip the signer pointer through `usize` so the spawned + // future's capture is `Send + 'static` (the raw pointer is `!Send`, + // but `usize` is). The underlying `Inner::Callback { ctx, vtable }` + // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. + let signer_addr = signer_address_handle as usize; - let wallet = unwrap_option_or_return!( - PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone()) - ); - let result = block_on_worker(async move { - let address_signer: &VTableSigner = - unsafe { &*(signer_addr as *const VTableSigner) }; + // Take the wallet out of the registry in a short read, so the registry + // is not locked while the host signs. + let wallet = + unwrap_option_or_return!(PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone())); + let result = block_on_worker(async move { + let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; + // The composite tops up the identity AND reconciles the spent + // platform-address balances from the proof, so the wallet's + // displayed balance and next input selection reflect the spend + // (covering addresses restored from disk that are no longer in + // a live derived pool). + match route { + AddressTopUpRoute::AnyIdentity => { wallet - .top_up_external_identity_from_addresses( - &identity_id, - rows, - address_signer, - None, - ) + .top_up_identity_from_addresses(&identity_id, rows, address_signer, None) .await - }); - let new_balance = unwrap_result_or_return!(result); - *out_new_balance = new_balance; - PlatformWalletFFIResult::ok() - }, - ) + } + AddressTopUpRoute::ManagedOnly => { + #[allow(deprecated)] + let top_up = wallet.top_up_from_addresses(&identity_id, rows, address_signer, None); + top_up.await + } + } + }); + let new_balance = unwrap_result_or_return!(result); + *out_new_balance = new_balance; + PlatformWalletFFIResult::ok() +} + +/// Marshal the address-input rows of an address-funded top-up into the +/// funding rows the library takes; the library sums rows naming the same +/// address and refuses what it cannot act on. +/// +/// # Safety +/// `inputs` must point at a valid `[IdentityFundingInputFFI; inputs_count]` +/// array. +unsafe fn funding_rows( + inputs: *const IdentityFundingInputFFI, + inputs_count: usize, +) -> Result, PlatformWalletFFIResult> { + slice::from_raw_parts(inputs, inputs_count) + .iter() + .map(|entry| match entry.address_type { + 0 => Ok((PlatformAddress::P2pkh(entry.hash), entry.credits)), + 1 => Ok((PlatformAddress::P2sh(entry.hash), entry.credits)), + _ => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "invalid address_type (expected 0 or 1)", + )), + }) + .collect() } /// Minimum asset-lock funding for a Core-funded identity top-up, in duffs. diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs index c04819b9ce0..cf5eaf8767b 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs @@ -1,6 +1,6 @@ -//! The external-identity top-up export: its argument guards, and an identity +//! The address top-up exports: their argument guards, and an identity //! Platform does not know reported as code 7 through the real wallet handle. -//! A panic in either address top-up export is reported as code 20. +//! A panic in any address top-up export is reported as code 20. use std::ptr::NonNull; use std::sync::Arc; @@ -14,9 +14,12 @@ use dpp::ProtocolError; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use rs_sdk_ffi::{SignerHandle, VTableSigner}; -use super::platform_wallet_top_up_external_identity_from_addresses_with_signer as top_up; -use super::platform_wallet_top_up_from_addresses_with_signer; -use crate::error::PlatformWalletFFIResultCode; +use super::{ + platform_wallet_top_up_external_identity_from_addresses_with_signer, + platform_wallet_top_up_from_addresses_with_signer, + platform_wallet_top_up_identity_from_addresses_with_signer, +}; +use crate::error::{PlatformWalletFFIResult, PlatformWalletFFIResultCode}; use crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; use crate::identity_registration::IdentityFundingInputFFI; use crate::runtime::runtime; @@ -25,6 +28,29 @@ use crate::test_fixtures::mock_manager; const IDENTITY: [u8; 32] = [9; 32]; const UNTOUCHED: u64 = 0xDEAD; +type Export = unsafe extern "C" fn( + Handle, + *const [u8; 32], + *const IdentityFundingInputFFI, + usize, + *mut SignerHandle, + *mut u64, +) -> PlatformWalletFFIResult; + +/// The top-up of any identity, then the deprecated managed and external +/// exports. +const EXPORTS: [(&str, Export); 3] = [ + ( + "any", + platform_wallet_top_up_identity_from_addresses_with_signer, + ), + ("managed", platform_wallet_top_up_from_addresses_with_signer), + ( + "external", + platform_wallet_top_up_external_identity_from_addresses_with_signer, + ), +]; + fn input(address_type: u8) -> IdentityFundingInputFFI { IdentityFundingInputFFI { address_type, @@ -65,41 +91,47 @@ fn should_refuse_null_pointers() { let id = IDENTITY; let inputs = [input(0)]; let mut balance = UNTOUCHED; - let calls = [ - unsafe { - top_up( - 0, - std::ptr::null(), - inputs.as_ptr(), - 1, - dangling_signer(), - &mut balance, - ) - }, - unsafe { top_up(0, &id, std::ptr::null(), 1, dangling_signer(), &mut balance) }, - unsafe { - top_up( - 0, - &id, - inputs.as_ptr(), - 1, - std::ptr::null_mut(), - &mut balance, - ) - }, - unsafe { - top_up( - 0, - &id, - inputs.as_ptr(), - 1, - dangling_signer(), - std::ptr::null_mut(), - ) - }, - ]; - for result in calls { - assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + for (name, top_up) in EXPORTS { + let calls = [ + unsafe { + top_up( + 0, + std::ptr::null(), + inputs.as_ptr(), + 1, + dangling_signer(), + &mut balance, + ) + }, + unsafe { top_up(0, &id, std::ptr::null(), 1, dangling_signer(), &mut balance) }, + unsafe { + top_up( + 0, + &id, + inputs.as_ptr(), + 1, + std::ptr::null_mut(), + &mut balance, + ) + }, + unsafe { + top_up( + 0, + &id, + inputs.as_ptr(), + 1, + dangling_signer(), + std::ptr::null_mut(), + ) + }, + ]; + for result in calls { + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorNullPointer, + "{name}" + ); + } } assert_eq!(balance, UNTOUCHED); } @@ -108,20 +140,23 @@ fn should_refuse_null_pointers() { fn should_refuse_an_unknown_address_type() { let id = IDENTITY; let mut balance = UNTOUCHED; - let unknown_type = unsafe { - top_up( - 0, - &id, - [input(2)].as_ptr(), - 1, - dangling_signer(), - &mut balance, - ) - }; - assert_eq!( - unknown_type.code, - PlatformWalletFFIResultCode::ErrorInvalidParameter - ); + for (name, top_up) in EXPORTS { + let unknown_type = unsafe { + top_up( + 0, + &id, + [input(2)].as_ptr(), + 1, + dangling_signer(), + &mut balance, + ) + }; + assert_eq!( + unknown_type.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "{name}" + ); + } assert_eq!(balance, UNTOUCHED); } @@ -155,10 +190,10 @@ fn release(handle: Handle, signer: *mut SignerHandle) { } /// Rows naming one address whose sum overflows reach the library, which -/// refuses them as an invalid parameter on both exports instead of +/// refuses them as an invalid parameter on every export instead of /// saturating the amount. #[test] -fn should_refuse_an_overflowing_funding_sum_on_both_exports() { +fn should_refuse_an_overflowing_funding_sum_on_every_export() { let (handle, signer) = wallet_handle(Some(platform_identity())); let rows = [ IdentityFundingInputFFI { @@ -173,43 +208,45 @@ fn should_refuse_an_overflowing_funding_sum_on_both_exports() { let id = IDENTITY; let mut balance = UNTOUCHED; - let external = unsafe { top_up(handle, &id, rows.as_ptr(), 2, signer, &mut balance) }; - let managed = unsafe { - platform_wallet_top_up_from_addresses_with_signer( - handle, - &id, - rows.as_ptr(), - 2, - signer, - &mut balance, - ) - }; + let results = EXPORTS.map(|(name, top_up)| { + (name, unsafe { + top_up(handle, &id, rows.as_ptr(), 2, signer, &mut balance) + }) + }); release(handle, signer); - for result in [external, managed] { + for (name, result) in results { assert_eq!( result.code, - PlatformWalletFFIResultCode::ErrorInvalidParameter + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "{name}" ); } assert_eq!(balance, UNTOUCHED); } /// No funding rows reach the library, which refuses them as an invalid -/// parameter before looking the identity up. +/// parameter before looking the identity up, on every export. #[test] fn should_report_empty_inputs_as_an_invalid_parameter() { let (handle, signer) = wallet_handle(Some(platform_identity())); let id = IDENTITY; let mut balance = UNTOUCHED; - let result = unsafe { top_up(handle, &id, [input(0)].as_ptr(), 0, signer, &mut balance) }; + let results = EXPORTS.map(|(name, top_up)| { + (name, unsafe { + top_up(handle, &id, [input(0)].as_ptr(), 0, signer, &mut balance) + }) + }); release(handle, signer); - assert_eq!( - result.code, - PlatformWalletFFIResultCode::ErrorInvalidParameter - ); + for (name, result) in results { + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "{name}" + ); + } assert_eq!(balance, UNTOUCHED); } @@ -223,10 +260,17 @@ fn platform_identity() -> Identity { } /// The identity is looked up on Platform, not in the wallet: an identity -/// Platform does not know is `ErrorIdentityNotFound` (7), the balance out -/// is not written, and the wallet still manages no identity. +/// Platform does not know is `ErrorIdentityNotFound` (7) on the top-up of +/// any identity and on the deprecated external export, the balance out is +/// not written, and the wallet still manages no identity. #[test] fn should_report_an_identity_platform_does_not_know_as_not_found() { + for (name, top_up) in [EXPORTS[0], EXPORTS[2]] { + identity_platform_does_not_know_is_not_found(name, top_up); + } +} + +fn identity_platform_does_not_know_is_not_found(name: &str, top_up: Export) { let manager = mock_manager(); let mut sdk = manager.sdk().clone(); runtime() @@ -255,7 +299,8 @@ fn should_report_an_identity_platform_does_not_know_as_not_found() { drop(unsafe { Box::from_raw(signer as *mut VTableSigner) }); assert_eq!( result.code, - PlatformWalletFFIResultCode::ErrorIdentityNotFound + PlatformWalletFFIResultCode::ErrorIdentityNotFound, + "{name}" ); assert_eq!(balance, UNTOUCHED); let identities = runtime().block_on(async { @@ -268,48 +313,42 @@ fn should_report_an_identity_platform_does_not_know_as_not_found() { .identity_manager .identity_count() }); - assert_eq!(identities, 0); + assert_eq!(identities, 0, "{name}"); } -/// A panic inside either address top-up export (here its blocking wait, +/// A panic inside any address top-up export (here its blocking wait, /// entered from inside a runtime) comes back as the "may have executed" /// code 20, not as an unwind through the C ABI that ends the host, and the /// balance out is not written. #[test] -fn should_turn_a_panic_in_either_export_into_the_unconfirmed_code() { +fn should_turn_a_panic_in_any_export_into_the_unconfirmed_code() { let (handle, signer) = wallet_handle(Some(platform_identity())); let id = IDENTITY; let rows = [input(0)]; let mut balance = UNTOUCHED; let out: *mut u64 = &mut balance; - let (external, managed) = tokio::runtime::Runtime::new() + let results = tokio::runtime::Runtime::new() .expect("a runtime") .block_on(async { - let external = unsafe { top_up(handle, &id, rows.as_ptr(), 1, signer, out) }; - let managed = unsafe { - platform_wallet_top_up_from_addresses_with_signer( - handle, - &id, - rows.as_ptr(), - 1, - signer, - out, - ) - }; - (external, managed) + EXPORTS.map(|(name, top_up)| { + (name, unsafe { + top_up(handle, &id, rows.as_ptr(), 1, signer, out) + }) + }) }); release(handle, signer); - for mut result in [external, managed] { + for (name, mut result) in results { assert_eq!( result.code, - PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed, + "{name}" ); let message = unsafe { std::ffi::CStr::from_ptr(result.message) } .to_string_lossy() .into_owned(); - assert!(message.contains("panicked"), "{message}"); + assert!(message.contains("panicked"), "{name}: {message}"); unsafe { crate::error::platform_wallet_ffi_result_free(&mut result) }; } assert_eq!(balance, UNTOUCHED); diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs index 01043843a8b..150acb31b46 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs @@ -1,4 +1,4 @@ -//! Both address top-up exports wait for the host signer without holding the +//! Every address top-up export waits for the host signer without holding the //! wallet handle registry: while a signature is pending, destroying another //! wallet handle and reading a balance must both complete. @@ -10,7 +10,7 @@ use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; -use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; +use dash_sdk::query_types::{AddressInfo, AddressInfos}; use dash_sdk::SdkBuilder; use dpp::address_funds::PlatformAddress; use dpp::identity::{Identity, IdentityV0}; @@ -27,6 +27,7 @@ use rs_sdk_ffi::{ use super::{ platform_wallet_top_up_external_identity_from_addresses_with_signer as top_up_external, platform_wallet_top_up_from_addresses_with_signer as top_up_managed, + platform_wallet_top_up_identity_from_addresses_with_signer as top_up_any, }; use crate::error::PlatformWalletFFIResult; use crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; @@ -133,11 +134,6 @@ async fn wallets() -> (Handle, Handle) { .expect_fetch::(Identifier::from(IDENTITY), Some(identity.clone())) .await .unwrap(); - // The managed route reads Platform's balance before signing. - sdk.mock() - .expect_fetch::(Identifier::from(IDENTITY), Some(0)) - .await - .unwrap(); let manager = PlatformWalletManager::new( Arc::new(sdk), Arc::new(NoPlatformPersistence), @@ -263,6 +259,11 @@ fn registry_is_free_while_the_signer_is_pending(export: Export) { ); } +#[test] +fn should_not_hold_the_wallet_registry_while_the_top_up_of_any_identity_waits_for_the_signer() { + registry_is_free_while_the_signer_is_pending(top_up_any); +} + #[test] fn should_not_hold_the_wallet_registry_while_the_external_top_up_waits_for_the_signer() { registry_is_free_while_the_signer_is_pending(top_up_external); diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs index ff18c8aad7c..53cf8bb979c 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs @@ -17,7 +17,7 @@ use dash_sdk::dapi_grpc::tonic::metadata::MetadataValue; use dash_sdk::dapi_grpc::tonic::Status; use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; use dash_sdk::platform::transition::put_settings::PutSettings; -use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; +use dash_sdk::query_types::{AddressInfo, AddressInfos}; use dash_sdk::{Error as SdkError, RequestSettings, Sdk, SdkBuilder}; use dpp::address_funds::{AddressWitness, PlatformAddress}; use dpp::consensus::state::address_funds::AddressInvalidNonceError; @@ -180,9 +180,10 @@ impl Fixture { .map_err(|status| transport_error(&wait_request, status)), ); sdk.mock().load_expectations_sync(directory.path()).unwrap(); - // The managed route reads Platform's balance before signing. + // The top-up reads the identity, and its balance, from Platform + // before signing. sdk.mock() - .expect_fetch::(identity.id(), Some(identity.balance())) + .expect_fetch::(identity.id(), Some(identity.clone())) .await .unwrap(); sdk.mock() @@ -238,20 +239,20 @@ impl Fixture { broadcasts: usize, waits: usize, ) -> String { - let error = self - .wallet - .top_up_from_addresses( - &self.identity_id, - BTreeMap::from([(ADDRESS, AMOUNT)]), - &self.signer, - Some(PutSettings { - request_settings: RequestSettings { - retries: Some(0), - ..Default::default() - }, + #[allow(deprecated)] + let top_up = self.wallet.top_up_from_addresses( + &self.identity_id, + BTreeMap::from([(ADDRESS, AMOUNT)]), + &self.signer, + Some(PutSettings { + request_settings: RequestSettings { + retries: Some(0), ..Default::default() - }), - ) + }, + ..Default::default() + }), + ); + let error = top_up .await .expect_err("a refused or unverified top-up must never succeed"); // This is the same blanket conversion used by the production FFI entry point. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 500acb46d89..688de77dc46 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -16,7 +16,7 @@ use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; -use dash_sdk::query_types::{AddressInfos, IdentityBalance}; +use dash_sdk::query_types::AddressInfos; use crate::error::{ preserve_signer_key_unavailable_or, promote_address_nonce_error, PlatformWalletError, @@ -33,78 +33,72 @@ mod external_identity_tests; // --------------------------------------------------------------------------- impl IdentityWallet { - /// Top up an identity by spending platform address balances. + /// Top up an identity by spending platform address balances, whoever + /// owns the identity. /// - /// Uses the `TopUpIdentityFromAddresses` SDK trait. Address nonces are - /// looked up automatically. + /// The identity is fetched from Platform (proved), never read from the + /// identity manager, and is never added to it: the manager's own + /// identities are written back by [`Self::record_top_up_balance`] once + /// the top-up is confirmed. The balance the top-up must grow is the one + /// in that fetched identity, read before anything is signed, so a cached + /// balance above Platform's cannot make an executed top-up look + /// unconfirmed. /// - /// This method owns only the identity-side balance update and returns - /// the proof-attested post-spend `AddressInfos` alongside the new - /// identity balance. The composite - /// [`PlatformWallet::top_up_from_addresses`] feeds the returned - /// `AddressInfos` through - /// [`PlatformAddressWallet::reconcile_address_infos`] — the - /// platform-address wallet holds the address provider needed to map a - /// spent address back to its derivation index (including addresses - /// restored from disk that are no longer in a live derived pool). + /// Returns the proof-attested post-spend `AddressInfos`, the identity's + /// proved new balance and the proof's metadata. Address nonces are + /// looked up automatically. /// - /// Crate-private: it does not check the wallet generation or reconcile - /// the spent addresses. Callers outside the crate use - /// [`PlatformWallet::top_up_from_addresses`], which holds the lifecycle - /// gate and reconciles. + /// Crate-private: it does not check the wallet generation, write the + /// managed balance back or reconcile the spent addresses. Callers + /// outside the crate use + /// [`PlatformWallet::top_up_identity_from_addresses`], which holds the + /// lifecycle gate, writes back and reconciles. /// - /// [`PlatformWallet::top_up_from_addresses`]: - /// crate::wallet::PlatformWallet::top_up_from_addresses - /// [`PlatformAddressWallet::reconcile_address_infos`]: - /// crate::wallet::PlatformAddressWallet::reconcile_address_infos + /// # Errors /// - /// The identity is signed for and reconciled as the identity manager - /// holds it, but the balance the top-up must grow is read from Platform - /// before anything is signed, so a cached balance above Platform's - /// cannot make an executed top-up look unconfirmed. A failed read is - /// [`PlatformWalletError::IdentityLookupFailed`], and Platform not - /// knowing the identity [`PlatformWalletError::IdentityNotFound`], both + /// Before any network I/O, funding rows that are empty or whose sum for + /// one address overflows are [`PlatformWalletError::InvalidParameter`]. + /// With `managed_only`, an identity the identity manager does not hold + /// is [`PlatformWalletError::IdentityNotFound`] before Platform is asked + /// (the contract of the deprecated managed-only route). Platform not + /// knowing the identity is [`PlatformWalletError::IdentityNotFound`] and + /// a failed lookup [`PlatformWalletError::IdentityLookupFailed`], both /// before anything is signed or broadcast. /// /// # Arguments /// /// * `identity_id` - The identity to top up. /// * `inputs` - Funding rows: platform addresses and the credits to - /// spend from each. Rows naming the same address are summed; a sum - /// that overflows is refused as an invalid parameter. + /// spend from each. Rows naming the same address are summed. /// * `address_signer` - Produces ECDSA signatures for the input /// [`PlatformAddress`]es. Construction is the caller's concern — /// seed-backed, hardware, FFI trampoline, whatever — the wallet /// struct carries no key material itself. - pub(crate) async fn top_up_from_addresses( + /// * `managed_only` - Refuse an identity the identity manager does not + /// hold, as the deprecated + /// [`PlatformWallet::top_up_from_addresses`] does. + /// + /// [`PlatformWallet::top_up_identity_from_addresses`]: + /// crate::wallet::PlatformWallet::top_up_identity_from_addresses + /// [`PlatformWallet::top_up_from_addresses`]: + /// crate::wallet::PlatformWallet::top_up_from_addresses + pub(crate) async fn top_up_identity_from_addresses( &self, identity_id: &Identifier, inputs: I, address_signer: &S, settings: Option, - ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> + managed_only: bool, + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> where S: Signer + Send + Sync, I: IntoIterator + 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)); + } + let identity = Identity::fetch(&self.sdk, *identity_id) .await .map_err(|source| PlatformWalletError::IdentityLookupFailed { identity_id: *identity_id, @@ -112,95 +106,56 @@ impl IdentityWallet { })? .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; - let (address_infos, mut new_balance, metadata) = self - .submit_top_up_from_addresses( - &identity, - balance_before, - inputs, - address_signer, - settings, - ) - .await?; - - let proof_height = metadata.height; - - // Reconcile the verified identity snapshot; failed cache writes remain pending. - { - let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; - if let Some(managed) = info.identity_manager.managed_identity_mut(identity_id) { - new_balance = managed.persist_confirmed_balance( - new_balance, - BlockTime::from(metadata), - &self.persister, - ); - } - } - - // The spent platform-address balances are reconciled by the - // composite `PlatformWallet::top_up_from_addresses`, which routes - // the returned `AddressInfos` through the platform-address wallet's - // shared reconciliation seam. - Ok((address_infos, new_balance, proof_height)) + self.submit_top_up_from_addresses( + &identity, + identity.balance(), + inputs, + address_signer, + settings, + ) + .await } - /// Top up an identity this wallet does not manage by spending platform - /// address balances. - /// - /// The identity is fetched from Platform (proved) rather than read from - /// the identity manager, and the identity manager is neither read nor - /// written: someone else's identity is never recorded as the wallet's - /// own. Returns the same proof-attested post-spend `AddressInfos`, new - /// identity balance and proof height as - /// [`Self::top_up_from_addresses`]. - /// - /// Crate-private: it does not check the wallet generation or reconcile - /// the spent addresses. Callers outside the crate use - /// [`PlatformWallet::top_up_external_identity_from_addresses`], which - /// holds the lifecycle gate and reconciles. - /// - /// Returns [`PlatformWalletError::IdentityNotFound`] before anything is - /// signed or broadcast when Platform has no identity with this id, and - /// [`PlatformWalletError::IdentityLookupFailed`], likewise before - /// anything is signed or broadcast, when the lookup itself fails. - /// `inputs` are funding rows as for [`Self::top_up_from_addresses`]. - /// - /// [`PlatformWallet::top_up_external_identity_from_addresses`]: - /// crate::wallet::PlatformWallet::top_up_external_identity_from_addresses - pub(crate) async fn top_up_external_from_addresses( + /// Whether the identity manager holds `identity_id`; + /// [`PlatformWalletError::WalletNotFound`] when the wallet manager has no + /// info for this wallet. + async fn manages_identity( &self, identity_id: &Identifier, - inputs: I, - address_signer: &S, - settings: Option, - ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> - where - S: Signer + Send + Sync, - I: IntoIterator + Send, - { - let inputs = funding_inputs(inputs)?; - let identity = Identity::fetch(&self.sdk, *identity_id) - .await - .map_err(|source| PlatformWalletError::IdentityLookupFailed { - identity_id: *identity_id, - source, - })? - .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; - - let (address_infos, new_balance, metadata) = self - .submit_top_up_from_addresses( - &identity, - identity.balance(), - inputs, - address_signer, - settings, + ) -> Result { + let wm = self.wallet_manager.read().await; + let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { + PlatformWalletError::WalletNotFound( + "Wallet info not found in wallet manager".to_string(), ) - .await?; - Ok((address_infos, new_balance, metadata.height)) + })?; + Ok(info.identity_manager.identity(identity_id).is_some()) + } + + /// Write a confirmed top-up's proved balance (`new_balance` at the + /// proof's `metadata`) back to the identity manager when it holds + /// `identity_id`, and return the balance the caller reports: the one the + /// manager keeps for a managed identity (a failed cache write stays + /// pending for a later retry), `new_balance` otherwise. An identity the + /// manager does not hold is left out of it. + pub(crate) async fn record_top_up_balance( + &self, + identity_id: &Identifier, + new_balance: Credits, + metadata: ResponseMetadata, + ) -> Credits { + let mut wm = self.wallet_manager.write().await; + match wm + .get_wallet_info_mut(&self.wallet_id) + .and_then(|info| info.identity_manager.managed_identity_mut(identity_id)) + { + Some(managed) => managed.persist_confirmed_balance( + new_balance, + BlockTime::from(metadata), + &self.persister, + ), + None => new_balance, + } } /// Build, sign, broadcast and wait for the top-up of `identity` from @@ -264,7 +219,7 @@ fn top_up_error(e: dash_sdk::Error) -> PlatformWalletError { /// The input map of an address-funded top-up from its funding rows: rows /// naming the same address are one input of their sum. A sum that overflows /// is refused with [`PlatformWalletError::InvalidParameter`], and so are no -/// rows at all: both routes call this before any network I/O, so an empty +/// rows at all: the top-up calls this before any network I/O, so an empty /// top-up is the caller's mistake whatever the identity lookup would say. pub(crate) fn funding_inputs( rows: impl IntoIterator, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index 27cb509f8ee..e0104ad7aa4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -29,7 +29,7 @@ use dash_sdk::dapi_grpc::platform::v0::{ }; use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; use dash_sdk::platform::transition::put_settings::PutSettings; -use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; +use dash_sdk::query_types::{AddressInfo, AddressInfos}; use dash_sdk::{RequestSettings, Sdk, SdkBuilder}; use dpp::address_funds::{AddressWitness, PlatformAddress}; use dpp::consensus::state::state_error::StateError; @@ -253,23 +253,37 @@ impl Fixture { self.top_up_with(vec![(ADDRESS, AMOUNT)]).await } + /// The top-up of any identity, topping up `target`. async fn top_up_with( &self, inputs: Vec<(PlatformAddress, u64)>, + ) -> Result { + self.wallet + .top_up_identity_from_addresses(&self.target, inputs, &self.signer, settings()) + .await + } + + /// The deprecated external route, topping up `target`. + #[allow(deprecated)] + async fn top_up_external_with( + &self, + inputs: Vec<(PlatformAddress, u64)>, ) -> Result { self.wallet .top_up_external_identity_from_addresses(&self.target, inputs, &self.signer, settings()) .await } - /// The managed route, topping up [`OWN_IDENTITY`]. - async fn top_up_own_with( + /// The deprecated managed route, topping up `identity_id`. + #[allow(deprecated)] + async fn top_up_managed_with( &self, + identity_id: [u8; 32], inputs: Vec<(PlatformAddress, u64)>, ) -> Result { self.wallet .top_up_from_addresses( - &Identifier::from(OWN_IDENTITY), + &Identifier::from(identity_id), inputs, &self.signer, settings(), @@ -277,6 +291,26 @@ impl Fixture { .await } + /// The deprecated managed route, topping up [`OWN_IDENTITY`]. + async fn top_up_own_with( + &self, + inputs: Vec<(PlatformAddress, u64)>, + ) -> Result { + self.top_up_managed_with(OWN_IDENTITY, inputs).await + } + + /// One top-up of [`AMOUNT`] from [`ADDRESS`] on each route, named: the + /// top-up of any identity and the deprecated external route topping up + /// `target`, the deprecated managed route [`OWN_IDENTITY`]. + async fn top_up_on_every_route(&self) -> [(&'static str, Result); 3] { + let rows = || vec![(ADDRESS, AMOUNT)]; + [ + ("any", self.top_up_with(rows()).await), + ("external", self.top_up_external_with(rows()).await), + ("managed", self.top_up_own_with(rows()).await), + ] + } + async fn managed_identity_ids(&self) -> Vec { self.wallet .wallet_manager() @@ -297,36 +331,69 @@ impl Fixture { /// The top-up of an identity the wallet does not manage is built from the /// identity Platform returned, signed once and submitted, instead of being -/// refused for not being in the identity manager. +/// refused for not being in the identity manager, by the top-up of any +/// identity and by the deprecated external route alike. #[tokio::test(flavor = "multi_thread")] async fn should_submit_a_top_up_for_an_identity_the_wallet_does_not_manage() { - let mut fixture = Fixture::new(true).await; + for external in [false, true] { + let mut fixture = Fixture::new(true).await; - let error = fixture - .top_up() - .await + let error = match external { + false => fixture.top_up().await, + true => fixture.top_up_external_with(vec![(ADDRESS, AMOUNT)]).await, + } .expect_err("the mock cannot prove the result"); - assert!( - matches!( - error, - PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(_)) - ), - "the top-up must be submitted, got {error:?}" - ); - assert_eq!(fixture.submissions().await, (1, 1, 1)); + assert!( + matches!( + error, + PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(_)) + ), + "external route {external}: the top-up must be submitted, got {error:?}" + ); + assert_eq!(fixture.submissions().await, (1, 1, 1)); + } } -/// Topping up someone else's identity never records it as the wallet's own. +/// Topping up someone else's identity never records it as the wallet's own, +/// on the top-up of any identity and on the deprecated external route. #[tokio::test(flavor = "multi_thread")] async fn should_leave_the_identity_manager_unchanged() { - let fixture = Fixture::new(true).await; - let before = fixture.managed_identity_ids().await; + for external in [false, true] { + let fixture = Fixture::new(true).await; + let before = fixture.managed_identity_ids().await; + + let _ = match external { + false => fixture.top_up().await, + true => fixture.top_up_external_with(vec![(ADDRESS, AMOUNT)]).await, + }; + + assert_eq!(fixture.managed_identity_ids().await, before); + assert_eq!(before, vec![Identifier::from(OWN_IDENTITY)]); + } +} + +/// The deprecated managed route keeps refusing an identity the identity +/// manager does not hold, even one Platform knows, with the typed not-found +/// error and nothing asked, signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_an_unmanaged_identity_on_the_deprecated_managed_route() { + let mut fixture = Fixture::new(true).await; + let target = fixture.target; - let _ = fixture.top_up().await; + let refused = fixture + .top_up_managed_with(target.to_buffer(), vec![(ADDRESS, AMOUNT)]) + .await; - assert_eq!(fixture.managed_identity_ids().await, before); - assert_eq!(before, vec![Identifier::from(OWN_IDENTITY)]); + assert!( + matches!(&refused, Err(PlatformWalletError::IdentityNotFound(id)) if *id == target), + "got {refused:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); + assert_eq!( + fixture.managed_identity_ids().await, + vec![Identifier::from(OWN_IDENTITY)] + ); } /// An identity Platform does not know is refused with the typed not-found @@ -371,23 +438,23 @@ async fn should_report_a_failed_recipient_lookup_as_not_sent() { assert_eq!(fixture.submissions().await, (0, 0, 0)); } -/// An empty funding map is the caller's mistake on both routes, refused as +/// An empty funding map is the caller's mistake on every route, refused as /// `InvalidParameter` before any network I/O, with nothing signed or /// submitted: whether Platform knows the identity, does not know it, or /// cannot be asked, the lookup never decides the error. #[tokio::test(flavor = "multi_thread")] -async fn should_report_empty_inputs_as_an_invalid_parameter_on_both_routes() { +async fn should_report_empty_inputs_as_an_invalid_parameter_on_every_route() { for on_platform in [Some(false), None, Some(true)] { let mut fixture = Fixture::build(on_platform, AMOUNT).await; - let external = fixture.top_up_with(Vec::new()).await; + let any = fixture.top_up_with(Vec::new()).await; + let external = fixture.top_up_external_with(Vec::new()).await; let managed = fixture.top_up_own_with(Vec::new()).await; let managed_unknown = fixture - .wallet - .top_up_from_addresses(&fixture.target, Vec::new(), &fixture.signer, settings()) + .top_up_managed_with(fixture.target.to_buffer(), Vec::new()) .await; - for result in [external, managed, managed_unknown] { + for result in [any, external, managed, managed_unknown] { assert!( matches!(&result, Err(PlatformWalletError::InvalidParameter(reason)) if reason == "no funding rows were provided"), @@ -398,11 +465,11 @@ async fn should_report_empty_inputs_as_an_invalid_parameter_on_both_routes() { } } -/// The managed route reads the identity's balance from Platform before -/// signing, the baseline its growth is measured against: a read that fails -/// (here no answer to the request) is the not-sent lookup failure, and -/// Platform not knowing the identity is not-found, both with nothing signed -/// or submitted. +/// The deprecated managed route reads the identity, and so the balance its +/// growth is measured against, from Platform before signing, as the top-up +/// of any identity does: a read that fails (here no answer to the request) +/// is the not-sent lookup failure, and Platform not knowing the identity is +/// not-found, both with nothing signed or submitted. #[tokio::test(flavor = "multi_thread")] async fn should_read_the_managed_identitys_balance_from_platform_before_signing() { let own = Identifier::from(OWN_IDENTITY); @@ -418,7 +485,7 @@ async fn should_read_the_managed_identitys_balance_from_platform_before_signing( fixture .sdk .mock() - .expect_fetch::(own, None) + .expect_fetch::(own, None) .await .unwrap(); let unknown = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; @@ -430,10 +497,11 @@ async fn should_read_the_managed_identitys_balance_from_platform_before_signing( } /// A handle to a wallet removed, or re-created under the same id, since it -/// was taken tops up nothing: refused before the identity is fetched, -/// anything is signed or submitted. +/// was taken tops up nothing, on the top-up of any identity and on both +/// deprecated routes: refused before the identity is fetched, anything is +/// signed or submitted. #[tokio::test(flavor = "multi_thread")] -async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_both_routes() { +async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_every_route() { let mut fixture = Fixture::new(true).await; let wallet_id = fixture.wallet.wallet_id(); fixture @@ -442,18 +510,13 @@ async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_both_routes() .await .expect("removed"); - let removed = fixture.top_up().await; - assert!( - matches!(&removed, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) - if *id == hex::encode(wallet_id)), - "{removed:?}" - ); - let removed_own = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; - assert!( - matches!(&removed_own, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) - if *id == hex::encode(wallet_id)), - "managed route: {removed_own:?}" - ); + for (route, removed) in fixture.top_up_on_every_route().await { + assert!( + matches!(&removed, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) + if *id == hex::encode(wallet_id)), + "{route} route: {removed:?}" + ); + } let recreated = fixture .manager @@ -466,22 +529,15 @@ async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_both_routes() .await .expect("re-created"); assert_eq!(recreated.wallet_id(), wallet_id); - let superseded = fixture.top_up().await; - assert!( - matches!( - superseded, - Err(PlatformWalletError::WalletRemovedBeforeSend(_)) - ), - "{superseded:?}" - ); - let superseded_own = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; - assert!( - matches!( - superseded_own, - Err(PlatformWalletError::WalletRemovedBeforeSend(_)) - ), - "managed route: {superseded_own:?}" - ); + for (route, superseded) in fixture.top_up_on_every_route().await { + assert!( + matches!( + superseded, + Err(PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "{route} route: {superseded:?}" + ); + } assert_eq!(fixture.submissions().await, (0, 0, 0)); } @@ -529,7 +585,7 @@ impl Signer for HeldSigner { } } -/// A removal waits for an external top-up that entered its fenced section, +/// A removal waits for a top-up that entered its fenced section, /// here held while signing, and completes once the top-up returns. #[tokio::test(flavor = "multi_thread")] async fn should_hold_a_wallets_removal_until_its_top_up_returns() { @@ -542,7 +598,7 @@ async fn should_hold_a_wallets_removal_until_its_top_up_returns() { let target = fixture.target; tokio::spawn(async move { wallet - .top_up_external_identity_from_addresses( + .top_up_identity_from_addresses( &target, BTreeMap::from([(ADDRESS, AMOUNT)]), &*signer, @@ -603,15 +659,20 @@ impl PlatformWalletPersistence for RecordingPersister { } } -/// A confirmed external top-up, through the composite's seam with a -/// proof-attested result in place of the network: the identity's new -/// balance is returned, the spent wallet address is reconciled and -/// persisted pinned at the proof's height, and the identity manager is -/// still unchanged. -#[tokio::test(flavor = "multi_thread")] -async fn should_reconcile_the_spent_addresses_of_a_confirmed_top_up() { - const NEW_BALANCE: u64 = 777_000; - const PROOF_HEIGHT: u64 = 4_242; +const NEW_BALANCE: u64 = 777_000; +const PROOF_HEIGHT: u64 = 4_242; + +/// A wallet whose persister records every store round, one of its own +/// platform addresses, and (with `managed`) [`OWN_IDENTITY`] in its identity +/// manager at [`BALANCE`]; the recorded rounds start empty. +async fn confirmed_top_up_wallet( + managed: bool, +) -> ( + PlatformWalletManager, + Arc, + Arc, + PlatformAddress, +) { let persister = Arc::new(RecordingPersister::default()); let manager = PlatformWalletManager::new( Arc::new(dash_sdk::Sdk::new_mock()), @@ -635,16 +696,35 @@ async fn should_reconcile_the_spent_addresses_of_a_confirmed_top_up() { }) .await .expect("a wallet address"); - let identities_before = wallet - .wallet_manager() - .read() - .await - .get_wallet_info(&wallet.wallet_id()) - .unwrap() - .identity_manager - .identity_ids(); + if managed { + wallet + .wallet_manager() + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + identity(OWN_IDENTITY), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } persister.0.lock().unwrap().clear(); + (manager, wallet, persister, spent) +} +/// Runs the composite's seam with a proof-attested result in place of the +/// network: `spent` at nonce 4 and balance 5, the identity at +/// [`NEW_BALANCE`], proved at [`PROOF_HEIGHT`]. Returns the balance the +/// top-up reports. +async fn confirm_top_up( + wallet: &PlatformWallet, + identity_id: Identifier, + spent: PlatformAddress, +) -> u64 { let confirmed = AddressInfos::from_iter([( spent, Some(AddressInfo { @@ -653,53 +733,117 @@ async fn should_reconcile_the_spent_addresses_of_a_confirmed_top_up() { balance: 5, }), )]); - let new_balance = wallet - .top_up_identity_with( - async { Ok((confirmed, NEW_BALANCE, PROOF_HEIGHT)) }, - "external identity top-up", - ) + let metadata = ResponseMetadata { + height: PROOF_HEIGHT, + time_ms: 1, + ..Default::default() + }; + wallet + .top_up_identity_with(&identity_id, async { + Ok((confirmed, NEW_BALANCE, metadata)) + }) .await - .expect("a confirmed top-up"); + .expect("a confirmed top-up") +} - assert_eq!(new_balance, NEW_BALANCE); +/// The spent address is reconciled and persisted pinned at the proof's +/// height. +async fn assert_spent_address_reconciled( + wallet: &PlatformWallet, + persister: &RecordingPersister, + spent: PlatformAddress, +) { assert!(wallet .platform() .addresses_with_balances() .await .contains(&(spent, 5))); - { - let stored = persister.0.lock().unwrap(); - let entry = stored - .iter() - .filter_map(|changeset| changeset.platform_addresses.as_ref()) - .flat_map(|addresses| addresses.addresses.iter()) - .find(|entry| PlatformAddress::P2pkh(entry.address.to_bytes()) == spent) - .expect("the spent address persisted"); - assert_eq!( - ( - entry.funds.balance, - entry.funds.nonce, - entry.funds.as_of_height - ), - (5, 4, PROOF_HEIGHT) - ); - assert!(stored - .iter() - .all(|changeset| changeset.identities.is_none())); - } + let stored = persister.0.lock().unwrap(); + let entry = stored + .iter() + .filter_map(|changeset| changeset.platform_addresses.as_ref()) + .flat_map(|addresses| addresses.addresses.iter()) + .find(|entry| PlatformAddress::P2pkh(entry.address.to_bytes()) == spent) + .expect("the spent address persisted"); assert_eq!( - wallet - .wallet_manager() - .read() - .await - .get_wallet_info(&wallet.wallet_id()) - .unwrap() - .identity_manager - .identity_ids(), - identities_before + ( + entry.funds.balance, + entry.funds.nonce, + entry.funds.as_of_height + ), + (5, 4, PROOF_HEIGHT) ); } +async fn identity_manager_ids(wallet: &PlatformWallet) -> Vec { + wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids() +} + +/// A confirmed top-up of an identity the wallet does not manage, through the +/// composite's seam with a proof-attested result in place of the network: +/// the identity's new balance is returned, the spent wallet address is +/// reconciled and persisted pinned at the proof's height, and the identity +/// manager is still unchanged, nothing about the identity stored. +#[tokio::test(flavor = "multi_thread")] +async fn should_reconcile_the_spent_addresses_of_a_confirmed_top_up() { + let (_manager, wallet, persister, spent) = confirmed_top_up_wallet(false).await; + let identities_before = identity_manager_ids(&wallet).await; + + let new_balance = confirm_top_up(&wallet, Identifier::from([9; 32]), spent).await; + + assert_eq!(new_balance, NEW_BALANCE); + assert_spent_address_reconciled(&wallet, &persister, spent).await; + assert!(persister + .0 + .lock() + .unwrap() + .iter() + .all(|changeset| changeset.identities.is_none())); + assert_eq!(identity_manager_ids(&wallet).await, identities_before); +} + +/// A confirmed top-up of one of the wallet's own identities writes the +/// proved balance back to the identity manager, and stores it, so the +/// cached balance is current without waiting for a sync; the spent address +/// is reconciled as for any identity and the manager holds the same +/// identities. +#[tokio::test(flavor = "multi_thread")] +async fn should_write_a_managed_identitys_balance_back_from_a_confirmed_top_up() { + let (_manager, wallet, persister, spent) = confirmed_top_up_wallet(true).await; + let own = Identifier::from(OWN_IDENTITY); + + let new_balance = confirm_top_up(&wallet, own, spent).await; + + assert_eq!(new_balance, NEW_BALANCE); + let cached = wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager + .identity(&own) + .expect("still managed") + .identity + .balance(); + assert_eq!(cached, NEW_BALANCE); + assert!(persister + .0 + .lock() + .unwrap() + .iter() + .any(|changeset| changeset.identities.is_some())); + assert_spent_address_reconciled(&wallet, &persister, spent).await; + assert_eq!(identity_manager_ids(&wallet).await, vec![own]); +} + /// Funding rows naming the same address are one input of their sum: the /// submitted transition is the one built from the single summed input. #[tokio::test(flavor = "multi_thread")] @@ -722,17 +866,18 @@ async fn should_sum_repeated_funding_rows_into_one_input() { } /// Rows whose sum for one address overflows are refused as the caller's -/// mistake on both routes, never saturated, with nothing signed or +/// mistake on every route, never saturated, with nothing signed or /// submitted. #[tokio::test(flavor = "multi_thread")] -async fn should_refuse_an_overflowing_funding_sum_on_both_routes() { +async fn should_refuse_an_overflowing_funding_sum_on_every_route() { let mut fixture = Fixture::new(true).await; let rows = vec![(ADDRESS, u64::MAX), (ADDRESS, 1)]; - let external = fixture.top_up_with(rows.clone()).await; + let any = fixture.top_up_with(rows.clone()).await; + let external = fixture.top_up_external_with(rows.clone()).await; let managed = fixture.top_up_own_with(rows).await; - for result in [external, managed] { + for result in [any, external, managed] { assert!( matches!(result, Err(PlatformWalletError::InvalidParameter(_))), "got {result:?}" diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 88f3bee5afb..44f531ecb37 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -39,6 +39,7 @@ use crate::changeset::{ ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::error::PlatformWalletError; +use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::query_types::AddressInfos; use dpp::address_funds::PlatformAddress; @@ -64,7 +65,6 @@ use { AutoAcceptProofSource, ContactCryptoProvider, ContactRequest, EstablishedContact, PaymentStarted, }, - dash_sdk::dapi_grpc::platform::v0::ResponseMetadata, dash_sdk::platform::dashpay::PRIVATE_CONTACT_REQUEST_DOCUMENT_TYPE_NAME, dpp::data_contract::accessors::v0::DataContractV0Getters, dpp::platform_value::BinaryData, @@ -585,33 +585,72 @@ impl PlatformWallet { // owns both sub-wallets, which is why the composition lives here. // ----------------------------------------------------------------- - /// Top up an existing identity's credit balance by spending platform - /// address balances, then reconcile the spent addresses' local - /// balances and nonces from the proof-attested post-spend - /// `AddressInfos`. + /// Top up an identity's credit balance by spending platform address + /// balances, whoever owns the identity, then reconcile the spent + /// addresses' local balances and nonces from the proof-attested + /// post-spend `AddressInfos`. /// - /// The identity-side semantics are those of the crate-private - /// `IdentityWallet::top_up_from_addresses`. Reconciliation failures are - /// logged inside the seam rather than propagated — Platform already - /// accepted the top-up, and a later sync reconciles. + /// The identity is fetched from Platform and never added to the identity + /// manager. When the identity manager holds it (one of this wallet's own + /// identities), its cached balance is written back from the proof, so + /// the host does not have to decide whether the identity is its own. + /// Reconciliation failures are logged inside the seam rather than + /// propagated — Platform already accepted the top-up, and a later sync + /// reconciles. /// /// The result stands only when its proof shows every input address at or /// past the nonce this top-up was signed with AND the identity balance - /// above the balance the top-up started from, a fresh read from Platform - /// taken before signing (not the identity manager's cached balance). - /// Otherwise the proof does not prove this top-up executed: it is - /// reported as `PlatformWalletError::Sdk` holding + /// above the balance the top-up started from, the one in the identity + /// fetched from Platform before signing (not the identity manager's + /// cached balance). Otherwise the proof does not prove this top-up + /// executed: it is reported as `PlatformWalletError::Sdk` holding /// `dash_sdk::Error::StateTransitionResultUnconfirmed` (it may still /// execute, so do not submit it again), and neither the identity balance /// nor the addresses are updated from it; the next sync settles them. /// - /// Holds the wallet generation's lifecycle gate like - /// [`Self::top_up_external_identity_from_addresses`]: a wallet removed or - /// re-created since this handle was taken is refused with - /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing signed or - /// broadcast. A caller must not hold the gate. + /// Before anything is signed or broadcast: empty or overflowing funding + /// rows are [`PlatformWalletError::InvalidParameter`], an identity + /// Platform does not know [`PlatformWalletError::IdentityNotFound`], and + /// a failed lookup [`PlatformWalletError::IdentityLookupFailed`]. + /// + /// Holds the wallet generation's lifecycle gate from the liveness check + /// through the fetch, signing, broadcast and reconciliation, so a + /// removal waits for it. A wallet removed or re-created since this + /// handle was taken is refused with + /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing + /// fetched, signed or broadcast. A caller must not hold the gate. + /// + /// Returns the identity's new credit balance: for a managed identity the + /// one the identity manager keeps. + pub async fn top_up_identity_from_addresses( + &self, + identity_id: &Identifier, + inputs: I, + address_signer: &S, + settings: Option, + ) -> Result + where + S: Signer + Send + Sync, + I: IntoIterator + Send, + { + self.top_up_identity(identity_id, inputs, address_signer, settings, false) + .await + } + + /// Top up an identity the identity manager holds, as + /// [`Self::top_up_identity_from_addresses`] does. + /// + /// Differs only in refusing an identity the identity manager does not + /// hold with [`PlatformWalletError::IdentityNotFound`] (after the + /// funding rows are checked, before Platform is asked), and in + /// [`PlatformWalletError::WalletNotFound`] when the wallet manager has no + /// info for this wallet. /// /// Returns the identity's new credit balance. + #[deprecated( + note = "use `top_up_identity_from_addresses`, which tops up any identity and writes a \ + managed identity's balance back" + )] pub async fn top_up_from_addresses( &self, identity_id: &Identifier, @@ -623,39 +662,22 @@ impl PlatformWallet { S: Signer + Send + Sync, I: IntoIterator + Send, { - self.top_up_identity_with( - self.identity - .top_up_from_addresses(identity_id, inputs, address_signer, settings), - "identity top-up", - ) - .await + self.top_up_identity(identity_id, inputs, address_signer, settings, true) + .await } - /// Top up an identity this wallet does not manage by spending platform - /// address balances, then reconcile the spent addresses exactly as - /// [`Self::top_up_from_addresses`] does. + /// Top up an identity this wallet does not manage: now + /// [`Self::top_up_identity_from_addresses`], which tops up any identity. /// /// The identity is fetched from Platform and never added to the identity - /// manager. - /// - /// Holds the wallet generation's lifecycle gate from the liveness check - /// through the fetch, signing, broadcast and reconciliation, so a - /// removal waits for it. A wallet removed or re-created since this - /// handle was taken is refused with - /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing - /// fetched, signed or broadcast. A caller must not hold the gate. - /// - /// The result stands only when its proof shows every input address at or - /// past the nonce this top-up was signed with AND the identity balance - /// above the balance the top-up started from, the one in the identity - /// fetched from Platform before signing. Otherwise the proof does not - /// prove this top-up executed: it is reported as - /// `PlatformWalletError::Sdk` holding - /// `dash_sdk::Error::StateTransitionResultUnconfirmed` (it may still - /// execute, so do not submit it again), and the addresses are not - /// updated from it; the next sync settles them. + /// manager. Should the identity manager hold it after all, its cached + /// balance is written back from the proof. /// /// Returns the identity's new credit balance. + #[deprecated( + note = "use `top_up_identity_from_addresses`, which tops up any identity and writes a \ + managed identity's balance back" + )] pub async fn top_up_external_identity_from_addresses( &self, identity_id: &Identifier, @@ -663,32 +685,54 @@ impl PlatformWallet { address_signer: &S, settings: Option, ) -> Result + where + S: Signer + Send + Sync, + I: IntoIterator + Send, + { + self.top_up_identity_from_addresses(identity_id, inputs, address_signer, settings) + .await + } + + /// [`Self::top_up_identity_from_addresses`], refusing an identity the + /// identity manager does not hold when `managed_only`. + async fn top_up_identity( + &self, + identity_id: &Identifier, + inputs: I, + address_signer: &S, + settings: Option, + managed_only: bool, + ) -> Result where S: Signer + Send + Sync, I: IntoIterator + Send, { self.top_up_identity_with( - self.identity.top_up_external_from_addresses( + identity_id, + self.identity.top_up_identity_from_addresses( identity_id, inputs, address_signer, settings, + managed_only, ), - "external identity top-up", ) .await } - /// An address top-up around its submission `top_up` (not yet started): - /// the lifecycle gate and liveness check, then the reconciliation of the - /// spent addresses at the proof's height (`AddressFunds::as_of_height`, - /// so the sync's delta replay never re-applies this transition's ops on - /// top of them). A seam so a test can hand in a confirmed result the - /// mock SDK cannot prove. + /// An address top-up of `identity_id` around its submission `top_up` + /// (not yet started): the lifecycle gate and liveness check, then the + /// bookkeeping of a confirmed result — the managed identity's balance + /// written back, and the spent addresses reconciled at the proof's + /// height (`AddressFunds::as_of_height`, so the sync's delta replay + /// never re-applies this transition's ops on top of them). A seam so a + /// test can hand in a confirmed result the mock SDK cannot prove. pub(crate) async fn top_up_identity_with( &self, - top_up: impl Future>, - label: &'static str, + identity_id: &Identifier, + top_up: impl Future< + Output = Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError>, + >, ) -> Result { let _lifecycle = self.core().generation_payment_guard().await; if !self.core().is_current_generation().await { @@ -696,9 +740,14 @@ impl PlatformWallet { self.wallet_id, ))); } - let (address_infos, new_balance, proof_height) = top_up.await?; + let (address_infos, new_balance, metadata) = top_up.await?; + let proof_height = metadata.height; + let new_balance = self + .identity + .record_top_up_balance(identity_id, new_balance, metadata) + .await; self.platform - .reconcile_address_infos(&address_infos, proof_height, label) + .reconcile_address_infos(&address_infos, proof_height, "identity top-up") .await; Ok(new_balance) } diff --git a/packages/rs-unified-sdk-jni/src/credits.rs b/packages/rs-unified-sdk-jni/src/credits.rs index 5d7831254d9..efd7b67c8f5 100644 --- a/packages/rs-unified-sdk-jni/src/credits.rs +++ b/packages/rs-unified-sdk-jni/src/credits.rs @@ -30,6 +30,7 @@ use jni::objects::{JByteArray, JClass, JString}; use jni::sys::{jboolean, jint, jlong}; use jni::JNIEnv; use platform_wallet_ffi::core_wallet_types::OutPointFFI; +use platform_wallet_ffi::error::PlatformWalletFFIResult; use platform_wallet_ffi::handle::Handle; use platform_wallet_ffi::identity_registration::IdentityFundingInputFFI; use platform_wallet_ffi::identity_transfer::PlatformAddressCreditOutputFFI; @@ -165,14 +166,46 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_withdra // ── Top up (existing identity ← Platform-address inputs) ─────────────── -/// Top up an existing identity's credit balance from one or more -/// Platform-address inputs, signed per-address via `signerHandle` (the -/// platform-address signer). Returns the post-transition credit balance. +/// Top up an identity's credit balance from one or more Platform-address +/// inputs, whoever owns the identity (the wallet's or someone else's), +/// signed per-address via `signerHandle` (the platform-address signer). +/// Returns the identity's post-transition credit balance. /// /// `inputsBlob` layout (big-endian): `u32 rowCount` then per row /// `u8 addressType (0 P2PKH / 1 P2SH), u8[20] hash, u64 credits`. /// -/// Wraps `platform_wallet_top_up_from_addresses_with_signer`. +/// Wraps `platform_wallet_top_up_identity_from_addresses_with_signer`, which +/// fetches the identity from Platform, never adds it to the wallet, and +/// updates the balance of an identity the wallet manages. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpIdentityFromAddresses( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + identity_id: JByteArray, + inputs_blob: JByteArray, + signer_handle: jlong, +) -> jlong { + address_top_up( + &mut env, + wallet_handle, + identity_id, + inputs_blob, + signer_handle, + platform_wallet_ffi::platform_wallet_top_up_identity_from_addresses_with_signer, + ) +} + +/// Top up an identity the wallet manages from one or more Platform-address +/// inputs, signed per-address via `signerHandle` (the platform-address +/// signer). Returns the post-transition credit balance. +/// +/// **Deprecated:** use `topUpIdentityFromAddresses`, which tops up any +/// identity; this one refuses an identity the wallet does not manage. +/// +/// `inputsBlob` layout as for `topUpIdentityFromAddresses`. +/// +/// Wraps the deprecated `platform_wallet_top_up_from_addresses_with_signer`. #[no_mangle] pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpFromAddresses( mut env: JNIEnv, @@ -182,7 +215,34 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpFr inputs_blob: JByteArray, signer_handle: jlong, ) -> jlong { - guard(&mut env, 0i64, |env| { + address_top_up( + &mut env, + wallet_handle, + identity_id, + inputs_blob, + signer_handle, + platform_wallet_ffi::platform_wallet_top_up_from_addresses_with_signer, + ) +} + +/// The marshalling the address top-up bridges share: decode the arguments, +/// call `export` and return the balance it writes, or throw its error. +fn address_top_up( + env: &mut JNIEnv, + wallet_handle: jlong, + identity_id: JByteArray, + inputs_blob: JByteArray, + signer_handle: jlong, + export: unsafe extern "C" fn( + Handle, + *const [u8; 32], + *const IdentityFundingInputFFI, + usize, + *mut SignerHandle, + *mut u64, + ) -> PlatformWalletFFIResult, +) -> jlong { + guard(env, 0i64, |env| { let Some(id) = read_id32(env, &identity_id, "identityId") else { return 0; }; @@ -196,7 +256,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpFr let mut out_balance: u64 = 0; let result = unsafe { - platform_wallet_ffi::platform_wallet_top_up_from_addresses_with_signer( + export( wallet_handle as Handle, &id as *const [u8; 32], inputs.as_ptr(), diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index 3f037a89cb4..938da9687d5 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -750,15 +750,23 @@ public final class ManagedPlatformWallet: @unchecked Sendable { // MARK: - Identity top-up (address-funded) - /// Top up an existing identity's credit balance from one or more - /// Platform addresses, using an external `KeychainSigner` for the + /// Top up an identity's credit balance from one or more Platform + /// addresses, whoever owns the identity (one of this wallet's or + /// someone else's), using an external `KeychainSigner` for the /// per-address funding signatures. /// + /// Bridges `platform_wallet_top_up_identity_from_addresses_with_signer`: + /// Rust fetches the identity from Platform, never adds it to the + /// wallet's identities, and updates the balance of an identity the + /// wallet manages, so the caller does not decide whether the identity + /// is its own. + /// /// Top-up state-transitions are signed entirely with the input /// addresses' private keys (no IdentityCreate to sign), so unlike /// `registerIdentityFromAddresses` only one signer is required — /// the same `KeychainSigner` you use for registration's - /// `addressSigner` role. + /// `addressSigner` role. An identity Platform does not know throws + /// `PlatformWalletError.identityNotFound` before anything is signed. /// /// - Parameters: /// - identityId: 32-byte identity id of the existing identity @@ -769,6 +777,29 @@ public final class ManagedPlatformWallet: @unchecked Sendable { /// for each input platform address. Borrowed for the /// duration of the call. /// + /// - Returns: the identity's new credit balance. + public func topUpIdentityFromAddresses( + identityId: Data, + inputs: [IdentityAddressInput], + addressSigner: KeychainSigner + ) async throws -> UInt64 { + try await topUpFromAddresses( + identityId: identityId, + inputs: inputs, + addressSigner: addressSigner, + call: addressTopUpExports.any + ) + } + + /// Top up an identity this wallet manages from one or more Platform + /// addresses. + /// + /// **Deprecated:** use `topUpIdentityFromAddresses`, which tops up any + /// identity and updates a managed one's balance the same way. This + /// method differs only in throwing `PlatformWalletError.identityNotFound` + /// for an identity the wallet does not manage. Arguments and signer + /// handling match `topUpIdentityFromAddresses`. + /// /// - Returns: the new credit balance reported by Platform. public func topUpFromAddresses( identityId: Data, @@ -786,6 +817,10 @@ public final class ManagedPlatformWallet: @unchecked Sendable { /// Top up an identity this wallet does **not** manage (someone /// else's) from one or more Platform addresses. /// + /// **Deprecated:** now the same operation as + /// `topUpIdentityFromAddresses`, which tops up any identity; use that + /// instead. + /// /// Bridges `platform_wallet_top_up_external_identity_from_addresses_with_signer`: /// Rust fetches the identity from Platform and never adds it to the /// wallet's identities, so nothing about it is persisted here either. @@ -807,10 +842,11 @@ public final class ManagedPlatformWallet: @unchecked Sendable { ) } - /// The two address-funded top-up exports each public wrapper hands its + /// The address-funded top-up exports each public wrapper hands its /// arguments to. A stored property so tests can swap in fakes and see /// which export a wrapper dispatches to. struct AddressTopUpExports { + var any: AddressTopUpCall = platform_wallet_top_up_identity_from_addresses_with_signer var managed: AddressTopUpCall = platform_wallet_top_up_from_addresses_with_signer var external: AddressTopUpCall = platform_wallet_top_up_external_identity_from_addresses_with_signer @@ -818,7 +854,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { var addressTopUpExports = AddressTopUpExports() - /// Signature shared by the two address-funded top-up exports. + /// Signature shared by the address-funded top-up exports. typealias AddressTopUpCall = @Sendable ( Handle, UnsafePointer?, diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TopUpIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TopUpIdentityView.swift index dc7b3ba68e7..5370e35dcce 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TopUpIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TopUpIdentityView.swift @@ -314,7 +314,7 @@ struct TopUpIdentityView: View { Task { do { - let balance = try await managedWallet.topUpFromAddresses( + let balance = try await managedWallet.topUpIdentityFromAddresses( identityId: identityId, inputs: inputs, addressSigner: signer diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift index 45e88fc19a8..eb2b2df2f4a 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift @@ -80,12 +80,17 @@ final class ExternalIdentityTopUpTests: XCTestCase { // MARK: - Export selection - /// Each public wrapper hands its arguments to its own export: the - /// external top-up never reaches the managed one, which would refuse an - /// identity the wallet does not manage. + /// Each public wrapper hands its arguments to its own export: neither + /// the top-up of any identity nor the external top-up reaches the + /// managed one, which would refuse an identity the wallet does not + /// manage. func testEachWrapperDispatchesToItsOwnExport() async throws { let wallet = ManagedPlatformWallet(handle: 42, walletId: Data()) wallet.addressTopUpExports = .init( + any: { _, _, _, _, _, outBalance in + outBalance!.pointee = 3 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + }, managed: { _, _, _, _, _, outBalance in outBalance!.pointee = 1 return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) @@ -103,6 +108,11 @@ final class ExternalIdentityTopUpTests: XCTestCase { identityId: identityId, inputs: [input], addressSigner: try signer() ) + let any = try await wallet.topUpIdentityFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + + XCTAssertEqual(any, 3, "the top-up of any identity must call its own export") XCTAssertEqual(external, 2, "the external wrapper must call the external export") XCTAssertEqual(managed, 1, "the managed wrapper must call the managed export") } From 51fc18519bd9b7a077e4dc135204d679d709a0ac Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 14 Nov 2026 04:32:51 +0200 Subject: [PATCH 2/7] fix(platform-wallet): take the address top-up's lifecycle gate after 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 --- .../identity/network/top_up_from_addresses.rs | 194 ++++++++++++++++-- .../external_identity_tests.rs | 142 ++++++++++--- .../src/wallet/platform_wallet.rs | 69 ++++--- 3 files changed, 333 insertions(+), 72 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 688de77dc46..6368f144577 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -1,7 +1,9 @@ //! Top-up an identity from platform addresses. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use dpp::address_funds::AddressWitness; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; use dpp::identity::Identity; @@ -15,6 +17,9 @@ use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; +use dpp::platform_value::BinaryData; +use dpp::ProtocolError; +use tokio::sync::OwnedRwLockReadGuard; use dash_sdk::query_types::AddressInfos; @@ -48,11 +53,19 @@ impl IdentityWallet { /// proved new balance and the proof's metadata. Address nonces are /// looked up automatically. /// - /// Crate-private: it does not check the wallet generation, write the - /// managed balance back or reconcile the spent addresses. Callers - /// outside the crate use - /// [`PlatformWallet::top_up_identity_from_addresses`], which holds the - /// lifecycle gate, writes back and reconciles. + /// The host signs through [`GatedAddressSigner`]: once the last input's + /// witness returns, the wallet generation's lifecycle gate is taken and + /// the generation checked current under it, so the broadcast and the + /// result wait run under the gate while the host's signing does not. The + /// gate comes back with the result, for the caller to hold through its + /// bookkeeping. A wallet removed, or re-created under its id, while the + /// host signed is [`PlatformWalletError::WalletRemovedBeforeSend`], with + /// nothing broadcast. + /// + /// Crate-private: it does not write the managed balance back or + /// reconcile the spent addresses. Callers outside the crate use + /// [`PlatformWallet::top_up_identity_from_addresses`], which writes back + /// and reconciles under the gate returned here. /// /// # Errors /// @@ -89,7 +102,13 @@ impl IdentityWallet { address_signer: &S, settings: Option, managed_only: bool, - ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> + ) -> Result< + ( + (AddressInfos, Credits, ResponseMetadata), + OwnedRwLockReadGuard<()>, + ), + PlatformWalletError, + > where S: Signer + Send + Sync, I: IntoIterator + Send, @@ -106,14 +125,15 @@ impl IdentityWallet { })? .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; - self.submit_top_up_from_addresses( - &identity, - identity.balance(), - inputs, - address_signer, - settings, - ) - .await + let gated = GatedAddressSigner::new(address_signer, self, inputs.keys().copied().collect()); + let confirmed = self + .submit_top_up_from_addresses(&identity, identity.balance(), inputs, &gated, settings) + .await + .map_err(|error| match gated.removed() { + true => PlatformWalletError::WalletRemovedBeforeSend(hex::encode(self.wallet_id)), + false => error, + })?; + Ok((confirmed, gated.into_gate().await)) } /// Whether the identity manager holds `identity_id`; @@ -207,6 +227,147 @@ impl IdentityWallet { } } +/// Where an address top-up's signing stands, for [`GatedAddressSigner`]. +enum TopUpGate { + /// The host has not signed every input yet: no gate is held. Holds the + /// inputs still to sign. + Signing(BTreeSet), + /// Every input is signed, and the wallet generation's lifecycle gate is + /// held from then on, until the top-up's bookkeeping ends. + Gated(OwnedRwLockReadGuard<()>), + /// Signed after the wallet was removed or replaced: nothing goes out. + Removed, +} + +/// The host's signer for an address top-up, taking the wallet generation's +/// lifecycle gate once the last input's witness returns and before it can +/// leave, as the contact request send does (its `GatedSigner`): the SDK +/// broadcasts right after signing, so the broadcast, the result wait and +/// the caller's bookkeeping run under the gate, while the host's signing +/// prompts do not. A wallet removed meanwhile does not wait for the host: +/// the last signature made after a removal, or after a re-creation under +/// the same id, is refused, so nothing is broadcast. +/// +/// The transition carries one witness per input, so it cannot be broadcast +/// before the last of them returned, and that one returns only with the +/// gate held. +pub(crate) struct GatedAddressSigner<'a, S: ?Sized> { + signer: &'a S, + wallet: &'a IdentityWallet, + gate: Mutex, +} + +impl<'a, S: ?Sized> GatedAddressSigner<'a, S> { + /// A signer for a top-up spending `inputs`, gated once each is signed. + pub(crate) fn new( + signer: &'a S, + wallet: &'a IdentityWallet, + inputs: BTreeSet, + ) -> Self { + Self { + signer, + wallet, + gate: Mutex::new(TopUpGate::Signing(inputs)), + } + } + + fn gate(&self) -> MutexGuard<'_, TopUpGate> { + self.gate.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Whether a signature was refused because the wallet was removed or + /// replaced while the host signed. + pub(crate) fn removed(&self) -> bool { + matches!(*self.gate(), TopUpGate::Removed) + } + + /// The lifecycle gate, for the caller to hold through the bookkeeping + /// of a submitted top-up. A submitted top-up signed every input, so the + /// gate is held already; were it not, it is taken here, so the + /// bookkeeping still runs under it. + pub(crate) async fn into_gate(self) -> OwnedRwLockReadGuard<()> { + let gate = self + .gate + .into_inner() + .unwrap_or_else(PoisonError::into_inner); + match gate { + TopUpGate::Gated(guard) => guard, + TopUpGate::Signing(_) | TopUpGate::Removed => { + self.wallet.generation.payment_guard_owned().await + } + } + } + + /// Note `address` signed. Once every input is, take the lifecycle gate + /// and check the wallet is still current under it. The gate is taken + /// before the wallet manager's lock, as the lock ordering requires. + async fn signed(&self, address: &PlatformAddress) -> Result<(), ProtocolError> { + match &mut *self.gate() { + TopUpGate::Signing(unsigned) => { + unsigned.remove(address); + if !unsigned.is_empty() { + return Ok(()); + } + } + TopUpGate::Gated(_) => return Ok(()), + TopUpGate::Removed => return Err(removed_while_signing()), + } + let guard = self.wallet.generation.payment_guard_owned().await; + let current = self + .wallet + .wallet_manager + .read() + .await + .get_wallet_info(&self.wallet.wallet_id) + .is_some_and(|info| Arc::ptr_eq(&info.generation, &self.wallet.generation)); + if current { + *self.gate() = TopUpGate::Gated(guard); + Ok(()) + } else { + *self.gate() = TopUpGate::Removed; + Err(removed_while_signing()) + } + } +} + +fn removed_while_signing() -> ProtocolError { + ProtocolError::Generic( + "the wallet was removed while the host signed the top-up: nothing is sent".to_string(), + ) +} + +impl std::fmt::Debug for GatedAddressSigner<'_, S> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GatedAddressSigner") + } +} + +#[async_trait::async_trait] +impl Signer for GatedAddressSigner<'_, S> +where + S: Signer + ?Sized + Send + Sync, +{ + async fn sign(&self, key: &PlatformAddress, data: &[u8]) -> Result { + let signature = self.signer.sign(key, data).await?; + self.signed(key).await?; + Ok(signature) + } + + async fn sign_create_witness( + &self, + key: &PlatformAddress, + data: &[u8], + ) -> Result { + let witness = self.signer.sign_create_witness(key, data).await?; + self.signed(key).await?; + Ok(witness) + } + + fn can_sign_with(&self, key: &PlatformAddress) -> bool { + self.signer.can_sign_with(key) + } +} + /// An SDK error of an address top-up as the wallet reports it: a nonce /// race promoted to its own error, every other error kept typed under /// [`PlatformWalletError::Sdk`]. @@ -271,7 +432,8 @@ pub(crate) fn funding_inputs( /// unexecuted top-up is then reported done. Closing that fully needs an /// execution-bound proof of this transition. The wallet does not serialise /// address spends per input address in-process: the address top-up holds -/// only the wallet generation's shared lifecycle gate (a read guard), and +/// only the wallet generation's shared lifecycle gate (a read guard, taken +/// once the host signed), and /// the per-wallet `shield_guard` single-flight covers the shield-class /// operations, not this path, so two concurrent spends from one address /// in one process can be signed with the same nonce. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index e0104ad7aa4..04ad3185c51 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -47,6 +47,7 @@ use key_wallet::account::account_collection::PlatformPaymentAccountKey; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use tokio::sync::{Notify, Semaphore}; +use super::GatedAddressSigner; use crate::changeset::{ ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, }; @@ -585,16 +586,15 @@ impl Signer for HeldSigner { } } -/// A removal waits for a top-up that entered its fenced section, -/// here held while signing, and completes once the top-up returns. -#[tokio::test(flavor = "multi_thread")] -async fn should_hold_a_wallets_removal_until_its_top_up_returns() { - let fixture = Fixture::new(true).await; - let wallet_id = fixture.wallet.wallet_id(); - let signer = Arc::new(HeldSigner::default()); +/// Spawns a top-up of `target` from [`ADDRESS`] signed by `signer`, and +/// returns once the host is asked to sign. +async fn spawn_held_top_up( + fixture: &Fixture, + signer: &Arc, +) -> tokio::task::JoinHandle> { let top_up = { let wallet = Arc::clone(&fixture.wallet); - let signer = Arc::clone(&signer); + let signer = Arc::clone(signer); let target = fixture.target; tokio::spawn(async move { wallet @@ -608,29 +608,128 @@ async fn should_hold_a_wallets_removal_until_its_top_up_returns() { }) }; signer.entered.notified().await; + top_up +} - let removal = { - let manager = Arc::clone(&fixture.manager); - tokio::spawn(async move { manager.remove_wallet(&wallet_id).await.map(|_| ()) }) - }; - tokio::time::sleep(Duration::from_millis(200)).await; +/// A removal does not wait for a top-up whose host is still signing: the +/// lifecycle gate is not held while the host signs. The signature returned +/// afterwards meets the removed wallet at the liveness check, so the top-up +/// is abandoned as removed before broadcast, with nothing submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_not_hold_a_wallets_removal_while_its_top_up_is_signed() { + let mut fixture = Fixture::new(true).await; + let wallet_id = fixture.wallet.wallet_id(); + let signer = Arc::new(HeldSigner::default()); + let top_up = spawn_held_top_up(&fixture, &signer).await; + + tokio::time::timeout( + Duration::from_secs(5), + fixture.manager.remove_wallet(&wallet_id), + ) + .await + .expect("the removal does not wait for the host's signature") + .expect("the removal completes"); + assert!(!fixture.wallet.core().is_current_generation().await); + + signer.release.add_permits(1); + let topped_up = top_up.await.expect("top-up task"); assert!( - !removal.is_finished(), - "the removal waits for the top-up being signed" + matches!(&topped_up, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) + if *id == hex::encode(wallet_id)), + "the wallet was removed while the host signed: {topped_up:?}" ); - assert!(fixture.wallet.core().is_current_generation().await); + let (broadcasts, waits, _) = fixture.submissions().await; + assert_eq!((broadcasts, waits), (0, 0), "nothing is broadcast"); +} + +/// The same for a wallet re-created under its id while the host signed: the +/// late signature meets a generation that is not the handle's, and nothing +/// is broadcast on the replacement. +#[tokio::test(flavor = "multi_thread")] +async fn should_abandon_a_top_up_signed_while_its_wallet_was_replaced() { + let mut fixture = Fixture::new(true).await; + let wallet_id = fixture.wallet.wallet_id(); + let signer = Arc::new(HeldSigner::default()); + let top_up = spawn_held_top_up(&fixture, &signer).await; + + fixture + .manager + .remove_wallet(&wallet_id) + .await + .expect("removed"); + fixture + .manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .expect("re-created"); signer.release.add_permits(1); let topped_up = top_up.await.expect("top-up task"); assert!( - !matches!( + matches!( topped_up, Err(PlatformWalletError::WalletRemovedBeforeSend(_)) ), - "the wallet was current when it was checked: {topped_up:?}" + "{topped_up:?}" + ); + let (broadcasts, waits, _) = fixture.submissions().await; + assert_eq!((broadcasts, waits), (0, 0), "nothing is broadcast"); +} + +/// The gate is taken once the last input's witness returns, not before: +/// with two inputs a removal completes after the first signature, and +/// after the last one it waits for the broadcast and bookkeeping that hold +/// the gate, completing once the top-up lets it go. +#[tokio::test(flavor = "multi_thread")] +async fn should_hold_a_wallets_removal_from_the_last_signature_until_the_top_up_ends() { + const SECOND: PlatformAddress = PlatformAddress::P2pkh([8; 20]); + let fixture = Fixture::new(true).await; + let wallet_id = fixture.wallet.wallet_id(); + let host = AddressSigner::default(); + let gated = GatedAddressSigner::new( + &host, + fixture.wallet.identity(), + BTreeSet::from([ADDRESS, SECOND]), + ); + + gated + .sign_create_witness(&ADDRESS, b"top-up") + .await + .expect("the first input signed"); + assert!( + tokio::time::timeout( + Duration::from_millis(200), + fixture.wallet.generation().teardown_guard() + ) + .await + .is_ok(), + "with an input left to sign, no gate is held" ); - removal + + gated + .sign_create_witness(&SECOND, b"top-up") .await + .expect("the last input signed on a current wallet"); + let removal = { + let manager = Arc::clone(&fixture.manager); + tokio::spawn(async move { manager.remove_wallet(&wallet_id).await.map(|_| ()) }) + }; + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !removal.is_finished(), + "the removal waits for a top-up past its last signature" + ); + assert!(fixture.wallet.core().is_current_generation().await); + + drop(gated.into_gate().await); + tokio::time::timeout(Duration::from_secs(5), removal) + .await + .expect("the removal completes once the top-up ends") .expect("removal task") .expect("the removal completes"); assert!(!fixture.wallet.core().is_current_generation().await); @@ -739,11 +838,8 @@ async fn confirm_top_up( ..Default::default() }; wallet - .top_up_identity_with(&identity_id, async { - Ok((confirmed, NEW_BALANCE, metadata)) - }) + .record_top_up(&identity_id, (confirmed, NEW_BALANCE, metadata)) .await - .expect("a confirmed top-up") } /// The spent address is reconciled and persisted pinned at the proof's diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 44f531ecb37..f70a7241a1d 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -1,7 +1,6 @@ //! The main PlatformWallet struct combining core, identity (+DashPay), and platform sub-wallets. use std::collections::BTreeMap; -use std::future::Future; use std::ops::{Deref, DerefMut}; use std::sync::Arc; @@ -613,12 +612,17 @@ impl PlatformWallet { /// Platform does not know [`PlatformWalletError::IdentityNotFound`], and /// a failed lookup [`PlatformWalletError::IdentityLookupFailed`]. /// - /// Holds the wallet generation's lifecycle gate from the liveness check - /// through the fetch, signing, broadcast and reconciliation, so a - /// removal waits for it. A wallet removed or re-created since this - /// handle was taken is refused with - /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing - /// fetched, signed or broadcast. A caller must not hold the gate. + /// Holds the wallet generation's lifecycle gate from the moment the host + /// signer returns the last input's signature, through the liveness + /// check, broadcast, result wait and bookkeeping, as the gate's contract + /// asks of an operation awaiting an external signer: a removal waits for + /// a top-up that is broadcasting, never for one whose signing prompt is + /// open. A wallet removed or re-created since this handle was taken is + /// refused with [`PlatformWalletError::WalletRemovedBeforeSend`]: before + /// anything is fetched or signed when that is already so at the start, + /// and at the liveness check after signing, with nothing broadcast, when + /// the removal happened while the host signed. A caller must not hold + /// the gate. /// /// Returns the identity's new credit balance: for a managed identity the /// one the identity manager keeps. @@ -707,40 +711,39 @@ impl PlatformWallet { S: Signer + Send + Sync, I: IntoIterator + Send, { - self.top_up_identity_with( - identity_id, - self.identity.top_up_identity_from_addresses( + // A point-in-time check, outside the gate: a handle to a wallet + // already removed asks the host for no signature. The decisive check + // runs under the gate once the host signed. + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id, + ))); + } + let (confirmed, _lifecycle) = self + .identity + .top_up_identity_from_addresses( identity_id, inputs, address_signer, settings, managed_only, - ), - ) - .await + ) + .await?; + Ok(self.record_top_up(identity_id, confirmed).await) } - /// An address top-up of `identity_id` around its submission `top_up` - /// (not yet started): the lifecycle gate and liveness check, then the - /// bookkeeping of a confirmed result — the managed identity's balance - /// written back, and the spent addresses reconciled at the proof's - /// height (`AddressFunds::as_of_height`, so the sync's delta replay - /// never re-applies this transition's ops on top of them). A seam so a - /// test can hand in a confirmed result the mock SDK cannot prove. - pub(crate) async fn top_up_identity_with( + /// The bookkeeping of a confirmed address top-up of `identity_id`, run + /// by the caller under the lifecycle gate: the managed identity's + /// balance written back, and the spent addresses reconciled at the + /// proof's height (`AddressFunds::as_of_height`, so the sync's delta + /// replay never re-applies this transition's ops on top of them). + /// Returns the balance the top-up reports. A seam so a test can hand in + /// a confirmed result the mock SDK cannot prove. + pub(crate) async fn record_top_up( &self, identity_id: &Identifier, - top_up: impl Future< - Output = Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError>, - >, - ) -> Result { - let _lifecycle = self.core().generation_payment_guard().await; - if !self.core().is_current_generation().await { - return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( - self.wallet_id, - ))); - } - let (address_infos, new_balance, metadata) = top_up.await?; + (address_infos, new_balance, metadata): (AddressInfos, Credits, ResponseMetadata), + ) -> Credits { let proof_height = metadata.height; let new_balance = self .identity @@ -749,7 +752,7 @@ impl PlatformWallet { self.platform .reconcile_address_infos(&address_infos, proof_height, "identity top-up") .await; - Ok(new_balance) + new_balance } /// Register a new identity funded by platform-address balances, then From 1244ad4257ec4bbe3005e44e3d1b95dfca4f4644 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 19:16:38 +0200 Subject: [PATCH 3/7] fix(kotlin-sdk): keep a completed address top-up when the caller is cancelled 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 --- .../dashsdk/credits/IdentityCredits.kt | 6 ++- .../credits/IdentityAddressTopUpTest.kt | 52 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index 996e65eaa10..c2262547294 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -1,6 +1,7 @@ package org.dashfoundation.dashsdk.credits import org.dashfoundation.dashsdk.wallet.op +import org.dashfoundation.dashsdk.wallet.opReturningCompletedResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -229,13 +230,16 @@ class IdentityCredits internal constructor( * to the wallet, and updates the balance of an identity the wallet * manages, so the caller does not decide whether it is its own. Returns * the identity's post-transition balance. + * + * Cancellation: a top-up that completed natively still returns its + * balance to a cancelled caller (see `TeardownGate.opReturningCompletedResult`). */ suspend fun topUpIdentityFromAddresses( walletHandle: Long, identityId: ByteArray, inputs: List, signerHandle: Long, - ): Long = gate.op { + ): Long = gate.opReturningCompletedResult { mapNativeErrors { addressTopUpNative.call( walletHandle, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt index c86902b9602..3a18abeadc4 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt @@ -1,8 +1,17 @@ package org.dashfoundation.dashsdk.credits +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import org.dashfoundation.dashsdk.wallet.TeardownGate import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test class IdentityAddressTopUpTest { @@ -42,4 +51,47 @@ class IdentityAddressTopUpTest { assertArrayEquals(FundingInput.encode(inputs), blob as ByteArray) assertEquals(5L, signer) } + + /** + * A top-up that completed natively after its caller was cancelled still + * hands the balance back, so the caller can tell the credits moved and + * does not retry the payment. + */ + @Test + fun `a cancelled caller still receives a completed top-up's balance`() = runBlocking { + for (gate in listOf(TeardownGate(), null)) { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val received = CompletableDeferred() + val credits = IdentityCredits( + gate = gate, + addressTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> + entered.countDown() + // The blocking JNI call does not observe cancellation; it + // completes only after the caller has been cancelled. + release.await() + 777L + }, + ) + + val op = launch(Dispatchers.Default) { + val balance = credits.topUpIdentityFromAddresses( + walletHandle = 42, + identityId = ByteArray(32) { 9 }, + inputs = listOf(FundingInput(addressType = 0, hash = ByteArray(20) { 7 }, credits = 1_000)), + signerHandle = 5, + ) + received.complete(balance) + } + assertTrue("native top-up never started", entered.await(5, TimeUnit.SECONDS)) + op.cancel() + release.countDown() + withTimeout(5_000) { op.join() } + + assertTrue(op.isCancelled) + assertTrue("completed top-up balance was dropped", received.isCompleted) + assertEquals(777L, received.await()) + gate?.let { withTimeout(5_000) { it.closeAndAwait() } } + } + } } From 57fe772c18f5abfa4d7f404e9aea298167d12fa1 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 19:16:38 +0200 Subject: [PATCH 4/7] refactor(platform-wallet): require the lifecycle gate for top-up bookkeeping 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 --- .../dashsdk/credits/IdentityCredits.kt | 4 ++++ .../org/dashfoundation/dashsdk/ffi/CreditsNative.kt | 4 ++++ .../identity/network/top_up_from_addresses.rs | 4 ++++ .../external_identity_tests.rs | 3 ++- .../src/wallet/platform_wallet.rs | 13 +++++++++---- packages/rs-unified-sdk-jni/src/credits.rs | 8 ++++++-- .../PlatformWallet/ManagedPlatformWallet.swift | 2 ++ 7 files changed, 31 insertions(+), 7 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index c2262547294..066c4312cad 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -259,6 +259,10 @@ class IdentityCredits internal constructor( * identity and updates a managed one's balance the same way; this one * differs only in refusing an identity the wallet does not manage. */ + @Deprecated( + "Use topUpIdentityFromAddresses, which tops up any identity.", + ReplaceWith("topUpIdentityFromAddresses(walletHandle, identityId, inputs, signerHandle)"), + ) suspend fun topUpFromAddresses( walletHandle: Long, identityId: ByteArray, diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt index a197d41a4d3..457ac19fd5d 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt @@ -97,6 +97,10 @@ internal object CreditsNative { * * @param inputsBlob as for [topUpIdentityFromAddresses]. */ + @Deprecated( + "Use topUpIdentityFromAddresses, which tops up any identity.", + ReplaceWith("topUpIdentityFromAddresses(walletHandle, identityId, inputsBlob, signerHandle)"), + ) external fun topUpFromAddresses( walletHandle: Long, identityId: ByteArray, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 6368f144577..14ada8f3b9d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -158,11 +158,15 @@ impl IdentityWallet { /// manager keeps for a managed identity (a failed cache write stays /// pending for a later retry), `new_balance` otherwise. An identity the /// manager does not hold is left out of it. + /// + /// `_lifecycle` is the wallet's held lifecycle gate: it must be held + /// across this manager write and the caller's address reconciliation. pub(crate) async fn record_top_up_balance( &self, identity_id: &Identifier, new_balance: Credits, metadata: ResponseMetadata, + _lifecycle: &OwnedRwLockReadGuard<()>, ) -> Credits { let mut wm = self.wallet_manager.write().await; match wm diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index 04ad3185c51..8d5510b8cc4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -837,8 +837,9 @@ async fn confirm_top_up( time_ms: 1, ..Default::default() }; + let lifecycle = wallet.generation().payment_guard_owned().await; wallet - .record_top_up(&identity_id, (confirmed, NEW_BALANCE, metadata)) + .record_top_up(&identity_id, (confirmed, NEW_BALANCE, metadata), &lifecycle) .await } diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index f70a7241a1d..4c393a8151a 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -11,7 +11,7 @@ use key_wallet::wallet::Wallet; #[cfg(feature = "shielded")] use key_wallet::PlatformP2PKHAddress; use key_wallet_manager::WalletManager; -use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; +use tokio::sync::{OwnedRwLockReadGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; use super::asset_lock::manager::AssetLockManager; use super::asset_lock::tracked::TrackedAssetLock; @@ -719,7 +719,7 @@ impl PlatformWallet { self.wallet_id, ))); } - let (confirmed, _lifecycle) = self + let (confirmed, lifecycle) = self .identity .top_up_identity_from_addresses( identity_id, @@ -729,7 +729,7 @@ impl PlatformWallet { managed_only, ) .await?; - Ok(self.record_top_up(identity_id, confirmed).await) + Ok(self.record_top_up(identity_id, confirmed, &lifecycle).await) } /// The bookkeeping of a confirmed address top-up of `identity_id`, run @@ -739,15 +739,20 @@ impl PlatformWallet { /// replay never re-applies this transition's ops on top of them). /// Returns the balance the top-up reports. A seam so a test can hand in /// a confirmed result the mock SDK cannot prove. + /// + /// `lifecycle` is the wallet's held lifecycle gate: it must be held + /// across the identity-manager write and the address reconciliation, so + /// a removal or replacement of the wallet cannot land between them. pub(crate) async fn record_top_up( &self, identity_id: &Identifier, (address_infos, new_balance, metadata): (AddressInfos, Credits, ResponseMetadata), + lifecycle: &OwnedRwLockReadGuard<()>, ) -> Credits { let proof_height = metadata.height; let new_balance = self .identity - .record_top_up_balance(identity_id, new_balance, metadata) + .record_top_up_balance(identity_id, new_balance, metadata, lifecycle) .await; self.platform .reconcile_address_infos(&address_infos, proof_height, "identity top-up") diff --git a/packages/rs-unified-sdk-jni/src/credits.rs b/packages/rs-unified-sdk-jni/src/credits.rs index efd7b67c8f5..4f6ea1f6a92 100644 --- a/packages/rs-unified-sdk-jni/src/credits.rs +++ b/packages/rs-unified-sdk-jni/src/credits.rs @@ -10,8 +10,12 @@ //! entry point (no stitching, per `packages/kotlin-sdk/CLAUDE.md`): //! - [`platform_wallet_transfer_credits_with_signer`] — identity → identity. //! - [`platform_wallet_withdraw_credits_with_signer`] — identity → L1 address. -//! - [`platform_wallet_top_up_from_addresses_with_signer`] — top up an -//! existing identity from Platform-address inputs (ID-06). +//! - [`platform_wallet_top_up_identity_from_addresses_with_signer`] — top up +//! any identity, the wallet's own or someone else's, from Platform-address +//! inputs (ID-06). +//! - [`platform_wallet_top_up_from_addresses_with_signer`] — **deprecated** +//! managed-only variant of the above: refuses an identity the wallet does +//! not manage. //! - [`platform_wallet_top_up_identity_with_funding_signer`] — top up an //! existing identity from a **new Core asset lock** (ID-05); this one //! takes a `MnemonicResolverHandle` (the Core asset-lock signer) rather diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index 938da9687d5..eff34580011 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -801,6 +801,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { /// handling match `topUpIdentityFromAddresses`. /// /// - Returns: the new credit balance reported by Platform. + @available(*, deprecated, message: "Use topUpIdentityFromAddresses") public func topUpFromAddresses( identityId: Data, inputs: [IdentityAddressInput], @@ -829,6 +830,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { /// `PlatformWalletError.identityNotFound` before anything is signed. /// /// - Returns: the identity's new credit balance reported by Platform. + @available(*, deprecated, message: "Use topUpIdentityFromAddresses") public func topUpExternalIdentityFromAddresses( identityId: Data, inputs: [IdentityAddressInput], From e2b52a10d1d8a0b9c9d9fd9c716f3b3fc5cb1fdf Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 23:24:35 +0200 Subject: [PATCH 5/7] fix(kotlin-sdk): keep a completed managed address top-up when the caller 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 --- .../dashsdk/credits/IdentityCredits.kt | 9 +++- .../credits/IdentityAddressTopUpTest.kt | 47 ++++++++++++------- 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index 066c4312cad..71fe2f6f4ac 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -93,6 +93,9 @@ class IdentityCredits internal constructor( ResumeTopUpNativeCall(CreditsNative::topUpIdentityWithExistingAssetLock), private val addressTopUpNative: AddressTopUpNativeCall = AddressTopUpNativeCall(CreditsNative::topUpIdentityFromAddresses), + @Suppress("DEPRECATION") + private val managedAddressTopUpNative: AddressTopUpNativeCall = + AddressTopUpNativeCall(CreditsNative::topUpFromAddresses), ) { /** @@ -258,6 +261,8 @@ class IdentityCredits internal constructor( * **Deprecated:** use [topUpIdentityFromAddresses], which tops up any * identity and updates a managed one's balance the same way; this one * differs only in refusing an identity the wallet does not manage. + * + * Cancellation: as for [topUpIdentityFromAddresses]. */ @Deprecated( "Use topUpIdentityFromAddresses, which tops up any identity.", @@ -268,9 +273,9 @@ class IdentityCredits internal constructor( identityId: ByteArray, inputs: List, signerHandle: Long, - ): Long = gate.op { + ): Long = gate.opReturningCompletedResult { mapNativeErrors { - CreditsNative.topUpFromAddresses( + managedAddressTopUpNative.call( walletHandle, identityId, FundingInput.encode(inputs), diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt index 3a18abeadc4..5200c7f48da 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityAddressTopUpTest.kt @@ -55,32 +55,41 @@ class IdentityAddressTopUpTest { /** * A top-up that completed natively after its caller was cancelled still * hands the balance back, so the caller can tell the credits moved and - * does not retry the payment. + * does not retry the payment. Holds for the deprecated managed-only + * route too. */ + @Suppress("DEPRECATION") @Test fun `a cancelled caller still receives a completed top-up's balance`() = runBlocking { + for (route in listOf(TopUpRoute.ANY_IDENTITY, TopUpRoute.MANAGED_DEPRECATED)) for (gate in listOf(TeardownGate(), null)) { val entered = CountDownLatch(1) val release = CountDownLatch(1) val received = CompletableDeferred() - val credits = IdentityCredits( - gate = gate, - addressTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> - entered.countDown() - // The blocking JNI call does not observe cancellation; it - // completes only after the caller has been cancelled. - release.await() - 777L - }, - ) + val native = AddressTopUpNativeCall { _, _, _, _ -> + entered.countDown() + // The blocking JNI call does not observe cancellation; it + // completes only after the caller has been cancelled. + release.await() + 777L + } + val unused = AddressTopUpNativeCall { _, _, _, _ -> error("wrong bridge") } + val credits = when (route) { + TopUpRoute.ANY_IDENTITY -> + IdentityCredits(gate = gate, addressTopUpNative = native, managedAddressTopUpNative = unused) + TopUpRoute.MANAGED_DEPRECATED -> + IdentityCredits(gate = gate, addressTopUpNative = unused, managedAddressTopUpNative = native) + } + val identityId = ByteArray(32) { 9 } + val inputs = listOf(FundingInput(addressType = 0, hash = ByteArray(20) { 7 }, credits = 1_000)) val op = launch(Dispatchers.Default) { - val balance = credits.topUpIdentityFromAddresses( - walletHandle = 42, - identityId = ByteArray(32) { 9 }, - inputs = listOf(FundingInput(addressType = 0, hash = ByteArray(20) { 7 }, credits = 1_000)), - signerHandle = 5, - ) + val balance = when (route) { + TopUpRoute.ANY_IDENTITY -> + credits.topUpIdentityFromAddresses(42, identityId, inputs, 5) + TopUpRoute.MANAGED_DEPRECATED -> + credits.topUpFromAddresses(42, identityId, inputs, 5) + } received.complete(balance) } assertTrue("native top-up never started", entered.await(5, TimeUnit.SECONDS)) @@ -89,9 +98,11 @@ class IdentityAddressTopUpTest { withTimeout(5_000) { op.join() } assertTrue(op.isCancelled) - assertTrue("completed top-up balance was dropped", received.isCompleted) + assertTrue("$route: completed top-up balance was dropped", received.isCompleted) assertEquals(777L, received.await()) gate?.let { withTimeout(5_000) { it.closeAndAwait() } } } } + + private enum class TopUpRoute { ANY_IDENTITY, MANAGED_DEPRECATED } } From 7535c902afff837a20b50da1f9757c5e5df02f68 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 23:28:06 +0200 Subject: [PATCH 6/7] refactor(platform-wallet): name the address top-up's identity scope 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 --- .../src/wallet/identity/network/mod.rs | 1 + .../identity/network/top_up_from_addresses.rs | 29 +++++++++------ .../src/wallet/platform_wallet.rs | 35 +++++++++++-------- 3 files changed, 41 insertions(+), 24 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index babb0e9fee1..1cffe91849c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -48,6 +48,7 @@ mod registration; mod state_transition_summary; mod top_up; mod top_up_from_addresses; +pub(crate) use top_up_from_addresses::TopUpScope; mod transfer; mod transfer_to_addresses; mod update; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 14ada8f3b9d..d30872ba5bc 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -37,6 +37,19 @@ mod external_identity_tests; // Top-up from platform addresses // --------------------------------------------------------------------------- +/// Which identities an address top-up accepts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum TopUpScope { + /// Any identity Platform knows, the wallet's own or someone else's. + AnyIdentity, + /// Only an identity the identity manager holds, as the deprecated + /// [`PlatformWallet::top_up_from_addresses`] does. + /// + /// [`PlatformWallet::top_up_from_addresses`]: + /// crate::wallet::PlatformWallet::top_up_from_addresses + ManagedOnly, +} + impl IdentityWallet { /// Top up an identity by spending platform address balances, whoever /// owns the identity. @@ -71,9 +84,9 @@ impl IdentityWallet { /// /// Before any network I/O, funding rows that are empty or whose sum for /// one address overflows are [`PlatformWalletError::InvalidParameter`]. - /// With `managed_only`, an identity the identity manager does not hold - /// is [`PlatformWalletError::IdentityNotFound`] before Platform is asked - /// (the contract of the deprecated managed-only route). Platform not + /// With [`TopUpScope::ManagedOnly`], an identity the identity manager + /// does not hold is [`PlatformWalletError::IdentityNotFound`] before + /// Platform is asked (the contract of the deprecated managed-only route). Platform not /// knowing the identity is [`PlatformWalletError::IdentityNotFound`] and /// a failed lookup [`PlatformWalletError::IdentityLookupFailed`], both /// before anything is signed or broadcast. @@ -87,21 +100,17 @@ impl IdentityWallet { /// [`PlatformAddress`]es. Construction is the caller's concern — /// seed-backed, hardware, FFI trampoline, whatever — the wallet /// struct carries no key material itself. - /// * `managed_only` - Refuse an identity the identity manager does not - /// hold, as the deprecated - /// [`PlatformWallet::top_up_from_addresses`] does. + /// * `scope` - Which identities the top-up accepts; see [`TopUpScope`]. /// /// [`PlatformWallet::top_up_identity_from_addresses`]: /// crate::wallet::PlatformWallet::top_up_identity_from_addresses - /// [`PlatformWallet::top_up_from_addresses`]: - /// crate::wallet::PlatformWallet::top_up_from_addresses pub(crate) async fn top_up_identity_from_addresses( &self, identity_id: &Identifier, inputs: I, address_signer: &S, settings: Option, - managed_only: bool, + scope: TopUpScope, ) -> Result< ( (AddressInfos, Credits, ResponseMetadata), @@ -114,7 +123,7 @@ impl IdentityWallet { I: IntoIterator + Send, { let inputs = funding_inputs(inputs)?; - if managed_only && !self.manages_identity(identity_id).await? { + if scope == TopUpScope::ManagedOnly && !self.manages_identity(identity_id).await? { return Err(PlatformWalletError::IdentityNotFound(*identity_id)); } let identity = Identity::fetch(&self.sdk, *identity_id) diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 4c393a8151a..51045762d7c 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -16,6 +16,7 @@ use tokio::sync::{OwnedRwLockReadGuard, RwLock, RwLockReadGuard, RwLockWriteGuar use super::asset_lock::manager::AssetLockManager; use super::asset_lock::tracked::TrackedAssetLock; use super::core::{CoreWallet, WalletBalance, WalletGeneration}; +use super::identity::network::TopUpScope; use super::identity::{IdentityManager, IdentityWallet}; #[cfg(feature = "shielded")] use super::persister::PrivatePaymentRestoreRetry; @@ -637,8 +638,14 @@ impl PlatformWallet { S: Signer + Send + Sync, I: IntoIterator + Send, { - self.top_up_identity(identity_id, inputs, address_signer, settings, false) - .await + self.top_up_identity( + identity_id, + inputs, + address_signer, + settings, + TopUpScope::AnyIdentity, + ) + .await } /// Top up an identity the identity manager holds, as @@ -666,8 +673,14 @@ impl PlatformWallet { S: Signer + Send + Sync, I: IntoIterator + Send, { - self.top_up_identity(identity_id, inputs, address_signer, settings, true) - .await + self.top_up_identity( + identity_id, + inputs, + address_signer, + settings, + TopUpScope::ManagedOnly, + ) + .await } /// Top up an identity this wallet does not manage: now @@ -697,15 +710,15 @@ impl PlatformWallet { .await } - /// [`Self::top_up_identity_from_addresses`], refusing an identity the - /// identity manager does not hold when `managed_only`. + /// [`Self::top_up_identity_from_addresses`], accepting the identities + /// `scope` names. async fn top_up_identity( &self, identity_id: &Identifier, inputs: I, address_signer: &S, settings: Option, - managed_only: bool, + scope: TopUpScope, ) -> Result where S: Signer + Send + Sync, @@ -721,13 +734,7 @@ impl PlatformWallet { } let (confirmed, lifecycle) = self .identity - .top_up_identity_from_addresses( - identity_id, - inputs, - address_signer, - settings, - managed_only, - ) + .top_up_identity_from_addresses(identity_id, inputs, address_signer, settings, scope) .await?; Ok(self.record_top_up(identity_id, confirmed, &lifecycle).await) } From dc11d90b7bf9f1f795b4174974a81cf78899d0a6 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 15 Nov 2026 23:37:32 +0200 Subject: [PATCH 7/7] fix(platform-wallet): recheck the wallet before asking the host to sign 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 --- .../identity/network/top_up_from_addresses.rs | 18 +++++++++- .../external_identity_tests.rs | 36 ++++++++++++++++++- .../src/wallet/platform_wallet.rs | 6 ++-- 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index d30872ba5bc..e519f5002b8 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -73,7 +73,9 @@ impl IdentityWallet { /// gate comes back with the result, for the caller to hold through its /// bookkeeping. A wallet removed, or re-created under its id, while the /// host signed is [`PlatformWalletError::WalletRemovedBeforeSend`], with - /// nothing broadcast. + /// nothing broadcast; one no longer current once the identity and the + /// address nonces are read is refused the same way before the host is + /// asked to sign. /// /// Crate-private: it does not write the managed balance back or /// reconcile the spent addresses. Callers outside the crate use @@ -227,6 +229,20 @@ impl IdentityWallet { .iter() .map(|(address, (nonce, _))| (*address, *nonce)) .collect(); + // A point-in-time check after the identity and nonce reads: a wallet + // removed during them asks the host for no signature. The decisive + // check still runs under the gate once the host signed. + let current = self + .wallet_manager + .read() + .await + .get_wallet_info(&self.wallet_id) + .is_some_and(|info| Arc::ptr_eq(&info.generation, &self.generation)); + if !current { + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id, + ))); + } let confirmed = identity .top_up_from_addresses_with_nonce_with_metadata( &self.sdk, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index 8d5510b8cc4..0ec00cdf102 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -47,7 +47,7 @@ use key_wallet::account::account_collection::PlatformPaymentAccountKey; use key_wallet::wallet::initialization::WalletAccountCreationOptions; use tokio::sync::{Notify, Semaphore}; -use super::GatedAddressSigner; +use super::{GatedAddressSigner, TopUpScope}; use crate::changeset::{ ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, }; @@ -542,6 +542,40 @@ async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_every_route() assert_eq!(fixture.submissions().await, (0, 0, 0)); } +/// 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!(&refused, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) + if *id == hex::encode(wallet_id)), + "{refused:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0), "nothing is signed"); +} + /// Signs like [`AddressSigner`], but only once released: holds a top-up in /// its signing step. #[derive(Debug)] diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 51045762d7c..50237125e7c 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -621,8 +621,10 @@ impl PlatformWallet { /// open. A wallet removed or re-created since this handle was taken is /// refused with [`PlatformWalletError::WalletRemovedBeforeSend`]: before /// anything is fetched or signed when that is already so at the start, - /// and at the liveness check after signing, with nothing broadcast, when - /// the removal happened while the host signed. A caller must not hold + /// before the host is asked to sign when the removal happened while the + /// identity and the address nonces were read, and at the liveness check + /// after signing, with nothing broadcast, when the removal happened while + /// the host signed. A caller must not hold /// the gate. /// /// Returns the identity's new credit balance: for a managed identity the