diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index ff3277332c9..a59a25072e7 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -71,6 +71,7 @@ "platform_wallet_token_purchase": "packages/rs-platform-wallet-ffi/src/tokens/purchase.rs", "platform_wallet_token_transfer": "packages/rs-platform-wallet-ffi/src/tokens/transfer.rs", "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_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", @@ -1468,6 +1469,39 @@ } ] }, + { + "id": "identity.external_top_up_from_addresses", + "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" + ], + "required_persistence_capabilities": [], + "hosts": { + "swift": { + "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." + }, + "kotlin": { + "sdk": "unsupported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "No JNI bridge or Kotlin wrapper for the external identity top-up yet." + } + }, + "verification": [ + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift", + "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 + } + ] + }, { "id": "tokens.authorization_decisions", "title": "Shared token authorization and group-proposal decisions", diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index 4f8eef43841..a62b3e0e164 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -2,23 +2,23 @@ # Kotlin/Swift executable parity summary Audit baseline: `PR #3999 @ 6dbc72a54df72d26eb9c4a014b425d2b95134e4e` -Capabilities tracked: **30** +Capabilities tracked: **31** ## Status counts | Host | Surface | Supported | Partial | Unsupported | Not applicable | | --- | --- | ---: | ---: | ---: | ---: | -| Swift | SDK | 17 | 11 | 1 | 1 | -| Swift | Example app | 5 | 14 | 2 | 9 | -| Kotlin | SDK | 14 | 14 | 1 | 1 | -| Kotlin | Example app | 6 | 13 | 1 | 10 | +| Swift | SDK | 18 | 11 | 1 | 1 | +| Swift | Example app | 5 | 14 | 3 | 9 | +| Kotlin | SDK | 14 | 14 | 2 | 1 | +| Kotlin | Example app | 6 | 13 | 2 | 10 | ## Restart coverage | Host | Tested | Required | Not applicable | | --- | ---: | ---: | ---: | -| Swift | 2 | 10 | 18 | -| Kotlin | 5 | 8 | 17 | +| Swift | 2 | 10 | 19 | +| Kotlin | 5 | 8 | 18 | ## Capability status @@ -42,6 +42,7 @@ Capabilities tracked: **30** | `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 | | `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/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 91547fb3e1d..0b5297dcd44 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -795,6 +795,19 @@ sealed class DashSdkError( class PublicContactRequestUnconfirmed(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * `ErrorIdentityLookupFailed` (native code 80). Platform could not be + * asked for an identity the operation names (the lookup failed, which + * is not Platform's answer that it does not exist, code 7). Nothing + * was signed, reserved or broadcast, so the operation may be retried + * as it is and is never a possibly delivered one. + * ← Swift `PlatformWalletError.identityLookupFailed`. + */ + class IdentityLookupFailed(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) { + override val isRetryable: Boolean get() = true + } + /** * Any other `PlatformWalletFFIResultCode` without a dedicated type. * Carries the platform-wallet [nativeCode] (already de-offset) and @@ -1004,6 +1017,7 @@ sealed class DashSdkError( 74 -> PlatformWallet.PrivateContactStoreNotRead(message, cause) // ErrorPrivateContactStoreNotRead 75 -> PlatformWallet.SdkPinnedBelowProtocolVersion(message, cause) // ErrorSdkPinnedBelowProtocolVersion 76 -> PlatformWallet.PublicContactRequestUnconfirmed(message, cause) // ErrorPublicContactRequestUnconfirmed + 80 -> PlatformWallet.IdentityLookupFailed(message, cause) // ErrorIdentityLookupFailed else -> // @Deprecated fallback — see the code-6 arm; code 31 is the // real discriminator. diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index f56f0736e5e..946d2a0882d 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -400,6 +400,20 @@ class DashSdkErrorTest { assertFalse("a sync settles it, not a retry", mapped.isRetryable) } + /** + * A failed identity lookup sent nothing: its own code, retryable as it is, + * apart from the unmapped SDK errors a host reads as possibly delivered. + */ + @Test + fun shouldReportAFailedIdentityLookupByItsOwnCode() { + val detail = "could not look up identity on Platform; nothing was sent" + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 80, detail) + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.IdentityLookupFailed) + assertEquals(detail, mapped.message) + assertTrue("nothing was sent, so it may be retried as it is", mapped.isRetryable) + } + @Test fun platformShieldCapacityCode41MapsTyped() { val message = diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index a5655430abd..7757bbbc2bf 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -114,7 +114,7 @@ These are shipped ABI. Do not renumber. | 98 | `NotFound` | Sentinel — `Option` returned as an error | | 99 | `ErrorUnknown` | Sentinel — unmapped/flattened errors | -**Next allocatable integer: 77**: 27–76 are all claimed (27, 29, 31, 34–42 +**Next allocatable integer: 81**: 27–80 are all claimed (27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their rows below); 49–54 proposed by active #4586 (the persister @@ -128,7 +128,7 @@ renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by by open branches with no row here yet (62 both `ErrorShieldedClaimBindingMismatch` and `ErrorIdentityRevisionMismatch`, 63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 -to 76 proposed for DashPay private contact requests; 28, 30, +to 76 proposed for DashPay private contact requests; 77–79 proposed by #5865 for the shielded spend plan (`ErrorShieldedPlanChanged`, `ErrorShieldedSpendTooManyNotes`, `ErrorShieldedWithdrawalAmountOutOfRange`); 80 proposed for the failed recipient lookup of the external identity top-up; 28, 30, 32 and 33 reserved). **28, 30, 32 and 33 are RESERVED, not free**: 28 and 30 were vacated when the reservation trio moved to 34–36; 32 and 33 lapsed when their in-repo owners @@ -184,7 +184,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 60 | `ErrorAssetLockTooManyInputs` | Core-to-shielded pooled Max | Proposed — an asset lock needs more inputs than one may carry (100 on Dash Core relay policy, and in Platform consensus for an instant proof): the full drain, or since #5712 a fixed amount held only in many small coins (identity registration, top-up, invitation, platform-address funding). Two meanings. On a build: nothing was broadcast, the reservation is released, no partial drain, and a rebuild after consolidating is safe. On the resume of a tracked `Built` / `Broadcast` lock over the cap (since #5714): it is not re-sent, but an earlier attempt may have reached peers; the row stays tracked and nothing is released. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | | 61 | `ErrorAssetLockRecipientMismatch` | dashpay/platform#5603 (tracked-lock shielded recipient) | Proposed — a shielded fund-from-asset-lock resume (the generic outpoint resume or a repeated-UUID wallet drain) names a different Orchard recipient than the one the tracked lock recorded when it was built. Nothing was submitted or paid; resume with the recorded recipient, which the row and `TrackedAssetLockFFI` expose. Rows tracked before recipients were recorded carry none and accept the caller's. Typed in Rust, Swift and Kotlin | | 68 | `ErrorPrivateContactRequestNeedsPrivateReply` | DashPay private contact requests | Proposed. The contact requests with that identity came or went privately (protocol version 15), so a `contactRequest` document to it, in reply or as a rotation, would publish the relationship: the public accept refuses a reply, and the public send refuses a request or a rotation. Nothing was sent; the request goes privately instead, and the in-kind accept picks the private reply itself. The shielded spend contract (`map_spend_result`) keeps the code, as the in-kind accept can raise it. Taken above 61–67, which open branches already hold. Returned by the public send and accept; the host sends with `platform_wallet_manager_send_private_contact_request`, or accepts with `platform_wallet_manager_accept_contact_request_replying_in_kind` (which picks the reply itself, so a host calling it does not route on 68) or `platform_wallet_manager_accept_private_contact_request`. Swift types it (`PlatformWalletError.privateContactRequestNeedsPrivateReply`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactRequestNeedsPrivateReply`, `DashSdkErrorTest` pin) | -| 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number. Returned by `platform_wallet_manager_accept_contact_request_replying_in_kind`, exported in every build. Swift types it (`PlatformWalletError.shieldedBuildRequired`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedBuildRequired`, `DashSdkErrorTest` pin) | +| 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number after 77–79, which the shielded spend plan PR (#5865) holds. Returned by `platform_wallet_manager_accept_contact_request_replying_in_kind`, exported in every build. Swift types it (`PlatformWalletError.shieldedBuildRequired`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedBuildRequired`, `DashSdkErrorTest` pin) | | 70 | `ErrorProtocolVersionNotActive` | DashPay private contact requests | Proposed. The SDK refused a request without sending it (`dash_sdk::Error::ProtocolVersionNotActive`, not pinned) because the network is proven at a protocol version below the one that serves it: for example the private contact request sync on a network before protocol version 15. Expected on such a network, so a host may stay quiet about it; it lifts when the network upgrades. An SDK pinned below the required version has its own code, 75. Mapped by the blanket conversion for every operation that propagates the SDK error. A refusal that may lift sooner (`is_transient_protocol_version_refusal`: the network's version could not be confirmed) keeps the catch-all `ErrorUnknown`, as before. Previously both fell to `ErrorUnknown`. Swift types it (`PlatformWalletError.protocolVersionNotActive`, `ErrorHandlingTests` pin) and SwiftExampleApp keeps a refresh quiet on it; Kotlin types it (`DashSdkError.PlatformWallet.ProtocolVersionNotActive`, `DashSdkErrorTest` pin) and KotlinExampleApp keeps a refresh quiet on it | | 71 | `ErrorPrivateContactRequestPending` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactRequestPending`: a private contact request to that identity is in flight (another private send or reply reserved it before sealing), or was paid for and a short read-back sync did not find the entry in the store yet, or a private payment the shielded store's journal keeps unresolved holds the pair. Nothing new was paid; a later private contact request sync settles it once the entry is read back, and the shielded sync once the payment provably never executes. Pending, not failed: the host must not submit it again. A private store read that did not finish before the request was decided is 74, not 71. The shielded spend contract (`map_spend_result`) keeps the code rather than flattening it to `ErrorWalletOperation`. Returned by the private send, the private accept and the in-kind accept, and by a public send or accept the pair holds; `platform_wallet_get_private_pair_held` reads one pair's hold as a send decides it. Swift types it (`PlatformWalletError.privateContactRequestPending`, `ErrorHandlingTests` pin; `ManagedPlatformWallet.privatePairHeld`), and SwiftExampleApp keeps the pair pending until that read says free; Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactRequestPending`, `DashSdkErrorTest` pin; `Dashpay.privateRepliesPending` reads the pair's hold through JNI `DashpayNative.privatePairHeld`), and KotlinExampleApp keeps the pair pending until that read says free | | 72 | `ErrorPrivateContactPaymentsNotRestored` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactPaymentsNotRestored`: wallet readiness, not one contact's pending request (71). The wallet's unconfirmed private payments may hold pairs no reservation shows yet, which only a restoration from the shielded store's journal shows. In a build with the `shielded` feature: the wallet was published (created or loaded) while no shielded store was configured, its persister declaring the private scan state (bit 15), which holds a wallet removed and registered again from the same seed, in this process or a new one; it was loaded after binding a shielded account in an earlier process; or its last restoration failed, or waits for a busy store. In every build: the identity was loaded with its private scan state marking a private payment that may be unresolved, or was added to a wallet whose backend kept its record marked after an earlier wallet under the id was removed (`ClientStartState::retained_private_contact_scan_states`). Contact requests and acceptances, public and private, are refused with nothing read, signed or broadcast until they are restored: configuring the shielded store restores them with no keys, as binding the wallet's shielded account does, and a contact request first retries a restoration once without waiting on the store; a private sync does not, and a build without the `shielded` feature never does. A host whose persister declares the private scan state configures the shielded store when it activates the manager, before loading or creating wallets: until it does, and while a failed configure is not retried, 72 holds. `platform_wallet_get_private_contact_readiness` reads whether the payments are restored and whether the last restoration failed (`private_payments_restore_failed`; the wallet's `PrivateContactReadiness::private_payments_restore_failure` holds the reason). `platform_wallet_get_private_payments_restore_failure` gives that reason. Swift types it (`PlatformWalletError.privateContactPaymentsNotRestored`, `ErrorHandlingTests` pin) and binds both reads (`ManagedPlatformWallet.privateContactReadiness`, `privatePaymentsRestoreFailure`); SwiftExampleApp configures the shielded store when it activates a manager, before loading wallets; on each DashPay refresh while the store did not open or the readiness reads not restored, it configures the store again (on a store already open, the wallet's own retry of every wallet still held, a restoration that failed after the open included) and reads the readiness after that, refreshing again on a timer (every 3 s for a minute, then every 15 s) for as long as the view is shown and the payments stay unrestored, and when a shielded sync pass ends; it shows "setting up" or the failure's reason until the readiness reads restored. Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactPaymentsNotRestored`, `DashSdkErrorTest` pin) and binds both reads (`Dashpay.privateContactReadiness`, `privatePaymentsRestoreFailure`); KotlinExampleApp configures the shielded store before loading wallets and on each DashPay refresh retries as SwiftExampleApp does, showing "setting up" or the failure's reason | @@ -192,6 +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) | **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/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 58194bf7197..7eb18c228f8 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -768,6 +768,15 @@ pub enum PlatformWalletFFIResultCode { /// [`Self::ErrorPrivateContactRequestPending`] (71). ErrorPublicContactRequestUnconfirmed = 76, + /// Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be + /// asked for an identity the operation names (a transport or proof + /// failure of the lookup, not Platform's answer that the identity does not + /// exist, which is [`Self::ErrorIdentityNotFound`] (7)). Nothing was + /// signed, reserved or broadcast, so the operation may be retried as it + /// is; a host need not treat it as possibly delivered. Returned by the + /// external identity top-up from Platform addresses. + ErrorIdentityLookupFailed = 80, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1248,6 +1257,11 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::PublicContactRequestUnconfirmed(..) => { PlatformWalletFFIResultCode::ErrorPublicContactRequestUnconfirmed } + // The recipient lookup failed before anything was signed or + // sent: a not-sent refusal, not an ambiguous SDK error. + PlatformWalletError::IdentityLookupFailed { .. } => { + PlatformWalletFFIResultCode::ErrorIdentityLookupFailed + } // The wallet's private payments from an earlier process are not // restored yet: wallet readiness, not one contact's pending request. PlatformWalletError::PrivateContactPaymentsNotRestored => { @@ -3170,6 +3184,21 @@ mod private_contact_request_error_tests { ); } + /// A failed identity lookup, which sent nothing, reaches the host by its + /// own code rather than as the SDK error it wraps. + #[test] + fn should_report_a_failed_identity_lookup_by_its_own_code() { + let result = PlatformWalletFFIResult::from(PlatformWalletError::IdentityLookupFailed { + identity_id: [7; 32].into(), + source: dash_sdk::Error::Generic("unreachable".to_string()), + }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorIdentityLookupFailed + ); + assert_eq!(result.code as u32, 80); + } + /// A public contact request a loaded wallet refuses until its private /// payments are restored reaches the host by its own code, not as a /// contact's pending request. 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 49c51337af8..e5642be3990 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -27,7 +27,6 @@ //! callers can re-read the balance via `ManagedIdentity` once this //! returns. -use std::collections::BTreeMap; use std::slice; use dpp::address_funds::PlatformAddress; @@ -43,9 +42,35 @@ use crate::identity_registration::IdentityFundingInputFFI; use crate::runtime::block_on_worker; use crate::{unwrap_option_or_return, unwrap_result_or_return}; +#[cfg(test)] +mod external_identity_tests; +#[cfg(test)] +mod registry_release_tests; #[cfg(test)] mod submission_result_tests; +/// What a host should know after an address top-up export panicked. +const ADDRESS_TOP_UP_PANIC_GUIDANCE: &str = "The top-up may have been signed and broadcast \ + and may still execute: do NOT submit it again; the next sync settles the outcome."; + +/// [`catch_panic_to_code`] for the address top-up exports. A panic can strike +/// in the identity lookup, the signing, after the broadcast or in the +/// reconciliation, so it is reported as +/// [`PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed`], +/// the code of a top-up whose execution is not proved, never as a definitive +/// unsent failure. +fn catch_address_top_up_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed, + ADDRESS_TOP_UP_PANIC_GUIDANCE, + body, + ) +} + /// Top up an existing identity's credit balance from one or more /// Platform addresses, using an external `SignerHandle` for the /// per-address funding signatures. @@ -57,6 +82,19 @@ mod submission_result_tests; /// `ManagedIdentity::balance` read on the same handle reflects the /// new value without an extra round trip. /// +/// 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. +/// +/// `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 /// - `wallet_handle` must come from the platform-wallet handle registry. /// - `identity_id` must point at a 32-byte identity id buffer for @@ -78,56 +116,30 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( signer_address_handle: *mut SignerHandle, out_new_balance: *mut u64, ) -> PlatformWalletFFIResult { - check_ptr!(identity_id); - check_ptr!(inputs); - check_ptr!(signer_address_handle); - check_ptr!(out_new_balance); - if inputs_count == 0 { - return PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "`inputs_count` is zero", - ); - } - - let identity_id_bytes: [u8; 32] = *identity_id; - let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - - let entries = slice::from_raw_parts(inputs, inputs_count); - let mut input_map: BTreeMap = BTreeMap::new(); - for entry in entries { - let address = match entry.address_type { - 0 => PlatformAddress::P2pkh(entry.hash), - 1 => PlatformAddress::P2sh(entry.hash), - _ => { - return PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "invalid address_type (expected 0 or 1)", - ); - } + 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, }; - // Caller may pass the same address twice (the Swift inputs - // builder is greedy and could legitimately split a single - // address across multiple rows in a future shape). Sum the - // contributions rather than overwriting — `BTreeMap::insert` - // would silently keep only the last credit value, causing - // the top-up to under-fund the identity by the difference. - // Saturating add keeps a pathological caller from looping - // overflow back to a small value. - input_map - .entry(address) - .and_modify(|existing| *existing = existing.saturating_add(entry.credits)) - .or_insert(entry.credits); - } - // 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; + // 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 option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { - let wallet = wallet.clone(); - block_on_worker(async move { + // 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 @@ -135,14 +147,113 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( // (covering addresses restored from disk that are no longer in // a live derived pool). wallet - .top_up_from_addresses(&identity_id, input_map, address_signer, None) + .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() + }) +} + +/// 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)", + )), }) - }); - let result = unwrap_option_or_return!(option); - let new_balance = unwrap_result_or_return!(result); - *out_new_balance = new_balance; - PlatformWalletFFIResult::ok() + .collect() +} + +/// 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, +/// 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`]. +/// +/// 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. +/// +/// `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 +/// Same contract as [`platform_wallet_top_up_from_addresses_with_signer`]. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses_with_signer( + wallet_handle: Handle, + identity_id: *const [u8; 32], + inputs: *const IdentityFundingInputFFI, + inputs_count: usize, + signer_address_handle: *mut SignerHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + 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, + }; + + // `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; + + 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) }; + wallet + .top_up_external_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() + }, + ) } /// 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 new file mode 100644 index 00000000000..c04819b9ce0 --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs @@ -0,0 +1,316 @@ +//! The external-identity top-up export: its 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. + +use std::ptr::NonNull; +use std::sync::Arc; + +use dpp::address_funds::AddressWitness; +use dpp::identity::signer::Signer; +use dpp::identity::{Identity, IdentityPublicKey, IdentityV0}; +use dpp::platform_value::BinaryData; +use dpp::prelude::Identifier; +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 crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; +use crate::identity_registration::IdentityFundingInputFFI; +use crate::runtime::runtime; +use crate::test_fixtures::mock_manager; + +const IDENTITY: [u8; 32] = [9; 32]; +const UNTOUCHED: u64 = 0xDEAD; + +fn input(address_type: u8) -> IdentityFundingInputFFI { + IdentityFundingInputFFI { + address_type, + hash: [7; 20], + credits: 100_000_000, + } +} + +/// Never asked to sign: every scenario here ends before signing. +#[derive(Debug)] +struct UnusedSigner; + +#[async_trait::async_trait] +impl Signer for UnusedSigner { + async fn sign(&self, _: &IdentityPublicKey, _: &[u8]) -> Result { + Err(ProtocolError::Generic("not expected to sign".into())) + } + + async fn sign_create_witness( + &self, + _: &IdentityPublicKey, + _: &[u8], + ) -> Result { + Err(ProtocolError::Generic("not expected to sign".into())) + } + + fn can_sign_with(&self, _: &IdentityPublicKey) -> bool { + false + } +} + +fn dangling_signer() -> *mut SignerHandle { + NonNull::::dangling().as_ptr() +} + +#[test] +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); + } + assert_eq!(balance, UNTOUCHED); +} + +#[test] +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 + ); + assert_eq!(balance, UNTOUCHED); +} + +/// A wallet handle over a mock SDK that knows `on_platform` under +/// [`IDENTITY`], and a signer that is never asked to sign. +fn wallet_handle(on_platform: Option) -> (Handle, *mut SignerHandle) { + let manager = mock_manager(); + let mut sdk = manager.sdk().clone(); + runtime() + .block_on( + sdk.mock() + .expect_fetch::(Identifier::from(IDENTITY), on_platform), + ) + .expect("the fetch expectation"); + let wallet = runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("a wallet"); + let signer = Box::into_raw(Box::new(VTableSigner::from_native(Arc::new(UnusedSigner)))) + as *mut SignerHandle; + (PLATFORM_WALLET_STORAGE.insert(wallet), signer) +} + +fn release(handle: Handle, signer: *mut SignerHandle) { + let _ = PLATFORM_WALLET_STORAGE.remove(handle); + drop(unsafe { Box::from_raw(signer as *mut VTableSigner) }); +} + +/// Rows naming one address whose sum overflows reach the library, which +/// refuses them as an invalid parameter on both exports instead of +/// saturating the amount. +#[test] +fn should_refuse_an_overflowing_funding_sum_on_both_exports() { + let (handle, signer) = wallet_handle(Some(platform_identity())); + let rows = [ + IdentityFundingInputFFI { + credits: u64::MAX, + ..input(0) + }, + IdentityFundingInputFFI { + credits: 1, + ..input(0) + }, + ]; + 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, + ) + }; + + release(handle, signer); + for result in [external, managed] { + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + } + assert_eq!(balance, UNTOUCHED); +} + +/// No funding rows reach the library, which refuses them as an invalid +/// parameter before looking the identity up. +#[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) }; + + release(handle, signer); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + assert_eq!(balance, UNTOUCHED); +} + +fn platform_identity() -> Identity { + Identity::V0(IdentityV0 { + id: Identifier::from(IDENTITY), + public_keys: Default::default(), + balance: 0, + revision: 0, + }) +} + +/// 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. +#[test] +fn should_report_an_identity_platform_does_not_know_as_not_found() { + let manager = mock_manager(); + let mut sdk = manager.sdk().clone(); + runtime() + .block_on( + sdk.mock() + .expect_fetch::(Identifier::from(IDENTITY), None), + ) + .expect("the fetch expectation"); + let wallet = runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("a wallet"); + let handle = PLATFORM_WALLET_STORAGE.insert(wallet.clone()); + let signer = Box::into_raw(Box::new(VTableSigner::from_native(Arc::new(UnusedSigner)))) + as *mut SignerHandle; + + let id = IDENTITY; + let mut balance = UNTOUCHED; + let result = unsafe { top_up(handle, &id, [input(0)].as_ptr(), 1, signer, &mut balance) }; + + let _ = PLATFORM_WALLET_STORAGE.remove(handle); + drop(unsafe { Box::from_raw(signer as *mut VTableSigner) }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorIdentityNotFound + ); + assert_eq!(balance, UNTOUCHED); + let identities = runtime().block_on(async { + wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .expect("the wallet's info") + .identity_manager + .identity_count() + }); + assert_eq!(identities, 0); +} + +/// A panic inside either 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() { + 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() + .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) + }); + + release(handle, signer); + for mut result in [external, managed] { + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed + ); + let message = unsafe { std::ffi::CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned(); + assert!(message.contains("panicked"), "{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 new file mode 100644 index 00000000000..01043843a8b --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs @@ -0,0 +1,274 @@ +//! Both address top-up exports wait 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. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::c_void; +use std::os::raw::c_char; +use std::sync::mpsc::{channel, Sender}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; +use dash_sdk::SdkBuilder; +use dpp::address_funds::PlatformAddress; +use dpp::identity::{Identity, IdentityV0}; +use dpp::prelude::Identifier; +use dpp::version::PlatformVersion; +use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use platform_wallet::events::{EventHandler, PlatformEventHandler}; +use platform_wallet::wallet::persister::NoPlatformPersistence; +use platform_wallet::PlatformWalletManager; +use rs_sdk_ffi::{ + dash_sdk_signer_create_with_ctx, dash_sdk_signer_destroy, SignCompletionCallback, SignerHandle, +}; + +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, +}; +use crate::error::PlatformWalletFFIResult; +use crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; +use crate::identity_registration::IdentityFundingInputFFI; +use crate::runtime::runtime; +use crate::wallet::{platform_wallet_destroy, platform_wallet_get_balance}; + +const IDENTITY: [u8; 32] = [9; 32]; +const ADDRESS_HASH: [u8; 20] = [7; 20]; +const AMOUNT: u64 = 100_000_000; +/// Long enough for a loaded CI machine to reach the signer, short enough to +/// fail instead of hanging when the registry is held. +const SIGNER_REACHED: Duration = Duration::from_secs(60); +const REGISTRY_FREE: Duration = Duration::from_secs(5); + +struct NoopEvents; +impl EventHandler for NoopEvents {} +impl PlatformEventHandler for NoopEvents {} + +/// A pending signature request the host has not answered yet. +struct PendingSignature { + completion_ctx: usize, + completion: SignCompletionCallback, +} + +struct SignerContext { + requests: Mutex>, +} + +unsafe extern "C" fn sign_async( + signer: *const c_void, + _pubkey_bytes: *const u8, + _pubkey_len: usize, + _key_type: u8, + _data: *const u8, + _data_len: usize, + completion_ctx: *mut c_void, + completion: SignCompletionCallback, +) { + let context = &*(signer as *const SignerContext); + let _ = context.requests.lock().unwrap().send(PendingSignature { + completion_ctx: completion_ctx as usize, + completion, + }); +} + +unsafe extern "C" fn can_sign_with(_: *const c_void, _: *const u8, _: usize, _: u8) -> bool { + true +} + +unsafe extern "C" fn destroy(signer: *mut c_void) { + drop(Box::from_raw(signer as *mut SignerContext)); +} + +fn pending_signer() -> ( + *mut SignerHandle, + std::sync::mpsc::Receiver, +) { + let (requests, pending) = channel(); + let context = Box::into_raw(Box::new(SignerContext { + requests: Mutex::new(requests), + })); + let signer = unsafe { + dash_sdk_signer_create_with_ctx( + context as *mut c_void, + sign_async, + can_sign_with, + Some(destroy), + ) + }; + (signer, pending) +} + +/// The wallet the export runs on (funded address, identity known both to the +/// wallet and to the mock Platform) and a second wallet to destroy. +async fn wallets() -> (Handle, Handle) { + let mut sdk = SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_time_tolerance(None) + .build() + .unwrap(); + let address = PlatformAddress::P2pkh(ADDRESS_HASH); + sdk.mock() + .expect_fetch_many::( + BTreeSet::from([address]), + Some(AddressInfos::from_iter([( + address, + Some(AddressInfo { + address, + nonce: 0, + balance: AMOUNT, + }), + )])), + ) + .await + .unwrap(); + let identity = Identity::V0(IdentityV0 { + id: Identifier::from(IDENTITY), + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }); + sdk.mock() + .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), + Arc::new(NoopEvents), + ); + let mut handles = Vec::new(); + for seed in [42u8, 43] { + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[seed; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + if seed == 42 { + wallet + .wallet_manager() + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity(identity.clone(), 0, wallet.wallet_id(), wallet.persister()) + .unwrap(); + } + handles.push(PLATFORM_WALLET_STORAGE.insert(wallet)); + } + (handles[0], handles[1]) +} + +type Export = unsafe extern "C" fn( + Handle, + *const [u8; 32], + *const IdentityFundingInputFFI, + usize, + *mut SignerHandle, + *mut u64, +) -> PlatformWalletFFIResult; + +/// Holds the signer while the export waits on it, destroys the second wallet +/// handle and reads a balance, and reports whether both finished before the +/// signer was answered. +fn registry_is_free_while_the_signer_is_pending(export: Export) { + let (export_handle, other_handle) = runtime().block_on(wallets()); + let (signer, pending) = pending_signer(); + + let signer_addr = signer as usize; + let exporting = thread::spawn(move || { + let row = IdentityFundingInputFFI { + address_type: 0, + hash: ADDRESS_HASH, + credits: AMOUNT, + }; + let id = IDENTITY; + let mut balance = 0u64; + unsafe { + export( + export_handle, + &id, + &row, + 1, + signer_addr as *mut SignerHandle, + &mut balance, + ) + }; + }); + let request = pending + .recv_timeout(SIGNER_REACHED) + .expect("the export never asked the signer for a signature"); + + let (finished, finishes) = channel(); + let destroyed = finished.clone(); + thread::spawn(move || { + unsafe { platform_wallet_destroy(other_handle) }; + let _ = destroyed.send("destroy"); + }); + thread::spawn(move || { + let mut confirmed = 0u64; + unsafe { + platform_wallet_get_balance( + export_handle, + &mut confirmed, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + let _ = finished.send("balance read"); + }); + let mut done_before_release = Vec::new(); + while done_before_release.len() < 2 { + match finishes.recv_timeout(REGISTRY_FREE) { + Ok(name) => done_before_release.push(name), + Err(_) => break, + } + } + + // Answer the signer whatever happened, so no thread outlives the test. + let signature = [0u8; 65]; + unsafe { + (request.completion)( + request.completion_ctx as *mut c_void, + signature.as_ptr(), + signature.len(), + 0, + std::ptr::null::(), + ) + }; + exporting.join().unwrap(); + for _ in done_before_release.len()..2 { + finishes.recv_timeout(SIGNER_REACHED).unwrap(); + } + let _ = PLATFORM_WALLET_STORAGE.remove(export_handle); + unsafe { dash_sdk_signer_destroy(signer) }; + + assert_eq!( + done_before_release.len(), + 2, + "only {done_before_release:?} finished while the export waited for the signer: \ + the wallet registry stayed locked" + ); +} + +#[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); +} + +#[test] +fn should_not_hold_the_wallet_registry_while_the_managed_top_up_waits_for_the_signer() { + registry_is_free_while_the_signer_is_pending(top_up_managed); +} 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 f0ebd8ebee1..ff18c8aad7c 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}; +use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; use dash_sdk::{Error as SdkError, RequestSettings, Sdk, SdkBuilder}; use dpp::address_funds::{AddressWitness, PlatformAddress}; use dpp::consensus::state::address_funds::AddressInvalidNonceError; @@ -180,6 +180,11 @@ 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. + sdk.mock() + .expect_fetch::(identity.id(), Some(identity.balance())) + .await + .unwrap(); sdk.mock() .expect_fetch_many::( BTreeSet::from([ADDRESS]), diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..08cc996a911 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -678,6 +678,20 @@ pub enum PlatformWalletError { #[error("SDK error: {0}")] Sdk(#[from] dash_sdk::Error), + /// Platform could not be asked for an identity an operation names, so + /// nothing was signed, reserved or broadcast: the operation never + /// started and may be retried as it is. Distinct from [`Self::Sdk`], + /// which a host that treats an unknown error as "may have gone through" + /// cannot tell from a failure after a dispatch, and from + /// [`Self::IdentityNotFound`], which is Platform's answer that the + /// identity does not exist. `source` is the SDK's error. + #[error("could not look up identity {identity_id} on Platform; nothing was sent: {source}")] + IdentityLookupFailed { + identity_id: Identifier, + #[source] + source: dash_sdk::Error, + }, + /// The contact requests with this identity came or went privately /// (protocol version 15): a `contactRequest` document to it, in reply or /// as a rotation, would publish the relationship, so it is sent privately. 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 39f62c43954..500acb46d89 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 @@ -2,16 +2,21 @@ use std::collections::BTreeMap; +use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; -use dpp::prelude::Identifier; +use dpp::identity::Identity; +use dpp::prelude::{AddressNonce, Identifier}; +use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; +use dash_sdk::platform::transition::fetch_inputs_with_nonce; use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::platform::transition::top_up_identity_from_addresses::TopUpIdentityFromAddressesWithMetadata; +use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; -use dash_sdk::query_types::AddressInfos; +use dash_sdk::query_types::{AddressInfos, IdentityBalance}; use crate::error::{ preserve_signer_key_unavailable_or, promote_address_nonce_error, PlatformWalletError, @@ -20,6 +25,9 @@ use crate::BlockTime; use super::*; +#[cfg(test)] +mod external_identity_tests; + // --------------------------------------------------------------------------- // Top-up from platform addresses // --------------------------------------------------------------------------- @@ -32,34 +40,54 @@ impl IdentityWallet { /// /// This method owns only the identity-side balance update and returns /// the proof-attested post-spend `AddressInfos` alongside the new - /// identity balance. Prefer the composite - /// [`PlatformWallet::top_up_from_addresses`], which feeds the returned + /// 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). /// + /// 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. + /// /// [`PlatformWallet::top_up_from_addresses`]: /// crate::wallet::PlatformWallet::top_up_from_addresses /// [`PlatformAddressWallet::reconcile_address_infos`]: /// crate::wallet::PlatformAddressWallet::reconcile_address_infos /// + /// 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 anything is signed or broadcast. + /// /// # Arguments /// /// * `identity_id` - The identity to top up. - /// * `inputs` - Map of platform addresses to credit amounts to spend. + /// * `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. /// * `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 async fn top_up_from_addresses + Send + Sync>( + pub(crate) async fn top_up_from_addresses( &self, identity_id: &Identifier, - inputs: BTreeMap, + inputs: I, address_signer: &S, settings: Option, - ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> { + ) -> Result<(AddressInfos, Credits, u64), 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(|| { @@ -73,20 +101,26 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))? }; - - let (address_infos, mut new_balance, metadata) = identity - .top_up_from_addresses_with_metadata(&self.sdk, inputs, address_signer, settings) + // 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) .await - .map_err(|e| { - preserve_signer_key_unavailable_or(e, |e| { - promote_address_nonce_error(&e).unwrap_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to top up identity from addresses: {}", - e - )) - }) - }) - })?; + .map_err(|source| PlatformWalletError::IdentityLookupFailed { + identity_id: *identity_id, + source, + })? + .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; @@ -113,4 +147,336 @@ impl IdentityWallet { // shared reconciliation seam. Ok((address_infos, new_balance, proof_height)) } + + /// 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( + &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, + ) + .await?; + Ok((address_infos, new_balance, metadata.height)) + } + + /// Build, sign, broadcast and wait for the top-up of `identity` from + /// `inputs`, mapping the SDK error the way every address top-up reports it. + /// + /// The result proof of this transition authenticates only the state it + /// affects (the identity's balance and the input addresses as of the + /// proof's block), not that this transition executed. The result stands + /// only once the proof shows every input address at or past the nonce + /// this transition was signed with and the identity balance above + /// `balance_before`, Platform's balance of the identity read before + /// signing ([`bind_to_submitted_nonces`]); otherwise the top-up is + /// reported unconfirmed and nothing is reconciled from it. + async fn submit_top_up_from_addresses + Send + Sync>( + &self, + identity: &Identity, + balance_before: Credits, + inputs: BTreeMap, + address_signer: &S, + settings: Option, + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + let inputs = fetch_inputs_with_nonce(&self.sdk, &inputs) + .await + .map_err(top_up_error)? + .into_iter() + .map(|(address, (nonce, credits))| { + let next = nonce.checked_add(1).ok_or_else(|| { + PlatformWalletError::InvalidParameter(format!( + "{address:?} has used every nonce and can fund nothing more" + )) + })?; + Ok((address, (next, credits))) + }) + .collect::, PlatformWalletError>>()?; + let submitted = inputs + .iter() + .map(|(address, (nonce, _))| (*address, *nonce)) + .collect(); + let confirmed = identity + .top_up_from_addresses_with_nonce_with_metadata( + &self.sdk, + inputs, + address_signer, + settings, + ) + .await + .map_err(top_up_error)?; + bind_to_submitted_nonces(&submitted, balance_before, confirmed) + } +} + +/// 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`]. +fn top_up_error(e: dash_sdk::Error) -> PlatformWalletError { + preserve_signer_key_unavailable_or(e, |e| { + promote_address_nonce_error(&e).unwrap_or(PlatformWalletError::Sdk(e)) + }) +} + +/// 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 +/// top-up is the caller's mistake whatever the identity lookup would say. +pub(crate) fn funding_inputs( + rows: impl IntoIterator, +) -> Result, PlatformWalletError> { + let mut inputs = BTreeMap::new(); + for (address, credits) in rows { + let sum: &mut Credits = inputs.entry(address).or_default(); + *sum = sum.checked_add(credits).ok_or_else(|| { + PlatformWalletError::InvalidParameter(format!( + "the funding amounts for {address:?} overflow" + )) + })?; + } + if inputs.is_empty() { + return Err(PlatformWalletError::InvalidParameter( + "no funding rows were provided".to_string(), + )); + } + Ok(inputs) +} + +/// The submitted top-up's result once its proof is bound to this +/// transition's address nonces (`submitted`) and to the identity balance +/// it started from (`balance_before`). +/// +/// An address nonce is used exactly once and only in order (Platform takes +/// stored + 1), and only the holder of the input addresses' keys (the +/// signer seam this top-up was signed through) can sign for them. A proof +/// showing every input address at or past the submitted nonce shows those +/// nonces consumed: this top-up executed, or a transition signed by the same +/// seam with the same nonces did and this one never can. Either way it can +/// no longer execute later. A proof showing an input address before its +/// submitted nonce (or not at all) is a snapshot that does not reflect this +/// top-up, which may still execute. +/// +/// Used nonces alone do not show that the identity was paid: the other +/// transition may have spent them elsewhere. The result stands only when +/// the proved identity balance is also above `balance_before`; a balance at +/// or below it is the snapshot of a top-up that did not reach the identity +/// (or of an identity that spent meanwhile, which reads the same way and +/// errs on the safe side). Every refusal is the SDK's unconfirmed outcome, +/// never done: the host must not pay again. +/// +/// Residual limit: the two checks bind the proof to this transition's +/// nonces and to some credit of the identity, not to this transition's +/// execution. A competing transition signed by the same signer seam with +/// the same nonces (which spends them elsewhere) together with an unrelated +/// credit to the same identity in the same window satisfies both, and an +/// 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 +/// 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. +fn bind_to_submitted_nonces( + submitted: &BTreeMap, + balance_before: Credits, + confirmed: (AddressInfos, Credits, ResponseMetadata), +) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + if confirmed.1 <= balance_before { + return Err(unconfirmed(format!( + "the identity top-up proof shows the identity balance at {}, not above the {} it \ + started from", + confirmed.1, balance_before + ))); + } + for (address, nonce) in submitted { + let proved = confirmed.0.get(address).and_then(|info| info.as_ref()); + if proved.is_none_or(|info| info.nonce < *nonce) { + return Err(unconfirmed(format!( + "the identity top-up proof shows {address:?} at nonce {:?}, before the \ + submitted nonce {nonce}", + proved.map(|info| info.nonce) + ))); + } + } + Ok(confirmed) +} + +/// The SDK's unconfirmed outcome for a proof that does not show this top-up. +fn unconfirmed(reason: String) -> PlatformWalletError { + PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(Box::new( + dash_sdk::Error::ExecutionNotProved(reason), + ))) +} + +#[cfg(test)] +mod nonce_binding_tests { + use super::*; + use dash_sdk::query_types::AddressInfo; + + const FIRST: PlatformAddress = PlatformAddress::P2pkh([1; 20]); + const SECOND: PlatformAddress = PlatformAddress::P2pkh([2; 20]); + + fn proved(nonces: &[(PlatformAddress, Option)]) -> AddressInfos { + AddressInfos::from_iter(nonces.iter().map(|(address, nonce)| { + ( + *address, + nonce.map(|nonce| AddressInfo { + address: *address, + nonce, + balance: 5, + }), + ) + })) + } + + const BALANCE_BEFORE: Credits = 700; + + fn bind_with_balance( + proved_nonces: &[(PlatformAddress, Option)], + proved_balance: Credits, + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + let submitted = BTreeMap::from([(FIRST, 4), (SECOND, 9)]); + bind_to_submitted_nonces( + &submitted, + BALANCE_BEFORE, + ( + proved(proved_nonces), + proved_balance, + ResponseMetadata::default(), + ), + ) + } + + fn bind( + proved_nonces: &[(PlatformAddress, Option)], + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + bind_with_balance(proved_nonces, 777) + } + + /// A proof that shows an input address before the nonce this top-up + /// was signed with is a snapshot from before it executed: the top-up + /// may still execute, so it is reported unconfirmed, not done. + #[test] + fn should_report_a_snapshot_before_the_submitted_nonces_as_unconfirmed() { + for proved_nonces in [ + [(FIRST, Some(3)), (SECOND, Some(8))], + [(FIRST, Some(4)), (SECOND, Some(8))], + [(FIRST, Some(4)), (SECOND, None)], + ] { + let result = bind(&proved_nonces); + assert!( + matches!( + &result, + Err(PlatformWalletError::Sdk(e)) if e.is_state_transition_result_unconfirmed() + ), + "{proved_nonces:?}: {result:?}" + ); + } + } + + /// Every input address at (or past) the nonce this top-up was signed + /// with: the nonces it used are consumed, so the result stands. + #[test] + fn should_keep_a_result_whose_proof_shows_the_submitted_nonces_used() { + for proved_nonces in [ + [(FIRST, Some(4)), (SECOND, Some(9))], + [(FIRST, Some(5)), (SECOND, Some(9))], + ] { + let (_, balance, _) = bind(&proved_nonces).expect("bound to the submitted nonces"); + assert_eq!(balance, 777); + } + } + + /// The submitted nonces are used but the identity balance did not grow: + /// another transition this wallet signed with the same nonces took them + /// and paid elsewhere. This top-up did not reach the identity, so the + /// result is unconfirmed, not done. + #[test] + fn should_report_used_nonces_without_a_higher_identity_balance_as_unconfirmed() { + for proved_balance in [BALANCE_BEFORE, BALANCE_BEFORE - 1] { + let result = bind_with_balance(&[(FIRST, Some(4)), (SECOND, Some(9))], proved_balance); + assert!( + matches!( + &result, + Err(PlatformWalletError::Sdk(e)) if e.is_state_transition_result_unconfirmed() + ), + "{proved_balance}: {result:?}" + ); + } + } + + /// The baseline is Platform's balance read before signing, not a cached + /// one: with the cache above Platform's value (credits spent from + /// another device, not yet synced), a top-up that grew the identity + /// above Platform's balance stands, where the stale cache as baseline + /// would have reported it unconfirmed. + #[test] + fn should_keep_growth_over_platforms_balance_that_a_stale_cache_hides() { + const STALE_CACHE: Credits = 800; + const PROVED: Credits = 750; + let submitted = BTreeMap::from([(FIRST, 4), (SECOND, 9)]); + let proof = || { + ( + proved(&[(FIRST, Some(4)), (SECOND, Some(9))]), + PROVED, + ResponseMetadata::default(), + ) + }; + + let (_, balance, _) = bind_to_submitted_nonces(&submitted, BALANCE_BEFORE, proof()) + .expect("growth over Platform's balance stands"); + assert_eq!(balance, PROVED); + let against_cache = bind_to_submitted_nonces(&submitted, STALE_CACHE, proof()); + assert!( + matches!( + &against_cache, + Err(PlatformWalletError::Sdk(e)) if e.is_state_transition_result_unconfirmed() + ), + "{against_cache:?}" + ); + } } 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 new file mode 100644 index 00000000000..27cb509f8ee --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -0,0 +1,761 @@ +//! Top-up of an identity the wallet does not manage, against mock DAPI +//! expectations. +//! +//! What is real and what is modelled: +//! - The identity fetch, the address-nonce lookup, the transition build, +//! its signing and its broadcast are real, answered by mock expectations. +//! The broadcast expectation is keyed by the exact bytes of the transition +//! built from the identity Platform returned. +//! - The mock SDK cannot answer the result wait with a verifiable proof, so +//! no scenario here reaches the success branch (and so the reconciliation +//! of the spent addresses, which only runs on success). The submitted +//! top-up ends `StateTransitionResultUnconfirmed`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use dash_sdk::dapi_client::mock::MockResult; +use dash_sdk::dapi_client::transport::TransportRequest; +use dash_sdk::dapi_client::{DumpData, ExecutionResponse}; +use dash_sdk::dapi_grpc::platform::v0::wait_for_state_transition_result_response::{ + wait_for_state_transition_result_response_v0::Result as WaitResult, Version as WaitVersion, + WaitForStateTransitionResultResponseV0, +}; +use dash_sdk::dapi_grpc::platform::v0::{ + BroadcastStateTransitionRequest, BroadcastStateTransitionResponse, Proof, ResponseMetadata, + WaitForStateTransitionResultRequest, WaitForStateTransitionResultResponse, +}; +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::{RequestSettings, Sdk, SdkBuilder}; +use dpp::address_funds::{AddressWitness, PlatformAddress}; +use dpp::consensus::state::state_error::StateError; +use dpp::consensus::ConsensusError; +use dpp::identity::accessors::IdentityGettersV0; +use dpp::identity::signer::Signer; +use dpp::identity::{Identity, IdentityV0}; +use dpp::platform_value::BinaryData; +use dpp::prelude::Identifier; +use dpp::state_transition::identity_topup_from_addresses_transition::methods::IdentityTopUpFromAddressesTransitionMethodsV0; +use dpp::state_transition::identity_topup_from_addresses_transition::IdentityTopUpFromAddressesTransition; +use dpp::version::PlatformVersion; +use dpp::ProtocolError; +use key_wallet::account::account_collection::PlatformPaymentAccountKey; +use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use tokio::sync::{Notify, Semaphore}; + +use crate::changeset::{ + ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, +}; +use crate::error::PlatformWalletError; +use crate::events::{EventHandler, PlatformEventHandler}; +use crate::wallet::persister::NoPlatformPersistence; +use crate::wallet::platform_wallet::WalletId; +use crate::{PlatformWallet, PlatformWalletManager}; + +const ADDRESS: PlatformAddress = PlatformAddress::P2pkh([7; 20]); +const AMOUNT: u64 = 100_000_000; +const BALANCE: u64 = 123_000; +/// An identity the wallet manages, unrelated to the one topped up. +const OWN_IDENTITY: [u8; 32] = [3; 32]; + +#[derive(Debug, Default)] +struct AddressSigner(AtomicUsize); + +#[async_trait::async_trait] +impl Signer for AddressSigner { + async fn sign(&self, _: &PlatformAddress, _: &[u8]) -> Result { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(vec![7; 65].into()) + } + + async fn sign_create_witness( + &self, + key: &PlatformAddress, + data: &[u8], + ) -> Result { + Ok(AddressWitness::P2pkh { + signature: self.sign(key, data).await?, + }) + } + + fn can_sign_with(&self, _: &PlatformAddress) -> bool { + true + } +} + +struct NoopEvents; +impl EventHandler for NoopEvents {} +impl PlatformEventHandler for NoopEvents {} + +fn identity(id: [u8; 32]) -> Identity { + Identity::V0(IdentityV0 { + id: Identifier::from(id), + public_keys: Default::default(), + balance: BALANCE, + revision: 0, + }) +} + +fn settings() -> Option { + Some(PutSettings { + request_settings: RequestSettings { + retries: Some(0), + ..Default::default() + }, + ..Default::default() + }) +} + +fn save(directory: &tempfile::TempDir, request: &R, response: &MockResult) { + let dump = DumpData::new(request, response); + dump.save(&directory.path().join(dump.filename().unwrap())) + .unwrap(); +} + +fn response(inner: R) -> ExecutionResponse { + ExecutionResponse { + inner, + retries: 0, + address: "http://127.0.0.1".parse().unwrap(), + } +} + +/// A wallet managing [`OWN_IDENTITY`], with Platform knowing `on_platform` +/// (or nothing) under `target`, and a funded [`ADDRESS`]. +struct Fixture { + manager: Arc>, + wallet: Arc, + sdk: Sdk, + target: Identifier, + broadcast: BroadcastStateTransitionRequest, + wait: WaitForStateTransitionResultRequest, + signer: AddressSigner, +} + +impl Fixture { + async fn new(on_platform: bool) -> Self { + Self::build(Some(on_platform), AMOUNT).await + } + + /// `on_platform` `None`: Platform cannot be reached to look the + /// identity up, there is no expectation for the request. + /// `address_balance` is what Platform holds on [`ADDRESS`]. + async fn build(on_platform: Option, address_balance: u64) -> Self { + let mut sdk = SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_time_tolerance(None) + .with_settings(RequestSettings { + retries: Some(0), + ..Default::default() + }) + .build() + .unwrap(); + let target = identity([9; 32]); + let transition = IdentityTopUpFromAddressesTransition::try_from_inputs_with_signer( + &target, + BTreeMap::from([(ADDRESS, (1, AMOUNT))]), + &AddressSigner::default(), + 0, + sdk.version(), + None, + ) + .await + .unwrap(); + let broadcast = transition.broadcast_request_for_state_transition().unwrap(); + let wait = transition + .wait_for_state_transition_result_request() + .unwrap(); + let directory = tempfile::tempdir().unwrap(); + save( + &directory, + &broadcast, + &Ok(response(BroadcastStateTransitionResponse {})), + ); + // A proof the mock cannot verify: the submitted top-up stays unconfirmed. + save( + &directory, + &wait, + &Ok(response(WaitForStateTransitionResultResponse { + version: Some(WaitVersion::V0(WaitForStateTransitionResultResponseV0 { + result: Some(WaitResult::Proof(Proof::default())), + metadata: Some(ResponseMetadata { + protocol_version: PlatformVersion::latest().protocol_version, + ..Default::default() + }), + })), + })), + ); + sdk.mock().load_expectations_sync(directory.path()).unwrap(); + if let Some(on_platform) = on_platform { + sdk.mock() + .expect_fetch(target.id(), on_platform.then(|| target.clone())) + .await + .unwrap(); + } + sdk.mock() + .expect_fetch_many::( + BTreeSet::from([ADDRESS]), + Some(AddressInfos::from_iter([( + ADDRESS, + Some(AddressInfo { + address: ADDRESS, + nonce: 0, + balance: address_balance, + }), + )])), + ) + .await + .unwrap(); + let manager = Arc::new(PlatformWalletManager::new( + Arc::new(sdk.clone()), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + )); + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + 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(); + Self { + manager, + wallet, + sdk, + target: target.id(), + broadcast, + wait, + signer: AddressSigner::default(), + } + } + + async fn top_up(&self) -> Result { + self.top_up_with(vec![(ADDRESS, AMOUNT)]).await + } + + async fn top_up_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( + &self, + inputs: Vec<(PlatformAddress, u64)>, + ) -> Result { + self.wallet + .top_up_from_addresses( + &Identifier::from(OWN_IDENTITY), + inputs, + &self.signer, + settings(), + ) + .await + } + + async fn managed_identity_ids(&self) -> Vec { + self.wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&self.wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids() + } + + async fn submissions(&mut self) -> (usize, usize, usize) { + let broadcasts = self.sdk.mock().request_count(&self.broadcast).await; + let waits = self.sdk.mock().request_count(&self.wait).await; + (broadcasts, waits, self.signer.0.load(Ordering::SeqCst)) + } +} + +/// 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. +#[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; + + let error = fixture + .top_up() + .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)); +} + +/// Topping up someone else's identity never records it as the wallet's own. +#[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; + + let _ = fixture.top_up().await; + + assert_eq!(fixture.managed_identity_ids().await, before); + assert_eq!(before, vec![Identifier::from(OWN_IDENTITY)]); +} + +/// An identity Platform does not know is refused with the typed not-found +/// error before anything is signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_an_identity_platform_does_not_know_without_submitting() { + let mut fixture = Fixture::new(false).await; + + let error = fixture + .top_up() + .await + .expect_err("an unknown identity cannot be topped up"); + + assert!( + matches!(error, PlatformWalletError::IdentityNotFound(id) if id == fixture.target), + "got {error:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); + assert_eq!( + fixture.managed_identity_ids().await, + vec![Identifier::from(OWN_IDENTITY)] + ); +} + +/// A recipient lookup that fails (here a transport error) is reported as its +/// own not-sent error, not as a generic SDK error a host must read as "may +/// have gone through", with nothing signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_report_a_failed_recipient_lookup_as_not_sent() { + let mut fixture = Fixture::build(None, AMOUNT).await; + + let error = fixture + .top_up() + .await + .expect_err("the identity cannot be looked up"); + + assert!( + matches!(&error, PlatformWalletError::IdentityLookupFailed { identity_id, .. } + if *identity_id == fixture.target), + "got {error:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + +/// An empty funding map is the caller's mistake on both routes, 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() { + 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 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()) + .await; + + for result in [external, managed, managed_unknown] { + assert!( + matches!(&result, Err(PlatformWalletError::InvalidParameter(reason)) + if reason == "no funding rows were provided"), + "{on_platform:?}: got {result:?}" + ); + } + assert_eq!(fixture.submissions().await, (0, 0, 0)); + } +} + +/// 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. +#[tokio::test(flavor = "multi_thread")] +async fn should_read_the_managed_identitys_balance_from_platform_before_signing() { + let own = Identifier::from(OWN_IDENTITY); + let mut fixture = Fixture::new(true).await; + + let unreachable = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; + assert!( + matches!(&unreachable, Err(PlatformWalletError::IdentityLookupFailed { identity_id, .. }) + if *identity_id == own), + "got {unreachable:?}" + ); + + fixture + .sdk + .mock() + .expect_fetch::(own, None) + .await + .unwrap(); + let unknown = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; + assert!( + matches!(&unknown, Err(PlatformWalletError::IdentityNotFound(id)) if *id == own), + "got {unknown:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + +/// 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. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_both_routes() { + let mut fixture = Fixture::new(true).await; + let wallet_id = fixture.wallet.wallet_id(); + fixture + .manager + .remove_wallet(&wallet_id) + .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:?}" + ); + + let recreated = fixture + .manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .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:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + +/// Signs like [`AddressSigner`], but only once released: holds a top-up in +/// its signing step. +#[derive(Debug)] +struct HeldSigner { + entered: Notify, + release: Semaphore, +} + +impl Default for HeldSigner { + fn default() -> Self { + Self { + entered: Notify::new(), + release: Semaphore::new(0), + } + } +} + +#[async_trait::async_trait] +impl Signer for HeldSigner { + async fn sign(&self, key: &PlatformAddress, data: &[u8]) -> Result { + self.entered.notify_one(); + self.release + .acquire() + .await + .map_err(|e| ProtocolError::Generic(e.to_string()))? + .forget(); + AddressSigner::default().sign(key, data).await + } + + async fn sign_create_witness( + &self, + key: &PlatformAddress, + data: &[u8], + ) -> Result { + Ok(AddressWitness::P2pkh { + signature: self.sign(key, data).await?, + }) + } + + fn can_sign_with(&self, _: &PlatformAddress) -> bool { + true + } +} + +/// A removal waits for an external 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()); + let top_up = { + let wallet = Arc::clone(&fixture.wallet); + let signer = Arc::clone(&signer); + let target = fixture.target; + tokio::spawn(async move { + wallet + .top_up_external_identity_from_addresses( + &target, + BTreeMap::from([(ADDRESS, AMOUNT)]), + &*signer, + settings(), + ) + .await + }) + }; + signer.entered.notified().await; + + 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 the top-up being signed" + ); + assert!(fixture.wallet.core().is_current_generation().await); + + signer.release.add_permits(1); + let topped_up = top_up.await.expect("top-up task"); + assert!( + !matches!( + topped_up, + Err(PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "the wallet was current when it was checked: {topped_up:?}" + ); + removal + .await + .expect("removal task") + .expect("the removal completes"); + assert!(!fixture.wallet.core().is_current_generation().await); +} + +/// Records every store round. +#[derive(Default)] +struct RecordingPersister(Mutex>); + +impl PlatformWalletPersistence for RecordingPersister { + fn store( + &self, + _: WalletId, + changeset: PlatformWalletChangeSet, + ) -> Result<(), PersistenceError> { + self.0.lock().unwrap().push(changeset); + Ok(()) + } + + fn flush(&self, _: WalletId) -> Result<(), PersistenceError> { + Ok(()) + } + + fn load(&self) -> Result { + Ok(ClientStartState::default()) + } +} + +/// 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; + let persister = Arc::new(RecordingPersister::default()); + let manager = PlatformWalletManager::new( + Arc::new(dash_sdk::Sdk::new_mock()), + Arc::clone(&persister), + Arc::new(NoopEvents), + ); + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("a wallet"); + let spent = wallet + .platform() + .next_unused_receive_address(PlatformPaymentAccountKey { + account: 0, + key_class: 0, + }) + .await + .expect("a wallet address"); + let identities_before = wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids(); + persister.0.lock().unwrap().clear(); + + let confirmed = AddressInfos::from_iter([( + spent, + Some(AddressInfo { + address: spent, + nonce: 4, + balance: 5, + }), + )]); + let new_balance = wallet + .top_up_identity_with( + async { Ok((confirmed, NEW_BALANCE, PROOF_HEIGHT)) }, + "external identity top-up", + ) + .await + .expect("a confirmed top-up"); + + assert_eq!(new_balance, NEW_BALANCE); + 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())); + } + assert_eq!( + wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids(), + identities_before + ); +} + +/// 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")] +async fn should_sum_repeated_funding_rows_into_one_input() { + let mut fixture = Fixture::new(true).await; + + let error = fixture + .top_up_with(vec![(ADDRESS, AMOUNT - 1), (ADDRESS, 1)]) + .await + .expect_err("the mock cannot prove the result"); + + assert!( + matches!( + error, + PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(_)) + ), + "the summed top-up must be submitted, got {error:?}" + ); + assert_eq!(fixture.submissions().await, (1, 1, 1)); +} + +/// Rows whose sum for one address overflows are refused as the caller's +/// mistake on both routes, never saturated, with nothing signed or +/// submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_an_overflowing_funding_sum_on_both_routes() { + 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 managed = fixture.top_up_own_with(rows).await; + + for result in [external, managed] { + assert!( + matches!(result, Err(PlatformWalletError::InvalidParameter(_))), + "got {result:?}" + ); + } + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + +/// An SDK error the top-up does not promote keeps its typed variant, here +/// the SDK's own refusal of an address short of the amount, with nothing +/// signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_keep_an_unpromoted_sdk_error_typed() { + let mut fixture = Fixture::build(Some(true), AMOUNT - 1).await; + + let error = fixture.top_up().await.expect_err("the address is short"); + + assert!( + matches!(&error, PlatformWalletError::Sdk(e) if matches!( + e.consensus_error(), + Some(ConsensusError::StateError(StateError::AddressNotEnoughFundsError(_))) + )), + "got {error:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index c67a5462f70..88f3bee5afb 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -1,6 +1,7 @@ //! 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; @@ -39,6 +40,7 @@ use crate::changeset::{ }; use crate::error::PlatformWalletError; use dash_sdk::platform::transition::put_settings::PutSettings; +use dash_sdk::query_types::AddressInfos; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; use dpp::identity::signer::Signer; @@ -588,28 +590,115 @@ impl PlatformWallet { /// balances and nonces from the proof-attested post-spend /// `AddressInfos`. /// - /// See [`IdentityWallet::top_up_from_addresses`] for the identity-side - /// semantics. Reconciliation failures are logged inside the seam - /// rather than propagated — Platform already accepted the top-up, and - /// a later sync reconciles. + /// 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 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 + /// `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. /// /// Returns the identity's new credit balance. - pub async fn top_up_from_addresses + Send + Sync>( + pub async fn top_up_from_addresses( &self, identity_id: &Identifier, - inputs: BTreeMap, + inputs: I, + address_signer: &S, + settings: Option, + ) -> Result + where + 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 + } + + /// 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. + /// + /// 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. + /// + /// Returns the identity's new credit balance. + pub async fn top_up_external_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_with( + self.identity.top_up_external_from_addresses( + identity_id, + inputs, + address_signer, + settings, + ), + "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. + pub(crate) async fn top_up_identity_with( + &self, + top_up: impl Future>, + label: &'static str, ) -> Result { - let (address_infos, new_balance, proof_height) = self - .identity - .top_up_from_addresses(identity_id, inputs, address_signer, settings) - .await?; - // The reconciled absolutes are pinned at the proof's block height - // (`AddressFunds::as_of_height`), so the sync's delta replay can - // never re-apply this transition's on-chain ops on top of them. + 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, proof_height) = top_up.await?; self.platform - .reconcile_address_infos(&address_infos, proof_height, "identity top-up") + .reconcile_address_infos(&address_infos, proof_height, label) .await; Ok(new_balance) } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index e8206d87778..3f037a89cb4 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -774,6 +774,75 @@ public final class ManagedPlatformWallet: @unchecked Sendable { identityId: Data, inputs: [IdentityAddressInput], addressSigner: KeychainSigner + ) async throws -> UInt64 { + try await topUpFromAddresses( + identityId: identityId, + inputs: inputs, + addressSigner: addressSigner, + call: addressTopUpExports.managed + ) + } + + /// Top up an identity this wallet does **not** manage (someone + /// else's) from one or more Platform addresses. + /// + /// 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. + /// Arguments, signer handling and error mapping match + /// `topUpFromAddresses`; an identity Platform does not know throws + /// `PlatformWalletError.identityNotFound` before anything is signed. + /// + /// - Returns: the identity's new credit balance reported by Platform. + public func topUpExternalIdentityFromAddresses( + identityId: Data, + inputs: [IdentityAddressInput], + addressSigner: KeychainSigner + ) async throws -> UInt64 { + try await topUpFromAddresses( + identityId: identityId, + inputs: inputs, + addressSigner: addressSigner, + call: addressTopUpExports.external + ) + } + + /// The two 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 managed: AddressTopUpCall = platform_wallet_top_up_from_addresses_with_signer + var external: AddressTopUpCall = + platform_wallet_top_up_external_identity_from_addresses_with_signer + } + + var addressTopUpExports = AddressTopUpExports() + + /// Signature shared by the two address-funded top-up exports. + typealias AddressTopUpCall = @Sendable ( + Handle, + UnsafePointer?, + UnsafePointer?, + UInt, + OpaquePointer?, + UnsafeMutablePointer? + ) -> PlatformWalletFFIResult + + typealias IdentityIdBytes = ( + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 + ) + + /// Guards and marshalling shared by the address-funded top-ups; + /// `call` is the export to hand the marshalled arguments to. + /// `internal` so tests can observe the marshalling. + func topUpFromAddresses( + identityId: Data, + inputs: [IdentityAddressInput], + addressSigner: KeychainSigner, + call: @escaping AddressTopUpCall ) async throws -> UInt64 { guard identityId.count == 32 else { throw PlatformWalletError.invalidParameter( @@ -801,17 +870,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { let addressSignerHandle = addressSigner.handle return try await Task.detached(priority: .userInitiated) { () -> UInt64 in - // Keepalive — see `registerIdentityFromAddresses` for - // rationale. The trampoline ctx pointer dangles unless - // the Swift owner stays alive across this detached work. - _ = addressSigner - - var idTuple: ( - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 - ) = ( + var idTuple: IdentityIdBytes = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -840,16 +899,25 @@ public final class ManagedPlatformWallet: @unchecked Sendable { var newBalance: UInt64 = 0 - let result = ffiInputs.withUnsafeBufferPointer { inputsBuf in - withUnsafePointer(to: &idTuple) { idPtr in - platform_wallet_top_up_from_addresses_with_signer( - handle, - idPtr, - inputsBuf.baseAddress, - UInt(inputsBuf.count), - addressSignerHandle, - &newBalance - ) + // `KeychainSigner` registers itself with the Rust signer as a + // `passUnretained` ctx and destroys the handle in `deinit`, and + // Swift lifetimes end at last use, not at scope end — a bare + // `_ = addressSigner` is no fence. `withExtendedLifetime` pins + // it across the whole synchronous FFI call (lookup, signing, + // broadcast and wait) and its buffer pinning. The wallet is + // pinned with it: its `deinit` destroys `handle`. + let result = withExtendedLifetime((self, addressSigner)) { + ffiInputs.withUnsafeBufferPointer { inputsBuf in + withUnsafePointer(to: &idTuple) { idPtr in + call( + handle, + idPtr, + inputsBuf.baseAddress, + UInt(inputsBuf.count), + addressSignerHandle, + &newBalance + ) + } } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index ee130585d2d..c83d3063322 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -322,6 +322,10 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// outcome yet. Nothing new was signed. Unconfirmed, not failed: do not /// submit it again; a public contact request sync settles it. case errorPublicContactRequestUnconfirmed = 76 + /// Platform could not be asked for an identity the operation names (the + /// lookup failed, which is not Platform's answer that it does not exist, + /// 7). Nothing was signed, reserved or broadcast: retry as it is. + case errorIdentityLookupFailed = 80 /// The named thing does not exist. Besides the handle/lookup failures this /// has always covered, BOTH deferred-send paths report the /// wallet-was-REMOVED case here. @@ -473,6 +477,8 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorSdkPinnedBelowProtocolVersion case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PUBLIC_CONTACT_REQUEST_UNCONFIRMED: self = .errorPublicContactRequestUnconfirmed + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_LOOKUP_FAILED: + self = .errorIdentityLookupFailed case PLATFORM_WALLET_FFI_RESULT_CODE_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -743,6 +749,11 @@ public enum PlatformWalletError: LocalizedError { /// `ManagedPlatformWallet.publicContactRequestUnconfirmed(senderId:recipientId:)` /// reads whether the pair is still held so. case publicContactRequestUnconfirmed(String) + /// Platform could not be asked for an identity the operation names (code + /// 80): the lookup itself failed, before anything was signed, reserved or + /// broadcast. Not sent, so it may be retried as it is; unlike an unmapped + /// SDK error it is never a possibly delivered operation. + case identityLookupFailed(String) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition never /// left the wallet (refused before anything was sent), so it cannot @@ -976,7 +987,7 @@ public enum PlatformWalletError: LocalizedError { .privateContactRequestPending(let m), .privateContactPaymentsNotRestored(let m), .privateContactRecoveryUnsupported(let m), .privateContactStoreNotRead(let m), .sdkPinnedBelowProtocolVersion(let m), - .publicContactRequestUnconfirmed(let m), + .publicContactRequestUnconfirmed(let m), .identityLookupFailed(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -1114,6 +1125,8 @@ public enum PlatformWalletError: LocalizedError { self = .sdkPinnedBelowProtocolVersion(detail) case .errorPublicContactRequestUnconfirmed: self = .publicContactRequestUnconfirmed(detail) + case .errorIdentityLookupFailed: + self = .identityLookupFailed(detail) case .errorWalletAlreadyExists: self = .walletAlreadyExists(detail) case .errorShieldedBroadcastFailed: self = .shieldedBroadcastFailed(detail) case .errorShieldedBroadcastUnconfirmed: self = .shieldedBroadcastUnconfirmed(detail) diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index b3bbb2a7d64..2702949f8ae 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -604,6 +604,23 @@ final class ErrorHandlingTests: XCTestCase { XCTAssertEqual(message, detail) } + /// A failed identity lookup, which sent nothing, has its own code and + /// typed case, apart from the unmapped SDK errors a host reads as possibly + /// delivered. + func testShouldReportAFailedIdentityLookupByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_LOOKUP_FAILED + ) + XCTAssertEqual(code, .errorIdentityLookupFailed) + XCTAssertEqual(code.rawValue, 80) + let detail = "could not look up identity 9fRYTJZW on Platform; nothing was sent" + guard case .identityLookupFailed(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed identity-lookup-failed error") + } + XCTAssertEqual(message, detail) + } + func testShouldReadEveryFieldOfThePrivateContactReadiness() { var ffi = PrivateContactReadinessFFI() ffi.private_payments_restored = false diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift new file mode 100644 index 00000000000..45e88fc19a8 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift @@ -0,0 +1,177 @@ +import DashSDKFFI +import Foundation +import XCTest +@testable import SwiftDashSDK + +/// `topUpExternalIdentityFromAddresses` is a bridge to +/// `platform_wallet_top_up_external_identity_from_addresses_with_signer`: +/// it rejects malformed arguments before the FFI, hands the rest to the +/// export and maps the export's result code. Nothing here reaches Platform. +final class ExternalIdentityTopUpTests: XCTestCase { + + private let identityId = Data((0..<32).map { UInt8($0) }) + private let input = ManagedPlatformWallet.IdentityAddressInput( + addressType: 0, hash: Data(repeating: 0xAB, count: 20), credits: 1_000 + ) + + private func wallet() -> ManagedPlatformWallet { + ManagedPlatformWallet(handle: NULL_HANDLE, walletId: Data()) + } + + private func signer() throws -> KeychainSigner { + KeychainSigner(modelContainer: try DashModelContainer.createInMemory(), network: .testnet) + } + + private func assertInvalidParameter( + identityId: Data, + inputs: [ManagedPlatformWallet.IdentityAddressInput], + contains expected: String, + file: StaticString = #filePath, + line: UInt = #line + ) async throws { + do { + _ = try await wallet().topUpExternalIdentityFromAddresses( + identityId: identityId, inputs: inputs, addressSigner: try signer() + ) + XCTFail("expected invalidParameter", file: file, line: line) + } catch PlatformWalletError.invalidParameter(let message) { + XCTAssertTrue(message.contains(expected), "got \(message)", file: file, line: line) + } catch { + XCTFail("expected invalidParameter, got \(error)", file: file, line: line) + } + } + + func testRejectsIdentityIdThatIsNot32BytesBeforeTheFFI() async throws { + try await assertInvalidParameter( + identityId: Data(repeating: 1, count: 31), inputs: [input], + contains: "identityId must be 32 bytes, got 31" + ) + } + + func testRejectsEmptyInputsBeforeTheFFI() async throws { + try await assertInvalidParameter( + identityId: identityId, inputs: [], contains: "inputs is empty" + ) + } + + func testRejectsMalformedAddressHashBeforeTheFFI() async throws { + let short = ManagedPlatformWallet.IdentityAddressInput( + addressType: 0, hash: Data(repeating: 0xAB, count: 19), credits: 1 + ) + try await assertInvalidParameter( + identityId: identityId, inputs: [input, short], + contains: "input hash must be 20 bytes, got 19" + ) + } + + /// Well-formed arguments reach the real export, which resolves the wallet + /// handle first: an unknown handle comes back as the registry's `notFound`. + func testWellFormedCallReachesTheExportAndMapsItsCode() async throws { + do { + _ = try await wallet().topUpExternalIdentityFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + XCTFail("a null wallet handle must not report a balance") + } catch PlatformWalletError.notFound { + } catch { + XCTFail("expected notFound from the export, got \(error)") + } + } + + // 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. + func testEachWrapperDispatchesToItsOwnExport() async throws { + let wallet = ManagedPlatformWallet(handle: 42, walletId: Data()) + wallet.addressTopUpExports = .init( + managed: { _, _, _, _, _, outBalance in + outBalance!.pointee = 1 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + }, + external: { _, _, _, _, _, outBalance in + outBalance!.pointee = 2 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + ) + + let external = try await wallet.topUpExternalIdentityFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + let managed = try await wallet.topUpFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + + XCTAssertEqual(external, 2, "the external wrapper must call the external export") + XCTAssertEqual(managed, 1, "the managed wrapper must call the managed export") + } + + // MARK: - Marshalling through the shared helper + + func testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites() async throws { + let signer = try signer() + let recorder = Recorder() + let inputs = [ + input, + .init(addressType: 1, hash: Data(repeating: 0xCD, count: 20), credits: 7) + ] + let balance = try await ManagedPlatformWallet(handle: 42, walletId: Data()) + .topUpFromAddresses( + identityId: identityId, inputs: inputs, addressSigner: signer + ) { handle, idPtr, inputsPtr, count, signerHandle, outBalance in + recorder.record( + handle: handle, + id: withUnsafeBytes(of: idPtr!.pointee) { Data($0) }, + rows: Array(UnsafeBufferPointer(start: inputsPtr, count: Int(count))), + signer: signerHandle + ) + outBalance!.pointee = 123_456 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + + XCTAssertEqual(balance, 123_456) + XCTAssertEqual(recorder.handle, 42) + XCTAssertEqual(recorder.id, identityId) + XCTAssertEqual(recorder.signer, signer.handle) + XCTAssertEqual(recorder.rows.map(\.address_type), [0, 1]) + XCTAssertEqual(recorder.rows.map(\.credits), [1_000, 7]) + XCTAssertEqual( + recorder.rows.map { row in withUnsafeBytes(of: row.hash) { Data($0) } }, + [Data(repeating: 0xAB, count: 20), Data(repeating: 0xCD, count: 20)] + ) + } + + func testIdentityNotFoundCodeMapsToIdentityNotFound() async throws { + XCTAssertEqual(PlatformWalletResultCode.errorIdentityNotFound.rawValue, 7) + do { + _ = try await wallet().topUpFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) { _, _, _, _, _, _ in + PlatformWalletFFIResult( + code: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_NOT_FOUND, + message: strdup("identity not found on Platform") + ) + } + XCTFail("code 7 must throw") + } catch PlatformWalletError.identityNotFound(let message) { + XCTAssertEqual(message, "identity not found on Platform") + } catch { + XCTFail("expected identityNotFound, got \(error)") + } + } + + private final class Recorder: @unchecked Sendable { + var handle: Handle = NULL_HANDLE + var id = Data() + var rows: [IdentityFundingInputFFI] = [] + var signer: OpaquePointer? + + func record(handle: Handle, id: Data, rows: [IdentityFundingInputFFI], signer: OpaquePointer?) { + self.handle = handle + self.id = id + self.rows = rows + self.signer = signer + } + } +}