diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index ff3277332c9..3a987491643 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -61,6 +61,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", @@ -2053,6 +2054,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 4f8eef43841..9db5f953eda 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 @@ -54,6 +54,7 @@ Capabilities tracked: **30** | `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 | | `network.adaptive_quorum_source` | supported / supported / tested | supported / supported / tested | +| `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. diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 2c28e59d1ad..3f6c18da91f 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -623,6 +623,13 @@ 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 { .. }) + // 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 @@ -1300,6 +1307,168 @@ 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. +/// +/// `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 +/// 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 +/// `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). +/// +/// 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. +/// +/// # 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. +/// - `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. +/// - `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, + memo_text: *const c_char, + 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, + memo_text, + 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, + memo_text: *const c_char, + 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); + + // 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, + }; + + // 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, + memo, + 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` @@ -2357,6 +2526,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() { @@ -2982,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"); @@ -2996,6 +3176,547 @@ 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 { + 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() + } 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, + memo_text, + 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" + ); + } + } + + /// 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] + 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 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); + } + + /// 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] + 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 { 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, 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]; diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift index f512c31e473..32b400ec2f2 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManager.swift @@ -719,6 +719,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 @@ -1383,7 +1390,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 @@ -1404,7 +1412,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 5befbfc41ec..308af56cb32 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, UnsafePointer?, 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 @@ -459,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() } @@ -1105,6 +1117,119 @@ 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). + /// + /// `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 + /// create, load and delete throw `invalidHandle` while it is in flight. + @discardableResult + public func shieldedShieldFromIdentityToRecipient( + walletId: Data, + shieldedAccount: UInt32 = 0, + identityId: Data, + recipientRaw43: Data, + amount: UInt64, + memo: String? = nil, + 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" + ) + } + // 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 + // 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 + 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" + ) + } + // `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) + } + } + } + } + } + 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/ShieldFromIdentityToRecipientAdmissionTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift new file mode 100644 index 00000000000..ca3097e65f6 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientAdmissionTests.swift @@ -0,0 +1,166 @@ +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, 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 + 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), 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) + + // 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) + } + + /// `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 {} + } + + /// 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 } } + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift new file mode 100644 index 00000000000..d296644f2b1 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldFromIdentityToRecipientGuardTests.swift @@ -0,0 +1,84 @@ +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), + memo: String? = nil + ) async throws { + try await manager.shieldedShieldFromIdentityToRecipient( + walletId: walletId, shieldedAccount: 0, identityId: identityId, + recipientRaw43: recipientRaw43, amount: 1, memo: memo, 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") + } + + /// 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 { + try await call(manager) + XCTFail("expected invalidHandle, call succeeded") + } catch PlatformWalletError.invalidHandle { + // expected + } catch { + XCTFail("expected invalidHandle, got \(error)") + } + } +}