Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions docs/sdk/sdk-parity-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand All @@ -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
}
]
},
Expand Down
4 changes: 2 additions & 2 deletions packages/kotlin-sdk/PARITY_SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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),
) {

/**
Expand Down Expand Up @@ -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<FundingInput>,
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Any>? = 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<Long>()
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)
}
}
48 changes: 48 additions & 0 deletions packages/rs-unified-sdk-jni/src/credits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading