From 2b50c4944606dafdb7a64c9c69728ac440e0aeb3 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 14:20:10 +0200 Subject: [PATCH 01/12] feat(platform-wallet-ffi): shield credits from an identity to a recipient's shielded address Adds platform_wallet_manager_shielded_shield_from_identity_to_recipient over PlatformWallet::shielded_shield_from_identity_to_recipient (empty memo). Same shape as the own-address variant: pointer checks before the handle, body under catch_spend_panic (a panic reports 18, do not retry), errors through map_spend_result, sync poke on an unconfirmed spend, out_new_balance written only on success. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 267 ++++++++++++++++++ 1 file changed, 267 insertions(+) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 00161411428..32a15eccf88 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -1350,6 +1350,128 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity( } } +/// Shield credits from one of the wallet's Platform identities to an arbitrary +/// external Orchard recipient: the Type 21 `ShieldFromIdentity` transition with +/// the note addressed to `recipient_raw_43` instead of the wallet's own +/// shielded account. The identity is debited `amount` plus the metered fee plus +/// the shielded compute fee. The memo is empty. +/// +/// `identity_id` is the 32-byte identity id; the identity must be managed by +/// this wallet. `recipient_raw_43` is the recipient's raw 43-byte Orchard +/// address. `signer_identity_handle` is a `*const SignerHandle` produced by +/// `dash_sdk_signer_create_with_ctx` that can sign with the identity's TRANSFER +/// key (the same handle credit transfers use). The caller retains ownership. +/// +/// `out_new_balance`, when non-null, receives the identity's proven +/// post-debit balance, written only on success. A result proof that is not this +/// identity's balance proof, or a failure verdict the proven identity nonce +/// cannot rule out, is reported as `ErrorShieldedSpendUnconfirmed` (the +/// transition may have executed; do not resubmit, the next sync reconciles). +/// +/// A signer that reports the TRANSFER key unavailable surfaces as code 31 +/// (`ErrorSigningKeyUnavailable`), the same key-repair signal the other +/// identity-signed operations use. +/// +/// # Safety +/// - `wallet_id_bytes` must point to 32 readable bytes. +/// - `identity_id` must point to 32 readable bytes. +/// - `recipient_raw_43` must point to 43 readable bytes. +/// - `signer_identity_handle` must be a valid, non-destroyed `*const SignerHandle` +/// that outlives this call and points at a `VTableSigner` with the callback +/// variant. +/// - `out_new_balance` must be null or point to writable `u64` storage. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity_to_recipient( + handle: Handle, + wallet_id_bytes: *const u8, + shielded_account: u32, + identity_id: *const u8, + recipient_raw_43: *const u8, + amount: u64, + signer_identity_handle: *const SignerHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + // Under `catch_unwind` like the other spend exports: a panic must not cross the C ABI, and + // the transition may already be broadcast, so the spend-unconfirmed contract applies. + catch_spend_panic("shielded shield from identity to recipient", || { + shielded_shield_from_identity_to_recipient_inner( + handle, + wallet_id_bytes, + shielded_account, + identity_id, + recipient_raw_43, + amount, + signer_identity_handle, + out_new_balance, + ) + }) +} + +/// Body of [`platform_wallet_manager_shielded_shield_from_identity_to_recipient`], as an +/// ordinary Rust function so a panic unwinds into [`catch_spend_panic`]. +/// +/// # Safety +/// Identical contract to the export that calls it. +#[allow(clippy::too_many_arguments)] +unsafe fn shielded_shield_from_identity_to_recipient_inner( + handle: Handle, + wallet_id_bytes: *const u8, + shielded_account: u32, + identity_id: *const u8, + recipient_raw_43: *const u8, + amount: u64, + signer_identity_handle: *const SignerHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(identity_id); + check_ptr!(recipient_raw_43); + check_ptr!(signer_identity_handle); + + let mut wallet_id = [0u8; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + let identity_id = unwrap_result_or_return!(read_identifier(identity_id)); + let mut recipient = [0u8; 43]; + std::ptr::copy_nonoverlapping(recipient_raw_43, recipient.as_mut_ptr(), 43); + + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(p) => p, + Err(result) => return result, + }; + + // Same pointer round-trip as `platform_wallet_manager_shielded_shield_from_identity`. + let signer_addr = signer_identity_handle as usize; + + let result = block_on_worker(async move { + // SAFETY: valid for the duration of this synchronously-awaited task per + // the caller's documented lifetime contract. + let identity_signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let prover = CachedOrchardProver::new(); + wallet + .shielded_shield_from_identity_to_recipient( + &coordinator, + shielded_account, + &identity_id, + &recipient, + amount, + [0u8; 36], + identity_signer, + &prover, + ) + .await + }); + poke_sync_on_unconfirmed(&result, handle); + match result { + Ok(new_balance) => { + if !out_new_balance.is_null() { + *out_new_balance = new_balance; + } + PlatformWalletFFIResult::ok() + } + Err(e) => map_spend_result(Err(e), "shielded shield from identity to recipient"), + } +} + /// Top up an existing Platform identity's balance from the wallet's shielded /// notes: the Type 22 `IdentityTopUpFromShieldedPool` transition. The identity /// receives `amount`; the flat pool-paid fee (`platform_wallet_shielded_estimate_fee` @@ -3046,6 +3168,151 @@ mod tests { ); } + /// Arguments for `platform_wallet_manager_shielded_shield_from_identity_to_recipient` that + /// are valid except for the one a test nulls out. The signer is a dangling, never-read pointer: + /// every path under test returns before it is dereferenced. + struct ToRecipientArgs { + wallet_id: [u8; 32], + identity_id: [u8; 32], + recipient: [u8; 43], + signer: *const SignerHandle, + } + + impl ToRecipientArgs { + fn new() -> Self { + Self { + wallet_id: [1; 32], + identity_id: [2; 32], + recipient: [3; 43], + signer: std::ptr::NonNull::::dangling().as_ptr(), + } + } + + /// Call the export with `NULL_HANDLE`, nulling the pointer argument named by `null`. + fn call(&self, null: &str, out: *mut u64) -> PlatformWalletFFIResult { + let pick = |name: &str, p: *const u8| { + if null == name { + std::ptr::null() + } else { + p + } + }; + unsafe { + platform_wallet_manager_shielded_shield_from_identity_to_recipient( + NULL_HANDLE, + pick("wallet_id", self.wallet_id.as_ptr()), + 0, + pick("identity_id", self.identity_id.as_ptr()), + pick("recipient", self.recipient.as_ptr()), + 1, + if null == "signer" { + std::ptr::null() + } else { + self.signer + }, + out, + ) + } + } + } + + #[test] + fn shield_from_identity_to_recipient_rejects_each_null_pointer() { + let args = ToRecipientArgs::new(); + for name in ["wallet_id", "identity_id", "recipient", "signer"] { + let result = args.call(name, std::ptr::null_mut()); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorNullPointer, + "a null {name} pointer must be rejected before the handle is resolved" + ); + } + } + + /// With every pointer valid and an unknown handle the export reports `ErrorInvalidHandle` + /// (a code that means nothing was broadcast), and `out_new_balance` is left untouched. + #[test] + fn shield_from_identity_to_recipient_leaves_out_balance_untouched_on_error() { + let args = ToRecipientArgs::new(); + let mut out: u64 = 0xDEAD_BEEF; + let result = args.call("", &mut out); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorInvalidHandle); + assert_eq!( + out, 0xDEAD_BEEF, + "out_new_balance must not be written on error" + ); + + let mut out: u64 = 0xDEAD_BEEF; + let result = args.call("recipient", &mut out); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + assert_eq!( + out, 0xDEAD_BEEF, + "out_new_balance must not be written on error" + ); + + // A null out_new_balance is allowed: it is not a null-pointer error. + let result = args.call("", std::ptr::null_mut()); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorInvalidHandle); + } + + /// The contract's error map for this export: 18 unconfirmed, 55 earlier debit pending, 31 + /// signing key unavailable, 6 build failed before broadcast (own or invalid recipient). + #[test] + fn shield_from_identity_to_recipient_error_map_pins_18_31_55_6() { + let op = "shielded shield from identity to recipient"; + let cases: [(PlatformWalletError, PlatformWalletFFIResultCode, i32); 4] = [ + ( + PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "shield from identity", + reason: "balance proof not confirmed".to_string(), + }, + PlatformWalletFFIResultCode::ErrorShieldedSpendUnconfirmed, + 18, + ), + ( + PlatformWalletError::Sdk(dash_sdk::Error::Protocol(ProtocolError::Generic( + format!("{DASH_SDK_SIGNER_ERR_KEY_UNAVAILABLE_PREFIX}transfer key missing"), + ))), + PlatformWalletFFIResultCode::ErrorSigningKeyUnavailable, + 31, + ), + ( + PlatformWalletError::ShieldedIdentityDebitPending { + identity_id: [7; 32], + }, + PlatformWalletFFIResultCode::ErrorShieldedIdentityDebitPending, + 55, + ), + ( + PlatformWalletError::ShieldedBuildError( + "recipient belongs to this shielded account".to_string(), + ), + PlatformWalletFFIResultCode::ErrorWalletOperation, + 6, + ), + ]; + for (error, code, number) in cases { + let result = map_spend_result(Err(error), op); + assert_eq!(result.code, code); + assert_eq!(result.code as i32, number); + } + } + + /// A panic in the new export's body must become code 18 (never abort the host), under the + /// export's own operation label. + #[test] + fn shield_from_identity_to_recipient_panic_maps_to_code_18() { + let result = catch_spend_panic("shielded shield from identity to recipient", || { + panic!("proving worker panicked"); + }); + assert_eq!(result.code as i32, 18); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedSpendUnconfirmed + ); + assert!(message_of(&result).contains("do NOT retry")); + } + #[test] fn should_map_shielded_identity_debit_pending_without_claiming_submission() { let error = PlatformWalletError::ShieldedIdentityDebitPending { From 7b2677fbc9e4a0e7551134cd5378f62c39a6965c Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 14:20:10 +0200 Subject: [PATCH 02/12] feat(swift-sdk): shieldedShieldFromIdentityToRecipient Swift binding for platform_wallet_manager_shielded_shield_from_identity_to_recipient. Same shape as shieldedShieldFromIdentity: an unconfigured manager throws invalidHandle, then the 32/32/43-byte length guards throw invalidParameter before the FFI call, which runs on a detached task while the identity signer is kept alive. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWalletManagerShieldedSync.swift | 79 +++++++++++++++++++ ...eldFromIdentityToRecipientGuardTests.swift | 76 ++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index a6feb022840..c6c1b4a0cf9 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -990,6 +990,85 @@ extension PlatformWalletManager { }.value } + /// Identity → EXTERNAL Shielded. The Type 21 `ShieldFromIdentity` transition + /// with the note assigned to `recipientRaw43` (a third-party raw 43-byte + /// Orchard payment address) instead of the wallet's own default address. + /// Same signer, confirmation and no-retry rules as + /// [`shieldedShieldFromIdentity`]. + /// + /// The identity is debited `amount` plus the metered fee plus the shielded + /// compute fee (`estimateShieldedFee(kind: .shieldFromIdentity)`). + /// Returns the identity's proven post-debit balance; any unconfirmed + /// outcome throws `.shieldedSpendUnconfirmed` (do not resubmit). + @discardableResult + public func shieldedShieldFromIdentityToRecipient( + walletId: Data, + shieldedAccount: UInt32 = 0, + identityId: Data, + recipientRaw43: Data, + amount: UInt64, + identitySigner: KeychainSigner + ) async throws -> UInt64 { + guard isConfigured, handle != NULL_HANDLE else { + throw PlatformWalletError.invalidHandle( + "PlatformWalletManager not configured" + ) + } + guard walletId.count == 32 else { + throw PlatformWalletError.invalidParameter( + "walletId must be exactly 32 bytes" + ) + } + guard identityId.count == 32 else { + throw PlatformWalletError.invalidParameter( + "identityId must be exactly 32 bytes" + ) + } + guard recipientRaw43.count == 43 else { + throw PlatformWalletError.invalidParameter( + "recipientRaw43 must be exactly 43 bytes" + ) + } + + let handle = self.handle + let signerHandle = identitySigner.handle + + return try await Task.detached(priority: .userInitiated) { () -> UInt64 in + var newBalance: UInt64 = 0 + try withExtendedLifetime(identitySigner) { + try walletId.withUnsafeBytes { widRaw in + guard let widPtr = widRaw.baseAddress?.assumingMemoryBound(to: UInt8.self) + else { + throw PlatformWalletError.invalidParameter("walletId baseAddress is nil") + } + try identityId.withUnsafeBytes { idRaw in + guard let idPtr = idRaw.baseAddress? + .assumingMemoryBound(to: UInt8.self) + else { + throw PlatformWalletError.invalidParameter( + "identityId baseAddress is nil" + ) + } + try recipientRaw43.withUnsafeBytes { rcpRaw in + guard let rcpPtr = rcpRaw.baseAddress? + .assumingMemoryBound(to: UInt8.self) + else { + throw PlatformWalletError.invalidParameter( + "recipientRaw43 baseAddress is nil" + ) + } + try platform_wallet_manager_shielded_shield_from_identity_to_recipient( + handle, widPtr, shieldedAccount, idPtr, rcpPtr, amount, + signerHandle, &newBalance + ).check() + } + } + } + } + return newBalance + }.value + } + /// Platform → EXTERNAL Shielded. The Type 15 shield with the note /// assigned to `recipientRaw43` (a third-party raw 43-byte Orchard /// payment address — same shape [`shieldedTransfer`] takes) instead diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift new file mode 100644 index 00000000000..28f9e13df3a --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift @@ -0,0 +1,76 @@ +import XCTest +@testable import SwiftDashSDK + +/// Input guards of `shieldedShieldFromIdentityToRecipient`: every guard throws +/// before any FFI call, so a fake handle is never dereferenced. +@MainActor +final class ShieldFromIdentityToRecipientGuardTests: XCTestCase { + private static let noopCalls: PlatformWalletNativeTeardownCalls = { + let ok: PlatformWalletNativeTeardownCalls.Call = { _ in + PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + return PlatformWalletNativeTeardownCalls( + spvStop: ok, platformAddressSyncStop: ok, shieldedSyncStop: ok, + dashPaySyncStop: ok, dpnsSyncStop: ok, destroy: ok) + }() + + private func makeSigner() throws -> KeychainSigner { + KeychainSigner(modelContainer: try DashModelContainer.createInMemory()) + } + + private func call( + _ manager: PlatformWalletManager, + walletId: Data = Data(repeating: 1, count: 32), + identityId: Data = Data(repeating: 2, count: 32), + recipientRaw43: Data = Data(repeating: 3, count: 43) + ) async throws { + try await manager.shieldedShieldFromIdentityToRecipient( + walletId: walletId, shieldedAccount: 0, identityId: identityId, + recipientRaw43: recipientRaw43, amount: 1, identitySigner: makeSigner()) + } + + private func assertInvalidParameter( + _ operation: () async throws -> Void, _ what: String, + file: StaticString = #filePath, line: UInt = #line + ) async { + do { + try await operation() + XCTFail("\(what): expected invalidParameter, call succeeded", file: file, line: line) + } catch PlatformWalletError.invalidParameter { + // expected + } catch { + XCTFail("\(what): expected invalidParameter, got \(error)", file: file, line: line) + } + } + + func testWalletIdNot32BytesThrowsInvalidParameter() async { + let manager = PlatformWalletManager.makeForTesting(handle: 91, calls: Self.noopCalls) + await assertInvalidParameter({ try await self.call(manager, walletId: Data(repeating: 1, count: 31)) }, "walletId 31") + await assertInvalidParameter({ try await self.call(manager, walletId: Data(repeating: 1, count: 33)) }, "walletId 33") + } + + func testIdentityIdNot32BytesThrowsInvalidParameter() async { + let manager = PlatformWalletManager.makeForTesting(handle: 92, calls: Self.noopCalls) + await assertInvalidParameter({ try await self.call(manager, identityId: Data(repeating: 2, count: 31)) }, "identityId 31") + await assertInvalidParameter({ try await self.call(manager, identityId: Data(repeating: 2, count: 33)) }, "identityId 33") + } + + func testRecipientNot43BytesThrowsInvalidParameter() async { + let manager = PlatformWalletManager.makeForTesting(handle: 93, calls: Self.noopCalls) + await assertInvalidParameter({ try await self.call(manager, recipientRaw43: Data(repeating: 3, count: 42)) }, "recipient 42") + await assertInvalidParameter({ try await self.call(manager, recipientRaw43: Data(repeating: 3, count: 44)) }, "recipient 44") + await assertInvalidParameter({ try await self.call(manager, recipientRaw43: Data()) }, "recipient empty") + } + + func testUnconfiguredManagerThrowsInvalidHandle() async { + let manager = PlatformWalletManager() + do { + try await call(manager) + XCTFail("expected invalidHandle, call succeeded") + } catch PlatformWalletError.invalidHandle { + // expected + } catch { + XCTFail("expected invalidHandle, got \(error)") + } + } +} From 0f219867bc77b9b3ecbb0964346fbdeae8e35e4c Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 14:20:10 +0200 Subject: [PATCH 03/12] docs(sdk): record shielding an identity's credits to a recipient in the parity manifest Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 36 ++++++++++++++++++++++++++- packages/kotlin-sdk/PARITY_SUMMARY.md | 15 +++++------ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index addcb451cca..42a7ac2fbd2 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -71,7 +71,8 @@ "platform_wallet_topup_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_tracked_asset_locks_free": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", "platform_wallet_tracked_asset_locks_list": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", - "restore_provider_special_txs": "packages/rs-platform-wallet-ffi/src/persistence.rs" + "restore_provider_special_txs": "packages/rs-platform-wallet-ffi/src/persistence.rs", + "platform_wallet_manager_shielded_shield_from_identity_to_recipient": "packages/rs-platform-wallet-ffi/src/shielded_send.rs" }, "capabilities": [ { @@ -1974,6 +1975,39 @@ "covers_restart": false } ] + }, + { + "id": "shielded.shield_from_identity_to_recipient", + "title": "Shield an identity's credits to someone else's shielded address", + "area": "correctness", + "shared_apis": [ + "platform_wallet_manager_shielded_shield_from_identity_to_recipient" + ], + "required_persistence_capabilities": [], + "hosts": { + "swift": { + "sdk": "supported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "PlatformWalletManager.shieldedShieldFromIdentityToRecipient bridges the export; the example app has no screen that pays an identity's credits to another wallet's shielded address." + }, + "kotlin": { + "sdk": "unsupported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "No JNI bridge or Kotlin wrapper for shielding an identity's credits to a recipient yet." + } + }, + "verification": [ + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift", + "id": "testRecipientNot43BytesThrowsInvalidParameter", + "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests", + "covers_restart": false + } + ] } ] } diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index 7bc14e553d1..477ab5765c8 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: **29** +Capabilities tracked: **30** ## Status counts | Host | Surface | Supported | Partial | Unsupported | Not applicable | | --- | --- | ---: | ---: | ---: | ---: | -| Swift | SDK | 16 | 11 | 1 | 1 | -| Swift | Example app | 4 | 14 | 2 | 9 | -| Kotlin | SDK | 13 | 14 | 1 | 1 | -| Kotlin | Example app | 5 | 13 | 1 | 10 | +| Swift | SDK | 17 | 11 | 1 | 1 | +| Swift | Example app | 4 | 14 | 3 | 9 | +| Kotlin | SDK | 13 | 14 | 2 | 1 | +| Kotlin | Example app | 5 | 13 | 2 | 10 | ## Restart coverage | Host | Tested | Required | Not applicable | | --- | ---: | ---: | ---: | -| Swift | 1 | 10 | 18 | -| Kotlin | 4 | 8 | 17 | +| Swift | 1 | 10 | 19 | +| Kotlin | 4 | 8 | 18 | ## Capability status @@ -53,6 +53,7 @@ Capabilities tracked: **29** | `persistence.pending_identity_key_repair` | unsupported / unsupported / not_applicable | supported / not-applicable / tested | | `errors.signing_key_unavailable_discriminator` | supported / not-applicable / not_applicable | supported / not-applicable / not_applicable | | `shielded.core_wallet_drain` | supported / unsupported / tested | unsupported / unsupported / not_applicable | +| `shielded.shield_from_identity_to_recipient` | supported / unsupported / not_applicable | unsupported / unsupported / not_applicable | Source: [`docs/sdk/sdk-parity-manifest.json`](../../docs/sdk/sdk-parity-manifest.json). Detailed legacy view mapping remains in [`PARITY.md`](PARITY.md), but its manual totals are not authoritative. From 7d1ca9b7880c607bc2d96b18c814c6e56a3508a9 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 16:43:41 +0200 Subject: [PATCH 04/12] docs(platform-wallet-ffi): state the bound-account and self-recipient rules of shield-from-identity-to-recipient Also keep shared_symbols in the parity manifest in alphabetical order. Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 4 ++-- packages/rs-platform-wallet-ffi/src/shielded_send.rs | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index 42a7ac2fbd2..46f2ad247f7 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -57,6 +57,7 @@ "platform_wallet_manager_persistence_capabilities": "packages/rs-platform-wallet-ffi/src/manager.rs", "platform_wallet_manager_send_private_contact_request": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_manager_shielded_fund_from_wallet_drain": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", + "platform_wallet_manager_shielded_shield_from_identity_to_recipient": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", "platform_wallet_manager_shielded_wallet_drain_preview": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", "platform_wallet_manager_shielded_wallet_drain_status": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", "platform_wallet_manager_spv_rescan_filters": "packages/rs-platform-wallet-ffi/src/spv.rs", @@ -71,8 +72,7 @@ "platform_wallet_topup_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_tracked_asset_locks_free": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", "platform_wallet_tracked_asset_locks_list": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", - "restore_provider_special_txs": "packages/rs-platform-wallet-ffi/src/persistence.rs", - "platform_wallet_manager_shielded_shield_from_identity_to_recipient": "packages/rs-platform-wallet-ffi/src/shielded_send.rs" + "restore_provider_special_txs": "packages/rs-platform-wallet-ffi/src/persistence.rs" }, "capabilities": [ { diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 32a15eccf88..91473ef61ac 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -1356,6 +1356,12 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity( /// shielded account. The identity is debited `amount` plus the metered fee plus /// the shielded compute fee. The memo is empty. /// +/// A shielded sub-wallet must still be bound at `shielded_account`: its outgoing +/// viewing key enables outgoing-note recovery, and the activity is recorded +/// under that account. A recipient recognized by the account's incoming viewing +/// key is rejected with `ErrorWalletOperation` (code 6); self-shields use +/// [`platform_wallet_manager_shielded_shield_from_identity`]. +/// /// `identity_id` is the 32-byte identity id; the identity must be managed by /// this wallet. `recipient_raw_43` is the recipient's raw 43-byte Orchard /// address. `signer_identity_handle` is a `*const SignerHandle` produced by From 31eb8df278123e8726cee755cac4dcf3b78d646c Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 16:57:39 +0200 Subject: [PATCH 05/12] fix(swift-sdk): keep shieldedShieldFromIdentityToRecipient admitted as a native operation The wrapper ran its FFI call in a detached task without registering a native operation, so once it suspended deleteWallet could pass its in-flight check and shutdown() could finish its drain and destroy the native manager while the spend still ran. It now holds admitNativeOp/finishNativeOp from the detached call through result delivery. A test pauses the spend and checks that deleteWallet is rejected and the native destroy waits. The other shielded wrappers have the same gap, tracked in #5868. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWalletManager.swift | 7 ++ .../PlatformWalletManagerShieldedSync.swift | 21 ++++- ...romIdentityToRecipientAdmissionTests.swift | 78 +++++++++++++++++++ 3 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index fce0f9505e5..04cacbb81e6 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -713,6 +713,13 @@ public class PlatformWalletManager: ObservableObject { /// injectable so ownership and shutdown admission are tested together. internal var nativeShieldedLocalBalanceCalls = PlatformWalletNativeShieldedLocalBalanceCalls.live + /// Test seam for the native call behind + /// `shieldedShieldFromIdentityToRecipient`, so its shutdown admission is + /// tested without a signer or network; same contract as + /// [`nativeTeardownCalls`]. + internal var nativeShieldFromIdentityToRecipientCall: ShieldFromIdentityToRecipientCall = + platform_wallet_manager_shielded_shield_from_identity_to_recipient + /// Test seam for the native reads behind the progress poller; same /// contract as [`nativeTeardownCalls`]. internal var nativePollCalls = PlatformWalletNativePollCalls.live diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index c6c1b4a0cf9..ba1127b1b12 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -82,6 +82,13 @@ public struct ShieldedSyncEvent: Sendable { } } +/// The native shield-from-identity-to-recipient call; injectable through +/// `PlatformWalletManager.nativeShieldFromIdentityToRecipientCall`. +typealias ShieldFromIdentityToRecipientCall = @Sendable ( + Handle, UnsafePointer, UInt32, UnsafePointer, UnsafePointer, + UInt64, OpaquePointer, UnsafeMutablePointer +) -> PlatformWalletFFIResult + extension PlatformWalletManager { /// Shutdown leaves the handle live for admitted operations after its /// early shielded stop. Do not restart or mutate that lifecycle while @@ -1000,6 +1007,11 @@ extension PlatformWalletManager { /// compute fee (`estimateShieldedFee(kind: .shieldFromIdentity)`). /// Returns the identity's proven post-debit balance; any unconfirmed /// outcome throws `.shieldedSpendUnconfirmed` (do not resubmit). + /// + /// Admitted as an async native operation until the result is delivered: + /// `shutdown()` waits for it, a call made once a shutdown has begun throws + /// `invalidHandle` before any native work, and the synchronous wallet + /// create, load and delete throw `invalidHandle` while it is in flight. @discardableResult public func shieldedShieldFromIdentityToRecipient( walletId: Data, @@ -1030,8 +1042,15 @@ extension PlatformWalletManager { ) } + // Admitted through the detached call and the result delivery, like + // `withWalletDrainNativeOperation`: `shutdown()` waits for the spend + // before destroying the handle, and `deleteWallet` is rejected while + // it runs. Cancelling the caller does not release it early. + try admitNativeOp("shieldedShieldFromIdentityToRecipient") + defer { finishNativeOp() } let handle = self.handle let signerHandle = identitySigner.handle + let shield = nativeShieldFromIdentityToRecipientCall return try await Task.detached(priority: .userInitiated) { () -> UInt64 in var newBalance: UInt64 = 0 @@ -1057,7 +1076,7 @@ extension PlatformWalletManager { "recipientRaw43 baseAddress is nil" ) } - try platform_wallet_manager_shielded_shield_from_identity_to_recipient( + try shield( handle, widPtr, shieldedAccount, idPtr, rcpPtr, amount, signerHandle, &newBalance ).check() diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift new file mode 100644 index 00000000000..4c01fed5348 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift @@ -0,0 +1,78 @@ +import XCTest +import Combine +import DashSDKFFI +@testable import SwiftDashSDK + +/// `shieldedShieldFromIdentityToRecipient` stays admitted as a native +/// operation from its FFI call through result delivery: while the spend runs, +/// the synchronous `deleteWallet` is rejected and `shutdown()` does not +/// destroy the native manager. +@MainActor +final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { + private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var raised = false + func raise() { lock.withLock { raised = true } } + var isRaised: Bool { lock.withLock { raised } } + } + + func testShouldHoldAdmissionWhileSpendIsInFlight() async throws { + let destroyed = expectation(description: "native destroy ran") + let destroyedEarly = expectation(description: "native destroy ran during the spend") + destroyedEarly.isInverted = true + let spendFinished = Flag() + let ok: PlatformWalletNativeTeardownCalls.Call = { _ in + PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + let calls = PlatformWalletNativeTeardownCalls( + spvStop: ok, platformAddressSyncStop: ok, shieldedSyncStop: ok, + dashPaySyncStop: ok, dpnsSyncStop: ok, + destroy: { _ in + if !spendFinished.isRaised { destroyedEarly.fulfill() } + destroyed.fulfill() + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + }) + let manager = PlatformWalletManager.makeForTesting(handle: 77, calls: calls) + + let entered = expectation(description: "spend entered the native call") + let gate = DispatchSemaphore(value: 0) + defer { gate.signal() } + manager.nativeShieldFromIdentityToRecipientCall = { handle, _, _, _, _, _, _, newBalance in + XCTAssertEqual(handle, 77) + entered.fulfill() + XCTAssertEqual(gate.wait(timeout: .now() + 10), .success) + newBalance.pointee = 7 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + let signer = KeychainSigner(modelContainer: try DashModelContainer.createInMemory()) + let spend = Task { + try await manager.shieldedShieldFromIdentityToRecipient( + walletId: Data(repeating: 1, count: 32), identityId: Data(repeating: 2, count: 32), + recipientRaw43: Data(repeating: 3, count: 43), amount: 1, identitySigner: signer) + } + await fulfillment(of: [entered], timeout: 5) + + // deleteWallet must be refused by the in-flight gate, not by a later + // precondition (the test manager has no persistence handler either). + do { + try manager.deleteWallet(walletId: Data(repeating: 1, count: 32)) + XCTFail("deleteWallet must be rejected while the spend is in flight") + } catch PlatformWalletError.invalidHandle(let message) { + XCTAssertTrue(message.contains("in flight"), "deleteWallet rejected for another reason: \(message)") + } + + let revoked = expectation(description: "shutdown revoked the public handle") + let subscription = manager.$isConfigured.dropFirst().sink { if !$0 { revoked.fulfill() } } + defer { subscription.cancel() } + let shutdown = Task { await manager.shutdown() } + await fulfillment(of: [revoked], timeout: 5) + await fulfillment(of: [destroyedEarly], timeout: 1) + + spendFinished.raise() + gate.signal() + let balance = try await spend.value + XCTAssertEqual(balance, 7) + _ = await shutdown.value + await fulfillment(of: [destroyed], timeout: 5) + } +} From da07bab42a480e80377508ae88bd024de05bea9c Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 11:47:20 +0200 Subject: [PATCH 06/12] fix(swift-sdk): reject clearing shielded state while a shielded spend is admitted clearShielded() now uses the shared synchronous-entrypoint admission gate, so it is refused while any async native operation (such as the identity-to-recipient shielded spend) is admitted. Clear could otherwise wipe or resurrect the spend's recovery state mid-payment. The gate is promoted from private so the shielded extension can reuse it. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWalletManager.swift | 2 +- .../PlatformWalletManagerShieldedSync.swift | 5 ++ ...romIdentityToRecipientAdmissionTests.swift | 48 +++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index 04cacbb81e6..a06ade97357 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -1360,7 +1360,7 @@ public class PlatformWalletManager: ObservableObject { /// permit mutation before a completed read's MainActor delivery: deletion /// could otherwise remove the wallet while its old snapshot is still queued. /// Both operations remain counted through delivery to close that window. - private func ensureSyncNativeOpAllowed(_ name: String) throws { + func ensureSyncNativeOpAllowed(_ name: String) throws { try ensureConfigured() guard !shutdownRequested else { throw PlatformWalletError.invalidHandle( diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index ba1127b1b12..19cee995b10 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -466,9 +466,14 @@ extension PlatformWalletManager { /// Throws `walletOperation` while an async [`stopShieldedSync()`] is in /// flight: Clear quiesces the same loop and would wait on the calling /// thread for the pass that stop is draining. + /// + /// Throws `invalidHandle` while an async native operation is admitted + /// (for example a shielded spend or a wallet drain): Clear would wipe the + /// recovery state that operation is about to write or has armed. public func clearShielded() throws { try ensureShieldedLifecycleAllowed("clearShielded") try ensureNoShieldedStopInFlight(before: "clearing shielded state") + try ensureSyncNativeOpAllowed("clearShielded") try withShieldedLocalBalanceMutation { try platform_wallet_manager_shielded_clear(handle).check() } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift index 4c01fed5348..b436408ffd7 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift @@ -75,4 +75,52 @@ final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { _ = await shutdown.value await fulfillment(of: [destroyed], timeout: 5) } + + /// `clearShielded` would wipe the recovery state the admitted spend is + /// about to write or has just armed, so it is refused while the spend is + /// in flight and is no longer refused by the gate once the spend finished. + func testShouldRejectClearShieldedWhileSpendIsInFlight() async throws { + let ok: PlatformWalletNativeTeardownCalls.Call = { _ in + PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + let calls = PlatformWalletNativeTeardownCalls( + spvStop: ok, platformAddressSyncStop: ok, shieldedSyncStop: ok, + dashPaySyncStop: ok, dpnsSyncStop: ok, destroy: ok) + let manager = PlatformWalletManager.makeForTesting(handle: 77, calls: calls) + + let entered = expectation(description: "spend entered the native call") + let gate = DispatchSemaphore(value: 0) + defer { gate.signal() } + manager.nativeShieldFromIdentityToRecipientCall = { _, _, _, _, _, _, _, newBalance in + entered.fulfill() + XCTAssertEqual(gate.wait(timeout: .now() + 10), .success) + newBalance.pointee = 7 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + let signer = KeychainSigner(modelContainer: try DashModelContainer.createInMemory()) + let spend = Task { + try await manager.shieldedShieldFromIdentityToRecipient( + walletId: Data(repeating: 1, count: 32), identityId: Data(repeating: 2, count: 32), + recipientRaw43: Data(repeating: 3, count: 43), amount: 1, identitySigner: signer) + } + await fulfillment(of: [entered], timeout: 5) + + do { + try manager.clearShielded() + XCTFail("clearShielded must be rejected while the spend is in flight") + } catch PlatformWalletError.invalidHandle(let message) { + XCTAssertTrue(message.contains("in flight"), "clearShielded rejected for another reason: \(message)") + } + + gate.signal() + _ = try await spend.value + + // The test handle is not a live native manager, so the FFI clear may + // fail; it must no longer be the admission gate that refuses it. + do { + try manager.clearShielded() + } catch PlatformWalletError.invalidHandle(let message) { + XCTAssertFalse(message.contains("in flight"), "clearShielded still gated after the spend: \(message)") + } catch {} + } } From d88b9527419acd0afa5e122559ae35cba863132b Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 15:08:27 +0200 Subject: [PATCH 07/12] test(swift-sdk): assert the recipient shield forwards its payment arguments The injected native call in the recipient-shield admission test now checks every payment argument it receives: wallet, identity and recipient byte patterns (32/32/43 bytes, all distinct), a non-default shielded account and a distinctive amount. Swapping or mis-forwarding any of them fails the test. Also list clearShielded among the synchronous native entrypoints in the admission-gate doc comment. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWallet/PlatformWalletManager.swift | 3 ++- ...hieldFromIdentityToRecipientAdmissionTests.swift | 13 ++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index a06ade97357..6ad6f2b63e6 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -1339,7 +1339,8 @@ public class PlatformWalletManager: ObservableObject { // MARK: - Wallet creation /// Admission gate for the SYNCHRONOUS native entrypoints (`createWallet`, - /// `createWalletFromSeed`, `loadFromPersistor`, `deleteWallet`). Rejects: + /// `createWalletFromSeed`, `loadFromPersistor`, `deleteWallet`, + /// `clearShielded`). Rejects: /// /// - once shutdown has closed admission — including the drain window, /// where the captured native handle remains live for an diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift index b436408ffd7..299dc050012 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift @@ -37,8 +37,13 @@ final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { let entered = expectation(description: "spend entered the native call") let gate = DispatchSemaphore(value: 0) defer { gate.signal() } - manager.nativeShieldFromIdentityToRecipientCall = { handle, _, _, _, _, _, _, newBalance in + manager.nativeShieldFromIdentityToRecipientCall = { handle, wid, acct, ident, rcp, amt, _, newBalance in XCTAssertEqual(handle, 77) + XCTAssertEqual(Data(bytes: wid, count: 32), Data(repeating: 1, count: 32)) + XCTAssertEqual(acct, 5) + XCTAssertEqual(Data(bytes: ident, count: 32), Data(repeating: 2, count: 32)) + XCTAssertEqual(Data(bytes: rcp, count: 43), Data(repeating: 3, count: 43)) + XCTAssertEqual(amt, 123_456_789) entered.fulfill() XCTAssertEqual(gate.wait(timeout: .now() + 10), .success) newBalance.pointee = 7 @@ -47,8 +52,10 @@ final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { let signer = KeychainSigner(modelContainer: try DashModelContainer.createInMemory()) let spend = Task { try await manager.shieldedShieldFromIdentityToRecipient( - walletId: Data(repeating: 1, count: 32), identityId: Data(repeating: 2, count: 32), - recipientRaw43: Data(repeating: 3, count: 43), amount: 1, identitySigner: signer) + walletId: Data(repeating: 1, count: 32), shieldedAccount: 5, + identityId: Data(repeating: 2, count: 32), + recipientRaw43: Data(repeating: 3, count: 43), amount: 123_456_789, + identitySigner: signer) } await fulfillment(of: [entered], timeout: 5) From 85650eb003eba2d23e45b16d9927982e246cab24 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 09:06:21 +0200 Subject: [PATCH 08/12] feat(platform-wallet-ffi): take a memo when shielding identity credits to a recipient platform_wallet_manager_shielded_shield_from_identity_to_recipient now takes an optional memo_text between amount and signer_identity_handle (9 parameters), matching the shape PR #5896 exports for the Kotlin/JNI binding. NULL or empty means no memo; otherwise the text is encoded with encode_memo_text (over 32 UTF-8 bytes is ErrorInvalidParameter, invalid UTF-8 is ErrorUtf8Conversion), before the wallet handle is resolved and after the pointer checks. Swift: shieldedShieldFromIdentityToRecipient gains memo: String? = nil, passed with withCString or nil like shieldedShieldToRecipient. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 98 ++++++++++++++++++- .../PlatformWalletManagerShieldedSync.swift | 25 ++++- ...romIdentityToRecipientAdmissionTests.swift | 37 ++++++- 3 files changed, 151 insertions(+), 9 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index a99b37c0de3..73bffd26088 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -1304,7 +1304,11 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity( /// external Orchard recipient: the Type 21 `ShieldFromIdentity` transition with /// the note addressed to `recipient_raw_43` instead of the wallet's own /// shielded account. The identity is debited `amount` plus the metered fee plus -/// the shielded compute fee. The memo is empty. +/// the shielded compute fee. +/// +/// `memo_text` is an optional NUL-terminated UTF-8 string attached to the recipient's note, with +/// the same rules as `platform_wallet_manager_shielded_shield_to_recipient`: `null` or empty means +/// no memo; a non-empty memo's UTF-8 byte length must be <= 32. /// /// A shielded sub-wallet must still be bound at `shielded_account`: its outgoing /// viewing key enables outgoing-note recovery, and the activity is recorded @@ -1332,6 +1336,8 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity( /// - `wallet_id_bytes` must point to 32 readable bytes. /// - `identity_id` must point to 32 readable bytes. /// - `recipient_raw_43` must point to 43 readable bytes. +/// - `memo_text`, when non-null, must be a valid NUL-terminated UTF-8 C string for the duration +/// of the call. /// - `signer_identity_handle` must be a valid, non-destroyed `*const SignerHandle` /// that outlives this call and points at a `VTableSigner` with the callback /// variant. @@ -1344,6 +1350,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity_t identity_id: *const u8, recipient_raw_43: *const u8, amount: u64, + memo_text: *const c_char, signer_identity_handle: *const SignerHandle, out_new_balance: *mut u64, ) -> PlatformWalletFFIResult { @@ -1357,6 +1364,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity_t identity_id, recipient_raw_43, amount, + memo_text, signer_identity_handle, out_new_balance, ) @@ -1376,6 +1384,7 @@ unsafe fn shielded_shield_from_identity_to_recipient_inner( identity_id: *const u8, recipient_raw_43: *const u8, amount: u64, + memo_text: *const c_char, signer_identity_handle: *const SignerHandle, out_new_balance: *mut u64, ) -> PlatformWalletFFIResult { @@ -1390,6 +1399,26 @@ unsafe fn shielded_shield_from_identity_to_recipient_inner( let mut recipient = [0u8; 43]; std::ptr::copy_nonoverlapping(recipient_raw_43, recipient.as_mut_ptr(), 43); + // Decode the optional memo string before resolving the wallet so a + // malformed memo fails fast without touching wallet state. + let memo_str = if memo_text.is_null() { + None + } else { + match CStr::from_ptr(memo_text).to_str() { + Ok(s) => Some(s), + Err(e) => { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorUtf8Conversion, + format!("memo_text is not valid UTF-8: {e}"), + ); + } + } + }; + let memo = match encode_memo_text(memo_str) { + Ok(m) => m, + Err(result) => return result, + }; + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { Ok(p) => p, Err(result) => return result, @@ -1410,7 +1439,7 @@ unsafe fn shielded_shield_from_identity_to_recipient_inner( &identity_id, &recipient, amount, - [0u8; 36], + memo, identity_signer, &prover, ) @@ -2485,6 +2514,7 @@ mod tests { use key_wallet::wallet::initialization::WalletAccountCreationOptions; use platform_wallet::wallet::shielded::store::PendingRedrive; use platform_wallet::wallet::shielded::{FileBackedShieldedStore, ShieldedStore, SubwalletId}; + use std::ffi::CString; #[test] fn encode_memo_text_none_is_empty() { @@ -3146,6 +3176,16 @@ mod tests { /// Call the export with `NULL_HANDLE`, nulling the pointer argument named by `null`. fn call(&self, null: &str, out: *mut u64) -> PlatformWalletFFIResult { + self.call_with_memo(null, std::ptr::null(), out) + } + + /// As [`Self::call`], with an explicit `memo_text`. + fn call_with_memo( + &self, + null: &str, + memo_text: *const c_char, + out: *mut u64, + ) -> PlatformWalletFFIResult { let pick = |name: &str, p: *const u8| { if null == name { std::ptr::null() @@ -3161,6 +3201,7 @@ mod tests { pick("identity_id", self.identity_id.as_ptr()), pick("recipient", self.recipient.as_ptr()), 1, + memo_text, if null == "signer" { std::ptr::null() } else { @@ -3185,6 +3226,59 @@ mod tests { } } + /// The memo is decoded before the handle is resolved: with an unknown handle, a memo over 32 + /// UTF-8 bytes is refused with the siblings' `ErrorInvalidParameter`. + #[test] + fn shield_from_identity_to_recipient_refuses_a_memo_over_32_bytes() { + let args = ToRecipientArgs::new(); + let memo = CString::new("a".repeat(MEMO_PAYLOAD_SIZE + 1)).unwrap(); + let mut out: u64 = 0xDEAD_BEEF; + let result = args.call_with_memo("", memo.as_ptr(), &mut out); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + assert_eq!( + out, 0xDEAD_BEEF, + "out_new_balance must not be written on error" + ); + } + + /// A NULL, empty or valid (including exactly 32 bytes) memo passes the decode and reaches the + /// handle lookup, which is where an unknown handle is reported. + #[test] + fn shield_from_identity_to_recipient_accepts_no_memo_empty_and_valid_memos() { + let args = ToRecipientArgs::new(); + let empty = CString::new("").unwrap(); + let hi = CString::new("hi").unwrap(); + let max = CString::new("a".repeat(MEMO_PAYLOAD_SIZE)).unwrap(); + for memo in [std::ptr::null(), empty.as_ptr(), hi.as_ptr(), max.as_ptr()] { + let result = args.call_with_memo("", memo, std::ptr::null_mut()); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorInvalidHandle); + } + } + + /// A memo that is not UTF-8 is `ErrorUtf8Conversion`, as in the siblings. + #[test] + fn shield_from_identity_to_recipient_refuses_a_memo_that_is_not_utf8() { + let args = ToRecipientArgs::new(); + let memo = CString::new(vec![0xFF, 0xFE]).unwrap(); + let result = args.call_with_memo("", memo.as_ptr(), std::ptr::null_mut()); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorUtf8Conversion + ); + } + + /// The pointer checks keep their place ahead of the memo decode. + #[test] + fn shield_from_identity_to_recipient_checks_pointers_before_the_memo() { + let args = ToRecipientArgs::new(); + let memo = CString::new("a".repeat(MEMO_PAYLOAD_SIZE + 1)).unwrap(); + let result = args.call_with_memo("signer", memo.as_ptr(), std::ptr::null_mut()); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + /// With every pointer valid and an unknown handle the export reports `ErrorInvalidHandle` /// (a code that means nothing was broadcast), and `out_new_balance` is left untouched. #[test] diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 4e8408488cf..c283f16daa4 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -86,7 +86,7 @@ public struct ShieldedSyncEvent: Sendable { /// `PlatformWalletManager.nativeShieldFromIdentityToRecipientCall`. typealias ShieldFromIdentityToRecipientCall = @Sendable ( Handle, UnsafePointer, UInt32, UnsafePointer, UnsafePointer, - UInt64, OpaquePointer, UnsafeMutablePointer + UInt64, UnsafePointer?, OpaquePointer, UnsafeMutablePointer ) -> PlatformWalletFFIResult extension PlatformWalletManager { @@ -1128,6 +1128,10 @@ extension PlatformWalletManager { /// Returns the identity's proven post-debit balance; any unconfirmed /// outcome throws `.shieldedSpendUnconfirmed` (do not resubmit). /// + /// `memo` follows [`shieldedShieldToRecipient`]'s rules: `nil` / empty + /// means no memo; a non-empty memo's UTF-8 byte length must be at most 32 + /// or the call throws `invalidParameter` (Rust owns the limit). + /// /// Admitted as an async native operation until the result is delivered: /// `shutdown()` waits for it, a call made once a shutdown has begun throws /// `invalidHandle` before any native work, and the synchronous wallet @@ -1139,6 +1143,7 @@ extension PlatformWalletManager { identityId: Data, recipientRaw43: Data, amount: UInt64, + memo: String? = nil, identitySigner: KeychainSigner ) async throws -> UInt64 { guard isConfigured, handle != NULL_HANDLE else { @@ -1196,10 +1201,20 @@ extension PlatformWalletManager { "recipientRaw43 baseAddress is nil" ) } - try shield( - handle, widPtr, shieldedAccount, idPtr, rcpPtr, amount, - signerHandle, &newBalance - ).check() + // `nil` / empty → null pointer (no memo); otherwise + // pass the text as a C string — Rust validates the + // 32-byte limit and does the 36-byte encoding. + let send: (UnsafePointer?) throws -> Void = { memoCStr in + try shield( + handle, widPtr, shieldedAccount, idPtr, rcpPtr, amount, + memoCStr, signerHandle, &newBalance + ).check() + } + if let memo, !memo.isEmpty { + try memo.withCString { try send($0) } + } else { + try send(nil) + } } } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift index 299dc050012..ca3097e65f6 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift @@ -37,13 +37,14 @@ final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { let entered = expectation(description: "spend entered the native call") let gate = DispatchSemaphore(value: 0) defer { gate.signal() } - manager.nativeShieldFromIdentityToRecipientCall = { handle, wid, acct, ident, rcp, amt, _, newBalance in + manager.nativeShieldFromIdentityToRecipientCall = { handle, wid, acct, ident, rcp, amt, memo, _, newBalance in XCTAssertEqual(handle, 77) XCTAssertEqual(Data(bytes: wid, count: 32), Data(repeating: 1, count: 32)) XCTAssertEqual(acct, 5) XCTAssertEqual(Data(bytes: ident, count: 32), Data(repeating: 2, count: 32)) XCTAssertEqual(Data(bytes: rcp, count: 43), Data(repeating: 3, count: 43)) XCTAssertEqual(amt, 123_456_789) + XCTAssertNil(memo, "no memo argument must reach the native call as NULL") entered.fulfill() XCTAssertEqual(gate.wait(timeout: .now() + 10), .success) newBalance.pointee = 7 @@ -98,7 +99,7 @@ final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { let entered = expectation(description: "spend entered the native call") let gate = DispatchSemaphore(value: 0) defer { gate.signal() } - manager.nativeShieldFromIdentityToRecipientCall = { _, _, _, _, _, _, _, newBalance in + manager.nativeShieldFromIdentityToRecipientCall = { _, _, _, _, _, _, _, _, newBalance in entered.fulfill() XCTAssertEqual(gate.wait(timeout: .now() + 10), .success) newBalance.pointee = 7 @@ -130,4 +131,36 @@ final class ShieldFromIdentityToRecipientAdmissionTests: XCTestCase { XCTAssertFalse(message.contains("in flight"), "clearShielded still gated after the spend: \(message)") } catch {} } + + /// The `memo` argument reaches the native call: `nil` and an empty string + /// as a null pointer, text as the C string. + func testShouldForwardTheMemoToTheNativeCall() async throws { + let ok: PlatformWalletNativeTeardownCalls.Call = { _ in + PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + let calls = PlatformWalletNativeTeardownCalls( + spvStop: ok, platformAddressSyncStop: ok, shieldedSyncStop: ok, + dashPaySyncStop: ok, dpnsSyncStop: ok, destroy: ok) + let manager = PlatformWalletManager.makeForTesting(handle: 77, calls: calls) + let seen = MemoLog() + manager.nativeShieldFromIdentityToRecipientCall = { _, _, _, _, _, _, memo, _, _ in + seen.append(memo.map { String(cString: $0) }) + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + let signer = KeychainSigner(modelContainer: try DashModelContainer.createInMemory()) + for memo in [nil, "", "hi"] as [String?] { + try await manager.shieldedShieldFromIdentityToRecipient( + walletId: Data(repeating: 1, count: 32), identityId: Data(repeating: 2, count: 32), + recipientRaw43: Data(repeating: 3, count: 43), amount: 1, memo: memo, + identitySigner: signer) + } + XCTAssertEqual(seen.values, [nil, nil, "hi"]) + } + + private final class MemoLog: @unchecked Sendable { + private let lock = NSLock() + private var items: [String?] = [] + func append(_ value: String?) { lock.withLock { items.append(value) } } + var values: [String?] { lock.withLock { items } } + } } From 0f13797eaa1d0e738fdf2814b943f25260d40623 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 09:59:27 +0200 Subject: [PATCH 09/12] fix(platform-wallet): refuse an identity shield whose balance cannot cover the amount and fee Read the identity's proved balance before the redrive guard is armed and refuse with InsufficientIdentityCredits (FFI code 39) when it is below the amount plus the consensus admission floor. CheckTx would otherwise refuse the debit after the guard was armed, leaving every later identity shield blocked by an unresolved debit that never executed. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 32 ++++ .../src/wallet/shielded/operations.rs | 170 +++++++++++++++++- 2 files changed, 200 insertions(+), 2 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 73bffd26088..4b56df6aee8 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -623,6 +623,10 @@ pub(crate) fn map_spend_result( // built or broadcast. Preserve that distinction from an unconfirmed // submission so hosts can wait for the original payment's sync. Err(e @ PlatformWalletError::ShieldedIdentityDebitPending { .. }) + // An identity shield whose proved balance cannot cover the amount and + // fee: refused before anything was armed or broadcast, code 39 with the + // figures in the stable JSON detail. + | Err(e @ PlatformWalletError::InsufficientIdentityCredits { .. }) | Err(e @ PlatformWalletError::ShieldedRecoveryCorrupted { .. }) | Err(e @ PlatformWalletError::ShieldedRecoveryKeysRequired { .. }) => e.into(), // A private contact request in flight, or paid and not yet read back @@ -1328,6 +1332,11 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity( /// cannot rule out, is reported as `ErrorShieldedSpendUnconfirmed` (the /// transition may have executed; do not resubmit, the next sync reconciles). /// +/// An identity whose proved balance is below `amount` plus the shielded +/// identity-debit fee floor (`platform_wallet_shielded_estimate_fee` kind 3, two +/// actions) is refused before anything is armed or broadcast, as +/// `ErrorInsufficientIdentityCredits` (39, JSON detail with `required` and `available`). +/// /// A signer that reports the TRANSFER key unavailable surfaces as code 31 /// (`ErrorSigningKeyUnavailable`), the same key-repair signal the other /// identity-signed operations use. @@ -3348,6 +3357,29 @@ mod tests { } } + /// A balance that cannot cover the amount and fee is refused before anything is armed or + /// broadcast; the host reads it as 39 with the figures in the stable JSON detail, not as 6. + #[test] + fn shield_from_identity_insufficient_balance_maps_to_code_39() { + let identity_id = dpp::prelude::Identifier::from([7; 32]); + let result = map_spend_result( + Err(PlatformWalletError::InsufficientIdentityCredits { + identity_id, + required: 200, + available: 100, + }), + "shielded shield from identity to recipient", + ); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInsufficientIdentityCredits + ); + assert_eq!(result.code as i32, 39); + let detail: serde_json::Value = serde_json::from_str(&message_of(&result)).unwrap(); + assert_eq!(detail["required"], 200); + assert_eq!(detail["available"], 100); + } + /// A panic in the new export's body must become code 18 (never abort the host), under the /// export's own operation label. #[test] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index abb0836f87d..ac73cba3806 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -53,7 +53,7 @@ use dash_sdk::platform::fetch_current_no_parameters::FetchCurrent; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::identity_create_from_shielded_pool::IdentityCreateFromShieldedPool; use dash_sdk::platform::Fetch; -use dash_sdk::query_types::IdentityNonceFetcher; +use dash_sdk::query_types::{IdentityBalance, IdentityNonceFetcher}; use dpp::address_funds::{ AddressFundsFeeStrategy, AddressFundsFeeStrategyStep, OrchardAddress, PlatformAddress, }; @@ -77,7 +77,7 @@ use dpp::shielded::builder::{ build_shielded_transfer_transition, build_shielded_withdrawal_transition, build_unshield_transition, OrchardProver, SpendableNote, }; -use dpp::shielded::compute_minimum_shielded_fee; +use dpp::shielded::{compute_minimum_shielded_fee, compute_shielded_identity_balance_write_fee}; use dpp::state_transition::proof_result::StateTransitionProofResult; use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; use dpp::state_transition::StateTransition; @@ -1114,6 +1114,29 @@ pub(in crate::wallet) async fn shield_from_identity_to< other => other, }; + // Refuse before the redrive guard is armed or anything is broadcast: consensus + // refuses a debit the identity cannot cover (amount plus the admission floor) + // at CheckTx, and a guard armed for a debit that never executes can never be + // resolved by the scan. The caller's managed identity may be stale, so read the + // proved balance. + let fee = compute_shielded_identity_balance_write_fee(2, sdk.version()).map_err(|e| { + PlatformWalletError::ShieldedBuildError(format!("compute identity shield fee: {e}")) + })?; + let required = amount.saturating_add(fee); + let available = IdentityBalance::fetch(sdk, identity_id) + .await + .map_err(|e| { + PlatformWalletError::ShieldedBuildError(format!("fetch identity balance: {e}")) + })? + .ok_or(PlatformWalletError::IdentityBalanceUnavailable(identity_id))?; + if available < required { + return Err(PlatformWalletError::InsufficientIdentityCredits { + identity_id, + required, + available, + }); + } + let nonce = sdk .get_identity_nonce(identity_id, true, None) .await @@ -4866,6 +4889,149 @@ mod redrive_tests { .into() } + /// Signer and prover for the pre-broadcast refusals: neither is reached. + #[derive(Debug)] + struct UnreachableIdentitySigner; + + #[async_trait::async_trait] + impl Signer for UnreachableIdentitySigner { + async fn sign(&self, _: &IdentityPublicKey, _: &[u8]) -> Result { + unreachable!("nothing is signed") + } + + async fn sign_create_witness( + &self, + _: &IdentityPublicKey, + _: &[u8], + ) -> Result { + unreachable!("nothing is signed") + } + + fn can_sign_with(&self, _: &IdentityPublicKey) -> bool { + false + } + } + + struct UnreachableIdentityProver; + impl OrchardProver for UnreachableIdentityProver { + fn proving_key(&self) -> &ProvingKey { + panic!("nothing is proved") + } + } + + /// Run `shield_from_identity_to` to a third party against a mock whose + /// proved balance for the identity is `proved_balance`, while the managed + /// identity (the caller's possibly stale copy) claims a huge balance. + /// Returns the result and the store, to inspect what was armed or recorded. + async fn identity_shield_with_proved_balance( + proved_balance: u64, + amount: u64, + ) -> ( + Result<(Credits, ResponseMetadata), PlatformWalletError>, + Arc>, + SubwalletId, + ) { + use dash_sdk::query_types::IdentityBalance; + use dpp::identity::v0::IdentityV0; + + let identity_id = Identifier::from([0x71; 32]); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("mock sdk"); + sdk.mock() + .expect_fetch::(identity_id, Some(proved_balance)) + .await + .expect("balance expectation"); + let sdk = Arc::new(sdk); + let wallet_id = [0x72; 32]; + let id = SubwalletId::new(wallet_id, 0); + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + let keys = OrchardKeySet::from_seed(&[0x42; 32], Network::Testnet, 0) + .expect("keys") + .viewing_keys(); + let recipient = OrchardKeySet::from_seed(&[0x24; 32], Network::Testnet, 0) + .expect("recipient keys") + .default_address; + let identity = Identity::V0(IdentityV0 { + id: identity_id, + public_keys: Default::default(), + balance: u64::MAX / 2, + revision: 0, + }); + let result = shield_from_identity_to( + &sdk, + &store, + None, + wallet_id, + &keys, + 0, + Some(&recipient), + &identity, + amount, + [0u8; 36], + &UnreachableIdentitySigner, + &UnreachableIdentityProver, + ) + .await; + (result, store, id) + } + + async fn assert_nothing_armed_or_recorded( + store: &Arc>, + id: SubwalletId, + ) { + let store = store.read().await; + assert!(store.pending_redrives(id).unwrap().is_empty(), "no guard"); + assert!(store.get_activity_ids(id).unwrap().is_empty(), "no row"); + } + + #[tokio::test] + async fn should_refuse_an_identity_shield_whose_balance_is_one_credit_short() { + let amount = 1_000_000; + let fee = dpp::shielded::compute_shielded_identity_balance_write_fee( + 2, + PlatformVersion::latest(), + ) + .expect("fee"); + + let (result, store, id) = + identity_shield_with_proved_balance(amount + fee - 1, amount).await; + + match result { + Err(PlatformWalletError::InsufficientIdentityCredits { + required, + available, + .. + }) => { + assert_eq!(required, amount + fee); + assert_eq!(available, amount + fee - 1); + } + other => panic!("expected InsufficientIdentityCredits, got {other:?}"), + } + assert_nothing_armed_or_recorded(&store, id).await; + } + + #[tokio::test] + async fn should_pass_the_balance_check_when_it_covers_the_amount_and_fee_exactly() { + let amount = 1_000_000; + let fee = dpp::shielded::compute_shielded_identity_balance_write_fee( + 2, + PlatformVersion::latest(), + ) + .expect("fee"); + + let (result, _store, _id) = identity_shield_with_proved_balance(amount + fee, amount).await; + + // The unconfigured mock refuses the nonce fetch that follows the check. + match result { + Err(PlatformWalletError::ShieldedBuildError(reason)) => { + assert!(reason.contains("fetch identity nonce"), "{reason}") + } + other => panic!("expected to reach the nonce fetch, got {other:?}"), + } + } + #[tokio::test] async fn should_release_only_explicitly_abandoned_guard_and_never_redrive_it() { let wallet_id = [4; 32]; From 418f95a642fe5a2924b720e4684573322f269088 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 10:07:29 +0200 Subject: [PATCH 10/12] test(platform-wallet-ffi): cover the identity recipient shield export end to end Drive platform_wallet_manager_shielded_shield_from_identity_to_recipient through a real wallet with a bound shielded account and a managed identity over a mock network: own recipient (6), unfunded identity (39), a funded identity reaching the nonce fetch, and a bad memo (InvalidParameter, Utf8Conversion), each leaving out_new_balance untouched and nothing armed. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 309 ++++++++++++++++++ .../src/test_fixtures.rs | 26 +- 2 files changed, 325 insertions(+), 10 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 4b56df6aee8..5eb84ef1078 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -3380,6 +3380,315 @@ mod tests { assert_eq!(detail["available"], 100); } + /// The recipient and signer are real; the wallet, its bound shielded account and the managed + /// identity are real too. Only the network is a mock: its answer for the identity's proved + /// balance is `proved_balance`, and it has no answer for anything else (the nonce fetch that + /// follows a passed balance check, so a call that reaches it stops there). + struct IdentityShieldFixture { + handle: Handle, + wallet_id: [u8; 32], + identity_id: [u8; 32], + store_path: std::path::PathBuf, + signer: *mut SignerHandle, + } + + impl IdentityShieldFixture { + const SEED: [u8; 64] = [42; 64]; + + fn new(proved_balance: u64) -> Self { + use dash_sdk::query_types::IdentityBalance; + use dpp::identity::v0::IdentityV0; + use dpp::prelude::Identifier; + + unsafe extern "C" fn begin(_: *mut c_void, _: *const u8) -> i32 { + 0 + } + unsafe extern "C" fn end(_: *mut c_void, _: *const u8, _: bool) -> i32 { + 0 + } + unsafe extern "C" fn sign( + _: *const c_void, + _: *const u8, + _: usize, + _: u8, + _: *const u8, + _: usize, + _: *mut c_void, + _: rs_sdk_ffi::SignCompletionCallback, + ) { + unreachable!("a refused identity shield signs nothing") + } + unsafe extern "C" fn can_sign(_: *const c_void, _: *const u8, _: usize, _: u8) -> bool { + false + } + + let identity_id = Identifier::from([0x71; 32]); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(dashcore::Network::Testnet) + .build() + .expect("mock sdk"); + runtime().block_on(async { + sdk.mock() + .expect_fetch::(identity_id, Some(proved_balance)) + .await + .expect("balance expectation"); + }); + let manager = crate::test_fixtures::mock_manager_on( + sdk, + crate::persistence::FFIPersister::new_with_persistence_capabilities( + PersistenceCallbacks { + on_changeset_begin_fn: Some(begin), + on_changeset_end_fn: Some(end), + on_persist_shielded_viewing_keys_fn: Some( + crate::test_fixtures::noop_persist_viewing_keys, + ), + on_load_shielded_viewing_keys_fn: Some( + crate::test_fixtures::noop_load_viewing_keys, + ), + on_load_shielded_viewing_keys_free_fn: Some( + crate::test_fixtures::noop_free_viewing_keys, + ), + ..Default::default() + }, + platform_wallet::changeset::PersistenceCapabilities::ATOMIC_CHANGESETS.union( + platform_wallet::changeset::PersistenceCapabilities::SHIELDED_VIEWING_KEYS, + ), + ), + ); + let store_path = std::env::temp_dir().join(format!( + "ffi-identity-shield-{}-{}.sqlite", + std::process::id(), + next_handle() + )); + let wallet_id = runtime().block_on(async { + let wallet = manager + .create_wallet_from_seed_bytes( + dashcore::Network::Testnet, + &Self::SEED, + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("create wallet"); + manager + .configure_shielded(&store_path) + .await + .expect("configure shielded"); + let coordinator = manager.shielded_coordinator().await.expect("coordinator"); + wallet + .bind_shielded(&Self::SEED, &[0], &coordinator) + .await + .expect("bind shielded"); + wallet + .wallet_manager() + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .expect("wallet info") + .identity_manager + .add_identity( + dpp::identity::Identity::V0(IdentityV0 { + id: identity_id, + public_keys: Default::default(), + balance: u64::MAX / 2, + revision: 0, + }), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .expect("manage the identity"); + wallet.wallet_id() + }); + let signer = unsafe { + rs_sdk_ffi::dash_sdk_signer_create_with_ctx( + std::ptr::null_mut(), + sign, + can_sign, + None, + ) + }; + Self { + handle: PLATFORM_WALLET_MANAGER_STORAGE.insert(manager), + wallet_id, + identity_id: identity_id.to_buffer(), + store_path, + signer, + } + } + + fn own_address(&self) -> [u8; 43] { + let mut out = [0u8; 43]; + let mut present = false; + let result = unsafe { + crate::platform_wallet_manager_shielded_default_address( + self.handle, + self.wallet_id.as_ptr(), + 0, + out.as_mut_ptr(), + &mut present, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + assert!(present); + out + } + + fn third_party_address() -> [u8; 43] { + platform_wallet::wallet::shielded::OrchardKeySet::from_seed( + &[0x24; 32], + dashcore::Network::Testnet, + 0, + ) + .expect("keys") + .default_address + .to_raw_address_bytes() + } + + fn shield( + &self, + recipient: &[u8; 43], + memo: *const c_char, + out: *mut u64, + ) -> PlatformWalletFFIResult { + unsafe { + platform_wallet_manager_shielded_shield_from_identity_to_recipient( + self.handle, + self.wallet_id.as_ptr(), + 0, + self.identity_id.as_ptr(), + recipient.as_ptr(), + 1_000_000, + memo, + self.signer, + out, + ) + } + } + + /// Nothing was armed and no activity row was recorded for the account. + fn assert_nothing_armed_or_recorded(&self) { + let id = SubwalletId::new(self.wallet_id, 0); + let (redrives, activity) = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(self.handle, |manager| { + runtime().block_on(async { + let coordinator = + manager.shielded_coordinator().await.expect("coordinator"); + let store = coordinator.store().read().await; + ( + store.pending_redrives(id).expect("redrives"), + store.get_activity_ids(id).expect("activity"), + ) + }) + }) + .expect("live manager"); + assert!(redrives.is_empty(), "no redrive guard"); + assert!(activity.is_empty(), "no activity row"); + } + } + + impl Drop for IdentityShieldFixture { + fn drop(&mut self) { + unsafe { + rs_sdk_ffi::dash_sdk_signer_destroy(self.signer); + let _ = platform_wallet_manager_destroy(self.handle); + } + let _ = std::fs::remove_file(&self.store_path); + } + } + + const UNTOUCHED: u64 = 0xDEAD_BEEF; + + /// The account's own address is not a third-party recipient: build failure before broadcast, + /// code 6, nothing armed or recorded, `out_new_balance` untouched. + #[test] + fn identity_recipient_shield_export_refuses_the_accounts_own_address_with_6() { + let fixture = IdentityShieldFixture::new(u64::MAX / 2); + let mut out = UNTOUCHED; + let result = fixture.shield(&fixture.own_address(), std::ptr::null(), &mut out); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + assert_eq!(result.code as i32, 6); + assert!(message_of(&result).contains("belongs to this shielded account")); + assert_eq!(out, UNTOUCHED); + fixture.assert_nothing_armed_or_recorded(); + } + + /// A proved balance below the amount plus the fee floor is refused as code 39 with the + /// figures in the JSON detail; nothing is armed or recorded and `out_new_balance` is + /// untouched. The mock has no nonce answer, so the refusal is the balance check's. + #[test] + fn identity_recipient_shield_export_refuses_an_unfunded_identity_with_39() { + let fixture = IdentityShieldFixture::new(999_999); + let mut out = UNTOUCHED; + let result = fixture.shield( + &IdentityShieldFixture::third_party_address(), + std::ptr::null(), + &mut out, + ); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInsufficientIdentityCredits + ); + assert_eq!(result.code as i32, 39); + let detail: serde_json::Value = serde_json::from_str(&message_of(&result)).unwrap(); + assert_eq!(detail["available"], 999_999); + assert!(detail["required"].as_u64().unwrap() > 1_000_000, "{detail}"); + assert_eq!(out, UNTOUCHED); + fixture.assert_nothing_armed_or_recorded(); + } + + /// A balance that covers the amount and fee passes the check and reaches the identity nonce + /// fetch, where the mock (no network) stops the call. This is where the export path stops + /// without a network mock for the nonce, proof and broadcast. + #[test] + fn identity_recipient_shield_export_passes_the_balance_check_and_stops_at_the_nonce_fetch() { + let fixture = IdentityShieldFixture::new(u64::MAX / 2); + let mut out = UNTOUCHED; + let result = fixture.shield( + &IdentityShieldFixture::third_party_address(), + std::ptr::null(), + &mut out, + ); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + assert!(message_of(&result).contains("fetch identity nonce")); + assert_eq!(out, UNTOUCHED); + fixture.assert_nothing_armed_or_recorded(); + } + + /// A memo over 32 bytes is `ErrorInvalidParameter` and invalid UTF-8 is + /// `ErrorUtf8Conversion`, both before the wallet is touched, with a real wallet behind the + /// handle: nothing armed or recorded, `out_new_balance` untouched. + #[test] + fn identity_recipient_shield_export_refuses_a_bad_memo_with_a_real_wallet() { + let fixture = IdentityShieldFixture::new(u64::MAX / 2); + let recipient = IdentityShieldFixture::third_party_address(); + + let too_long = CString::new("a".repeat(MEMO_PAYLOAD_SIZE + 1)).unwrap(); + let mut out = UNTOUCHED; + let result = fixture.shield(&recipient, too_long.as_ptr(), &mut out); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + assert_eq!(out, UNTOUCHED); + + let not_utf8 = CString::new(vec![0xFF, 0xFE]).unwrap(); + let mut out = UNTOUCHED; + let result = fixture.shield(&recipient, not_utf8.as_ptr(), &mut out); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorUtf8Conversion + ); + assert_eq!(out, UNTOUCHED); + fixture.assert_nothing_armed_or_recorded(); + } + /// A panic in the new export's body must become code 18 (never abort the host), under the /// export's own operation label. #[test] diff --git a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs index a6039c4ec65..32152daed20 100644 --- a/packages/rs-platform-wallet-ffi/src/test_fixtures.rs +++ b/packages/rs-platform-wallet-ffi/src/test_fixtures.rs @@ -31,6 +31,21 @@ pub(crate) fn mock_manager() -> PlatformWalletManager { /// [`mock_manager`] over `persister`. pub(crate) fn mock_manager_with(persister: FFIPersister) -> PlatformWalletManager { + mock_manager_on( + dash_sdk::SdkBuilder::new_mock() + .with_network(dashcore::Network::Testnet) + .build() + .expect("mock sdk"), + persister, + ) +} + +/// [`mock_manager_with`] over a caller-built mock `sdk`, for tests that seed +/// the mock's expectations before the manager takes ownership of it. +pub(crate) fn mock_manager_on( + sdk: dash_sdk::Sdk, + persister: FFIPersister, +) -> PlatformWalletManager { let events = FFIEventHandler::new( EventHandlerCallbacks { context: std::ptr::null_mut(), @@ -45,16 +60,7 @@ pub(crate) fn mock_manager_with(persister: FFIPersister) -> PlatformWalletManage None, ); let _runtime_guard = runtime().enter(); - PlatformWalletManager::new( - Arc::new( - dash_sdk::SdkBuilder::new_mock() - .with_network(dashcore::Network::Testnet) - .build() - .expect("mock sdk"), - ), - Arc::new(persister), - Arc::new(events), - ) + PlatformWalletManager::new(Arc::new(sdk), Arc::new(persister), Arc::new(events)) } /// Runs `call` with a dangling out pointer and returns the C string it wrote, From fc3ab5d01f971d2ca0e4b6c3328614154b563511 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 16:01:11 +0200 Subject: [PATCH 11/12] fix(platform-wallet-ffi): keep IdentityBalanceUnavailable (58) in map_spend_result The identity shield's balance precheck can return IdentityBalanceUnavailable right after registration; map_spend_result now passes it through as its retryable code 58 instead of the generic code 6. Co-Authored-By: Claude Opus 5.5 --- .../rs-platform-wallet-ffi/src/shielded_send.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 5eb84ef1078..3f6c18da91f 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -627,6 +627,9 @@ pub(crate) fn map_spend_result( // fee: refused before anything was armed or broadcast, code 39 with the // figures in the stable JSON detail. | Err(e @ PlatformWalletError::InsufficientIdentityCredits { .. }) + // No balance for the identity on Platform yet (right after + // registration): refused before anything was armed, code 58, retry. + | Err(e @ PlatformWalletError::IdentityBalanceUnavailable(..)) | Err(e @ PlatformWalletError::ShieldedRecoveryCorrupted { .. }) | Err(e @ PlatformWalletError::ShieldedRecoveryKeysRequired { .. }) => e.into(), // A private contact request in flight, or paid and not yet read back @@ -3149,6 +3152,16 @@ mod tests { "no-recorded-anchor message must be the retryable guidance" ); + // No identity balance on Platform yet (the identity shield's + // precheck): its own retryable code, not the generic failure. + let no_balance: Result<(), PlatformWalletError> = Err( + PlatformWalletError::IdentityBalanceUnavailable([7; 32].into()), + ); + assert_eq!( + map_spend_result(no_balance, "shielded shield from identity").code, + PlatformWalletFFIResultCode::ErrorIdentityBalanceUnavailable + ); + let other: Result<(), PlatformWalletError> = Err(PlatformWalletError::ShieldedNoUnspentNotes); let result = map_spend_result(other, "shielded withdraw"); From 71c1a697066e5aa4417a57e9669cef0c9f0563c2 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 16:01:11 +0200 Subject: [PATCH 12/12] fix(swift-sdk): refuse a memo with a NUL in shieldedShieldFromIdentityToRecipient The memo crosses the FFI as a C string, which ends at the first NUL, so such a memo would be sent cut short. It is refused as invalidParameter before the operation is admitted. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWalletManagerShieldedSync.swift | 7 +++++++ .../ShieldFromIdentityToRecipientGuardTests.swift | 12 ++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index c283f16daa4..308af56cb32 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -1166,6 +1166,13 @@ extension PlatformWalletManager { "recipientRaw43 must be exactly 43 bytes" ) } + // The memo crosses the FFI as a C string, which ends at the first + // NUL: a memo holding one would be sent cut short. + guard memo?.utf8.contains(0) != true else { + throw PlatformWalletError.invalidParameter( + "memo must not contain NUL characters" + ) + } // Admitted through the detached call and the result delivery, like // `withWalletDrainNativeOperation`: `shutdown()` waits for the spend diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift index 28f9e13df3a..d296644f2b1 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift @@ -22,11 +22,12 @@ final class ShieldFromIdentityToRecipientGuardTests: XCTestCase { _ manager: PlatformWalletManager, walletId: Data = Data(repeating: 1, count: 32), identityId: Data = Data(repeating: 2, count: 32), - recipientRaw43: Data = Data(repeating: 3, count: 43) + recipientRaw43: Data = Data(repeating: 3, count: 43), + memo: String? = nil ) async throws { try await manager.shieldedShieldFromIdentityToRecipient( walletId: walletId, shieldedAccount: 0, identityId: identityId, - recipientRaw43: recipientRaw43, amount: 1, identitySigner: makeSigner()) + recipientRaw43: recipientRaw43, amount: 1, memo: memo, identitySigner: makeSigner()) } private func assertInvalidParameter( @@ -62,6 +63,13 @@ final class ShieldFromIdentityToRecipientGuardTests: XCTestCase { await assertInvalidParameter({ try await self.call(manager, recipientRaw43: Data()) }, "recipient empty") } + /// A C string ends at its first NUL, so such a memo would reach Rust cut short. + func testMemoWithNULThrowsInvalidParameter() async { + let manager = PlatformWalletManager.makeForTesting(handle: 94, calls: Self.noopCalls) + await assertInvalidParameter({ try await self.call(manager, memo: "hi\u{0}there") }, "memo with NUL") + await assertInvalidParameter({ try await self.call(manager, memo: "\u{0}") }, "memo of a NUL") + } + func testUnconfiguredManagerThrowsInvalidHandle() async { let manager = PlatformWalletManager() do {