diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/DashpayKeyProvisioning.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/DashpayKeyProvisioning.kt index 198b847e3dc..e14e4c84113 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/DashpayKeyProvisioning.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/DashpayKeyProvisioning.kt @@ -2,13 +2,14 @@ package org.dashfoundation.example.services import org.dashfoundation.dashsdk.identity.IdentityKeyPreview import org.dashfoundation.dashsdk.identity.RegistrationKeySet +import org.dashfoundation.dashsdk.identity.RegistrationKeySlot import org.dashfoundation.dashsdk.identity.RegistrationKeys /** * Registration key provisioning — the derive-set → persist → zero → * build-rich-rows sequence the create-identity flow runs before it broadcasts. * App-level analog of Swift's `CreateIdentityView` submit path - * (`prePersistIdentityKeysForRegistration` + `makeDashpayKeyPair`). + * (`prePersistIdentityKeysForRegistration`). * * ## Why a dedicated helper rather than reusing `IdentityKeyAdditionFlow` * @@ -22,11 +23,11 @@ import org.dashfoundation.dashsdk.identity.RegistrationKeys * `previewRegistrationKeySet` pass — the secret-lifecycle mandate is one * derivation, not N overlapping ones; * - its policy depends on the existing identity's current key IDs and builds - * an update batch, while registration needs a fixed 0..N role table before - * the identity exists. + * an update batch, while registration needs the Rust-owned creation layout + * before the identity exists. * * Forcing registration through it would fork its semantics; this helper reuses - * the shared pieces instead — the SDK's [RegistrationKeys] role table for the + * the shared pieces instead — the Rust layout via [RegistrationKeys] for the * on-chain rows and [IdentityKeyPersistence] for the store-then-zero secret * discipline (shared with [IdentityKeyAdditionFlow]). */ @@ -37,8 +38,8 @@ object DashpayKeyProvisioning { * rich rows the registration wire format carries, tied to the identity HD * slot that produced them. * - * [previews] must be exactly `RegistrationKeys.keyCount(includeDashPayKeys)` - * rows in key-ID order — the single [IdentityKeyPreview] derivation pass + * [previews] must be exactly one row per [slots] entry, in key-ID order + * ([slots] is `RegistrationKeys.layout(...)` for the flow's layout) — the single [IdentityKeyPreview] derivation pass * (`previewRegistrationKeySet`). Every preview's private array is zeroed on * both the success and every failure path (including the count-mismatch * rejection); a partial persist failure never leaves a plaintext scalar @@ -53,11 +54,11 @@ object DashpayKeyProvisioning { */ suspend fun provision( previews: List, - includeDashPayKeys: Boolean, + slots: List, walletId: ByteArray, persister: IdentityKeyPersistence.PrivateKeyPersister, ): RegistrationKeySet { - val expected = RegistrationKeys.keyCount(includeDashPayKeys) + val expected = slots.size try { // Inside the try so the catch below scrubs the derived scalars even // on a count-mismatch rejection (a wire-skew symptom) — no plaintext @@ -89,7 +90,7 @@ object DashpayKeyProvisioning { identityIndex = previews.first().identityIndex, rows = RegistrationKeys.buildRegistrationRows( previews.map { it.publicKey }, - includeDashPayKeys, + slots, ), ) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt index bcf176f8985..f433277d21b 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ClaimInvitationSheet.kt @@ -25,6 +25,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import org.dashfoundation.dashsdk.identity.IdentityCreationKeyLayout import org.dashfoundation.dashsdk.identity.RegistrationKeys import org.dashfoundation.dashsdk.tokens.InvitationPreview import org.dashfoundation.example.di.LocalAppContainer @@ -144,17 +145,18 @@ fun ClaimInvitationSheet( .filter { it.walletId?.contentEquals(wallet.walletId) == true } .map { it.identityIndex } + heldByCoordinator, ) - // Full fresh-registration set: base four + the DashPay - // enc/dec pair, pre-persisted before the broadcast. + // Full fresh-registration set (Rust layout, DashPay + // enc/dec pair included), pre-persisted before the broadcast. + val layout = IdentityCreationKeyLayout.NEW_IDENTITY_WITH_DASHPAY_KEYS val previews = mgr.identityRegistration.previewRegistrationKeySet( walletHandle = wallet.handle, mnemonicResolverHandle = mgr.mnemonicResolverHandle, identityIndex = identityIndex, - count = RegistrationKeys.keyCount(includeDashPayKeys = true), + layout = layout, ) val keySet = DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = true, + slots = RegistrationKeys.layout(layout), walletId = wallet.walletId, persister = { keyHex, priv, owner -> container.walletStorage.storePrivateKey( diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ReclaimInvitationSheet.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ReclaimInvitationSheet.kt index dba53d47d68..72535b1cb16 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ReclaimInvitationSheet.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ReclaimInvitationSheet.kt @@ -24,6 +24,8 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import org.dashfoundation.dashsdk.identity.IdentityCreationKeyLayout +import org.dashfoundation.dashsdk.identity.RegistrationKeys import org.dashfoundation.dashsdk.persistence.entities.InvitationEntity import org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet import org.dashfoundation.example.di.LocalAppContainer @@ -151,19 +153,19 @@ fun ReclaimInvitationSheet( walletIdentities.map { it.identityIndex } + heldByCoordinator, ) // Pre-broadcast local work — BEFORE the marker, so a - // failure here leaves no in-flight marker. Base 4-key - // set: a reclaim sends no contact request (iOS - // authKeyCount = 4). + // failure here leaves no in-flight marker. New-identity + // set without DashPay keys: a reclaim sends no contact + // request. + val layout = IdentityCreationKeyLayout.NEW_IDENTITY val previews = mgr.identityRegistration.previewRegistrationKeySet( walletHandle = wallet.handle, mnemonicResolverHandle = mgr.mnemonicResolverHandle, identityIndex = identityIndex, - count = org.dashfoundation.dashsdk.identity.RegistrationKeys - .keyCount(includeDashPayKeys = false), + layout = layout, ) val keySet = DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = false, + slots = RegistrationKeys.layout(layout), walletId = wallet.walletId, persister = { keyHex, priv, owner -> container.walletStorage.storePrivateKey( diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/CreateIdentityScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/CreateIdentityScreen.kt index f989d9094f9..027c9528b54 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/CreateIdentityScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/CreateIdentityScreen.kt @@ -32,6 +32,7 @@ import androidx.navigation.NavHostController import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import org.dashfoundation.dashsdk.credits.FundingInput +import org.dashfoundation.dashsdk.identity.IdentityCreationKeyLayout import org.dashfoundation.dashsdk.identity.RegistrationKeys import org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet import org.dashfoundation.dashsdk.wallet.TrackedAssetLock @@ -120,6 +121,33 @@ fun CreateIdentityScreen(navController: NavHostController) { } } + // Rust-owned funding minimums for the fresh layout this source + // registers; a failed query is shown and blocks submit. + var fundingMinimums by remember { mutableStateOf(null) } + var fundingMinimumsError by remember { mutableStateOf(null) } + LaunchedEffect(manager, selectedWallet, fundingSource) { + fundingMinimums = null + fundingMinimumsError = null + val mgr = manager + val wallet = selectedWallet + val layout = fundingSource.freshKeyLayout + if (mgr == null || wallet == null || layout == null) return@LaunchedEffect + try { + fundingMinimums = CreateIdentityFundingMinimums( + coreFundingDuffs = mgr.identityRegistration.creationMinFundingDuffs( + wallet.handle, + layout, + ), + addressFundingFeeCredits = mgr.identityRegistration.creationFromAddressesMinFees( + wallet.handle, + layout, + ), + ) + } catch (e: Exception) { + fundingMinimumsError = e.message ?: "Failed to load the identity funding minimum" + } + } + val scope = androidx.compose.runtime.rememberCoroutineScope() Scaffold( @@ -191,6 +219,15 @@ fun CreateIdentityScreen(navController: NavHostController) { onIndexChange = { identityIndexText = it.filter(Char::isDigit) }, ) + fundingMinimumsError?.let { message -> + Text( + "Cannot load the funding minimum: $message", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.testTag("createIdentity.fundingMinimumError"), + ) + } + SubmitButton( text = "Create Identity", isLoading = isSubmitting, @@ -198,6 +235,7 @@ fun CreateIdentityScreen(navController: NavHostController) { isCreateIdentityFundingAmountValid( fundingSource, amountText.toLongOrNull(), + fundingMinimums, ) && (fundingSource != CreateIdentityFundingSource.AssetLockResume || selectedRecoveryLock != null) && @@ -212,21 +250,20 @@ fun CreateIdentityScreen(navController: NavHostController) { selectedRecoveryLock = selectedRecoveryLock, ) ?: return@SubmitButton val amount = submission.amount - if (!isCreateIdentityFundingAmountValid(submission.fundingSource, amount)) { - error = if (submission.fundingSource == CreateIdentityFundingSource.CoreBalance) { - val minimum = minimumCoreFundingDuffsForKeyCount( - RegistrationKeys.keyCount(submission.includesDashPayKeys), - ) - "Core-funded registration with DashPay keys requires at least " + - "$minimum duffs." - } else { - "Funding amount must be positive." + val minimums = fundingMinimums + if (!isCreateIdentityFundingAmountValid(submission.fundingSource, amount, minimums)) { + error = when { + submission.fundingSource.needsFundingMinimums && minimums == null -> + fundingMinimumsError ?: "The funding minimum is still loading." + submission.fundingSource == CreateIdentityFundingSource.CoreBalance -> + "Core-funded registration with DashPay keys requires at least " + + "${minimums?.coreFundingDuffs} duffs." + else -> "Funding amount must be positive." } return@SubmitButton } val identityIndex = submission.identityIndex val mgr = manager ?: return@SubmitButton - val registerDashPayKeys = submission.includesDashPayKeys isSubmitting = true scope.launch { try { @@ -242,7 +279,8 @@ fun CreateIdentityScreen(navController: NavHostController) { val inputs = packFundingInputs( candidates = wallet.addressesWithBalances(), target = requiredAmount, - keyCount = RegistrationKeys.keyCount(registerDashPayKeys), + addressFundingFeeCredits = minimums?.addressFundingFeeCredits + ?: error("The funding minimum is not loaded"), ) if (inputs.isEmpty()) { error = "Not enough Platform-address balance to fund " + @@ -269,26 +307,29 @@ fun CreateIdentityScreen(navController: NavHostController) { null } + // A fresh registration gets the DashPay layout; a resume + // re-derives the base four keys. Rust refuses a resume + // whose lock cannot pay for them before signing. + val keyLayout = submission.keyLayout + // Step 1 (`.preparingKeys`): derive the full registration // key set in ONE pass, persist each private key to the - // Keystore, and build the rich on-chain rows. Rust derives - // keyId 0..N (base: MASTER auth, CRITICAL auth, HIGH auth, - // TRANSFER/CRITICAL; plus the DashPay ENCRYPTION/DECRYPTION - // pair on fresh funding), and the DPP role for each keyId - // is stamped Kotlin-side by RegistrationKeys and shipped - // over the wire. Fresh funding registers all 6 keys so the - // new identity can send contact requests immediately; - // asset-lock resume keeps the base 4 it originally - // committed to on-chain (§ DashPay resume exclusion). + // Keystore, and build the rich on-chain rows. Both the + // keys and their DPP roles come from the Rust-owned + // creation layout: fresh funding registers the DashPay + // layout so the new identity can send contact + // requests immediately; + // asset-lock resume never adds the DashPay pair + // (§ DashPay resume exclusion). val previews = mgr.identityRegistration.previewRegistrationKeySet( walletHandle = wallet.handle, mnemonicResolverHandle = mgr.mnemonicResolverHandle, identityIndex = identityIndex, - count = RegistrationKeys.keyCount(registerDashPayKeys), + layout = keyLayout, ) val keySet = DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = registerDashPayKeys, + slots = RegistrationKeys.layout(keyLayout), walletId = wallet.walletId, // Prestored BEFORE the registration broadcasts: only // the owner index makes it reachable by wallet deletion @@ -444,6 +485,20 @@ enum class CreateIdentityFundingSource( */ val includesDashPayKeys: Boolean get() = this != AssetLockResume + + /** + * The Rust creation key layout this funding path registers: the DashPay + * layout for fresh funding, the base layout for [AssetLockResume]. + */ + val keyLayout: IdentityCreationKeyLayout + get() = IdentityCreationKeyLayout.forNewIdentity(includesDashPayKeys) + + /** + * [keyLayout] when this path funds a new lock, whose minimum the screen + * enforces; null for [AssetLockResume], whose lock already exists. + */ + val freshKeyLayout: IdentityCreationKeyLayout? + get() = if (this == AssetLockResume) null else keyLayout } /** Immutable control values captured synchronously when Submit is tapped. */ @@ -454,6 +509,8 @@ internal data class CreateIdentitySubmissionSnapshot( val recoveryLock: TrackedAssetLock?, ) { val includesDashPayKeys: Boolean = fundingSource.includesDashPayKeys + val keyLayout: IdentityCreationKeyLayout = fundingSource.keyLayout + val freshKeyLayout: IdentityCreationKeyLayout? = fundingSource.freshKeyLayout } /** @@ -489,61 +546,37 @@ internal fun createIdentitySubmissionSnapshot( ) } -/** Credits charged by the active fee schedule before the per-key surcharge. */ -private const val IDENTITY_CREATE_BASE_COST_CREDITS = 2_000_000L - -/** Credits charged for each public key in an identity-create transition. */ -private const val IDENTITY_KEY_CREATION_COST_CREDITS = 6_500_000L - -/** Credits charged for every Platform-address funding input. */ -private const val ADDRESS_FUNDING_INPUT_COST_CREDITS = 500_000L - -/** Core asset-lock floor required before identity-create processing starts. */ -private const val IDENTITY_ASSET_LOCK_BASE_DUFFS = 200_000L - -private const val CREDITS_PER_DUFF = 1_000L - /** - * Protocol minimum for a Core-funded identity create with [keyCount] keys. - * Mirrors `IdentityCreateTransition::calculate_min_required_fee_v1` and the - * iOS `CreateIdentityView.minFundingDuffs(forKeyCount:)` parity reference. + * Funding minimums Rust computes for a fresh registration's layout from its + * versioned fee schedule (`IdentityRegistration.creationMinFundingDuffs` and + * `creationFromAddressesMinFees`). Kotlin keeps no fee constants. */ -internal fun minimumCoreFundingDuffsForKeyCount(keyCount: Int): Long { - require(keyCount > 0) { "keyCount must be positive, got $keyCount" } - return IDENTITY_ASSET_LOCK_BASE_DUFFS + - (IDENTITY_CREATE_BASE_COST_CREDITS + - IDENTITY_KEY_CREATION_COST_CREDITS * keyCount) / CREDITS_PER_DUFF -} +internal data class CreateIdentityFundingMinimums( + /** Minimum Core asset-lock value, in duffs. */ + val coreFundingDuffs: Long, + /** + * Minimum address-funded identity-create fee, in credits: element + * `n - 1` is the fee with `n` inputs; the size is the protocol maximum. + */ + val addressFundingFeeCredits: List, +) -/** - * Protocol fee for an address-funded identity create without a refund output. - * Mirrors `IdentityCreateFromAddressesTransition::calculate_min_required_fee`. - */ -internal fun minimumPlatformAddressFundingFeeCredits( - keyCount: Int, - inputCount: Int, -): Long { - require(keyCount > 0) { "keyCount must be positive, got $keyCount" } - require(inputCount > 0) { "inputCount must be positive, got $inputCount" } - return IDENTITY_CREATE_BASE_COST_CREDITS + - IDENTITY_KEY_CREATION_COST_CREDITS * keyCount + - ADDRESS_FUNDING_INPUT_COST_CREDITS * inputCount -} +/** Whether this source's amount check needs the Rust funding minimums. */ +internal val CreateIdentityFundingSource.needsFundingMinimums: Boolean + get() = this == CreateIdentityFundingSource.CoreBalance || + this == CreateIdentityFundingSource.PlatformAddress /** Single submit/UI gate for the active funding source's amount semantics. */ internal fun isCreateIdentityFundingAmountValid( source: CreateIdentityFundingSource, amount: Long?, + minimums: CreateIdentityFundingMinimums?, ): Boolean = when (source) { - CreateIdentityFundingSource.CoreBalance -> { - val minimum = minimumCoreFundingDuffsForKeyCount( - RegistrationKeys.keyCount(source.includesDashPayKeys), - ) - amount != null && amount >= minimum - } - CreateIdentityFundingSource.PlatformAddress, - CreateIdentityFundingSource.ShieldedBalance, - -> amount != null && amount > 0 + CreateIdentityFundingSource.CoreBalance -> + minimums != null && amount != null && amount >= minimums.coreFundingDuffs + CreateIdentityFundingSource.PlatformAddress -> + minimums != null && amount != null && amount > 0 + CreateIdentityFundingSource.ShieldedBalance -> amount != null && amount > 0 CreateIdentityFundingSource.AssetLockResume -> true } @@ -694,26 +727,28 @@ private fun FundingSection( * Select the smallest feasible Platform-address input set that contributes * exactly [target] credits while leaving the full identity-create fee on the * address that Rust's default `DeductFromInput(0)` strategy will use. + * [addressFundingFeeCredits] is Rust's fee per input count (element `n - 1` + * for `n` inputs); its size caps the input count. * * The native FFI collects inputs into a `BTreeMap`, * so input 0 is the lowest `(addressType, unsigned hash bytes)` address, not * the first item in this list. Each attempted fee payer therefore selects only * lexicographically greater companion inputs. The payer keeps - * [minimumPlatformAddressFundingFeeCredits] after its requested spend; all + * fee for the input count after its requested spend; all * selected inputs contribute at least one credit. Returns an empty list when * the requested identity balance plus fee cannot be funded. */ internal fun packFundingInputs( candidates: List, target: Long, - keyCount: Int = RegistrationKeys.keyCount(includeDashPayKeys = true), + addressFundingFeeCredits: List, ): List { if (target <= 0) return emptyList() val byAddress = candidates.sortedWith(::comparePlatformAddresses) - for (inputCount in 1..byAddress.size) { + for (inputCount in 1..minOf(byAddress.size, addressFundingFeeCredits.size)) { if (target < inputCount) break // every encoded input must spend >= 1 credit - val fee = minimumPlatformAddressFundingFeeCredits(keyCount, inputCount) + val fee = addressFundingFeeCredits[inputCount - 1] for (payerIndex in byAddress.indices) { val payer = byAddress[payerIndex] diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/DashpayKeyProvisioningTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/DashpayKeyProvisioningTest.kt index b6f04b792f7..5f8fab090ba 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/DashpayKeyProvisioningTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/DashpayKeyProvisioningTest.kt @@ -5,6 +5,7 @@ import org.dashfoundation.dashsdk.identity.ContractBounds import org.dashfoundation.dashsdk.identity.IdentityKeyPreview import org.dashfoundation.dashsdk.identity.KeyPurpose import org.dashfoundation.dashsdk.identity.KeyType +import org.dashfoundation.dashsdk.identity.RegistrationKeySlot import org.dashfoundation.dashsdk.identity.RegistrationKeys import org.dashfoundation.dashsdk.identity.SecurityLevel import org.dashfoundation.example.ui.identity.CreateIdentityFundingSource @@ -16,12 +17,38 @@ import org.junit.Test /** * Lifecycle + policy coverage for [DashpayKeyProvisioning] and the - * funding-source DashPay-provisioning gate. Verifies the exact 6-key - * (fresh) / 4-key (resume) row set, and that every derived private scalar is - * scrubbed on both the success and the failure path. + * funding-source DashPay-provisioning gate. Verifies the rows follow the + * supplied Rust layout slots (6-key fresh / 4-key resume fixtures mirroring + * `platform_wallet::IdentityCreationKeyLayout`), and that every derived + * private scalar is scrubbed on both the success and the failure path. */ class DashpayKeyProvisioningTest { + private fun slot( + keyId: Int, + purpose: KeyPurpose, + level: SecurityLevel, + bounds: ContractBounds? = null, + ) = RegistrationKeySlot(keyId, keyId, KeyType.ECDSA_SECP256K1, purpose, level, bounds) + + private fun resumeSlots(): List = listOf( + slot(0, KeyPurpose.AUTHENTICATION, SecurityLevel.MASTER), + slot(1, KeyPurpose.AUTHENTICATION, SecurityLevel.CRITICAL), + slot(2, KeyPurpose.AUTHENTICATION, SecurityLevel.HIGH), + slot(3, KeyPurpose.TRANSFER, SecurityLevel.CRITICAL), + ) + + private fun dashPaySlots(): List { + val bounds = ContractBounds.SingleContractDocumentType( + RegistrationKeys.DASHPAY_CONTRACT_ID, + RegistrationKeys.DASHPAY_CONTACT_REQUEST_DOCUMENT_TYPE, + ) + return resumeSlots() + listOf( + slot(4, KeyPurpose.ENCRYPTION, SecurityLevel.MEDIUM, bounds), + slot(5, KeyPurpose.DECRYPTION, SecurityLevel.MEDIUM, bounds), + ) + } + /** A derived preview at [keyId] with a non-zero private scalar. */ private fun preview(keyId: Int): IdentityKeyPreview = IdentityKeyPreview( identityIndex = 5, @@ -31,14 +58,14 @@ class DashpayKeyProvisioningTest { ) @Test - fun `fresh funding provisions all six keys with DashPay bounds`() = runTest { + fun `fresh funding provisions every layout key with DashPay bounds`() = runTest { val previews = (0 until 6).map(::preview) val walletId = ByteArray(32) { 9 } data class StoredKey(val hex: String, val scalar: ByteArray, val owner: ByteArray) val stored = mutableListOf() val keySet = DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = true, + slots = dashPaySlots(), walletId = walletId, persister = { hex, privateKey, owner -> stored += StoredKey(hex, privateKey.copyOf(), owner.copyOf()) @@ -81,7 +108,7 @@ class DashpayKeyProvisioningTest { val previews = (0 until 4).map(::preview) val keySet = DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = false, + slots = resumeSlots(), walletId = ByteArray(32) { 9 }, persister = { _, _, _ -> }, ) @@ -96,9 +123,9 @@ class DashpayKeyProvisioningTest { val failure = runCatching { DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = true, + slots = dashPaySlots(), walletId = ByteArray(32) { 9 }, - // Fail on the 3rd key — keys 0/1 persisted, 3/4/5 never reached. + // Fail on the 3rd key — keys 0/1 persisted, 3..5 never reached. persister = { _, _, _ -> if (persistCount++ == 2) throw IllegalStateException("keystore down") }, @@ -116,11 +143,11 @@ class DashpayKeyProvisioningTest { @Test fun `wrong preview count is rejected before any persist and still scrubs scalars`() = runTest { var persisted = false - val previews = (0 until 5).map(::preview) // neither 4 nor 6 + val previews = (0 until 5).map(::preview) // not the 6 the layout has val failure = runCatching { DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = true, + slots = dashPaySlots(), walletId = ByteArray(32) { 9 }, persister = { _, _, _ -> persisted = true }, ) @@ -149,7 +176,7 @@ class DashpayKeyProvisioningTest { val failure = runCatching { DashpayKeyProvisioning.provision( previews = previews, - includeDashPayKeys = false, + slots = resumeSlots(), walletId = ByteArray(32) { 9 }, persister = { _, _, _ -> persisted = true }, ) diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/CreateIdentityFundingPolicyTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/CreateIdentityFundingPolicyTest.kt index 8a04ce543f0..c34b0bd8238 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/CreateIdentityFundingPolicyTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/identity/CreateIdentityFundingPolicyTest.kt @@ -1,6 +1,7 @@ package org.dashfoundation.example.ui.identity import org.dashfoundation.dashsdk.credits.FundingInput +import org.dashfoundation.dashsdk.identity.IdentityCreationKeyLayout import org.dashfoundation.dashsdk.wallet.TrackedAssetLock import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals @@ -10,24 +11,45 @@ import org.junit.Test class CreateIdentityFundingPolicyTest { - @Test - fun `Core minimum scales with the number of registration keys`() { - assertEquals(228_000L, minimumCoreFundingDuffsForKeyCount(4)) - assertEquals(241_000L, minimumCoreFundingDuffsForKeyCount(6)) - } + /** Rust-computed minimums as the screen receives them (values arbitrary). */ + private val minimums = CreateIdentityFundingMinimums( + coreFundingDuffs = 247_500L, + addressFundingFeeCredits = listOf(41_500_000L, 42_000_000L), + ) @Test - fun `fresh six-key Core funding rejects amounts below the protocol floor`() { + fun `fresh Core funding rejects amounts below the Rust minimum`() { assertFalse( isCreateIdentityFundingAmountValid( CreateIdentityFundingSource.CoreBalance, - 240_999L, + 247_499L, + minimums, ), ) assertTrue( isCreateIdentityFundingAmountValid( CreateIdentityFundingSource.CoreBalance, - 241_000L, + 247_500L, + minimums, + ), + ) + } + + @Test + fun `fundings that need the Rust minimum are invalid until it loads`() { + for (source in listOf( + CreateIdentityFundingSource.CoreBalance, + CreateIdentityFundingSource.PlatformAddress, + )) { + assertTrue(source.needsFundingMinimums) + assertFalse(isCreateIdentityFundingAmountValid(source, 10_000_000L, null)) + } + assertFalse(CreateIdentityFundingSource.ShieldedBalance.needsFundingMinimums) + assertTrue( + isCreateIdentityFundingAmountValid( + CreateIdentityFundingSource.ShieldedBalance, + 10_000_000L, + null, ), ) } @@ -38,10 +60,28 @@ class CreateIdentityFundingPolicyTest { isCreateIdentityFundingAmountValid( CreateIdentityFundingSource.AssetLockResume, null, + null, ), ) } + @Test + fun `resume re-derives the base layout while fresh funding gets the DashPay layout`() { + assertEquals( + IdentityCreationKeyLayout.NEW_IDENTITY, + CreateIdentityFundingSource.AssetLockResume.keyLayout, + ) + assertEquals(null, CreateIdentityFundingSource.AssetLockResume.freshKeyLayout) + for (source in listOf( + CreateIdentityFundingSource.CoreBalance, + CreateIdentityFundingSource.PlatformAddress, + CreateIdentityFundingSource.ShieldedBalance, + )) { + assertEquals(IdentityCreationKeyLayout.NEW_IDENTITY_WITH_DASHPAY_KEYS, source.keyLayout) + assertEquals(source.keyLayout, source.freshKeyLayout) + } + } + @Test fun `Platform address packing reserves the six-key fee on input zero`() { val inputs = packFundingInputs( @@ -53,18 +93,29 @@ class CreateIdentityFundingPolicyTest { ), ), target = 30_000_000L, + addressFundingFeeCredits = minimums.addressFundingFeeCredits, ) - // One six-key input needs 41.5M credits left after the requested + // One input needs a 41.5M-credit fee left after the requested // 30M spend. This address would leave only 40M, so submitting it // would persist all keys and then fail on-chain. assertTrue(inputs.isEmpty()) } @Test - fun `Platform address fee scales with key and input counts`() { - assertEquals(41_500_000L, minimumPlatformAddressFundingFeeCredits(6, 1)) - assertEquals(42_000_000L, minimumPlatformAddressFundingFeeCredits(6, 2)) + fun `Platform address packing never exceeds the Rust maximum input count`() { + val inputs = packFundingInputs( + candidates = listOf( + fundingInput(hashByte = 1, credits = 41_500_010L), + fundingInput(hashByte = 2, credits = 10L), + fundingInput(hashByte = 3, credits = 10L), + ), + target = 30L, + addressFundingFeeCredits = listOf(41_500_000L), + ) + + // Thirty credits need three inputs, but Rust allows only one. + assertTrue(inputs.isEmpty()) } @Test @@ -72,7 +123,7 @@ class CreateIdentityFundingPolicyTest { val inputs = packFundingInputs( candidates = listOf(fundingInput(hashByte = 1, credits = 71_500_000L)), target = 30_000_000L, - keyCount = 6, + addressFundingFeeCredits = minimums.addressFundingFeeCredits, ) assertEquals(1, inputs.size) @@ -87,7 +138,7 @@ class CreateIdentityFundingPolicyTest { // Deliberately reverse native BTreeMap order. candidates = listOf(higherAddress, lowerAddress), target = 30_000_000L, - keyCount = 6, + addressFundingFeeCredits = minimums.addressFundingFeeCredits, ) assertEquals(2, inputs.size) @@ -120,6 +171,8 @@ class CreateIdentityFundingPolicyTest { assertEquals(CreateIdentityFundingSource.AssetLockResume, snapshot.fundingSource) assertFalse(snapshot.includesDashPayKeys) + assertEquals(null, snapshot.freshKeyLayout) + assertEquals(IdentityCreationKeyLayout.NEW_IDENTITY, snapshot.keyLayout) assertEquals(5, snapshot.identityIndex) assertEquals(null, snapshot.amount) assertEquals(5, snapshot.recoveryLock!!.registrationIndex) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt index 3e6b8114b6b..0d7b2570903 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/IdentityNative.kt @@ -31,6 +31,21 @@ internal object IdentityNative { identityId: ByteArray, ): Int + /** + * The minimum asset-lock value (duffs) registering the layout with + * `IdentityCreationKeyLayout.nativeCode` [layout] needs at the wallet's + * platform version (thin marshal of + * `platform_wallet_identity_creation_min_funding_duffs`). + */ + external fun identityCreationMinFundingDuffs(walletHandle: Long, layout: Int): Long + + /** + * The minimum fees (credits) of an address-funded identity create of + * [layout], one per input count from 1 to the protocol maximum (thin + * marshal of `platform_wallet_identity_creation_from_addresses_min_fees`). + */ + external fun identityCreationFromAddressesMinFees(walletHandle: Long, layout: Int): LongArray + /** * Resume registration from the exact tracked Core outpoint. * @@ -84,34 +99,40 @@ internal object IdentityNative { /** * Derive the full identity-registration key **set** for a single - * identity: keyId 0..[count] at the fixed [identityIndex]. Unlike + * identity at the fixed [identityIndex]. Unlike * [previewRegistrationKeys] (which fixes the MASTER key slot and walks * the *identity* index for the discovery preview), this fixes the * identity index and walks the *key* index — so it returns every * keypair a freshly-created identity is built from. * - * [count] < 0 derives the canonical default set (4 keys: MASTER auth, - * CRITICAL auth, HIGH auth, TRANSFER/CRITICAL); the create-identity flow - * may request more (e.g. 6, appending the DashPay ENCRYPTION/DECRYPTION - * pair). Returns the same flat BLOB layout as [previewRegistrationKeys], + * One keypair is derived per slot of the Rust identity-creation key + * layout selected by [layout]. Returns the same flat BLOB layout as [previewRegistrationKeys], * decoded by * [org.dashfoundation.dashsdk.identity.IdentityKeyPreview.decodeAll]. - * The row carries only the derived ECDSA keypair — the per-key DPP role is - * stamped Kotlin-side by - * [org.dashfoundation.dashsdk.identity.RegistrationKeys] when the rich - * registration rows are built. + * The row carries only the derived ECDSA keypair — the per-key DPP role + * comes from the same Rust layout via [identityCreationKeyLayout]. * * @param resolverHandle `MnemonicResolverHandle`, needed for * watch-only / external-signable wallets; ignored for resident-key * wallets. + * @param layout `IdentityCreationKeyLayout.nativeCode` — one keypair is + * derived per slot of that layout. */ external fun previewRegistrationKeySet( walletHandle: Long, resolverHandle: Long, identityIndex: Int, - count: Int, + layout: Int, ): ByteArray + /** + * The identity-creation key layout Rust owns, as the BLOB decoded by + * [org.dashfoundation.dashsdk.identity.RegistrationKeys.decodeLayout]. + * + * @param layout `IdentityCreationKeyLayout.nativeCode`. + */ + external fun identityCreationKeyLayout(layout: Int): ByteArray + /** * Resolver-keyed single-slot identity private-key derive for the * **persistence-callback** path. diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt index b8c4cd647f4..4430c7cc392 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/IdentityRegistration.kt @@ -131,6 +131,36 @@ class IdentityRegistration internal constructor( } } + /** + * The minimum asset-lock value (duffs) that registers [layout] at the + * wallet's platform version, from Rust's versioned fee schedule. Show and + * enforce it; never recompute it from fee constants. Rust refuses a + * wallet-funded registration below it. + */ + suspend fun creationMinFundingDuffs( + walletHandle: Long, + layout: IdentityCreationKeyLayout, + ): Long = gate.op { + mapNativeErrors { + IdentityNative.identityCreationMinFundingDuffs(walletHandle, layout.nativeCode) + } + } + + /** + * The minimum fees (credits) of an address-funded identity create of + * [layout] without a refund output, at the wallet's platform version: + * element `n - 1` is the fee with `n` inputs, and the size is the + * protocol's maximum input count. From Rust's versioned fee schedule. + */ + suspend fun creationFromAddressesMinFees( + walletHandle: Long, + layout: IdentityCreationKeyLayout, + ): List = gate.op { + mapNativeErrors { + IdentityNative.identityCreationFromAddressesMinFees(walletHandle, layout.nativeCode) + }.toList() + } + /** * Resume identity registration from [lock]'s exact persisted outpoint. * Rust owns rebroadcast/proof/status decisions; Kotlin never builds a @@ -139,15 +169,11 @@ class IdentityRegistration internal constructor( * * [keys] carries the rich registration rows (built via * [RegistrationKeys.buildRegistrationRows]) and the HD slot that derived - * them. Resume carries the SAME key - * set the interrupted registration originally committed to on-chain — the - * base four auth/transfer keys, **without** the DashPay pair: an - * already-spent asset lock funds a fixed key count, so retroactively - * growing the transition it funds risks a resume that fails after the - * user's DASH is already irreversibly locked (matching iOS, which excludes - * DashPay provisioning from the resume path). A user who resumes and wants - * DashPay capability adds those keys afterward via the Add Identity Key - * flow. + * them, derived from [IdentityCreationKeyLayout.NEW_IDENTITY]. Rust + * refuses the resume before signing when the lock cannot pay for [keys]. + * A resume never adds the DashPay pair, since the lock funds a fixed key + * count (matching iOS); a user who wants DashPay capability adds those + * keys afterward via the Add Identity Key flow. */ suspend fun resumeWithExistingAssetLock( walletHandle: Long, @@ -210,9 +236,10 @@ class IdentityRegistration internal constructor( * not a [TrackedAssetLock] — invitation locks are deliberately * excluded from the generic tracked-lock recovery model, and no * funding-type or registration-index gate applies: the identity slot - * is freely chosen (next unused). [keys] carries the **base 4-key** - * registration set (`includeDashPayKeys = false`) — a reclaim sends - * no contact request, matching iOS's `authKeyCount = 4`. + * is freely chosen (next unused). [keys] carries the + * [IdentityCreationKeyLayout.NEW_IDENTITY] set (no DashPay keys: a + * reclaim sends no contact request). A reclaim creates a new identity, + * so Rust applies the creation key check to it. * `consumeInvitationVoucher = true` is the explicit authorization * Rust core requires; this is one of the two call sites that pass it. * @@ -270,9 +297,9 @@ class IdentityRegistration internal constructor( * onboarding path. ← Swift `ManagedPlatformWallet.claimInvitation` * (packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift). * - * [keys] carries the full fresh-registration set (the base four - * auth/transfer keys PLUS the DashPay ENCRYPTION/DECRYPTION pair, - * `RegistrationKeys.buildRegistrationRows(includeDashPayKeys = true)`) + * [keys] carries the full fresh-registration set, every key of + * [IdentityCreationKeyLayout.NEW_IDENTITY_WITH_DASHPAY_KEYS] including + * the DashPay ENCRYPTION/DECRYPTION pair * — unlike asset-lock resume, a claim funds a brand-new transition, so * the invitee gets DashPay capability from the start. Each row's * private key must already be persisted (see @@ -354,33 +381,23 @@ class IdentityRegistration internal constructor( } /** - * Derive the full identity-registration key SET for a single identity - * — keyId 0..[count] at the fixed [identityIndex]. This is the call - * the create-identity flow uses: it fixes the identity index and walks - * the key index, so a freshly created identity is provisioned with the - * whole canonical key set (keyId 0 MASTER/AUTH, 1 CRITICAL/AUTH, 2 - * HIGH/AUTH, 3 TRANSFER/CRITICAL) rather than just the MASTER key. + * Derive the full identity-registration key SET of [layout] for a single + * identity at the fixed [identityIndex]: one keypair per slot of the Rust + * layout, in key-id order. This is the call the create-identity flow uses: + * it fixes the identity index and walks the key index, so a new identity + * is provisioned with every key of its layout rather than just the MASTER + * key. ([previewRegistrationKeys], by contrast, walks the *identity* index + * at the MASTER slot for the discovery preview.) * - * Without the full set, all Platform writes fail validation right - * after creation: document / DPNS / token / contract transitions need - * a HIGH-or-CRITICAL AUTHENTICATION key, and credit transfers / - * withdrawals need the TRANSFER key ("no transfer public key"). - * - * Each row here carries only the derived keypair; the per-key DPP role is - * stamped Kotlin-side by [RegistrationKeys] when the rich registration rows - * are built. The caller persists each row's private key to the Keystore - * before registering. - * - * @param count number of keys to derive; < 0 uses the canonical - * default set (4 keys). ([previewRegistrationKeys], by contrast, - * walks the *identity* index at the MASTER slot for the discovery - * preview.) + * Each row here carries only the derived keypair; the per-key DPP role + * comes from [RegistrationKeys.layout] for the same [layout]. The caller + * persists each row's private key to the Keystore before registering. */ suspend fun previewRegistrationKeySet( walletHandle: Long, mnemonicResolverHandle: Long, identityIndex: Int, - count: Int = -1, + layout: IdentityCreationKeyLayout, ): List = gate.opWithCleanupOnCancellation( cleanup = { previews -> previews.forEach { it.privateKey.fill(0) } }, ) { @@ -389,7 +406,7 @@ class IdentityRegistration internal constructor( walletHandle, mnemonicResolverHandle, identityIndex, - count, + layout.nativeCode, ) } IdentityKeyPreview.decodeAll(blob) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeys.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeys.kt index dcb76ef305b..8ae6bbcc06f 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeys.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeys.kt @@ -1,5 +1,7 @@ package org.dashfoundation.dashsdk.identity +import org.dashfoundation.dashsdk.ffi.IdentityNative + /** * Rich registration rows tied to the identity HD slot that produced them. * @@ -20,48 +22,64 @@ class RegistrationKeySet( } /** - * The canonical DPP-role layout for a freshly-registered identity's keys — - * the Kotlin source of truth that replaces the retired Rust - * `role_for_registration_key_id`. Since the registration wire format now - * carries each key's full role (see [IdentityPubkeyCodec]) instead of - * reconstructing it positionally on the Rust side, the layout is stamped here - * and shipped over the boundary. + * Which key layout an identity-creation flow registers — the Kotlin mirror of + * Rust's `platform_wallet::IdentityCreationKeyLayout`. [nativeCode] is the + * ordinal `IdentityNative.identityCreationKeyLayout` and + * `IdentityNative.previewRegistrationKeySet` take. + */ +enum class IdentityCreationKeyLayout(val nativeCode: Int) { + /** + * A new identity without DashPay keys; also what a resume of a tracked + * registration asset lock re-derives. + */ + NEW_IDENTITY(0), + + /** A new identity with the DashPay ENCRYPTION / DECRYPTION keys. */ + NEW_IDENTITY_WITH_DASHPAY_KEYS(1); + + companion object { + /** The layout a fresh registration uses. */ + fun forNewIdentity(includeDashPayKeys: Boolean): IdentityCreationKeyLayout = + if (includeDashPayKeys) NEW_IDENTITY_WITH_DASHPAY_KEYS else NEW_IDENTITY + } +} + +/** + * One key of an [IdentityCreationKeyLayout], as Rust defines it: the key id, + * the DIP-9 key index it is derived at, and the role it is registered with. + */ +data class RegistrationKeySlot( + val keyId: Int, + val derivationKeyIndex: Int, + val keyType: KeyType, + val purpose: KeyPurpose, + val securityLevel: SecurityLevel, + val contractBounds: ContractBounds?, +) + +/** + * The identity-creation key layout, read from Rust. Kotlin decides nothing + * here: the layout (which keys, which ids, which roles) is owned by + * `platform_wallet::IdentityCreationKeyLayout` and marshalled through + * `IdentityNative.identityCreationKeyLayout`. This object decodes it and + * stamps each slot's role onto the derived public keys. * - * Byte-for-byte identical to the iOS reference (SwiftExampleApp's - * `CreateIdentityView.defaultKeyCount` role table + `makeDashpayKeyPair`): + * The layouts today (all ECDSA_SECP256K1, DIP-9 key index = key id): * - * | keyId | keyType | purpose | securityLevel | bounds | - * |-------|-----------------|----------------|---------------|---------------------------| - * | 0 | ECDSA_SECP256K1 | AUTHENTICATION | MASTER | — | - * | 1 | ECDSA_SECP256K1 | AUTHENTICATION | CRITICAL | — | - * | 2 | ECDSA_SECP256K1 | AUTHENTICATION | HIGH | — | - * | 3 | ECDSA_SECP256K1 | TRANSFER | CRITICAL | — | - * | 4 | ECDSA_SECP256K1 | ENCRYPTION | MEDIUM | DashPay / contactRequest | - * | 5 | ECDSA_SECP256K1 | DECRYPTION | MEDIUM | DashPay / contactRequest | + * | keyId | purpose | securityLevel | layouts | + * |-------|----------------|---------------|---------------------------------| + * | 0 | AUTHENTICATION | MASTER | all | + * | 1 | AUTHENTICATION | CRITICAL | all | + * | 2 | AUTHENTICATION | HIGH | all | + * | 3 | TRANSFER | CRITICAL | all | + * | 4 | ENCRYPTION | MEDIUM | NEW_IDENTITY_WITH_DASHPAY_KEYS | + * | 5 | DECRYPTION | MEDIUM | NEW_IDENTITY_WITH_DASHPAY_KEYS | * - * - keyId 0 (MASTER/AUTH) signs the IdentityCreate / IdentityUpdate transition. - * - keyId 1 (CRITICAL/AUTH) signs token state transitions — without it the - * identity can't mint / burn / freeze tokens. - * - keyId 2 (HIGH/AUTH) signs general document / DPNS / contract transitions. - * - keyId 3 (TRANSFER/CRITICAL) signs IdentityCreditTransfer / …Withdrawal — - * without it those broadcasts are rejected on-chain with "no transfer public - * key". - * - keyId 4 (ENCRYPTION) + keyId 5 (DECRYPTION), bound to DashPay's - * `contactRequest` document type, let the new identity send / receive - * contact requests. Without them the app's own Add Contact flow rejects the - * identity: `select_own_encryption_key` requires an enabled ECDSA - * ENCRYPTION key. These two are appended only on fresh-funding registration, - * not on asset-lock resume (which never grows past the key set it originally - * committed to on-chain). + * Rust's write path refuses a new identity without an AUTHENTICATION key at + * each of MASTER, CRITICAL and HIGH. */ object RegistrationKeys { - /** Base auth/transfer key count (keyIds 0..3), every registration path. */ - const val BASE_KEY_COUNT: Int = 4 - - /** Extra DashPay ENCRYPTION + DECRYPTION keys (keyIds 4..5). */ - const val DASHPAY_KEY_COUNT: Int = 2 - /** Immutable backing bytes for [DASHPAY_CONTRACT_ID] — never handed out directly. */ private val DASHPAY_CONTRACT_ID_BYTES: ByteArray = byteArrayOf( 162.toByte(), 161.toByte(), 180.toByte(), 172.toByte(), 111, 239.toByte(), 34, 234.toByte(), @@ -72,10 +90,9 @@ object RegistrationKeys { /** * DashPay data-contract id (32 bytes) — source of truth - * `packages/dashpay-contract/src/lib.rs::ID_BYTES`. Mirrored here so the - * contract-bounds payload for the ENCRYPTION / DECRYPTION keys can be built - * without a contract fetch; pinned against the Rust constant by the - * cross-language golden fixture in the tests. Network-agnostic. + * `packages/dashpay-contract/src/lib.rs::ID_BYTES`. Used by the manual + * Add Identity Key flow; registration takes its bounds from the Rust + * layout instead. Network-agnostic. * * Returns a fresh copy on every access — the id is process-global, so * handing out the backing array would let a stray write corrupt every @@ -91,85 +108,117 @@ object RegistrationKeys { */ const val DASHPAY_CONTACT_REQUEST_DOCUMENT_TYPE: String = "contactRequest" - /** Total keys a registration derives for the given DashPay choice. */ - fun keyCount(includeDashPayKeys: Boolean): Int = - BASE_KEY_COUNT + if (includeDashPayKeys) DASHPAY_KEY_COUNT else 0 + /** The slots of [layout], from Rust, in key-id order. */ + fun layout(layout: IdentityCreationKeyLayout): List = + decodeLayout(IdentityNative.identityCreationKeyLayout(layout.nativeCode)) + + /** Total keys [layout] registers, for sizing the creation fee. */ + fun keyCount(layout: IdentityCreationKeyLayout): Int = layout(layout).size /** - * Stamp the canonical DPP roles onto [publicKeys], producing the rich - * [IdentityPubkey] rows the registration wire format carries. [publicKeys] - * must be exactly [keyCount] entries in keyId order (index i → keyId i); - * each is the on-chain public payload for that slot (the derived - * compressed pubkey, already persisted to the Keystore by the caller). No - * private material is touched here. + * Stamp each slot's role onto [publicKeys], producing the rich + * [IdentityPubkey] rows the registration wire format carries. + * [publicKeys] must be exactly one per slot, in slot order; each is the + * on-chain public payload for that slot (the derived compressed pubkey, + * already persisted to the Keystore by the caller). No private material + * is touched here. * - * @throws IllegalArgumentException if the count doesn't match the policy. + * @throws IllegalArgumentException if the count doesn't match the layout. */ fun buildRegistrationRows( publicKeys: List, - includeDashPayKeys: Boolean, + slots: List, ): List { - val expected = keyCount(includeDashPayKeys) - require(publicKeys.size == expected) { - "expected $expected registration public keys, got ${publicKeys.size}" + require(publicKeys.size == slots.size) { + "expected ${slots.size} registration public keys, got ${publicKeys.size}" + } + return slots.zip(publicKeys) { slot, pubkey -> + IdentityPubkey( + keyId = slot.keyId, + keyType = slot.keyType, + purpose = slot.purpose, + securityLevel = slot.securityLevel, + pubkeyBytes = pubkey, + contractBounds = slot.contractBounds, + ) } - return publicKeys.mapIndexed { keyId, pubkey -> rowFor(keyId, pubkey) } } - /** The DashPay contact-request contract-document bounds for the enc/dec keys. */ - private fun dashPayBounds(): ContractBounds = - ContractBounds.SingleContractDocumentType( - // The accessor already returns a fresh copy the bounds object owns. - contractId = DASHPAY_CONTRACT_ID, - documentTypeName = DASHPAY_CONTACT_REQUEST_DOCUMENT_TYPE, - ) - - private fun rowFor(keyId: Int, pubkey: ByteArray): IdentityPubkey = when (keyId) { - 0 -> IdentityPubkey( - keyId = 0, - keyType = KeyType.ECDSA_SECP256K1, - purpose = KeyPurpose.AUTHENTICATION, - securityLevel = SecurityLevel.MASTER, - pubkeyBytes = pubkey, - ) - 1 -> IdentityPubkey( - keyId = 1, - keyType = KeyType.ECDSA_SECP256K1, - purpose = KeyPurpose.AUTHENTICATION, - securityLevel = SecurityLevel.CRITICAL, - pubkeyBytes = pubkey, - ) - 2 -> IdentityPubkey( - keyId = 2, - keyType = KeyType.ECDSA_SECP256K1, - purpose = KeyPurpose.AUTHENTICATION, - securityLevel = SecurityLevel.HIGH, - pubkeyBytes = pubkey, - ) - 3 -> IdentityPubkey( - keyId = 3, - keyType = KeyType.ECDSA_SECP256K1, - purpose = KeyPurpose.TRANSFER, - securityLevel = SecurityLevel.CRITICAL, - pubkeyBytes = pubkey, - ) - 4 -> IdentityPubkey( - keyId = 4, - keyType = KeyType.ECDSA_SECP256K1, - purpose = KeyPurpose.ENCRYPTION, - securityLevel = SecurityLevel.MEDIUM, - pubkeyBytes = pubkey, - contractBounds = dashPayBounds(), - ) - 5 -> IdentityPubkey( - keyId = 5, - keyType = KeyType.ECDSA_SECP256K1, - purpose = KeyPurpose.DECRYPTION, - securityLevel = SecurityLevel.MEDIUM, - pubkeyBytes = pubkey, - contractBounds = dashPayBounds(), - ) - // Unreachable: buildRegistrationRows caps the count at keyCount(true) = 6. - else -> error("no registration role defined for keyId $keyId") + /** + * Decode the layout BLOB `IdentityNative.identityCreationKeyLayout` + * returns (all integers big-endian): + * + * ```text + * u32 row_count + * repeat row_count times: + * u32 key_id + * u32 derivation_key_index + * u8 key_type, u8 purpose, u8 security_level (DPP discriminants) + * u8 contract_bounds_kind (0 none, 1 SingleContract, 2 SingleContractDocumentType) + * if contract_bounds_kind != 0: u8[32] contract_bounds_id + * if contract_bounds_kind == 2: u16 doc_type_len, u8[doc_type_len] doc_type (UTF-8) + * ``` + * + * Strict: truncation, trailing bytes and unknown discriminants throw, so + * a Kotlin artifact paired with a mismatched native library fails loudly. + * + * @throws IllegalArgumentException on a malformed BLOB. + */ + fun decodeLayout(blob: ByteArray): List { + val buf = java.nio.ByteBuffer.wrap(blob) + fun need(n: Int, what: String) { + require(buf.remaining() >= n) { "layout blob truncated at $what" } + } + need(4, "row count") + val count = buf.int + require(count >= 0) { "layout blob row count must be non-negative, got $count" } + val slots = ArrayList(minOf(count, 16)) + repeat(count) { i -> + need(12, "row $i header") + val keyId = buf.int + val derivationKeyIndex = buf.int + val keyTypeByte = buf.get().toInt() and 0xFF + val purposeByte = buf.get().toInt() and 0xFF + val levelByte = buf.get().toInt() and 0xFF + val boundsKind = buf.get().toInt() and 0xFF + val keyType = requireNotNull(KeyType.entries.firstOrNull { it.ffiValue == keyTypeByte }) { + "layout blob row $i has unknown key type $keyTypeByte" + } + val purpose = requireNotNull(KeyPurpose.entries.firstOrNull { it.ffiValue == purposeByte }) { + "layout blob row $i has unknown purpose $purposeByte" + } + val securityLevel = + requireNotNull(SecurityLevel.entries.firstOrNull { it.ffiValue == levelByte }) { + "layout blob row $i has unknown security level $levelByte" + } + val bounds = when (boundsKind) { + 0 -> null + 1 -> { + need(32, "row $i contract id") + ContractBounds.SingleContract(ByteArray(32).also { buf.get(it) }) + } + 2 -> { + need(32 + 2, "row $i contract id") + val id = ByteArray(32).also { buf.get(it) } + val nameLen = buf.short.toInt() and 0xFFFF + need(nameLen, "row $i document type") + val name = ByteArray(nameLen).also { buf.get(it) } + ContractBounds.SingleContractDocumentType(id, String(name, Charsets.UTF_8)) + } + else -> throw IllegalArgumentException( + "layout blob row $i has unknown contract bounds kind $boundsKind", + ) + } + slots += RegistrationKeySlot( + keyId = keyId, + derivationKeyIndex = derivationKeyIndex, + keyType = keyType, + purpose = purpose, + securityLevel = securityLevel, + contractBounds = bounds, + ) + } + require(!buf.hasRemaining()) { "layout blob has ${buf.remaining()} trailing bytes" } + return slots } } diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeysTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeysTest.kt index 3d2001d4e89..1bf2efacc61 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeysTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/RegistrationKeysTest.kt @@ -14,63 +14,95 @@ class RegistrationKeysTest { private fun fixturePubkeys(count: Int): List = (0 until count).map(::fixturePubkey) + private fun golden(name: String): ByteArray = + javaClass.getResourceAsStream("/golden/identity_creation_key_layout_${name}_v1.bin") + .use { requireNotNull(it) { "golden layout fixture $name missing" }.readBytes() } + + /** + * The Rust layouts, decoded from the golden BLOBs the Rust JNI encoder is + * pinned to (`identity::tests::should_encode_*`). + */ + private val newIdentity get() = RegistrationKeys.decodeLayout(golden("new_identity")) + private val withDashPayKeys get() = RegistrationKeys.decodeLayout(golden("new_identity_with_dashpay_keys")) + + private fun roles(slots: List) = + slots.map { Triple(it.keyId, it.purpose, it.securityLevel) } + @Test - fun `base four rows carry the canonical auth and transfer roles`() { - val rows = RegistrationKeys.buildRegistrationRows(fixturePubkeys(4), includeDashPayKeys = false) - assertEquals(4, rows.size) - assertEquals( - listOf(0, 1, 2, 3), - rows.map { it.keyId }, - ) + fun `new identity layout registers the four base keys`() { assertEquals( listOf( - Triple(KeyPurpose.AUTHENTICATION, SecurityLevel.MASTER, null), - Triple(KeyPurpose.AUTHENTICATION, SecurityLevel.CRITICAL, null), - Triple(KeyPurpose.AUTHENTICATION, SecurityLevel.HIGH, null), - Triple(KeyPurpose.TRANSFER, SecurityLevel.CRITICAL, null), + Triple(0, KeyPurpose.AUTHENTICATION, SecurityLevel.MASTER), + Triple(1, KeyPurpose.AUTHENTICATION, SecurityLevel.CRITICAL), + Triple(2, KeyPurpose.AUTHENTICATION, SecurityLevel.HIGH), + Triple(3, KeyPurpose.TRANSFER, SecurityLevel.CRITICAL), ), - rows.map { Triple(it.purpose, it.securityLevel, it.contractBounds) }, + roles(newIdentity), ) - rows.forEach { + newIdentity.forEach { assertEquals(KeyType.ECDSA_SECP256K1, it.keyType) - assertEquals(false, it.readOnly) + assertEquals(it.keyId, it.derivationKeyIndex) + assertNull(it.contractBounds) } } @Test - fun `six rows append the DashPay encryption and decryption pair`() { - val rows = RegistrationKeys.buildRegistrationRows(fixturePubkeys(6), includeDashPayKeys = true) - assertEquals(6, rows.size) - - val enc = rows[4] - val dec = rows[5] - assertEquals(KeyPurpose.ENCRYPTION, enc.purpose) - assertEquals(KeyPurpose.DECRYPTION, dec.purpose) - for (row in listOf(enc, dec)) { - assertEquals(KeyType.ECDSA_SECP256K1, row.keyType) - assertEquals(SecurityLevel.MEDIUM, row.securityLevel) - assertEquals(false, row.readOnly) - val bounds = row.contractBounds + fun `DashPay layout adds the DashPay pair at ids four and five`() { + val slots = withDashPayKeys + assertEquals( + listOf( + Triple(0, KeyPurpose.AUTHENTICATION, SecurityLevel.MASTER), + Triple(1, KeyPurpose.AUTHENTICATION, SecurityLevel.CRITICAL), + Triple(2, KeyPurpose.AUTHENTICATION, SecurityLevel.HIGH), + Triple(3, KeyPurpose.TRANSFER, SecurityLevel.CRITICAL), + Triple(4, KeyPurpose.ENCRYPTION, SecurityLevel.MEDIUM), + Triple(5, KeyPurpose.DECRYPTION, SecurityLevel.MEDIUM), + ), + roles(slots), + ) + for (slot in listOf(slots[4], slots[5])) { + val bounds = slot.contractBounds assertTrue(bounds is ContractBounds.SingleContractDocumentType) bounds as ContractBounds.SingleContractDocumentType assertArrayEquals(RegistrationKeys.DASHPAY_CONTRACT_ID, bounds.contractId) - assertEquals( - RegistrationKeys.DASHPAY_CONTACT_REQUEST_DOCUMENT_TYPE, - bounds.documentTypeName, - ) + assertEquals(RegistrationKeys.DASHPAY_CONTACT_REQUEST_DOCUMENT_TYPE, bounds.documentTypeName) + } + assertEquals(roles(newIdentity), roles(slots).take(4)) + } + + @Test + fun `rows stamp each slot role onto its public key`() { + val rows = RegistrationKeys.buildRegistrationRows(fixturePubkeys(6), withDashPayKeys) + assertEquals(listOf(0, 1, 2, 3, 4, 5), rows.map { it.keyId }) + rows.forEachIndexed { i, row -> + assertArrayEquals(fixturePubkey(i), row.pubkeyBytes) + assertEquals(withDashPayKeys[i].purpose, row.purpose) + assertEquals(withDashPayKeys[i].securityLevel, row.securityLevel) + assertEquals(withDashPayKeys[i].contractBounds, row.contractBounds) + assertEquals(false, row.readOnly) } - // The base four keep their auth/transfer roles unbounded. - (0..3).forEach { assertNull(rows[it].contractBounds) } } @Test fun `wrong key count is rejected`() { val failure = runCatching { - RegistrationKeys.buildRegistrationRows(fixturePubkeys(5), includeDashPayKeys = true) + RegistrationKeys.buildRegistrationRows(fixturePubkeys(5), withDashPayKeys) } assertTrue(failure.exceptionOrNull() is IllegalArgumentException) } + @Test + fun `malformed layout blobs are rejected`() { + val blob = golden("new_identity") + for (bad in listOf( + blob.copyOf(blob.size - 1), // truncated + blob + byteArrayOf(0), // trailing byte + blob.copyOf().also { it[4 + 8 + 3] = 9 }, // unknown bounds kind on row 0 + )) { + assertTrue(runCatching { RegistrationKeys.decodeLayout(bad) }.exceptionOrNull() is IllegalArgumentException) + } + } + /** * Cross-language wire pin: the Kotlin encoder must produce exactly the * checked-in golden bytes. A byte-identical Rust test @@ -85,7 +117,8 @@ class RegistrationKeysTest { val golden = javaClass.getResourceAsStream("/golden/registration_pubkeys_v2.bin") .use { requireNotNull(it) { "golden fixture resource missing" }.readBytes() } - val rows = RegistrationKeys.buildRegistrationRows(fixturePubkeys(6), includeDashPayKeys = true) + // The golden fixture holds the six rows of the DashPay layout. + val rows = RegistrationKeys.buildRegistrationRows(fixturePubkeys(6), withDashPayKeys) val encoded = IdentityPubkeyCodec.encode(rows) assertArrayEquals( diff --git a/packages/kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_v1.bin b/packages/kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_v1.bin new file mode 100644 index 00000000000..d816c7a13cd Binary files /dev/null and b/packages/kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_v1.bin differ diff --git a/packages/kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_with_dashpay_keys_v1.bin b/packages/kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_with_dashpay_keys_v1.bin new file mode 100644 index 00000000000..62a222ac29c Binary files /dev/null and b/packages/kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_with_dashpay_keys_v1.bin differ diff --git a/packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs b/packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs new file mode 100644 index 00000000000..5b394abf3d0 --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/identity_creation_key_layout.rs @@ -0,0 +1,464 @@ +//! The key layout a new identity is created with, marshalled from +//! [`platform_wallet::IdentityCreationKeyLayout`]. +//! +//! Hosts read the layout here instead of keeping their own table: each row +//! names the key id, the DIP-9 key index to derive it at, and the role +//! (type, purpose, security level, contract bounds) to register it with. + +use std::ffi::CString; +use std::os::raw::c_char; +use std::ptr; + +use dpp::identity::identity_public_key::contract_bounds::ContractBounds; +use platform_wallet::{IdentityCreationKeyLayout, IdentityCreationKeySlot}; + +use crate::check_ptr; +use crate::error::*; +use crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; +use crate::{unwrap_option_or_return, unwrap_result_or_return}; + +/// Which key layout an identity-creation flow registers. Mirrors +/// [`IdentityCreationKeyLayout`]. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IdentityCreationKeyLayoutFFI { + /// A new identity without DashPay keys; also what a resume of a tracked + /// registration lock re-derives. + NewIdentity = 0, + /// A new identity with the DashPay ENCRYPTION / DECRYPTION keys. + NewIdentityWithDashPayKeys = 1, +} + +impl From for IdentityCreationKeyLayout { + fn from(layout: IdentityCreationKeyLayoutFFI) -> Self { + match layout { + IdentityCreationKeyLayoutFFI::NewIdentity => Self::NewIdentity, + IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys => { + Self::NewIdentityWithDashPayKeys + } + } + } +} + +impl From for IdentityCreationKeyLayoutFFI { + fn from(layout: IdentityCreationKeyLayout) -> Self { + match layout { + IdentityCreationKeyLayout::NewIdentity => Self::NewIdentity, + IdentityCreationKeyLayout::NewIdentityWithDashPayKeys => { + Self::NewIdentityWithDashPayKeys + } + } + } +} + +/// One key of the layout. +/// +/// `contract_bounds_kind` uses the encoding of +/// [`crate::IdentityPubkeyFFI`]: `0` none, `1` `SingleContract`, `2` +/// `SingleContractDocumentType`. `contract_bounds_id` is zero when the kind +/// is `0`; `contract_bounds_document_type` is a Rust-owned NUL-terminated +/// string when the kind is `2`, null otherwise. +#[repr(C)] +pub struct IdentityCreationKeySlotFFI { + pub key_id: u32, + /// DIP-9 key index (`m/9'/coin'/5'/0'/0'/identity_index'/key_index'`). + pub derivation_key_index: u32, + pub key_type: u8, + pub purpose: u8, + pub security_level: u8, + pub contract_bounds_kind: u8, + pub contract_bounds_id: [u8; 32], + pub contract_bounds_document_type: *mut c_char, +} + +/// Heap-allocated array of [`IdentityCreationKeySlotFFI`] rows in key-id +/// order. Release with [`platform_wallet_identity_creation_key_layout_free`]. +#[repr(C)] +pub struct IdentityCreationKeySlotsFFI { + pub items: *mut IdentityCreationKeySlotFFI, + pub count: usize, +} + +impl IdentityCreationKeySlotFFI { + fn from_slot(slot: &IdentityCreationKeySlot) -> Result { + let (contract_bounds_kind, contract_bounds_id, contract_bounds_document_type) = + match &slot.contract_bounds { + None => (0, [0u8; 32], ptr::null_mut()), + Some(ContractBounds::SingleContract { id }) => (1, id.to_buffer(), ptr::null_mut()), + Some(ContractBounds::SingleContractDocumentType { + id, + document_type_name, + }) => { + let name = CString::new(document_type_name.as_str()).map_err(|e| { + PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorUtf8Conversion, + format!("document type name contains a NUL byte: {e}"), + ) + })?; + (2, id.to_buffer(), name.into_raw()) + } + Some(ContractBounds::ContractGroup { .. }) => { + return Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorSerialization, + "identity creation layout slot has contract-group bounds, which this \ + row cannot carry", + )); + } + }; + Ok(Self { + key_id: slot.key_id, + derivation_key_index: slot.derivation_key_index(), + key_type: slot.key_type as u8, + purpose: slot.purpose as u8, + security_level: slot.security_level as u8, + contract_bounds_kind, + contract_bounds_id, + contract_bounds_document_type, + }) + } + + /// Release the row's owned document type string. + unsafe fn release(&mut self) { + if !self.contract_bounds_document_type.is_null() { + drop(CString::from_raw(self.contract_bounds_document_type)); + self.contract_bounds_document_type = ptr::null_mut(); + } + } +} + +/// Write the key layout an identity-creation flow registers to +/// `out_slots`, one row per key in key-id order. +/// +/// On error `*out_slots` is left empty. +/// +/// # Safety +/// `out_slots` must be a valid, writable pointer. Release a populated +/// result with [`platform_wallet_identity_creation_key_layout_free`]. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_identity_creation_key_layout( + layout: IdentityCreationKeyLayoutFFI, + out_slots: *mut IdentityCreationKeySlotsFFI, +) -> PlatformWalletFFIResult { + check_ptr!(out_slots); + *out_slots = IdentityCreationKeySlotsFFI { + items: ptr::null_mut(), + count: 0, + }; + + let mut rows = Vec::new(); + for slot in IdentityCreationKeyLayout::from(layout).slots() { + match IdentityCreationKeySlotFFI::from_slot(&slot) { + Ok(row) => rows.push(row), + Err(e) => { + for mut row in rows { + row.release(); + } + return e; + } + } + } + + let mut boxed = rows.into_boxed_slice(); + *out_slots = IdentityCreationKeySlotsFFI { + items: boxed.as_mut_ptr(), + count: boxed.len(), + }; + std::mem::forget(boxed); + PlatformWalletFFIResult::ok() +} + +/// Release a layout written by [`platform_wallet_identity_creation_key_layout`] +/// and reset it to empty. Safe on an empty or null struct. +/// +/// # Safety +/// `slots` must be null or point at a struct populated by +/// [`platform_wallet_identity_creation_key_layout`] that was not freed yet. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_identity_creation_key_layout_free( + slots: *mut IdentityCreationKeySlotsFFI, +) { + if slots.is_null() { + return; + } + let slots = &mut *slots; + if !slots.items.is_null() { + let rows = Vec::from_raw_parts(slots.items, slots.count, slots.count); + for mut row in rows { + row.release(); + } + } + slots.items = ptr::null_mut(); + slots.count = 0; +} + +/// Write the minimum asset-lock value (duffs) that registers `layout` at +/// the wallet's platform version to `out_duffs`, from the versioned fee +/// schedule (`IdentityWallet::identity_creation_min_funding_duffs`). Hosts +/// show and enforce it; Rust refuses a wallet-funded registration, or the +/// resume of a tracked lock, below it. +/// +/// # Safety +/// `out_duffs` must be a valid, writable pointer. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_identity_creation_min_funding_duffs( + wallet_handle: Handle, + layout: IdentityCreationKeyLayoutFFI, + out_duffs: *mut u64, +) -> PlatformWalletFFIResult { + check_ptr!(out_duffs); + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + wallet + .identity() + .identity_creation_min_funding_duffs(layout.into()) + }); + let result = unwrap_option_or_return!(option); + *out_duffs = unwrap_result_or_return!(result); + PlatformWalletFFIResult::ok() +} + +/// Minimum fees (credits) of an address-funded identity create, one per +/// input count: `items[n - 1]` is the fee with `n` inputs, and `count` is +/// the protocol's maximum input count. Release with +/// [`platform_wallet_identity_creation_from_addresses_min_fees_free`]. +#[repr(C)] +pub struct IdentityCreationFeesFFI { + pub items: *mut u64, + pub count: usize, +} + +/// Write the minimum fees of an address-funded identity create of `layout` +/// (no refund output) at the wallet's platform version to `out_fees`, from +/// the versioned fee schedule +/// (`IdentityWallet::identity_creation_from_addresses_min_fees`). +/// +/// On error `*out_fees` is left empty. +/// +/// # Safety +/// `out_fees` must be a valid, writable pointer. Release a populated result +/// with [`platform_wallet_identity_creation_from_addresses_min_fees_free`]. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_identity_creation_from_addresses_min_fees( + wallet_handle: Handle, + layout: IdentityCreationKeyLayoutFFI, + out_fees: *mut IdentityCreationFeesFFI, +) -> PlatformWalletFFIResult { + check_ptr!(out_fees); + *out_fees = IdentityCreationFeesFFI { + items: ptr::null_mut(), + count: 0, + }; + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + wallet + .identity() + .identity_creation_from_addresses_min_fees(layout.into()) + }); + let result = unwrap_option_or_return!(option); + let fees = unwrap_result_or_return!(result); + let mut boxed = fees.into_boxed_slice(); + *out_fees = IdentityCreationFeesFFI { + items: boxed.as_mut_ptr(), + count: boxed.len(), + }; + std::mem::forget(boxed); + PlatformWalletFFIResult::ok() +} + +/// Release fees written by +/// [`platform_wallet_identity_creation_from_addresses_min_fees`] and reset +/// the struct to empty. Safe on an empty or null struct. +/// +/// # Safety +/// `fees` must be null or point at a struct populated by +/// [`platform_wallet_identity_creation_from_addresses_min_fees`] that was +/// not freed yet. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_identity_creation_from_addresses_min_fees_free( + fees: *mut IdentityCreationFeesFFI, +) { + if fees.is_null() { + return; + } + let fees = &mut *fees; + if !fees.items.is_null() { + drop(Vec::from_raw_parts(fees.items, fees.count, fees.count)); + } + fees.items = ptr::null_mut(); + fees.count = 0; +} + +#[cfg(test)] +mod tests { + use super::*; + use dpp::data_contracts::SystemDataContract; + use dpp::identity::{KeyType, Purpose, SecurityLevel}; + use platform_wallet::test_support::test_platform_wallet_manager; + use std::ffi::CStr; + + use crate::runtime::runtime; + + fn read_layout(layout: IdentityCreationKeyLayoutFFI) -> Vec<(u32, u32, u8, u8, u8, u8)> { + let mut out = IdentityCreationKeySlotsFFI { + items: ptr::null_mut(), + count: 0, + }; + let result = unsafe { platform_wallet_identity_creation_key_layout(layout, &mut out) }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + let rows = unsafe { std::slice::from_raw_parts(out.items, out.count) } + .iter() + .map(|r| { + ( + r.key_id, + r.derivation_key_index, + r.key_type, + r.purpose, + r.security_level, + r.contract_bounds_kind, + ) + }) + .collect(); + unsafe { platform_wallet_identity_creation_key_layout_free(&mut out) }; + assert!(out.items.is_null()); + assert_eq!(out.count, 0); + rows + } + + const SECP: u8 = KeyType::ECDSA_SECP256K1 as u8; + const AUTH: u8 = Purpose::AUTHENTICATION as u8; + + #[test] + fn should_marshal_the_new_identity_layout() { + assert_eq!( + read_layout(IdentityCreationKeyLayoutFFI::NewIdentity), + vec![ + (0, 0, SECP, AUTH, SecurityLevel::MASTER as u8, 0), + (1, 1, SECP, AUTH, SecurityLevel::CRITICAL as u8, 0), + (2, 2, SECP, AUTH, SecurityLevel::HIGH as u8, 0), + ( + 3, + 3, + SECP, + Purpose::TRANSFER as u8, + SecurityLevel::CRITICAL as u8, + 0 + ), + ] + ); + } + + #[test] + fn should_marshal_the_dashpay_layout_with_contact_request_bounds() { + let mut out = IdentityCreationKeySlotsFFI { + items: ptr::null_mut(), + count: 0, + }; + let result = unsafe { + platform_wallet_identity_creation_key_layout( + IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys, + &mut out, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + let rows = unsafe { std::slice::from_raw_parts(out.items, out.count) }; + assert_eq!(rows.len(), 6); + for (row, purpose) in [ + (&rows[4], Purpose::ENCRYPTION), + (&rows[5], Purpose::DECRYPTION), + ] { + assert_eq!(row.purpose, purpose as u8); + assert_eq!(row.security_level, SecurityLevel::MEDIUM as u8); + assert_eq!(row.contract_bounds_kind, 2); + assert_eq!( + row.contract_bounds_id, + SystemDataContract::Dashpay.id().to_buffer() + ); + let name = unsafe { CStr::from_ptr(row.contract_bounds_document_type) }; + assert_eq!(name.to_str().unwrap(), "contactRequest"); + } + unsafe { platform_wallet_identity_creation_key_layout_free(&mut out) }; + } + + #[test] + fn should_tolerate_freeing_a_null_or_empty_layout() { + unsafe { platform_wallet_identity_creation_key_layout_free(ptr::null_mut()) }; + let mut empty = IdentityCreationKeySlotsFFI { + items: ptr::null_mut(), + count: 0, + }; + unsafe { platform_wallet_identity_creation_key_layout_free(&mut empty) }; + } + + #[test] + fn should_marshal_the_rust_creation_minimums_for_each_layout() { + let (manager, wallet) = runtime().block_on(async { + let (manager, wallet_id) = test_platform_wallet_manager().await; + let wallet = manager.get_wallet(&wallet_id).await.expect("test wallet"); + (manager, wallet) + }); + let handle = PLATFORM_WALLET_STORAGE.insert(wallet.clone()); + for (ffi, layout) in [ + ( + IdentityCreationKeyLayoutFFI::NewIdentity, + IdentityCreationKeyLayout::NewIdentity, + ), + ( + IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys, + IdentityCreationKeyLayout::NewIdentityWithDashPayKeys, + ), + ] { + let mut duffs = 0u64; + let result = unsafe { + platform_wallet_identity_creation_min_funding_duffs(handle, ffi, &mut duffs) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + assert_eq!( + duffs, + wallet + .identity() + .identity_creation_min_funding_duffs(layout) + .expect("fee") + ); + + let mut fees = IdentityCreationFeesFFI { + items: ptr::null_mut(), + count: 0, + }; + let result = unsafe { + platform_wallet_identity_creation_from_addresses_min_fees(handle, ffi, &mut fees) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + assert_eq!( + unsafe { std::slice::from_raw_parts(fees.items, fees.count) }, + wallet + .identity() + .identity_creation_from_addresses_min_fees(layout) + .expect("fees") + .as_slice() + ); + unsafe { platform_wallet_identity_creation_from_addresses_min_fees_free(&mut fees) }; + assert!(fees.items.is_null()); + assert_eq!(fees.count, 0); + } + + PLATFORM_WALLET_STORAGE.remove(handle); + let mut duffs = 0u64; + let result = unsafe { + platform_wallet_identity_creation_min_funding_duffs( + handle, + IdentityCreationKeyLayoutFFI::NewIdentity, + &mut duffs, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::NotFound); + drop(manager); + } + + #[test] + fn should_tolerate_freeing_null_or_empty_fees() { + unsafe { platform_wallet_identity_creation_from_addresses_min_fees_free(ptr::null_mut()) }; + let mut empty = IdentityCreationFeesFFI { + items: ptr::null_mut(), + count: 0, + }; + unsafe { platform_wallet_identity_creation_from_addresses_min_fees_free(&mut empty) }; + } +} diff --git a/packages/rs-platform-wallet-ffi/src/identity_derive_and_persist.rs b/packages/rs-platform-wallet-ffi/src/identity_derive_and_persist.rs index e395ca03219..4da5ac4d45a 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_derive_and_persist.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_derive_and_persist.rs @@ -37,44 +37,13 @@ //! //! # Policy lives in Rust //! -//! Per-key metadata (key_type / purpose / security_level) is -//! computed on the Rust side using the DPP discriminants directly, -//! removing the policy-encoded-in-Swift block that the lower- -//! level FFI required the Swift caller to maintain. For the -//! identity-registration flow: -//! -//! | key_id | key_type | purpose | security_level | -//! |--------|-----------------|----------------|----------------| -//! | 0 | ECDSA_SECP256K1 | AUTHENTICATION | MASTER | -//! | 1 | ECDSA_SECP256K1 | AUTHENTICATION | CRITICAL | -//! | 2 | ECDSA_SECP256K1 | AUTHENTICATION | HIGH | -//! | 3 | ECDSA_SECP256K1 | TRANSFER | CRITICAL | -//! | > 3 | ECDSA_SECP256K1 | AUTHENTICATION | HIGH | -//! -//! Mirrors rs-dpp's canonical -//! `main_keys_with_random_authentication_keys_*` layout (MASTER → -//! CRITICAL → HIGH). The CRITICAL key at id 1 is what signs token -//! state transitions — rs-dpp's -//! `combined_security_level_requirement` collapses any batch -//! containing a token transition to `[CRITICAL]` only, so without -//! a CRITICAL key the identity cannot mint / burn / freeze tokens. -//! -//! Key id 3 is a `TRANSFER`/`CRITICAL` key. Dash Platform requires a -//! `purpose=TRANSFER`, `security_level=CRITICAL`, ECDSA_SECP256K1 key -//! to sign `IdentityCreditTransfer` (ID-04) and -//! `IdentityCreditWithdrawal` (ID-10) state transitions; without it -//! those broadcasts are rejected on-chain with -//! `Protocol error: missing key: no transfer public key`. So the -//! canonical default set provisions one. Slots 0/1/2 keep their -//! pre-existing `(purpose, security_level)` bytes byte-for-byte, so a -//! caller that still requests `key_count == 3` is completely -//! unchanged. `TRANSFER` keys take no contract bounds (only -//! ENCRYPTION/DECRYPTION require them), and this function never sets -//! bounds anyway. -//! -//! If DPP renumbers any of those enum discriminants, this file is -//! the single place that needs updating — the Swift caller just -//! writes whatever bytes it's told. +//! The key layout (key id, DIP-9 key index, key type, purpose, security +//! level) comes from [`platform_wallet::IdentityCreationKeyLayout`]; the +//! caller only picks which layout its flow registers. The persister +//! receives each key's DPP discriminant bytes and the Swift caller writes +//! whatever it is told. Contract bounds (the DashPay ENCRYPTION / +//! DECRYPTION keys) are not part of the persister row; read them from +//! [`crate::platform_wallet_identity_creation_key_layout`]. //! //! # Output shape //! @@ -94,12 +63,14 @@ use std::ptr; use crate::types::{FFINetwork, Network}; use dashcore::hashes::Hash; use key_wallet::bip32::{ExtendedPrivKey, ExtendedPubKey}; +use platform_wallet::IdentityCreationKeyLayout; use zeroize::{Zeroize, Zeroizing}; use crate::derive_and_persist_callbacks::{ IdentityKeyPersisterHandle, PersistKeyArgs, PERSIST_KEY_SUCCESS, }; use crate::error::*; +use crate::identity_creation_key_layout::IdentityCreationKeyLayoutFFI; use crate::identity_key_preview::IdentityKeyPreviewFFI; use crate::identity_keys_from_mnemonic::{ identity_auth_derivation_path, parse_mnemonic_any_language, @@ -110,22 +81,7 @@ use rs_sdk_ffi::{ mnemonic_resolver_result, MnemonicResolverHandle, MNEMONIC_RESOLVER_BUFFER_CAPACITY, }; -/// DPP `KeyType::ECDSA_SECP256K1` discriminant byte. -const KEY_TYPE_ECDSA_SECP256K1: u8 = 0; -/// DPP `Purpose::AUTHENTICATION` discriminant byte. -const PURPOSE_AUTHENTICATION: u8 = 0; -/// DPP `Purpose::TRANSFER` discriminant byte. Required (with -/// `SECURITY_LEVEL_CRITICAL`) to sign `IdentityCreditTransfer` / -/// `IdentityCreditWithdrawal` state transitions. -const PURPOSE_TRANSFER: u8 = 3; -/// DPP `SecurityLevel::MASTER` discriminant byte. -const SECURITY_LEVEL_MASTER: u8 = 0; -/// DPP `SecurityLevel::CRITICAL` discriminant byte. -const SECURITY_LEVEL_CRITICAL: u8 = 1; -/// DPP `SecurityLevel::HIGH` discriminant byte. -const SECURITY_LEVEL_HIGH: u8 = 2; - -/// Derive `key_count` identity-registration keypairs at DIP-9 +/// Derive the identity-registration keypairs of `layout` at their DIP-9 /// paths and persist each one's private key to the Swift-owned /// Keychain via the supplied callback handles. /// @@ -146,8 +102,9 @@ const SECURITY_LEVEL_HIGH: u8 = 2; /// Swift impl can stamp `walletId` into Keychain metadata /// without remembering which call this row came from. /// - `identity_index`: BIP-9 identity index slot. -/// - `key_count`: number of consecutive `key_index` slots to -/// derive, starting at 0. +/// - `layout`: which [`platform_wallet::IdentityCreationKeyLayout`] the +/// flow registers. One key is derived and persisted per slot, in key-id +/// order. /// - `mnemonic_resolver_handle`: opaque handle from /// [`crate::dash_sdk_mnemonic_resolver_create`]. /// - `persister_handle`: opaque handle from @@ -179,7 +136,7 @@ pub unsafe extern "C" fn dash_sdk_derive_and_persist_identity_keys( network: FFINetwork, wallet_id_bytes: *const u8, identity_index: u32, - key_count: u32, + layout: IdentityCreationKeyLayoutFFI, mnemonic_resolver_handle: *mut MnemonicResolverHandle, persister_handle: *mut IdentityKeyPersisterHandle, out_pubkeys: *mut IdentityRegistrationKeyDerivationsFFI, @@ -196,9 +153,7 @@ pub unsafe extern "C" fn dash_sdk_derive_and_persist_identity_keys( check_ptr!(mnemonic_resolver_handle); check_ptr!(persister_handle); - if key_count == 0 { - return PlatformWalletFFIResult::ok(); - } + let slots = IdentityCreationKeyLayout::from(layout).slots(); // ---- Resolve mnemonic ---------------------------------------------------- // Stack-resident, zeroized-on-drop buffer the resolver writes into. @@ -264,7 +219,7 @@ pub unsafe extern "C" fn dash_sdk_derive_and_persist_identity_keys( let persister = &*persister_handle; let persister_vtable = &*persister.vtable; - let mut rows: Vec = Vec::with_capacity(key_count as usize); + let mut rows: Vec = Vec::with_capacity(slots.len()); // Hand-roll cleanup: each successfully-pushed row owns a // CString allocation (path) + a heap-allocated pubkey buffer @@ -281,7 +236,8 @@ pub unsafe extern "C" fn dash_sdk_derive_and_persist_identity_keys( } }; - for key_index in 0..key_count { + for slot in &slots { + let key_index = slot.derivation_key_index(); let path = match identity_auth_derivation_path(kw_network, identity_index, key_index) { Ok(p) => p, Err(detail) => { @@ -331,44 +287,19 @@ pub unsafe extern "C" fn dash_sdk_derive_and_persist_identity_keys( } }; - // Per-key DPP metadata. Canonical default identity layout, - // extending rs-dpp's `main_keys_with_random_authentication_keys_*` - // (MASTER → CRITICAL → HIGH) with a dedicated TRANSFER key: - // 0 → AUTHENTICATION / MASTER (signs IdentityUpdate / IdentityCreate) - // 1 → AUTHENTICATION / CRITICAL (signs token state transitions — - // `combined_security_level_requirement` collapses any batch - // containing a token transition to `[CRITICAL]`; without a - // CRITICAL key the identity cannot mint / burn / freeze tokens) - // 2 → AUTHENTICATION / HIGH (general document operations) - // 3 → TRANSFER / CRITICAL (signs IdentityCreditTransfer / - // IdentityCreditWithdrawal; without it those broadcasts fail - // on-chain with "no transfer public key") - // > 3 → AUTHENTICATION / HIGH (any further keys) - // - // Slots 0/1/2 keep their pre-existing (purpose, security_level) - // bytes byte-for-byte, so a caller still passing key_count == 3 - // is unchanged. TRANSFER keys take no contract bounds, and this - // function never sets bounds for any key. - let (purpose, security_level) = match key_index { - 0 => (PURPOSE_AUTHENTICATION, SECURITY_LEVEL_MASTER), - 1 => (PURPOSE_AUTHENTICATION, SECURITY_LEVEL_CRITICAL), - 2 => (PURPOSE_AUTHENTICATION, SECURITY_LEVEL_HIGH), - 3 => (PURPOSE_TRANSFER, SECURITY_LEVEL_CRITICAL), - _ => (PURPOSE_AUTHENTICATION, SECURITY_LEVEL_HIGH), - }; let args = PersistKeyArgs { wallet_id_bytes, identity_index, - key_id: key_index, + key_id: slot.key_id, key_index, derivation_path_cstr: path_cstring.as_ptr(), public_key_bytes: pub_bytes.as_ptr(), public_key_len: pub_bytes.len(), public_key_hash_bytes: pub_hash.as_ptr(), private_key_bytes: priv_scalar.as_ptr(), - key_type: KEY_TYPE_ECDSA_SECP256K1, - purpose, - security_level, + key_type: slot.key_type as u8, + purpose: slot.purpose as u8, + security_level: slot.security_level as u8, }; let persist_rc = (persister_vtable.persist_key)(persister.ctx as *const c_void, &args as *const _); @@ -434,6 +365,7 @@ mod tests { use crate::derive_and_persist_callbacks::{ dash_sdk_identity_key_persister_create, dash_sdk_identity_key_persister_destroy, }; + use dpp::identity::{KeyType, Purpose, SecurityLevel}; use rs_sdk_ffi::{dash_sdk_mnemonic_resolver_create, dash_sdk_mnemonic_resolver_destroy}; use std::ffi::CStr; use std::sync::Mutex; @@ -572,8 +504,11 @@ mod tests { } } - #[test] - fn happy_path_persists_three_keys_and_returns_pubkeys() { + /// Derive + persist `layout` at identity index 7 on testnet and return + /// the captured persister rows plus the returned pubkeys. + fn derive_and_capture( + layout: IdentityCreationKeyLayoutFFI, + ) -> (Vec, Vec>) { let (resolver, persister, capture) = make_capturing_handles(); let wallet_id = [42u8; 32]; let mut out = IdentityRegistrationKeyDerivationsFFI { @@ -585,117 +520,116 @@ mod tests { FFINetwork::Testnet, wallet_id.as_ptr(), 7, // identity_index - 3, // key_count + layout, resolver, persister, &mut out, ) }; assert_eq!(rc.code, PlatformWalletFFIResultCode::Success); - assert_eq!(out.count, 3); - // SAFETY: `capture` is alive (we're about to free it - // below) and the persister can no longer fire — the FFI - // call has already returned synchronously. + // SAFETY: `capture` is alive (freed below) and the persister can no + // longer fire — the FFI call has already returned synchronously. let captured = unsafe { (*capture).rows.lock().unwrap().clone() }; - assert_eq!(captured.len(), 3); - - // key_id, key_index sequence - for (i, row) in captured.iter().enumerate() { + let pubkeys = unsafe { std::slice::from_raw_parts(out.items, out.count) } + .iter() + .map(|row| unsafe { + std::slice::from_raw_parts(row.public_key, row.public_key_len).to_vec() + }) + .collect(); + for row in &captured { assert_eq!(row.identity_index, 7); - assert_eq!(row.key_id, i as u32); - assert_eq!(row.key_index, i as u32); - assert_eq!(row.key_type, KEY_TYPE_ECDSA_SECP256K1); - assert_eq!(row.purpose, PURPOSE_AUTHENTICATION); - assert_eq!( - row.security_level, - match i { - 0 => SECURITY_LEVEL_MASTER, - 1 => SECURITY_LEVEL_CRITICAL, - _ => SECURITY_LEVEL_HIGH, - } - ); + assert_eq!(row.wallet_id, wallet_id); assert_eq!(row.public_key.len(), 33); - assert_eq!(row.public_key_hash.len(), 20); assert_eq!(row.private_key.len(), 32); - assert_eq!(row.wallet_id, wallet_id); - // hash160 sanity check: matches what the helper would compute. let expected_hash = dashcore::hashes::hash160::Hash::hash(&row.public_key).to_byte_array(); assert_eq!(row.public_key_hash.as_slice(), expected_hash.as_slice()); - // Path shape: testnet coin = 1. - assert_eq!(row.path, format!("m/9'/1'/5'/0'/0'/7'/{}'", i)); + // Derivation slot == key id; testnet coin = 1. + assert_eq!(row.key_index, row.key_id); + assert_eq!(row.path, format!("m/9'/1'/5'/0'/0'/7'/{}'", row.key_id)); } unsafe { crate::dash_sdk_derive_identity_keys_from_mnemonic_free(&mut out); dash_sdk_mnemonic_resolver_destroy(resolver); dash_sdk_identity_key_persister_destroy(persister); - // Reclaim the per-test capture box. let _ = Box::from_raw(capture); } + (captured, pubkeys) } - #[test] - fn key_count_four_includes_transfer_critical_key() { - let (resolver, persister, capture) = make_capturing_handles(); - let wallet_id = [42u8; 32]; - let mut out = IdentityRegistrationKeyDerivationsFFI { - items: std::ptr::null_mut(), - count: 0, - }; - let rc = unsafe { - dash_sdk_derive_and_persist_identity_keys( - FFINetwork::Testnet, - wallet_id.as_ptr(), - 7, // identity_index - 4, // key_count — now provisions the TRANSFER key at id 3 - resolver, - persister, - &mut out, - ) - }; - assert_eq!(rc.code, PlatformWalletFFIResultCode::Success); - assert_eq!(out.count, 4); + /// The `(key_id, key_type, purpose, security_level)` bytes the Rust + /// layout assigns. + fn layout_roles(layout: IdentityCreationKeyLayoutFFI) -> Vec<(u32, u8, u8, u8)> { + IdentityCreationKeyLayout::from(layout) + .slots() + .iter() + .map(|s| { + ( + s.key_id, + s.key_type as u8, + s.purpose as u8, + s.security_level as u8, + ) + }) + .collect() + } - let captured = unsafe { (*capture).rows.lock().unwrap().clone() }; - assert_eq!(captured.len(), 4); - - // Slots 0/1/2 are unchanged from the legacy 3-key layout: - // AUTHENTICATION with MASTER / CRITICAL / HIGH respectively. - for (i, expected_level) in [ - SECURITY_LEVEL_MASTER, - SECURITY_LEVEL_CRITICAL, - SECURITY_LEVEL_HIGH, - ] - .iter() - .enumerate() - { - assert_eq!(captured[i].key_type, KEY_TYPE_ECDSA_SECP256K1); - assert_eq!(captured[i].purpose, PURPOSE_AUTHENTICATION); - assert_eq!(captured[i].security_level, *expected_level); - } + fn captured_roles(captured: &[CapturedPersist]) -> Vec<(u32, u8, u8, u8)> { + captured + .iter() + .map(|r| (r.key_id, r.key_type, r.purpose, r.security_level)) + .collect() + } - // Slot 3 is the new TRANSFER / CRITICAL key required to sign - // IdentityCreditTransfer (ID-04) / IdentityCreditWithdrawal - // (ID-10) — without it those broadcasts fail on-chain with - // "no transfer public key". - let transfer = &captured[3]; - assert_eq!(transfer.key_id, 3); - assert_eq!(transfer.key_index, 3); - assert_eq!(transfer.key_type, KEY_TYPE_ECDSA_SECP256K1); - assert_eq!(transfer.purpose, PURPOSE_TRANSFER); - assert_eq!(transfer.security_level, SECURITY_LEVEL_CRITICAL); - assert_eq!(transfer.public_key.len(), 33); - assert_eq!(transfer.private_key.len(), 32); - assert_eq!(transfer.path, "m/9'/1'/5'/0'/0'/7'/3'"); + #[test] + fn should_persist_every_key_of_the_rust_layout_with_its_role() { + for layout in [ + IdentityCreationKeyLayoutFFI::NewIdentity, + IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys, + ] { + let (captured, pubkeys) = derive_and_capture(layout); + assert_eq!( + captured_roles(&captured), + layout_roles(layout), + "{layout:?}" + ); + let persisted: Vec> = captured.iter().map(|r| r.public_key.clone()).collect(); + assert_eq!(pubkeys, persisted, "{layout:?}"); + } + } - unsafe { - crate::dash_sdk_derive_identity_keys_from_mnemonic_free(&mut out); - dash_sdk_mnemonic_resolver_destroy(resolver); - dash_sdk_identity_key_persister_destroy(persister); - let _ = Box::from_raw(capture); + #[test] + fn should_derive_the_same_base_keys_with_and_without_dashpay_keys() { + // Ids 0-3 derive the same keys with the same roles in both layouts, + // at DIP-9 key index = key id; the DashPay layout adds ids 4-5. + let (base, _) = derive_and_capture(IdentityCreationKeyLayoutFFI::NewIdentity); + let (with_dashpay, _) = + derive_and_capture(IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys); + assert_eq!((base.len(), with_dashpay.len()), (4, 6)); + for (old, new) in base.iter().zip(&with_dashpay) { + assert_eq!(old.key_id, new.key_id); + assert_eq!(old.public_key, new.public_key); + assert_eq!( + (old.purpose, old.security_level), + (new.purpose, new.security_level) + ); } + assert_eq!(base[3].path, "m/9'/1'/5'/0'/0'/7'/3'"); + assert_eq!( + [captured_roles(&base)[3]], + [( + 3, + KeyType::ECDSA_SECP256K1 as u8, + Purpose::TRANSFER as u8, + SecurityLevel::CRITICAL as u8 + )] + ); + assert_eq!( + (with_dashpay[4].purpose, with_dashpay[5].purpose), + (Purpose::ENCRYPTION as u8, Purpose::DECRYPTION as u8) + ); } #[test] @@ -711,7 +645,7 @@ mod tests { FFINetwork::Testnet, wallet_id.as_ptr(), 0, - 2, + IdentityCreationKeyLayoutFFI::NewIdentity, resolver, persister, &mut out, @@ -736,7 +670,7 @@ mod tests { FFINetwork::Testnet, wallet_id.as_ptr(), 0, - 1, + IdentityCreationKeyLayoutFFI::NewIdentity, resolver, persister, std::ptr::null_mut(), @@ -754,7 +688,7 @@ mod tests { FFINetwork::Testnet, std::ptr::null(), 0, - 1, + IdentityCreationKeyLayoutFFI::NewIdentity, resolver, persister, &mut out, @@ -767,33 +701,4 @@ mod tests { let _ = Box::from_raw(capture); } } - - #[test] - fn key_count_zero_is_success_no_calls() { - let (resolver, persister, capture) = make_capturing_handles(); - let wallet_id = [0u8; 32]; - let mut out = IdentityRegistrationKeyDerivationsFFI { - items: std::ptr::null_mut(), - count: 0, - }; - let rc = unsafe { - dash_sdk_derive_and_persist_identity_keys( - FFINetwork::Testnet, - wallet_id.as_ptr(), - 0, - 0, - resolver, - persister, - &mut out, - ) - }; - assert_eq!(rc.code, PlatformWalletFFIResultCode::Success); - assert_eq!(out.count, 0); - assert_eq!(unsafe { (*capture).rows.lock().unwrap().len() }, 0); - unsafe { - dash_sdk_mnemonic_resolver_destroy(resolver); - dash_sdk_identity_key_persister_destroy(persister); - let _ = Box::from_raw(capture); - } - } } diff --git a/packages/rs-platform-wallet-ffi/src/identity_key_preview.rs b/packages/rs-platform-wallet-ffi/src/identity_key_preview.rs index a1f81582de3..b467e1eb6ae 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_key_preview.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_key_preview.rs @@ -68,32 +68,15 @@ use dashcore::PrivateKey as DashPrivateKey; use key_wallet::bip32::ExtendedPrivKey; use key_wallet::Wallet; use platform_wallet::wallet::identity::network::derive_ecdsa_identity_auth_keypair_from_master; -use platform_wallet::{derive_identity_auth_keypair, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX}; +use platform_wallet::{ + derive_identity_auth_keypair, IdentityCreationKeyLayout, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, +}; use zeroize::{Zeroize, Zeroizing}; use crate::error::*; use crate::handle::*; +use crate::identity_creation_key_layout::IdentityCreationKeyLayoutFFI; -/// Canonical default number of keys a freshly-created identity is -/// provisioned with — the set -/// [`platform_wallet_preview_identity_registration_key_set`] derives -/// when the caller passes `count < 0`. -/// -/// Mirrors the iOS reference (`CreateIdentityView.defaultKeyCount` / -/// the per-slot table in `identity_derive_and_persist.rs`): -/// - keyId 0 → AUTHENTICATION / MASTER (signs IdentityCreate / IdentityUpdate) -/// - keyId 1 → AUTHENTICATION / CRITICAL (signs token state transitions) -/// - keyId 2 → AUTHENTICATION / HIGH (general document operations) -/// - keyId 3 → TRANSFER / CRITICAL (signs IdentityCreditTransfer / …Withdrawal) -/// -/// Without the CRITICAL auth key (keyId 1) the identity cannot mint / -/// burn / freeze tokens; without the TRANSFER key (keyId 3) credit -/// transfers and withdrawals are rejected on-chain with "no transfer -/// public key". This preview row carries only the derived keypair — the -/// DPP role→keyId mapping lives with each host's registration policy (the -/// Kotlin `RegistrationKeys` table / the Swift create-identity flow), which -/// stamps the role onto the registration wire rows. -pub const IDENTITY_REGISTRATION_KEY_SET_COUNT: u32 = 4; use crate::identity_keys_from_mnemonic::{resolve_master_from_resolver, zeroize_and_free_row}; use crate::types::Network; use crate::{check_ptr, unwrap_option_or_return, unwrap_result_or_return}; @@ -256,10 +239,11 @@ pub unsafe extern "C" fn platform_wallet_preview_identity_registration_keys( ) } -/// Derive the full identity-registration key **set** for a single -/// identity: keyId 0..`count_or_neg1` at the fixed identity index -/// `start_index`, on the DIP-9 identity-authentication path -/// `m/9'/coin'/5'/0'/0'/start_index'/keyId'`. +/// Derive the full identity-registration key **set** of `layout` for a +/// single identity: one keypair per slot of the +/// [`platform_wallet::IdentityCreationKeyLayout`], in key-id order, at the +/// fixed identity index on the DIP-9 identity-authentication path +/// `m/9'/coin'/5'/0'/0'/identity_index'/key_index'` (key index = key id). /// /// This is the sibling of /// [`platform_wallet_preview_identity_registration_keys`] — that @@ -268,18 +252,12 @@ pub unsafe extern "C" fn platform_wallet_preview_identity_registration_keys( /// identity index and walks the *key* index, so it surfaces every /// keypair a freshly-created identity is built from. /// -/// The rows come back in keyId order. The **per-key DPP role** (purpose -/// / security level) is NOT encoded on the row — every row derives an -/// ECDSA_SECP256K1 keypair, and the host's registration policy stamps the -/// purpose / security level (and any contract bounds) by keyId when it builds -/// the registration wire rows (the Kotlin `RegistrationKeys` table / the Swift -/// create-identity flow). -/// -/// `count_or_neg1 < 0` derives the canonical default set -/// ([`IDENTITY_REGISTRATION_KEY_SET_COUNT`] = 4: MASTER auth, CRITICAL -/// auth, HIGH auth, TRANSFER/CRITICAL). Release the result with -/// [`platform_wallet_preview_identity_registration_keys_free`] — same -/// row layout, same free function. +/// The rows carry the keypairs only. The role of each key (type, purpose, +/// security level, contract bounds) comes from the same layout through +/// [`crate::platform_wallet_identity_creation_key_layout`]; hosts stamp it +/// from there and decide nothing themselves. Release the result with +/// [`platform_wallet_preview_identity_registration_keys_free`] — same row +/// layout, same free function. /// /// # Safety /// Same contract as @@ -289,14 +267,12 @@ pub unsafe extern "C" fn platform_wallet_preview_identity_registration_key_set( wallet_handle: Handle, mnemonic_resolver_handle: *mut MnemonicResolverHandle, identity_index: u32, - count_or_neg1: i32, + layout: IdentityCreationKeyLayoutFFI, out_previews: *mut IdentityKeyPreviewsFFI, ) -> PlatformWalletFFIResult { - let count = if count_or_neg1 < 0 { - IDENTITY_REGISTRATION_KEY_SET_COUNT as i32 - } else { - count_or_neg1 - }; + // Key ids are contiguous from 0 and each key derives at its own id, so + // walking key indices 0..len derives exactly the layout's slots. + let count = IdentityCreationKeyLayout::from(layout).key_count() as i32; preview_identity_registration_keys_inner( wallet_handle, mnemonic_resolver_handle, diff --git a/packages/rs-platform-wallet-ffi/src/lib.rs b/packages/rs-platform-wallet-ffi/src/lib.rs index 609f72d136a..6c7ecfa09cc 100644 --- a/packages/rs-platform-wallet-ffi/src/lib.rs +++ b/packages/rs-platform-wallet-ffi/src/lib.rs @@ -37,6 +37,7 @@ pub mod error; pub mod established_contact; pub mod event_handler; pub mod handle; +pub mod identity_creation_key_layout; pub mod identity_derive_and_persist; pub mod identity_discovery; pub mod identity_key_limits; @@ -125,6 +126,7 @@ pub use error::*; pub use established_contact::*; pub use event_handler::*; pub use handle::*; +pub use identity_creation_key_layout::*; pub use identity_derive_and_persist::*; pub use identity_discovery::*; pub use identity_key_preview::*; diff --git a/packages/rs-unified-sdk-jni/src/identity.rs b/packages/rs-unified-sdk-jni/src/identity.rs index f7249a3118d..45449921fdb 100644 --- a/packages/rs-unified-sdk-jni/src/identity.rs +++ b/packages/rs-unified-sdk-jni/src/identity.rs @@ -34,12 +34,16 @@ use crate::pubkey_rows::decode_registration_pubkeys_blob; use crate::support::{guard, net_from_ord, take_pwffi_error, throw_sdk_exception}; use jni::objects::{JByteArray, JClass, JString, JValue}; -use jni::sys::{jboolean, jbyteArray, jint, jlong, jobject}; +use jni::sys::{jboolean, jbyteArray, jint, jlong, jlongArray, jobject}; use jni::JNIEnv; use platform_wallet_ffi::core_wallet_types::OutPointFFI; use platform_wallet_ffi::derive_connect_key::ConnectDerivedKeyFFI; use platform_wallet_ffi::error::{platform_wallet_ffi_result_free, PlatformWalletFFIResult}; use platform_wallet_ffi::handle::Handle; +use platform_wallet_ffi::identity_creation_key_layout::{ + IdentityCreationFeesFFI, IdentityCreationKeyLayoutFFI, IdentityCreationKeySlotFFI, + IdentityCreationKeySlotsFFI, +}; use platform_wallet_ffi::identity_discovery::DiscoveredIdentityIdsFFI; use platform_wallet_ffi::identity_key_preview::{IdentityKeyPreviewFFI, IdentityKeyPreviewsFFI}; use platform_wallet_ffi::identity_registration::IdentityFundingInputFFI; @@ -198,20 +202,17 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_previe }) } -/// Derive the full identity-registration key **set** for a single -/// identity: keyId 0..`count` at the fixed `identityIndex`. Unlike -/// [`Java_..._previewRegistrationKeys`] (which fixes the MASTER key slot -/// and walks the *identity* index for the discovery preview), this fixes -/// the identity index and walks the *key* index — so it returns every -/// keypair a freshly-created identity is built from (keyId 0..N). +/// Derive the full identity-registration key **set** of one creation key +/// layout for a single identity: one keypair per slot, in key-id order, at +/// the fixed `identityIndex`. Unlike [`Java_..._previewRegistrationKeys`] +/// (which fixes the MASTER key slot and walks the *identity* index for the +/// discovery preview), this fixes the identity index and walks the *key* +/// index. /// -/// `count < 0` derives the canonical default set -/// (`IDENTITY_REGISTRATION_KEY_SET_COUNT` = 4: MASTER auth, CRITICAL -/// auth, HIGH auth, TRANSFER/CRITICAL). The create-identity flow may request -/// more (e.g. 6, appending the DashPay ENCRYPTION/DECRYPTION pair). Every row -/// is an ECDSA_SECP256K1 keypair; the DPP role for each keyId is stamped by -/// the Kotlin side (`RegistrationKeys`) and shipped on the registration wire, -/// not carried on this derived row. +/// `layout` is the `IdentityCreationKeyLayout` ordinal (see +/// [`layout_from_ord`]). Every row is an ECDSA_SECP256K1 keypair; the DPP +/// role of each key comes from the same Rust layout through +/// [`Java_..._identityCreationKeyLayout`], not from Kotlin. /// /// Returns the same flat `byte[]` BLOB layout as /// [`Java_..._previewRegistrationKeys`], decoded by @@ -224,13 +225,21 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_previe wallet_handle: jlong, resolver_handle: jlong, identity_index: jint, - count: jint, + layout: jint, ) -> jbyteArray { guard(&mut env, ptr::null_mut(), |env| { if identity_index < 0 { throw_sdk_exception(env, 1, "identityIndex must be non-negative"); return ptr::null_mut(); } + let Some(layout) = layout_from_ord(layout) else { + throw_sdk_exception( + env, + 1, + &format!("unknown identity creation key layout {layout}"), + ); + return ptr::null_mut(); + }; let mut previews = IdentityKeyPreviewsFFI { items: ptr::null_mut(), count: 0, @@ -240,7 +249,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_previe wallet_handle as Handle, resolver_handle as *mut MnemonicResolverHandle, identity_index as u32, - count, + layout, &mut previews as *mut IdentityKeyPreviewsFFI, ) }; @@ -266,6 +275,109 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_previe }) } +/// Map the Kotlin `IdentityCreationKeyLayout` ordinal to the FFI enum: +/// `0` new identity, `1` new identity with DashPay keys. `None` for any +/// other value. +fn layout_from_ord(ord: jint) -> Option { + match ord { + 0 => Some(IdentityCreationKeyLayoutFFI::NewIdentity), + 1 => Some(IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys), + _ => None, + } +} + +/// The key layout an identity-creation flow registers, from +/// `platform_wallet_identity_creation_key_layout`. `layout` is the ordinal +/// of [`layout_from_ord`]. +/// +/// Returns a flat `byte[]` BLOB (all integers big-endian), decoded by +/// `RegistrationKeys.decodeLayout`: +/// +/// ```text +/// u32 row_count +/// repeat row_count times: +/// u32 key_id +/// u32 derivation_key_index +/// u8 key_type, u8 purpose, u8 security_level (DPP discriminants) +/// u8 contract_bounds_kind (0 none, 1 SingleContract, 2 SingleContractDocumentType) +/// if contract_bounds_kind != 0: u8[32] contract_bounds_id +/// if contract_bounds_kind == 2: u16 doc_type_len, u8[doc_type_len] doc_type (UTF-8) +/// ``` +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_identityCreationKeyLayout( + mut env: JNIEnv, + _class: JClass, + layout: jint, +) -> jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + let Some(layout) = layout_from_ord(layout) else { + throw_sdk_exception( + env, + 1, + &format!("unknown identity creation key layout {layout}"), + ); + return ptr::null_mut(); + }; + let mut slots = IdentityCreationKeySlotsFFI { + items: ptr::null_mut(), + count: 0, + }; + let result = unsafe { + platform_wallet_ffi::platform_wallet_identity_creation_key_layout(layout, &mut slots) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + let blob = unsafe { encode_layout_rows(&slots) }; + unsafe { + platform_wallet_ffi::platform_wallet_identity_creation_key_layout_free(&mut slots) + }; + env.byte_array_from_slice(&blob) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Serialize layout rows into the BLOB documented on +/// [`Java_..._identityCreationKeyLayout`]. +/// +/// # Safety +/// `slots` must be a populated `IdentityCreationKeySlotsFFI` with `count` +/// valid rows (or an empty struct). +unsafe fn encode_layout_rows(slots: &IdentityCreationKeySlotsFFI) -> Vec { + let rows: &[IdentityCreationKeySlotFFI] = if slots.items.is_null() { + &[] + } else { + std::slice::from_raw_parts(slots.items, slots.count) + }; + let mut out = Vec::new(); + out.extend_from_slice(&(rows.len() as u32).to_be_bytes()); + for row in rows { + out.extend_from_slice(&row.key_id.to_be_bytes()); + out.extend_from_slice(&row.derivation_key_index.to_be_bytes()); + out.extend_from_slice(&[ + row.key_type, + row.purpose, + row.security_level, + row.contract_bounds_kind, + ]); + if row.contract_bounds_kind != 0 { + out.extend_from_slice(&row.contract_bounds_id); + } + if row.contract_bounds_kind == 2 { + let name = if row.contract_bounds_document_type.is_null() { + &[][..] + } else { + CStr::from_ptr(row.contract_bounds_document_type).to_bytes() + }; + // Document type names are capped at 64 bytes by DPP. + out.extend_from_slice(&(name.len() as u16).to_be_bytes()); + out.extend_from_slice(name); + } + } + out +} + /// Serialize the preview rows into the BLOB layout documented on /// [`Java_..._previewRegistrationKeys`]. Copies every field out of the /// FFI buffer so the caller can free it immediately after. @@ -649,6 +761,118 @@ fn connect_key_to_java( // ── Registration (wallet-balance funded) ────────────────────────────── +/// The minimum asset-lock value (duffs) that registers the layout with +/// ordinal `layout` at the wallet's platform version, from +/// `platform_wallet_identity_creation_min_funding_duffs`. Kotlin shows and +/// enforces it instead of keeping a copy of the fee schedule. Returns `-1` +/// with a pending `DashSDKException` on error. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_identityCreationMinFundingDuffs( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + layout: jint, +) -> jlong { + guard(&mut env, -1, |env| { + let Some(layout) = layout_from_ord(layout) else { + throw_sdk_exception( + env, + 1, + &format!("unknown identity creation key layout {layout}"), + ); + return -1; + }; + let mut duffs = 0u64; + let result = unsafe { + platform_wallet_ffi::platform_wallet_identity_creation_min_funding_duffs( + wallet_handle as Handle, + layout, + &mut duffs, + ) + }; + if take_pwffi_error(env, result) { + return -1; + } + match jlong::try_from(duffs) { + Ok(duffs) => duffs, + Err(_) => { + throw_sdk_exception(env, 1, "identity creation minimum exceeds a Java long"); + -1 + } + } + }) +} + +/// The minimum fees (credits) of an address-funded identity create of the +/// layout with ordinal `layout`, without a refund output, at the wallet's +/// platform version: element `n - 1` is the fee with `n` inputs, and the +/// length is the protocol's maximum input count. Thin marshal of +/// `platform_wallet_identity_creation_from_addresses_min_fees`. Returns +/// `null` with a pending `DashSDKException` on error. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_identityCreationFromAddressesMinFees( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + layout: jint, +) -> jlongArray { + guard(&mut env, ptr::null_mut(), |env| { + let Some(layout) = layout_from_ord(layout) else { + throw_sdk_exception( + env, + 1, + &format!("unknown identity creation key layout {layout}"), + ); + return ptr::null_mut(); + }; + let mut fees = IdentityCreationFeesFFI { + items: ptr::null_mut(), + count: 0, + }; + let result = unsafe { + platform_wallet_ffi::platform_wallet_identity_creation_from_addresses_min_fees( + wallet_handle as Handle, + layout, + &mut fees, + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + let values: Option> = if fees.items.is_null() { + Some(Vec::new()) + } else { + unsafe { std::slice::from_raw_parts(fees.items, fees.count) } + .iter() + .map(|fee| jlong::try_from(*fee).ok()) + .collect() + }; + unsafe { + platform_wallet_ffi::platform_wallet_identity_creation_from_addresses_min_fees_free( + &mut fees, + ) + }; + let Some(values) = values else { + throw_sdk_exception(env, 1, "identity creation fee exceeds a Java long"); + return ptr::null_mut(); + }; + let Ok(len) = jint::try_from(values.len()) else { + throw_sdk_exception(env, 1, "too many identity creation fees"); + return ptr::null_mut(); + }; + match env.new_long_array(len) { + Ok(arr) => { + if env.set_long_array_region(&arr, 0, &values).is_err() { + ptr::null_mut() + } else { + arr.into_raw() + } + } + Err(_) => ptr::null_mut(), + } + }) +} + /// Resume a previously interrupted identity registration from a tracked /// asset-lock outpoint. The returned managed-identity handle is transferred /// to Kotlin only after the result object is constructed successfully; every @@ -1307,10 +1531,19 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_IdentityNative_update #[cfg(test)] mod tests { + use super::{encode_layout_rows, layout_from_ord}; + use dpp::data_contracts::SystemDataContract; use platform_wallet_ffi::derive_connect_key::{ CONNECT_KEY_PURPOSE_DECRYPTION, CONNECT_KEY_PURPOSE_ENCRYPTION, CONNECT_KEY_SUB_FEATURE_APP_ENCRYPTION, CONNECT_KEY_SUB_FEATURE_SESSION_AUTHENTICATION, }; + use platform_wallet_ffi::identity_creation_key_layout::{ + IdentityCreationKeyLayoutFFI, IdentityCreationKeySlotsFFI, + }; + use platform_wallet_ffi::{ + platform_wallet_identity_creation_key_layout, + platform_wallet_identity_creation_key_layout_free, PlatformWalletFFIResultCode, + }; const PLATFORM_WALLET_MANAGER_KT: &str = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), @@ -1339,4 +1572,61 @@ mod tests { ); } } + + fn layout_blob(ord: i32) -> Vec { + let layout = layout_from_ord(ord).expect("known layout ordinal"); + let mut slots = IdentityCreationKeySlotsFFI { + items: std::ptr::null_mut(), + count: 0, + }; + let result = unsafe { platform_wallet_identity_creation_key_layout(layout, &mut slots) }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + let blob = unsafe { encode_layout_rows(&slots) }; + unsafe { platform_wallet_identity_creation_key_layout_free(&mut slots) }; + blob + } + + /// Golden layout BLOBs shared byte-for-byte with the Kotlin decoder test + /// (`RegistrationKeysTest`), so an encoder/decoder skew fails one side. + const GOLDEN_NEW_IDENTITY: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_v1.bin" + )); + const GOLDEN_WITH_DASHPAY_KEYS: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../kotlin-sdk/sdk/src/test/resources/golden/identity_creation_key_layout_new_identity_with_dashpay_keys_v1.bin" + )); + + #[test] + fn should_encode_the_new_identity_layout() { + assert_eq!(layout_blob(0), GOLDEN_NEW_IDENTITY); + } + + #[test] + fn should_encode_the_dashpay_layout_with_contact_request_bounds() { + let blob = layout_blob(1); + assert_eq!(blob, GOLDEN_WITH_DASHPAY_KEYS); + // The golden file pins the real DashPay contract id, not a mirror. + let dashpay = SystemDataContract::Dashpay.id().to_buffer(); + assert_eq!(blob.windows(32).filter(|w| *w == dashpay).count(), 2); + } + + #[test] + fn should_map_the_kotlin_layout_ordinals() { + assert_eq!( + layout_from_ord(0), + Some(IdentityCreationKeyLayoutFFI::NewIdentity) + ); + assert_eq!( + layout_from_ord(1), + Some(IdentityCreationKeyLayoutFFI::NewIdentityWithDashPayKeys) + ); + } + + #[test] + fn should_reject_an_unknown_layout_ordinal() { + // `2` was the removed asset-lock resume layout. + assert!(layout_from_ord(2).is_none()); + assert!(layout_from_ord(-1).is_none()); + } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index bbab259f54e..1f9d218df1f 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -1766,6 +1766,102 @@ extension ManagedPlatformWallet { ) } + /// Which key layout an identity-creation flow registers. Mirrors + /// Rust's `platform_wallet::IdentityCreationKeyLayout`; the layout + /// itself (key ids, roles, bounds) is read from Rust, never decided + /// here. + public enum IdentityCreationKeyLayout: Sendable, Equatable { + /// A new identity without DashPay keys; also what a resume of a + /// tracked registration asset lock re-derives. + case newIdentity + /// A new identity with the DashPay ENCRYPTION / DECRYPTION keys. + case newIdentityWithDashPayKeys + + var ffiValue: IdentityCreationKeyLayoutFFI { + switch self { + case .newIdentity: + return IDENTITY_CREATION_KEY_LAYOUT_FFI_NEW_IDENTITY + case .newIdentityWithDashPayKeys: + return IDENTITY_CREATION_KEY_LAYOUT_FFI_NEW_IDENTITY_WITH_DASH_PAY_KEYS + } + } + } + + /// One key of an `IdentityCreationKeyLayout`, as Rust defines it. + public struct IdentityCreationKeySlot: Sendable, Equatable { + public let keyId: UInt32 + /// DIP-9 key index the key is derived at. + public let derivationKeyIndex: UInt32 + public let keyType: KeyType + public let purpose: KeyPurpose + public let securityLevel: SecurityLevel + public let contractBounds: ContractBounds? + } + + /// The slots of `layout`, in key-id order, from + /// `platform_wallet_identity_creation_key_layout`. Use `.count` to size + /// the creation fee. + public static func identityCreationKeyLayout( + _ layout: IdentityCreationKeyLayout + ) throws -> [IdentityCreationKeySlot] { + var out = IdentityCreationKeySlotsFFI() + let result = platform_wallet_identity_creation_key_layout(layout.ffiValue, &out) + defer { platform_wallet_identity_creation_key_layout_free(&out) } + try result.check() + guard let base = out.items, out.count > 0 else { return [] } + + var slots: [IdentityCreationKeySlot] = [] + slots.reserveCapacity(Int(out.count)) + for i in 0.. [IdentityPubkey] { - guard keyCount > 0 else { return [] } + let slots = try Self.identityCreationKeyLayout(layout) // Single-FFI derivation + persist. The mnemonic is pulled // from Keychain by the resolver callback (Rust → Swift), @@ -1859,7 +1953,7 @@ extension ManagedPlatformWallet { network.ffiValue, walletPtr, identityIndex, - keyCount, + layout.ffiValue, resolver.handle, persister.handle, &out @@ -1872,10 +1966,10 @@ extension ManagedPlatformWallet { guard let base = out.items, out.count > 0 else { return [] } // Build `IdentityPubkey` rows from (a) the FFI's pubkey - // bytes and (b) the persister's captured per-key metadata - // — both indexed in derivation order. Rust decided - // (keyType, purpose, securityLevel); Swift just maps each - // discriminant byte back into its strongly-typed enum. + // bytes, (b) the persister's captured per-key metadata and + // (c) the Rust layout's contract bounds — all indexed in + // derivation order. Rust decided every role; Swift just maps + // each discriminant byte back into its strongly-typed enum. // // Both an FFI/Swift count drift AND any unknown enum // discriminant byte are surfaced as a recoverable @@ -1887,10 +1981,10 @@ extension ManagedPlatformWallet { // fail loudly so the caller learns about the ABI break // immediately. let captured = persister.persistedKeys - guard captured.count == Int(out.count), Int(out.count) == Int(keyCount) else { + guard captured.count == Int(out.count), Int(out.count) == slots.count else { throw PlatformWalletError.walletOperation( "derive_and_persist_identity_keys returned \(out.count) pubkeys for " - + "\(keyCount) requested keys; persister captured \(captured.count)" + + "\(slots.count) layout keys; persister captured \(captured.count)" ) } @@ -1924,6 +2018,12 @@ extension ManagedPlatformWallet { + "securityLevel=\(meta.securityLevel)) for keyId=\(meta.keyId)" ) } + guard meta.keyId == slots[i].keyId else { + throw PlatformWalletError.walletOperation( + "derive_and_persist_identity_keys row \(i) has keyId=\(meta.keyId), " + + "layout expects \(slots[i].keyId)" + ) + } pubkeys.append( IdentityPubkey( keyId: meta.keyId, @@ -1931,7 +2031,8 @@ extension ManagedPlatformWallet { purpose: purpose, securityLevel: securityLevel, pubkeyBytes: pubData, - readOnly: false + readOnly: false, + contractBounds: slots[i].contractBounds ) ) } @@ -5294,6 +5395,24 @@ extension ManagedPlatformWallet { }.value } + /// The minimum asset-lock value (duffs) that registers `layout` at + /// this wallet's platform version + /// (`platform_wallet_identity_creation_min_funding_duffs`), from Rust's + /// versioned fee schedule. Show and enforce it; never recompute it from + /// fee constants. Rust refuses a wallet-funded registration, or the + /// resume of a tracked lock, below it. + public func identityCreationMinFundingDuffs( + layout: IdentityCreationKeyLayout + ) throws -> UInt64 { + var duffs: UInt64 = 0 + try platform_wallet_identity_creation_min_funding_duffs( + self.handle, + layout.ffiValue, + &duffs + ).check() + return duffs + } + /// Resume identity registration from an existing tracked asset lock. /// /// Sibling to @@ -5312,8 +5431,8 @@ extension ManagedPlatformWallet { /// caller is responsible for decoding back from the display-order /// hex before passing in. /// - /// Caller MUST pre-derive `identityPubkeys` (typically via - /// `dash_sdk_derive_identity_keys_from_mnemonic`) AND pre-persist + /// Caller MUST pre-derive `identityPubkeys` from the `.newIdentity` + /// layout AND pre-persist /// each key's private material to the Keychain using /// `prePersistIdentityKeysForRegistration` BEFORE calling this — /// same precondition as `registerIdentityWithFunding`. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationKeys.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationKeys.swift deleted file mode 100644 index 8b8a7acf665..00000000000 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Services/IdentityRegistrationKeys.swift +++ /dev/null @@ -1,122 +0,0 @@ -import Foundation -import SwiftDashSDK - -/// Identity-registration key derivation used by the invitation-claim flow. -/// -/// Claiming an invitation is ordinary identity registration funded by the -/// imported voucher, so the invitee's keys are derived exactly as for a normal -/// new-identity registration — including the DashPay Encryption/Decryption pair -/// that lets the new identity send a contact request back to the inviter. -/// -/// `makeDashpayKeyPair` is intentionally a MIRROR of -/// `CreateIdentityView.makeDashpayKeyPair`; any change to the DashPay-key -/// derivation policy must be made in both (a future refactor should unify them). -enum IdentityRegistrationKeys { - /// DashPay data-contract id — the enc/dec keys are contract-bounded to it. - static let dashpayContractId = Data([ - 162, 161, 180, 172, 111, 239, 34, 234, - 42, 26, 104, 232, 18, 54, 68, 179, - 87, 135, 95, 107, 65, 44, 24, 16, - 146, 129, 193, 70, 231, 178, 113, 188, - ]) - - /// DashPay document type these keys are bound to — the only one in the - /// contract that declares `requiresIdentityEncryptionBoundedKey`. - static let dashpayContactRequestDocumentType = "contactRequest" - - /// Derive + persist the DashPay Encryption (kid=firstKeyId) + Decryption - /// (kid=firstKeyId+1) key pair for a registering/claiming identity, bounded - /// to DashPay's `contactRequest` document type, MEDIUM security level, - /// ECDSA-secp256k1. Each key is cross-checked against its public key and - /// written to the Keychain by pubkey hash so the signing trampoline can find - /// it, then returned as `IdentityPubkey` rows to append to the registration / - /// claim key set. - @MainActor - static func makeDashpayKeyPair( - managedWallet: ManagedPlatformWallet, - walletId: Data, - identityIndex: UInt32, - firstKeyId: UInt32, - network: Network - ) throws -> [ManagedPlatformWallet.IdentityPubkey] { - let purposes: [(keyId: UInt32, purpose: KeyPurpose)] = [ - (firstKeyId, .encryption), - (firstKeyId + 1, .decryption), - ] - let bounds: ManagedPlatformWallet.ContractBounds = .singleContractDocumentType( - id: dashpayContractId, - documentTypeName: dashpayContactRequestDocumentType - ) - let walletIdHex = walletId.toHexString() - // Overwritten by the persister callback when the identity actually lands - // on-chain; the metadata written here only needs to satisfy the keychain - // round-trip lookup by pubkey hex. - let identityIdPlaceholder = "" - - var rows: [ManagedPlatformWallet.IdentityPubkey] = [] - rows.reserveCapacity(purposes.count) - - for (keyId, purpose) in purposes { - let preview = try managedWallet.deriveIdentityAuthKeyAtSlot( - identityIndex: identityIndex, - keyId: keyId, - network: network - ) - - // Defence against derivation drift / FFI marshalling bugs. A - // mismatched DashPay key lands on Platform as a key the trampoline - // can't sign with and surfaces as an opaque "encrypted xpub" failure - // on the first contact-request flow — much harder to debug after the - // fact than failing fast here. - guard - KeyValidation.validatePrivateKeyForPublicKey( - privateKeyHex: preview.privateKeyData.toHexString(), - publicKeyHex: preview.publicKeyHex, - keyType: .ecdsaSecp256k1, - network: network - ) - else { - throw PlatformWalletError.walletOperation( - "Derived DashPay key (kid \(keyId), purpose \(purpose.name)) didn't match its public key — refusing to persist" - ) - } - - let pubKeyHashHex = SwiftDashSDK.KeychainManager.computePublicKeyHashHex( - preview.publicKeyData - ) - let metadata = IdentityPrivateKeyMetadata( - identityId: identityIdPlaceholder, - keyId: keyId, - walletId: walletIdHex, - identityIndex: identityIndex, - keyIndex: keyId, - derivationPath: preview.derivationPath, - publicKey: preview.publicKeyHex, - publicKeyHash: pubKeyHashHex, - keyType: KeyType.ecdsaSecp256k1.rawValue, - purpose: purpose.rawValue, - securityLevel: SecurityLevel.medium.rawValue - ) - guard KeychainManager.shared.storeIdentityPrivateKey( - preview.privateKeyData, - derivationPath: preview.derivationPath, - metadata: metadata - ) != nil else { - throw PlatformWalletError.walletOperation( - "Could not persist DashPay key (kid \(keyId), purpose \(purpose.name)) to Keychain" - ) - } - rows.append( - ManagedPlatformWallet.IdentityPubkey( - keyId: keyId, - keyType: .ecdsaSecp256k1, - purpose: purpose, - securityLevel: .medium, - pubkeyBytes: preview.publicKeyData, - contractBounds: bounds - ) - ) - } - return rows - } -} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift index d47274cd161..999294bb171 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift @@ -64,45 +64,6 @@ struct CreateIdentityView: View { @EnvironmentObject var walletManager: PlatformWalletManager @EnvironmentObject var platformState: AppState - /// Default number of Platform identity keys to register in this - /// first-pass flow. The Rust-owned per-slot policy - /// (`dash_sdk_derive_and_persist_identity_keys`) maps these to: - /// key 0 AUTHENTICATION/MASTER, key 1 AUTHENTICATION/CRITICAL, - /// key 2 AUTHENTICATION/HIGH, key 3 TRANSFER/CRITICAL. The - /// TRANSFER/CRITICAL key is required to sign IdentityCreditTransfer - /// (ID-04) and IdentityCreditWithdrawal (ID-10) — without it those - /// broadcasts are rejected on-chain with "no transfer public key". - /// Advanced override is intentionally not exposed here yet. - private static let defaultKeyCount: UInt32 = 4 - - /// Number of extra keys added when `addDashPayKeys` is on - /// (encryption + decryption). - private static let dashPayExtraKeyCount: UInt32 = 2 - - /// Per-key cost in credits (from - /// `IdentityCreateTransition::calculate_min_required_fee_v1`). - /// Used to scale the asset-lock minimum when extra keys are - /// requested. - private static let identityKeyCreationCostCredits: UInt64 = 6_500_000 - - /// DashPay system contract id (32 bytes), source-of-truth - /// `packages/dashpay-contract/src/lib.rs::ID_BYTES`. Mirrored - /// here so the contract-bounds payload for the optional - /// encryption/decryption keys can be built without a contract - /// fetch round-trip. Also matches the registry in - /// `AddIdentityKeyView.systemContractsAllowingKeyBounds`. - private static let dashpayContractId = Data([ - 162, 161, 180, 172, 111, 239, 34, 234, - 42, 26, 104, 232, 18, 54, 68, 179, - 87, 135, 95, 107, 65, 44, 24, 16, - 146, 129, 193, 70, 231, 178, 113, 188, - ]) - - /// DashPay document type these keys are bound to — the only - /// one in the contract that declares - /// `requiresIdentityEncryptionBoundedKey`. - private static let dashpayContactRequestDocumentType = "contactRequest" - /// Credits per DASH (1e11) — the divisor used for Platform-side /// credit amounts. Duplicated from `PersistentPlatformAddress` /// docstring; kept here so the conversion logic stays local. @@ -119,8 +80,7 @@ struct CreateIdentityView: View { /// `packages/rs-platform-version/src/version/drive_abci_versions/` /// `drive_abci_validation_versions/` (`v8.rs` pre-v13, `v9.rs` /// from v13). There is no FFI getter for this set, so it's - /// mirrored here — same precedent as - /// `identityKeyCreationCostCredits` / `dashpayContractId`. If the + /// mirrored here. If the /// versioned set changes on the Rust side, update these constants /// to match (a submitted denomination not in the on-chain set is /// rejected at validation). @@ -161,31 +121,6 @@ struct CreateIdentityView: View { /// identity path. private static let duffsPerDash: UInt64 = 100_000_000 - /// Protocol minimum asset-lock funding for an identity create. - /// Mirrors `IdentityCreateTransition::calculate_min_required_fee_v1` - /// in `rs-platform-version`: - /// identity_create_base_cost (2_000_000 credits) - /// + asset_lock_base (200_000 duffs * 1000 credits/duff = 200_000_000) - /// + identity_key_in_creation_cost (6_500_000) * defaultKeyCount (4) - /// = 228_000_000 credits / 1000 = 228_000 duffs (0.002280 DASH). - /// The v0 floor was 200_000 duffs but with key_in_creation_cost - /// dynamic at v1, the per-key surcharge has to be added. Submitting - /// below this gets rejected by Platform with - /// `IdentityAssetLockTransactionOutPointNotEnoughBalance`. Use - /// `minFundingDuffs(forKeyCount:)` for the active per-flow value - /// when extra keys (e.g. the DashPay encryption/decryption pair) - /// bump the per-key surcharge. - private static let minIdentityFundingDuffsForDefaultKeys: UInt64 = 228_000 - - /// Recompute the minimum-funding floor for `keyCount` total - /// identity keys. Formula above; result is in duffs (credits ÷ 1000). - private static func minFundingDuffs(forKeyCount keyCount: UInt32) -> UInt64 { - let base: UInt64 = 2_000_000 - let assetLockBaseCredits: UInt64 = 200_000_000 - let perKey = identityKeyCreationCostCredits * UInt64(keyCount) - return (base + assetLockBaseCredits + perKey) / 1_000 - } - /// Whether the DashPay-keys toggle ACTUALLY applies to the /// active submission, mirroring `dashpayKeysSection`'s /// visibility predicate. The Toggle UI is hidden for resume / @@ -193,25 +128,39 @@ struct CreateIdentityView: View { /// indices today), so an `@State` `addDashPayKeys = true` value /// would still be true when the user is in those flows. Routing /// every call site through this gate keeps the funding-minimum - /// calculation and the actual `makeDashpayKeyPair` invocation - /// in lock-step with what the user sees. + /// calculation and the layout actually registered in lock-step + /// with what the user sees. private var shouldRegisterDashPayKeys: Bool { guard case .wallet = walletSelection else { return false } guard fundingSelection != .unusedAssetLock else { return false } return addDashPayKeys } - /// Total identity keys this submission will register, given the - /// current DashPay-keys toggle. Drives the asset-lock minimum - /// + the on-screen min-funding hint. - private var plannedIdentityKeyCount: UInt32 { - Self.defaultKeyCount + (shouldRegisterDashPayKeys ? Self.dashPayExtraKeyCount : 0) + /// The Rust creation key layout the submission registers: the + /// DashPay pair is added when the toggle applies, so a resume always + /// re-derives `.newIdentity`. + private var plannedKeyLayout: ManagedPlatformWallet.IdentityCreationKeyLayout { + shouldRegisterDashPayKeys ? .newIdentityWithDashPayKeys : .newIdentity + } + + /// The minimum asset-lock value (duffs) Rust computes for `layout` + /// at the selected wallet's platform version, from its versioned fee + /// schedule. Fails when no wallet is loaded or the query fails; the + /// view shows the error and blocks submit rather than guessing. + private func minFundingDuffs( + for layout: ManagedPlatformWallet.IdentityCreationKeyLayout + ) -> Result { + guard let walletId = selectedWalletId, + let managedWallet = walletManager.wallet(for: walletId) else { + return .failure(PlatformWalletError.walletOperation("the selected wallet is not loaded")) + } + return Result { try managedWallet.identityCreationMinFundingDuffs(layout: layout) } } - /// Per-submission minimum funding in duffs — scales with - /// `plannedIdentityKeyCount`. - private var currentMinFundingDuffs: UInt64 { - Self.minFundingDuffs(forKeyCount: plannedIdentityKeyCount) + /// Per-submission minimum funding for `plannedKeyLayout`. Drives the + /// asset-lock minimum + the on-screen min-funding hint. + private var currentMinFunding: Result { + minFundingDuffs(for: plannedKeyLayout) } /// Default funding amount pre-filled into the field for the Core @@ -752,11 +701,17 @@ struct CreateIdentityView: View { raw: coreAccountBalanceDuffs(account), divisor: Double(Self.duffsPerDash) ) - let minimum = Self.formatDash( - raw: currentMinFundingDuffs, - divisor: Double(Self.duffsPerDash) - ) - Text("Available: \(available). Minimum: \(minimum). Rust builds an asset-lock transaction from your Core UTXOs and the locked funds become the new identity's initial credit balance.") + switch currentMinFunding { + case .success(let minimumDuffs): + let minimum = Self.formatDash( + raw: minimumDuffs, + divisor: Double(Self.duffsPerDash) + ) + Text("Available: \(available). Minimum: \(minimum). Rust builds an asset-lock transaction from your Core UTXOs and the locked funds become the new identity's initial credit balance.") + case .failure(let error): + Text("Available: \(available). Cannot load the funding minimum: \(error.localizedDescription)") + .foregroundColor(.red) + } } } } @@ -924,9 +879,11 @@ struct CreateIdentityView: View { if fundingSelection == .shieldedBalance { return "The two extra keys add their per-key creation cost to the metered fee taken from the chosen denomination." } - let extraDuffs = currentMinFundingDuffs - - Self.minFundingDuffs(forKeyCount: Self.defaultKeyCount) - return "Adds \(extraDuffs) duffs to the asset-lock minimum." + guard case .success(let withDashPay) = minFundingDuffs(for: .newIdentityWithDashPayKeys), + case .success(let without) = minFundingDuffs(for: .newIdentity) else { + return "Adds their per-key creation cost to the asset-lock minimum." + } + return "Adds \(withDashPay - without) duffs to the asset-lock minimum." } /// Toggle for the optional DashPay encryption/decryption key @@ -1037,7 +994,8 @@ struct CreateIdentityView: View { if let account = selectedCoreAccount { guard let duffs = parsedAmountDuffs else { return false } let available = coreAccountBalanceDuffs(account) - return duffs >= currentMinFundingDuffs && duffs <= available + guard case .success(let minimum) = currentMinFunding else { return false } + return duffs >= minimum && duffs <= available } if fundingSelection == .shieldedBalance { // Re-check availability (the bound wallet / balance could @@ -1105,10 +1063,10 @@ struct CreateIdentityView: View { // buffers immediately. The mnemonic stays in Keychain; the // derivation path lives on `PersistentPlatformAddress`. let signer = KeychainSigner(modelContainer: modelContext.container) - var identityPubkeys: [ManagedPlatformWallet.IdentityPubkey] + let identityPubkeys: [ManagedPlatformWallet.IdentityPubkey] do { // Single-FFI derive + persist. The Rust side owns the - // per-key MASTER-vs-HIGH policy and ships back the + // key layout (DashPay pair included) and ships back the // ready-to-use `IdentityPubkey` rows; the Swift caller // does not recreate the policy. See // swift-sdk/CLAUDE.md "no mnemonic round-tripping" — @@ -1117,7 +1075,7 @@ struct CreateIdentityView: View { // the Rust loop, not Swift-side glue. identityPubkeys = try managedWallet.prePersistIdentityKeysForRegistration( identityIndex: identityIndex, - keyCount: Self.defaultKeyCount, + layout: plannedKeyLayout, network: platformState.currentNetwork ) } catch { @@ -1127,40 +1085,6 @@ struct CreateIdentityView: View { return } - // Optional DashPay key pair — Encryption (kid=N) + Decryption - // (kid=N+1) bound to DashPay's `contactRequest` document - // type, MEDIUM security level, ECDSA-secp256k1. Registered - // alongside the default auth keys when the user has - // `addDashPayKeys` on (default) so the post-registration - // DashPay flow (send contact request, accept, send payment) - // is usable without a follow-up Add Identity Key round. - // - // The Rust pre-persist call above only knows about the - // auth-key policy (master + HIGH). For the encryption / - // decryption pair we re-use the same per-slot derivation - // FFI the manual Add Identity Key flow uses, build the - // matching `IdentityPubkey` rows here with explicit - // `contractBounds`, and store the private bytes under the - // walletId-namespaced keychain account so the trampoline - // can find them when DashPay flows ask the new keys to - // sign. - if shouldRegisterDashPayKeys { - do { - identityPubkeys.append(contentsOf: try makeDashpayKeyPair( - managedWallet: managedWallet, - walletId: walletId, - identityIndex: identityIndex, - firstKeyId: Self.defaultKeyCount, - network: platformState.currentNetwork - )) - } catch { - submitError = .init( - message: "Could not derive DashPay keys: \(error.localizedDescription)" - ) - return - } - } - let network: Network = platformState.currentNetwork // Dispatch by funding source. @@ -1848,112 +1772,6 @@ struct CreateIdentityView: View { return nil } - /// Derive + Keychain-persist the DashPay encryption/decryption - /// key pair (kid `firstKeyId` = ENCRYPTION, kid `firstKeyId+1` = - /// DECRYPTION), build the matching `IdentityPubkey` rows with - /// contract bounds pointing at the DashPay system contract's - /// `contactRequest` document type, and return both. Throws on - /// any derivation / keychain-write failure so the caller can - /// surface the error inline and bail out of the registration. - /// - /// Conceptually this is the per-key body that - /// `prePersistIdentityKeysForRegistration` would emit if Rust - /// owned the DashPay-purpose policy too — we keep it Swift-side - /// for now because the Rust function's per-slot purpose table - /// is hardcoded to the auth pattern (MASTER + HIGH×N). - private func makeDashpayKeyPair( - managedWallet: ManagedPlatformWallet, - walletId: Data, - identityIndex: UInt32, - firstKeyId: UInt32, - network: Network - ) throws -> [ManagedPlatformWallet.IdentityPubkey] { - let purposes: [(keyId: UInt32, purpose: KeyPurpose)] = [ - (firstKeyId, .encryption), - (firstKeyId + 1, .decryption), - ] - let bounds: ManagedPlatformWallet.ContractBounds = .singleContractDocumentType( - id: Self.dashpayContractId, - documentTypeName: Self.dashpayContactRequestDocumentType - ) - let walletIdHex = walletId.toHexString() - let identityIdPlaceholder = "" // overwritten by persister callback - // when the identity actually - // lands on-chain; the metadata - // we write here only needs to - // satisfy the keychain - // round-trip lookup by pubkey - // hex. - - var rows: [ManagedPlatformWallet.IdentityPubkey] = [] - rows.reserveCapacity(purposes.count) - - for (keyId, purpose) in purposes { - let preview = try managedWallet.deriveIdentityAuthKeyAtSlot( - identityIndex: identityIndex, - keyId: keyId, - network: network - ) - - // Defence against derivation drift / FFI marshalling - // bugs — mirrors `AddIdentityKeyView.submit`'s cross- - // check. A mismatched DashPay key lands on Platform as - // a key the trampoline can't sign with and surfaces as - // an opaque "encrypted xpub" failure on the first - // contact-request flow, which is much harder to debug - // after the fact than failing fast here. - guard - KeyValidation.validatePrivateKeyForPublicKey( - privateKeyHex: preview.privateKeyData.toHexString(), - publicKeyHex: preview.publicKeyHex, - keyType: .ecdsaSecp256k1, - network: network - ) - else { - throw PlatformWalletError.walletOperation( - "Derived DashPay key (kid \(keyId), purpose \(purpose.name)) didn't match its public key — refusing to persist" - ) - } - - let pubKeyHashHex = SwiftDashSDK.KeychainManager.computePublicKeyHashHex( - preview.publicKeyData - ) - let metadata = IdentityPrivateKeyMetadata( - identityId: identityIdPlaceholder, - keyId: keyId, - walletId: walletIdHex, - identityIndex: identityIndex, - keyIndex: keyId, - derivationPath: preview.derivationPath, - publicKey: preview.publicKeyHex, - publicKeyHash: pubKeyHashHex, - keyType: KeyType.ecdsaSecp256k1.rawValue, - purpose: purpose.rawValue, - securityLevel: SecurityLevel.medium.rawValue - ) - guard KeychainManager.shared.storeIdentityPrivateKey( - preview.privateKeyData, - derivationPath: preview.derivationPath, - metadata: metadata - ) != nil else { - throw PlatformWalletError.walletOperation( - "Could not persist DashPay key (kid \(keyId), purpose \(purpose.name)) to Keychain" - ) - } - rows.append( - ManagedPlatformWallet.IdentityPubkey( - keyId: keyId, - keyType: .ecdsaSecp256k1, - purpose: purpose, - securityLevel: .medium, - pubkeyBytes: preview.publicKeyData, - contractBounds: bounds - ) - ) - } - return rows - } - /// Spendable balance (duffs) for a Core / CoinJoin account. /// Reads live FFI-backed balance from the platform-wallet manager /// (the SwiftData per-account `balanceConfirmed` scalar isn't diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift index 6953c89e694..a40293e8972 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ClaimInvitationSheet.swift @@ -44,10 +44,6 @@ struct ClaimInvitationSheet: View { let username: String } - /// Default identity auth-key count (mirrors `CreateIdentityView`). The - /// DashPay enc/dec pair is appended at ids `authKeyCount` / `authKeyCount+1`. - private static let authKeyCount: UInt32 = 4 - init(walletId: Data, network: Network, initialURI: String = "") { self.walletId = walletId self.network = network @@ -203,20 +199,13 @@ struct ClaimInvitationSheet: View { let identityIndex = nextUnusedIdentityIndex() // Register the invitee's own keys exactly like a normal - // registration: master + auth keys, plus a DashPay enc/dec pair + // registration: the Rust layout with the DashPay enc/dec pair, // so the new identity can send the contact request back. - var keys = try wallet.prePersistIdentityKeysForRegistration( + let keys = try wallet.prePersistIdentityKeysForRegistration( identityIndex: identityIndex, - keyCount: Self.authKeyCount, + layout: .newIdentityWithDashPayKeys, network: network ) - keys.append(contentsOf: try IdentityRegistrationKeys.makeDashpayKeyPair( - managedWallet: wallet, - walletId: walletId, - identityIndex: identityIndex, - firstKeyId: Self.authKeyCount, - network: network - )) let managed = try await wallet.claimInvitation( uri: submittedURI, diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ReclaimInvitationSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ReclaimInvitationSheet.swift index 57ee7f841b4..991c6f50b51 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ReclaimInvitationSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ReclaimInvitationSheet.swift @@ -37,12 +37,6 @@ struct ReclaimInvitationSheet: View { case register } - /// Default identity auth-key count for the register arm (mirrors - /// `CreateIdentityView` / `ClaimInvitationSheet`). No DashPay enc/dec pair is - /// appended — a reclaim recovers funds into a fresh identity and sends no - /// contact request. - private static let authKeyCount: UInt32 = 4 - init(invitation: PersistentInvitation, walletId: Data, network: Network) { self.invitation = invitation self.walletId = walletId @@ -237,9 +231,12 @@ struct ReclaimInvitationSheet: View { let identityIndex = nextUnusedIdentityIndex() // Pre-broadcast local work — BEFORE the marker is set, so a // failure here leaves no in-flight marker. + // A reclaim creates a new identity: the Rust new-identity + // layout without the DashPay pair (it sends no contact + // request). let keys = try wallet.prePersistIdentityKeysForRegistration( identityIndex: identityIndex, - keyCount: Self.authKeyCount, + layout: .newIdentity, network: network ) try markInFlight() diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKIntegrationTests/Platform/CoreToPlatformIntegrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKIntegrationTests/Platform/CoreToPlatformIntegrationTests.swift index 8b57ac8e5a5..7d2cc493733 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKIntegrationTests/Platform/CoreToPlatformIntegrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKIntegrationTests/Platform/CoreToPlatformIntegrationTests.swift @@ -221,14 +221,17 @@ final class CoreToPlatformIntegrationTests: IntegrationTestCase { let wallet = alice.getPlatformWallet() let identityIndex: UInt32 = 0 - let keyCount: UInt32 = 3 + let layout = ManagedPlatformWallet.IdentityCreationKeyLayout.newIdentity let pubkeys = try wallet.prePersistIdentityKeysForRegistration( identityIndex: identityIndex, - keyCount: keyCount, + layout: layout, network: .regtest ) - XCTAssertEqual(pubkeys.count, Int(keyCount)) + XCTAssertEqual( + pubkeys.count, + try ManagedPlatformWallet.identityCreationKeyLayout(layout).count + ) let signer = KeychainSigner( modelContainer: env.modelContainer,