diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index a59a25072e7..07b97adcf6c 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -1485,10 +1485,10 @@ "reason": "ManagedPlatformWallet.topUpExternalIdentityFromAddresses bridges the export; the example app has no screen that pays to someone else's identity." }, "kotlin": { - "sdk": "unsupported", + "sdk": "supported", "example_app": "unsupported", "restart": "not_applicable", - "reason": "No JNI bridge or Kotlin wrapper for the external identity top-up yet." + "reason": "IdentityCredits.topUpExternalIdentityFromAddresses bridges the export through CreditsNative; the example app has no screen that pays to someone else's identity." } }, "verification": [ @@ -1499,6 +1499,14 @@ "id": "testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites", "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:SwiftDashSDKTests/ExternalIdentityTopUpTests", "covers_restart": false + }, + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt", + "id": "should pass the handles, id and encoded inputs to the external export and return its balance", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:testDebugUnitTest --tests 'org.dashfoundation.dashsdk.credits.ExternalIdentityTopUpTest'", + "covers_restart": false } ] }, diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index a62b3e0e164..ca40353d7a2 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -10,7 +10,7 @@ Capabilities tracked: **31** | --- | --- | ---: | ---: | ---: | ---: | | Swift | SDK | 18 | 11 | 1 | 1 | | Swift | Example app | 5 | 14 | 3 | 9 | -| Kotlin | SDK | 14 | 14 | 2 | 1 | +| Kotlin | SDK | 15 | 14 | 1 | 1 | | Kotlin | Example app | 6 | 13 | 2 | 10 | ## Restart coverage @@ -42,7 +42,7 @@ Capabilities tracked: **31** | `persistence.dashpay_payment_history` | partial / not-applicable / required | not-applicable / not-applicable / not_applicable | | `network.masternode_discovery` | partial / not-applicable / not_applicable | partial / not-applicable / not_applicable | | `identity.platform_address_auto_funding` | partial / partial / not_applicable | partial / partial / not_applicable | -| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | unsupported / unsupported / not_applicable | +| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | supported / unsupported / not_applicable | | `tokens.authorization_decisions` | partial / partial / not_applicable | partial / partial / not_applicable | | `tokens.direct_purchase_quote` | partial / partial / not_applicable | partial / partial / not_applicable | | `protocol.address_validation` | supported / supported / not_applicable | partial / partial / not_applicable | diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt index 419de77c636..1fe99638156 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt @@ -3,6 +3,8 @@ package org.dashfoundation.dashsdk import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import kotlinx.coroutines.Dispatchers +import org.dashfoundation.dashsdk.credits.FundingInput +import org.dashfoundation.dashsdk.ffi.CreditsNative import org.dashfoundation.dashsdk.ffi.DashSDKException import org.dashfoundation.dashsdk.ffi.DashpayNative import org.dashfoundation.dashsdk.ffi.NativePersistenceBridge @@ -161,6 +163,27 @@ class FfiSmokeTest { } } + /** + * The external identity top-up's `CreditsNative` symbol binds with the + * descriptor Kotlin declares, and reaches its own export: a 31-byte + * identity id is refused by the JNI argument check (code 1) before any + * handle is read or anything is signed. The top-up itself is covered by + * the platform-wallet and platform-wallet-ffi external-identity tests. + */ + @Test + fun externalIdentityTopUpSymbolBindsAndRejectsInvalidInput() { + NativeLoader.ensureLoaded() + val error = assertThrows(DashSDKException::class.java) { + CreditsNative.topUpExternalIdentityFromAddresses( + 0L, + ByteArray(31), + FundingInput.encode(emptyList()), + 0L, + ) + } + assertEquals(1, error.code) + } + /** * The private contact request scan state needs every override it * depends on, and atomic changesets: JNI wires its slots only for a diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index d03f3de82c8..c6f1871af8e 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -1,6 +1,7 @@ package org.dashfoundation.dashsdk.credits import org.dashfoundation.dashsdk.wallet.op +import org.dashfoundation.dashsdk.wallet.opReturningCompletedResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -19,6 +20,15 @@ internal fun interface ResumeTopUpNativeCall { ): Long } +internal fun interface AddressTopUpNativeCall { + fun call( + walletHandle: Long, + identityId: ByteArray, + inputsBlob: ByteArray, + signerHandle: Long, + ): Long +} + /** * One Platform-address funding input for an identity top-up — port of the * `IdentityAddressInput` tuple the Swift `TopUpIdentityView` packs. Encodes @@ -81,6 +91,8 @@ class IdentityCredits internal constructor( private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, private val resumeTopUpNative: ResumeTopUpNativeCall = ResumeTopUpNativeCall(CreditsNative::topUpIdentityWithExistingAssetLock), + private val externalTopUpNative: AddressTopUpNativeCall = + AddressTopUpNativeCall(CreditsNative::topUpExternalIdentityFromAddresses), ) { /** @@ -231,6 +243,49 @@ class IdentityCredits internal constructor( } } + /** + * Top up [identityId] (32 bytes), an identity this wallet does **not** + * manage (someone else's), from the wallet's Platform-address [inputs], + * signed via [signerHandle]. Returns the identity's post-transition + * balance. ← Swift `ManagedPlatformWallet.topUpExternalIdentityFromAddresses` + * (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift). + * + * Rust fetches the identity from Platform and never adds it to the + * wallet; the spent addresses' balances are reconciled as for + * [topUpFromAddresses]. Rust also owns the input rules (empty or + * overflowing inputs are refused there). + * + * Outcomes the caller must tell apart: + * - [org.dashfoundation.dashsdk.errors.DashSdkError.NotFound]: Platform + * does not know the identity; nothing was signed or sent. + * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.IdentityLookupFailed]: + * the identity could not be read from Platform; nothing was signed or + * sent, and the call can be retried. + * - [org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed]: + * the top-up may have executed or may still execute; do not submit it + * again, the next sync settles it. + * + * The native call cannot observe coroutine cancellation, so a top-up can + * finish after the caller was cancelled; its balance is then returned + * rather than thrown away ([opReturningCompletedResult]), so a completed + * payment is never hidden and retried. + */ + suspend fun topUpExternalIdentityFromAddresses( + walletHandle: Long, + identityId: ByteArray, + inputs: List, + signerHandle: Long, + ): Long = gate.opReturningCompletedResult { + mapNativeErrors { + externalTopUpNative.call( + walletHandle, + identityId, + FundingInput.encode(inputs), + signerHandle, + ) + } + } + /** * Transfer credits from [fromIdentityId] (32 bytes) to one or more * Platform-address recipients ([outputs]), signed by the identity's diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt index 395cf3ddd21..f4e36f1083b 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt @@ -84,6 +84,22 @@ internal object CreditsNative { signerHandle: Long, ): Long + /** + * Top up [identityId] (32 bytes), an identity this wallet does **not** + * manage, from the wallet's Platform-address inputs, signed per-address + * via [signerHandle]. The identity is fetched from Platform and never + * added to the wallet. Returns the identity's post-transition credit + * balance. ← Swift `ManagedPlatformWallet.topUpExternalIdentityFromAddresses`. + * + * @param inputsBlob same layout as [topUpFromAddresses]. + */ + external fun topUpExternalIdentityFromAddresses( + walletHandle: Long, + identityId: ByteArray, + inputsBlob: ByteArray, + signerHandle: Long, + ): Long + /** * Transfer credits from [fromIdentityId] (32 bytes) to one or more * Platform-address recipients, signed by the identity's transfer key diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt new file mode 100644 index 00000000000..d57df9e8df6 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/ExternalIdentityTopUpTest.kt @@ -0,0 +1,136 @@ +package org.dashfoundation.dashsdk.credits + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.dashfoundation.dashsdk.wallet.TeardownGate +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ExternalIdentityTopUpTest { + + private val identityId = ByteArray(32) { 7 } + private val inputs = listOf( + FundingInput(addressType = 0, hash = ByteArray(20) { 1 }, credits = 50_000L), + FundingInput(addressType = 1, hash = ByteArray(20) { 2 }, credits = 25_000L), + ) + + @Test + fun `should pass the handles, id and encoded inputs to the external export and return its balance`() = runTest { + var seen: List? = null + val credits = IdentityCredits( + externalTopUpNative = AddressTopUpNativeCall { wallet, id, blob, signer -> + seen = listOf(wallet, id, blob, signer) + 9_000L + }, + ) + + val balance = credits.topUpExternalIdentityFromAddresses(11L, identityId, inputs, 22L) + + assertEquals(9_000L, balance) + val call = checkNotNull(seen) + assertEquals(11L, call[0]) + assertArrayEquals(identityId, call[1] as ByteArray) + assertArrayEquals(FundingInput.encode(inputs), call[2] as ByteArray) + assertEquals(22L, call[3]) + } + + @Test + fun `should map an unknown identity to NotFound`() = runTest { + val failure = failureFor(7) // ErrorIdentityNotFound + + assertTrue("expected NotFound, got $failure", failure is DashSdkError.NotFound) + } + + @Test + fun `should map a failed identity lookup to a retryable IdentityLookupFailed`() = runTest { + val failure = failureFor(80) // ErrorIdentityLookupFailed + + assertTrue( + "expected IdentityLookupFailed, got $failure", + failure is DashSdkError.PlatformWallet.IdentityLookupFailed, + ) + assertTrue((failure as DashSdkError).isRetryable) + } + + @Test + fun `should map an unproved result to TransactionBroadcastUnconfirmed`() = runTest { + val failure = failureFor(20) // ErrorTransactionBroadcastUnconfirmed + + assertTrue( + "expected TransactionBroadcastUnconfirmed, got $failure", + failure is DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed, + ) + } + + @Test + fun `should return a top-up that completes after the caller was cancelled`() = runBlocking { + for (gate in listOf(TeardownGate(), null)) { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + val received = CompletableDeferred() + val credits = IdentityCredits( + gate = gate, + externalTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> + entered.countDown() + // The native top-up does not observe cancellation; it pays + // the identity only after the caller has been cancelled. + release.await() + 9_000L + }, + ) + + val call = launch(Dispatchers.Default) { + received.complete( + credits.topUpExternalIdentityFromAddresses(1L, identityId, inputs, 2L), + ) + } + assertTrue("native top-up never started", entered.await(5, TimeUnit.SECONDS)) + call.cancel() + release.countDown() + withTimeout(5_000) { call.join() } + + assertTrue("completed top-up was dropped", received.isCompleted) + assertEquals(9_000L, received.await()) + gate?.let { withTimeout(5_000) { it.closeAndAwait() } } + } + } + + private suspend fun failureFor(platformWalletCode: Int): Throwable? { + val credits = IdentityCredits( + externalTopUpNative = AddressTopUpNativeCall { _, _, _, _ -> + throw DashSDKException( + DashSdkError.PLATFORM_WALLET_CODE_OFFSET + platformWalletCode, + "native failure $platformWalletCode", + ) + }, + ) + return runCatching { + credits.topUpExternalIdentityFromAddresses(1L, identityId, inputs, 2L) + }.exceptionOrNull() + } + + @Test + fun `should leave empty inputs to Rust rather than refusing them in Kotlin`() = runTest { + var blob: ByteArray? = null + val credits = IdentityCredits( + externalTopUpNative = AddressTopUpNativeCall { _, _, b, _ -> + blob = b + 0L + }, + ) + + credits.topUpExternalIdentityFromAddresses(1L, identityId, emptyList(), 2L) + + assertArrayEquals(FundingInput.encode(emptyList()), blob) + } +} diff --git a/packages/rs-unified-sdk-jni/src/credits.rs b/packages/rs-unified-sdk-jni/src/credits.rs index 5d7831254d9..82c361f38a7 100644 --- a/packages/rs-unified-sdk-jni/src/credits.rs +++ b/packages/rs-unified-sdk-jni/src/credits.rs @@ -12,6 +12,8 @@ //! - [`platform_wallet_withdraw_credits_with_signer`] — identity → L1 address. //! - [`platform_wallet_top_up_from_addresses_with_signer`] — top up an //! existing identity from Platform-address inputs (ID-06). +//! - [`platform_wallet_top_up_external_identity_from_addresses_with_signer`] +//! — the same, for an identity the wallet does not manage. //! - [`platform_wallet_top_up_identity_with_funding_signer`] — top up an //! existing identity from a **new Core asset lock** (ID-05); this one //! takes a `MnemonicResolverHandle` (the Core asset-lock signer) rather @@ -212,6 +214,52 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpFr }) } +/// Top up an identity this wallet does **not** manage (someone else's) +/// from one or more of the wallet's Platform-address inputs, signed +/// per-address via `signerHandle`. Returns the identity's post-transition +/// credit balance. The identity is fetched from Platform and never added +/// to the wallet. +/// +/// `inputsBlob` has the same layout as `topUpFromAddresses`. An empty +/// input list is not checked here: the library owns that rule (an empty +/// `Vec`'s pointer is non-null, so it reaches the library). +/// +/// Wraps `platform_wallet_top_up_external_identity_from_addresses_with_signer`. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpExternalIdentityFromAddresses( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + identity_id: JByteArray, + inputs_blob: JByteArray, + signer_handle: jlong, +) -> jlong { + guard(&mut env, 0i64, |env| { + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return 0; + }; + let Some(inputs) = decode_inputs_blob(env, &inputs_blob) else { + return 0; + }; + + let mut out_balance: u64 = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_top_up_external_identity_from_addresses_with_signer( + wallet_handle as Handle, + &id as *const [u8; 32], + inputs.as_ptr(), + inputs.len(), + signer_handle as *mut SignerHandle, + &mut out_balance as *mut u64, + ) + }; + if take_pwffi_error(env, result) { + return 0; + } + out_balance as i64 + }) +} + // ── Transfer (identity → Platform addresses) ─────────────────────────── /// Transfer credits from `fromIdentityId` (32 bytes) to one or more