diff --git a/packages/kotlin-sdk/PARITY.md b/packages/kotlin-sdk/PARITY.md index b9273492c0c..65c52d05bd3 100644 --- a/packages/kotlin-sdk/PARITY.md +++ b/packages/kotlin-sdk/PARITY.md @@ -174,7 +174,7 @@ rebuilt `libdash_sdk_jni.so` and a network at protocol version 15. | QRScannerView.swift | ui/scanner/QrScannerScreen.kt · `QrScanner` | ported | | ReceiveAddressView.swift | ui/wallet/ReceiveAddressSheet.kt | ported | | SeedBackupView.swift | ui/wallet/SeedBackupScreen.kt · `SeedBackup` | ported | -| SendTransactionView.swift | ui/wallet/SendTransactionScreen.kt · `SendTransaction` | ported — `ManagedPlatformWallet.sendToAddresses` drives the atomic finalized-transaction path (`CoreTransactionBuilder.finalizeAtomic` → `core_wallet_tx_builder_finalize` → `core_wallet_broadcast_signed_transaction`); shared Rust owns selection, reservation, signing, and broadcast classification. The SDK also bridges Swift's `shieldedShieldToRecipient` (Platform credits → a third party's Orchard address) as `PlatformWalletManager.shieldedShieldToRecipient` (JNI `FundingNative.shieldedShieldToRecipient` → `platform_wallet_manager_shielded_shield_to_recipient`); SDK only, no UI: like SwiftExampleApp, the screen does not call it, and its caller is the Android wallet | +| SendTransactionView.swift | ui/wallet/SendTransactionScreen.kt · `SendTransaction` | ported — `ManagedPlatformWallet.sendToAddresses` drives the atomic finalized-transaction path (`CoreTransactionBuilder.finalizeAtomic` → `core_wallet_tx_builder_finalize` → `core_wallet_broadcast_signed_transaction`); shared Rust owns selection, reservation, signing, and broadcast classification. The SDK also bridges Swift's `shieldedShieldToRecipient` (Platform credits → a third party's Orchard address) as `PlatformWalletManager.shieldedShieldToRecipient` (JNI `FundingNative.shieldedShieldToRecipient` → `platform_wallet_manager_shielded_shield_to_recipient`); SDK only, no UI: like SwiftExampleApp, the screen does not call it, and its caller is the Android wallet. Its identity-funded sibling `PlatformWalletManager.shieldedShieldFromIdentityToRecipient` (identity balance → a third party's Orchard address; JNI `FundingNative.shieldedShieldFromIdentityToRecipient` → `platform_wallet_manager_shielded_shield_from_identity_to_recipient`) is also SDK only, no UI, and has no Swift counterpart yet; its caller is the Android wallet | | ShieldedActivityView.swift | ui/shielded/ShieldedActivityScreen.kt · `ShieldedActivity` | ported | | TransactionDetailView.swift | ui/wallet/TransactionDetailScreen.kt · `WalletTransactionDetail` | ported | | TransactionListView.swift | ui/wallet/TransactionListScreen.kt · `WalletTransactions` | ported | diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/ShieldFromIdentityToRecipientBindingTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/ShieldFromIdentityToRecipientBindingTest.kt new file mode 100644 index 00000000000..3103d619078 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/ShieldFromIdentityToRecipientBindingTest.kt @@ -0,0 +1,126 @@ +package org.dashfoundation.dashsdk.wallet + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.dashfoundation.dashsdk.ffi.FundingNative +import org.dashfoundation.dashsdk.ffi.NativeLoader +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Binding-level coverage for the `shieldedShieldFromIdentityToRecipient` JNI + * export, with the same no-wallet discipline as [ShieldToRecipientBindingTest]. + * It proves the Kotlin `external` declaration, the generated JNI symbol and + * the parameter descriptor stay in lockstep (a mismatch surfaces here as + * `UnsatisfiedLinkError`), and pins each rejection to its layer. No network, + * no wallet, no funds. + * + * Three layers are asserted apart: + * - the JNI trampoline's marshalling checks (sign checks before the unsigned + * casts, fixed-size arrays, non-null signer) throw [DashSDKException] with + * RAW code 1 and a message naming the argument, BEFORE any FFI call. The + * two 32-byte ids share a descriptor slot type, so the message checks + * double as parameter-order pins; + * - a zero amount and an over-limit memo are not checked there. Zero passes + * the JNI layer and fails at the dead handle; the memo is rejected inside + * the FFI by Rust's `encode_memo_text` (the single owner of the 32-byte + * rule) as `ErrorInvalidParameter`, before the handle is resolved; + * - a well-formed call with dead manager handle 0 reaches the FFI's handle + * lookup and comes back as `ErrorInvalidHandle`. + * + * The FFI encodes the memo and resolves the manager handle before it ever + * dereferences the signer pointer, so [DUMMY_SIGNER] is never read; it only + * has to be non-zero to pass the JNI null check. + */ +@RunWith(AndroidJUnit4::class) +class ShieldFromIdentityToRecipientBindingTest { + + private companion object { + const val DEAD_HANDLE = 0L + const val DUMMY_SIGNER = 1L + + /** `PlatformWalletFFIResultCode` values, shifted into the Kotlin range. */ + const val INVALID_HANDLE = DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 1 + const val INVALID_PARAMETER = DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 2 + } + + private fun callExpectingThrow( + walletId: ByteArray = ByteArray(32) { 1 }, + shieldedAccount: Int = 0, + identityId: ByteArray = ByteArray(32) { 3 }, + recipient: ByteArray = ByteArray(43) { 2 }, + amount: Long = 1_000L, + memo: String? = null, + signer: Long = DUMMY_SIGNER, + ): DashSDKException { + NativeLoader.ensureLoaded() + return assertThrows(DashSDKException::class.java) { + FundingNative.shieldedShieldFromIdentityToRecipient( + DEAD_HANDLE, + walletId, + shieldedAccount, + identityId, + recipient, + amount, + memo, + signer, + ) + } + } + + private fun assertJniRejection(e: DashSDKException, argument: String) { + assertEquals("JNI-side rejection carries raw code 1: ${e.message}", 1, e.code) + assertTrue( + "the rejection must name $argument, got: ${e.message}", + e.message.orEmpty().contains(argument), + ) + } + + @Test + fun shouldRejectNegativeAmountAndAccountBeforeTheFfi() { + assertJniRejection(callExpectingThrow(amount = -1L), "amount") + assertJniRejection(callExpectingThrow(shieldedAccount = -1), "shieldedAccount") + } + + @Test + fun shouldRejectANullSignerBeforeTheFfi() { + assertJniRejection(callExpectingThrow(signer = 0L), "signerIdentityHandle") + } + + @Test + fun shouldRejectMisSizedIdsBeforeTheFfi() { + assertJniRejection(callExpectingThrow(walletId = ByteArray(31)), "walletId") + assertJniRejection(callExpectingThrow(identityId = ByteArray(33)), "identityId") + assertJniRejection(callExpectingThrow(recipient = ByteArray(42)), "recipientRaw43") + } + + @Test + fun shouldLeaveAZeroAmountToRust() { + // The JNI layer only blocks negatives; zero crosses into the FFI and + // here fails at the dead handle, before the wallet's own > 0 check. + val e = callExpectingThrow(amount = 0L) + assertEquals("zero amount: ${e.message}", INVALID_HANDLE, e.code) + } + + @Test + fun shouldLeaveTheMemoLimitToRust() { + // 20 × "€" = 60 UTF-8 bytes. Neither Kotlin nor the JNI layer checks + // the length; Rust's encode_memo_text rejects it inside the FFI. + val e = callExpectingThrow(memo = "€".repeat(20)) + assertEquals("over-limit memo: ${e.message}", INVALID_PARAMETER, e.code) + } + + @Test + fun shouldReachTheFfiInvalidHandlePathForWellFormedCalls() { + // null, empty and a multibyte memo within 32 UTF-8 bytes (10 × "€" = + // 30 bytes) all pass every check and fail only at the handle lookup. + for (memo in listOf(null, "", "€".repeat(10))) { + val e = callExpectingThrow(memo = memo) + assertEquals("memo=${memo?.length}: ${e.message}", INVALID_HANDLE, e.code) + } + } +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt index 6d19dfb6359..8c14605dfe4 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt @@ -197,6 +197,26 @@ internal object FundingNative { signerIdentityHandle: Long, ): Long + /** + * Shield from a Platform IDENTITY's balance to a third-party Orchard + * address, Type 21 (bridges + * `platform_wallet_manager_shielded_shield_from_identity_to_recipient`). + * See + * [org.dashfoundation.dashsdk.wallet.PlatformWalletManager.shieldedShieldFromIdentityToRecipient]. + * [memoText] null or empty means no memo. Blocks for the ~30s Halo 2 + * proof; returns the identity's proven post-debit credit balance. + */ + external fun shieldedShieldFromIdentityToRecipient( + managerHandle: Long, + walletId: ByteArray, + shieldedAccount: Int, + identityId: ByteArray, + recipientRaw43: ByteArray, + amount: Long, + memoText: String?, + signerIdentityHandle: Long, + ): Long + /** * Create an identity funded from the shielded pool, Type 20 (bridges * `platform_wallet_manager_shielded_identity_create_from_pool`). Spends a diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index 1e7198a4a70..99950b104e0 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -1941,6 +1941,86 @@ class PlatformWalletManager( } } + /** + * Identity → EXTERNAL shielded (Type 21). The same `ShieldFromIdentity` + * transition as [shieldedShieldFromIdentity], with the same identity + * debit ([amount] plus the metered fee plus the shielded compute fee), + * the same Keystore identity signer ([signerHandle], TRANSFER key) and + * the same error shapes. The only difference is that the note is + * assigned to [recipientRaw43], a third party's raw 43-byte Orchard + * payment address, instead of this wallet's own default address. + * + * The recipient must actually be a third party: Rust rejects an address + * the account's own IVK recognizes (default or any diversified index). + * Self-shields must use [shieldedShieldFromIdentity]. A bound shielded + * account ([shieldedAccount]) is still required: the send is + * OVK-encrypted to that account and recorded there, which is how the + * wallet's own scan later shows it as sent history. + * + * [memo] is optional: null or empty means no memo. When set, its UTF-8 + * byte length must be at most 32. Rust owns these rules, as it owns the + * zero-amount rejection, so a violation surfaces as a native error, not a + * Kotlin precondition. + * + * Do NOT retry on either of these; a retry could debit the identity + * twice, and the next sync reconciles the outcome: + * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed]: + * the transition may already have executed. + * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.ShieldedIdentityDebitPending]: + * an earlier identity debit is still unresolved, so this one was + * never built or broadcast. + * + * Cancellation: if the caller is cancelled after the native call has + * completed, the post-debit balance is still returned (see + * [opReturningCompletedResult]), so a completed identity debit is never + * hidden. Handle the return before the next suspension point. + * + * Blocks for the ~30s Halo 2 proof; the note arrives on the recipient's + * next shielded sync pass. + * + * @param walletId the 32-byte wallet id. + * @param identityId the 32-byte funding identity id; must be managed by + * this wallet. + * @param recipientRaw43 the recipient's raw 43-byte Orchard payment + * address (11-byte diversifier + 32-byte pk_d), the same shape + * [shieldedTransfer] takes. + * @param amount credits to shield (1 DASH = 1e11). + * @param memo optional UTF-8 memo for the recipient's note. + * @return the identity's proven post-debit credit balance. + */ + suspend fun shieldedShieldFromIdentityToRecipient( + walletId: ByteArray, + identityId: ByteArray, + recipientRaw43: ByteArray, + amount: Long, + shieldedAccount: Int = 0, + memo: String? = null, + ): Long = teardownGate.opReturningCompletedResult { + require(identityId.size == 32) { + "identityId must be exactly 32 bytes, got ${identityId.size}" + } + require(recipientRaw43.size == 43) { + "recipientRaw43 must be exactly 43 bytes, got ${recipientRaw43.size}" + } + // Sign checks only, before the native unsigned casts; zero is Rust's call. + require(amount >= 0) { "amount must be non-negative, got $amount" } + require(shieldedAccount >= 0) { + "shieldedAccount must be non-negative, got $shieldedAccount" + } + mapNativeErrors { + FundingNative.shieldedShieldFromIdentityToRecipient( + managerHandle, + walletId, + shieldedAccount, + identityId, + recipientRaw43, + amount, + memo, + signerHandle, + ) + } + } + /** List active and archived durable identity-funded shields for this manager's wallet. */ suspend fun shieldedIdentityDebitRecoveryRecords( walletId: ByteArray, diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 2c28e59d1ad..e5a61d10c90 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -1300,6 +1300,164 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_shield_from_identity( } } +/// [`platform_wallet_manager_shielded_shield_from_identity`] with the note paid +/// to a THIRD-PARTY Orchard address: the same Type 21 `ShieldFromIdentity` +/// transition, debit, fees, signer and error shapes, but the note is assigned to +/// `recipient_raw_43` (the recipient's raw 43-byte Orchard payment address, the +/// shape `platform_wallet_manager_shielded_transfer` takes) instead of +/// `shielded_account`'s own default address. +/// +/// The recipient must actually be a third party: an address the account's own +/// IVK recognizes (default or any diversified index) is rejected by the wallet; +/// self-shields go through [`platform_wallet_manager_shielded_shield_from_identity`]. +/// Bytes that do not decode to an Orchard payment address are rejected the same +/// way, before anything is built. A bound shielded account is still required: +/// the send is OVK-encrypted to, and its activity recorded under, that account. +/// +/// `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_transfer`: `null` or empty means no memo, +/// and a non-empty memo's UTF-8 byte length must be at most 32. +/// +/// `out_new_balance`, when non-null, receives the identity's proven post-debit +/// balance, written only on success. +/// +/// Do NOT retry on `ErrorShieldedSpendUnconfirmed` (18) or +/// `ErrorShieldedIdentityDebitPending` (55). The first means the transition may +/// already have executed (including a panic inside the call, which is caught and +/// mapped to 18); the second means an earlier identity debit is still +/// unresolved. A retry in either case could debit the identity twice; the next +/// sync reconciles the outcome. +/// +/// # 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 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] +#[allow(clippy::too_many_arguments)] +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 { + // The whole body runs under `catch_unwind`, as for the shield-to-recipient + // export: `block_on_worker` re-panics on a panicking proving task, and a panic + // must not reach this `extern "C"` frame, where it would abort the host. The + // signed transition may already be persisted and broadcast when the panic + // strikes, so the ambiguous 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`] instead of across +/// the C ABI. +/// +/// # 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 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 + }); + 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 +2515,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() { @@ -2836,6 +2995,152 @@ mod tests { } } + /// Call the identity → third-party shield with each pointer overridable, so a + /// test can null one required argument while the rest stay valid. + unsafe fn shield_from_identity_to_recipient_call( + handle: Handle, + wallet_id: *const u8, + identity_id: *const u8, + recipient: *const u8, + memo_text: *const c_char, + signer: *const SignerHandle, + ) -> PlatformWalletFFIResult { + platform_wallet_manager_shielded_shield_from_identity_to_recipient( + handle, + wallet_id, + 0, + identity_id, + recipient, + 1_000, + memo_text, + signer, + std::ptr::null_mut(), + ) + } + + /// A signer pointer that is non-null but never dereferenced: every test below + /// fails before the signer is used. + fn undereferenced_signer() -> *const SignerHandle { + std::ptr::NonNull::::dangling().as_ptr() + } + + #[test] + fn should_reject_each_null_required_pointer_for_shield_from_identity_to_recipient() { + let wallet_id = [1u8; 32]; + let identity_id = [2u8; 32]; + let recipient = [3u8; 43]; + let signer = undereferenced_signer(); + let null_u8 = std::ptr::null::(); + let cases: [(&str, *const u8, *const u8, *const u8, *const SignerHandle); 4] = [ + ( + "wallet_id", + null_u8, + identity_id.as_ptr(), + recipient.as_ptr(), + signer, + ), + ( + "identity_id", + wallet_id.as_ptr(), + null_u8, + recipient.as_ptr(), + signer, + ), + ( + "recipient", + wallet_id.as_ptr(), + identity_id.as_ptr(), + null_u8, + signer, + ), + ( + "signer", + wallet_id.as_ptr(), + identity_id.as_ptr(), + recipient.as_ptr(), + std::ptr::null(), + ), + ]; + for (name, wallet, identity, recipient, signer) in cases { + let result = unsafe { + shield_from_identity_to_recipient_call( + NULL_HANDLE, + wallet, + identity, + recipient, + std::ptr::null(), + signer, + ) + }; + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorNullPointer, + "a null {name} must be rejected as a null pointer" + ); + } + } + + #[test] + fn should_reject_a_bad_memo_before_resolving_the_wallet_for_shield_from_identity_to_recipient() + { + let wallet_id = [1u8; 32]; + let identity_id = [2u8; 32]; + let recipient = [3u8; 43]; + // NULL_HANDLE would yield ErrorInvalidHandle if the wallet were resolved + // first, so each memo code proves the memo is decoded before that. + let over_limit = CString::new("a".repeat(MEMO_PAYLOAD_SIZE + 1)).unwrap(); + let invalid_utf8 = CString::new(vec![0xffu8, 0xfe]).unwrap(); + let cases = [ + ( + over_limit.as_ptr(), + PlatformWalletFFIResultCode::ErrorInvalidParameter, + ), + ( + invalid_utf8.as_ptr(), + PlatformWalletFFIResultCode::ErrorUtf8Conversion, + ), + ]; + for (memo, expected) in cases { + let result = unsafe { + shield_from_identity_to_recipient_call( + NULL_HANDLE, + wallet_id.as_ptr(), + identity_id.as_ptr(), + recipient.as_ptr(), + memo, + undereferenced_signer(), + ) + }; + assert_eq!(result.code, expected); + } + } + + #[test] + fn should_reject_an_unknown_manager_handle_for_shield_from_identity_to_recipient() { + let wallet_id = [1u8; 32]; + let identity_id = [2u8; 32]; + let recipient = [3u8; 43]; + let mut balance = 42u64; + let result = unsafe { + platform_wallet_manager_shielded_shield_from_identity_to_recipient( + NULL_HANDLE, + wallet_id.as_ptr(), + 0, + identity_id.as_ptr(), + recipient.as_ptr(), + 1_000, + std::ptr::null(), + undereferenced_signer(), + &mut balance, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorInvalidHandle); + assert_eq!( + balance, 42, + "out_new_balance must be written only on success" + ); + } + /// Read the Rust-owned message out of an FFI result for assertions. fn message_of(result: &PlatformWalletFFIResult) -> String { assert!( diff --git a/packages/rs-unified-sdk-jni/src/funding.rs b/packages/rs-unified-sdk-jni/src/funding.rs index 7a318b7eff7..ac84c9ed9d8 100644 --- a/packages/rs-unified-sdk-jni/src/funding.rs +++ b/packages/rs-unified-sdk-jni/src/funding.rs @@ -867,6 +867,83 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_shielde }) } +/// Shield from a Platform IDENTITY's balance to a third-party Orchard address, +/// Type 21 (bridges `platform_wallet_manager_shielded_shield_from_identity_to_recipient`). +/// See Kotlin's `PlatformWalletManager.shieldedShieldFromIdentityToRecipient` +/// for the contract. +/// +/// Only marshals: sign checks before the unsigned casts, the fixed-size id and +/// recipient arrays, and the memo string. A zero amount, the memo rules and the +/// own-address rejection belong to the FFI and the wallet. `memo_text` null or +/// empty maps to a null pointer (no memo). The caller retains ownership of +/// `signer_identity_handle`. Blocks for the ~30s Halo 2 proof; returns the +/// identity's proven post-debit credit balance. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_shieldedShieldFromIdentityToRecipient( + mut env: JNIEnv, + _class: JClass, + manager_handle: jlong, + wallet_id: JByteArray, + shielded_account: jint, + identity_id: JByteArray, + recipient_raw43: JByteArray, + amount: jlong, + memo_text: JString, + signer_identity_handle: jlong, +) -> jlong { + guard(&mut env, 0i64, |env| { + // Reject sign errors at the boundary: negatives would otherwise + // bit-cast to huge unsigned values (never clamp). + if amount < 0 { + throw_sdk_exception(env, 1, "amount must be non-negative"); + return 0; + } + if shielded_account < 0 { + throw_sdk_exception(env, 1, "shieldedAccount must be non-negative"); + return 0; + } + if signer_identity_handle == 0 { + throw_sdk_exception(env, 1, "signerIdentityHandle must be non-null"); + return 0; + } + let Some(wid) = read_id32(env, &wallet_id, "walletId") else { + return 0; + }; + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return 0; + }; + let Some(recipient) = read_recipient43(env, &recipient_raw43) else { + return 0; + }; + // null / empty memo → null pointer (no memo). The CString owns the + // bytes through the blocking FFI call below. + let memo = match read_cstring_opt(env, &memo_text, "memoText") { + Ok(m) => m, + Err(()) => return 0, + }; + let memo_ptr = memo.as_ref().map_or(ptr::null(), |c| c.as_ptr()); + let mut out_balance: u64 = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_manager_shielded_shield_from_identity_to_recipient( + manager_handle as Handle, + wid.as_ptr(), + shielded_account as u32, + id.as_ptr(), + recipient.as_ptr(), + amount as u64, + memo_ptr, + signer_identity_handle as *const SignerHandle, + &mut out_balance as *mut u64, + ) + }; + if take_pwffi_error(env, result) { + return 0; + } + out_balance as i64 + }) +} + /// List recovery records, freeing the C allocation before JVM object creation. #[no_mangle] pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_shieldedIdentityDebitRecoveryRecords(