From 99bb21e92d78742240b8c6288ee45539880c0cb2 Mon Sep 17 00:00:00 2001 From: pasta Date: Wed, 14 Oct 2026 22:16:22 -0500 Subject: [PATCH 01/41] feat(platform-wallet)!: support DashPay shielded tips with dedicated accounts Publish a reusable Orchard tip address on a DashPay profile and pay it by username. Wallet-generated tip addresses come from a dedicated ZIP-32 account per identity (0x40000000 + identity index), so tip viewing keys stay separate from ordinary wallet activity. Externally generated Orchard addresses can be published too. Carries the profile payment fields through the Rust wallet, SQLite storage (V019), the C FFI and JNI, SwiftData and Room (14 to 15), and the Swift and Kotlin example apps. Identity changeset replay now follows re-slotted identities, so the tip account follows its identity's verified index. BREAKING CHANGE: IdentityEntryFFI, ContactProfileRowFFI and the native profile structs gained payment address fields; C ABI consumers, the Swift xcframework and the Android JNI library must be rebuilt with the host. The Rust profile models gained fields. Migrated wallet databases cannot be opened by older SDKs. Squashed from 25 commits (previous head 74a473f8f4) onto v5.1-dev. Co-Authored-By: Claude Opus 5.5 --- .../dashfoundation/example/di/AppContainer.kt | 3 + .../example/ui/dashpay/DashPayJson.kt | 6 + .../ui/dashpay/DashPayProfileScreen.kt | 74 +++ .../example/ui/dashpay/DashPayTabScreen.kt | 60 ++ .../example/ui/dashpay/ShieldedTipFailure.kt | 24 + .../example/ui/dashpay/ShieldedTipSheet.kt | 123 ++++ .../ui/dashpay/ShieldedTipSubmission.kt | 57 ++ .../SearchWalletsForIdentitiesScreen.kt | 15 + .../ui/wallet/SendTransactionScreen.kt | 4 +- .../example/ui/wallet/WalletDetailScreen.kt | 4 +- .../ui/dashpay/ShieldedTipFailureTest.kt | 41 ++ .../ui/dashpay/ShieldedTipSubmissionTest.kt | 85 +++ .../persistence/DashDatabaseMigrationTest.kt | 67 +- .../dashsdk/ffi/DashpayNative.kt | 6 + .../dashsdk/ffi/FundingNative.kt | 11 + .../dashsdk/ffi/NativePersistenceBridge.kt | 14 +- .../dashsdk/persistence/DashDatabase.kt | 17 +- .../PlatformWalletPersistenceHandler.kt | 26 + .../entities/DashpayContactProfileEntity.kt | 3 + .../entities/DashpayProfileEntity.kt | 3 + .../dashsdk/services/ShieldedService.kt | 4 +- .../dashfoundation/dashsdk/tokens/Dashpay.kt | 13 + .../dashsdk/tokens/PaymentAddressUpdate.kt | 8 + .../dashsdk/tokens/ShieldedTipRecipient.kt | 16 + .../tokens/ShieldedTipRecipientHistory.kt | 40 ++ .../dashsdk/wallet/ManagedPlatformWallet.kt | 23 + .../dashsdk/wallet/PlatformWalletManager.kt | 21 + .../dashsdk/persistence/DashDatabaseTest.kt | 5 +- .../PlatformWalletPersistenceHandlerTest.kt | 21 + .../tokens/ShieldedTipRecipientHistoryTest.kt | 58 ++ .../src/dashpay_profile.rs | 190 +++++- .../src/identity_persistence.rs | 136 +++- .../rs-platform-wallet-ffi/src/persistence.rs | 239 ++++++- .../src/shielded_send.rs | 457 +++++++++++++ .../src/shielded_sync.rs | 83 +++ .../src/wallet_restore_types.rs | 11 +- packages/rs-platform-wallet-storage/SCHEMA.md | 15 + .../V021__profile_address_encoding.rs | 19 + .../src/sqlite/mod.rs | 3 + .../src/sqlite/schema/blob.rs | 5 +- .../src/sqlite/schema/dashpay.rs | 36 +- .../src/sqlite/schema/identities.rs | 25 +- .../schema/identity_profile_encoding.rs | 259 ++++++++ .../src/sqlite/schema/mod.rs | 6 +- .../sqlite_identity_index_uniqueness.rs | 30 + .../integration/sqlite_persist_roundtrip.rs | 1 + .../tests/sqlite_profile_address_encoding.rs | 335 ++++++++++ .../rs-platform-wallet/docs/SHIELDED_TIPS.md | 85 +++ .../src/changeset/changeset.rs | 14 +- packages/rs-platform-wallet/src/error.rs | 13 + packages/rs-platform-wallet/src/lib.rs | 14 +- .../rs-platform-wallet/src/wallet/apply.rs | 235 ++++++- .../src/wallet/identity/mod.rs | 5 +- .../src/wallet/identity/network/discovery.rs | 80 ++- .../src/wallet/identity/network/loading.rs | 18 +- .../src/wallet/identity/network/profile.rs | 429 ++++++++++++ .../wallet/identity/state/manager/apply.rs | 141 +++- .../identity/state/manager/lifecycle.rs | 124 +++- .../src/wallet/identity/state/manager/mod.rs | 169 +++++ .../src/wallet/identity/state/mod.rs | 1 + .../src/wallet/identity/types/dashpay/mod.rs | 2 +- .../wallet/identity/types/dashpay/profile.rs | 48 ++ .../src/wallet/identity/types/mod.rs | 3 +- .../src/wallet/platform_wallet.rs | 78 ++- .../src/wallet/shielded/mod.rs | 2 + .../shielded/sync/memo_roundtrip_tests.rs | 30 + .../src/wallet/shielded/tips.rs | 317 +++++++++ .../wallet/shielded/viewing_key_bind_tests.rs | 621 ++++++++++++++++++ packages/rs-sdk/src/platform/dashpay/mod.rs | 2 +- .../rs-sdk/src/platform/dashpay/profile.rs | 103 ++- packages/rs-unified-sdk-jni/src/dashpay.rs | 36 +- packages/rs-unified-sdk-jni/src/funding.rs | 152 +++++ .../rs-unified-sdk-jni/src/persistence.rs | 133 +++- packages/rs-unified-sdk-jni/src/tokens.rs | 48 ++ packages/swift-sdk/SCHEMA_RELEASES.md | 36 +- .../Persistence/DashLegacyStoreSQLite.swift | 44 +- .../Persistence/DashModelContainer.swift | 5 +- .../PersistentDashpayContactProfile.swift | 15 +- .../PersistentDashpayPaymentAddresses.swift | 63 ++ .../Models/PersistentDashpayProfile.swift | 13 + .../Models/PersistentIdentity.swift | 4 + .../PlatformWallet/DashPayProfile.swift | 58 +- .../ManagedPlatformWallet.swift | 42 +- .../PlatformWalletManagerShieldedSync.swift | 102 +++ .../PlatformWalletPersistenceHandler.swift | 135 +++- .../SwiftDashSDK/PlatformWallet/README.md | 27 + .../PlatformWallet/ShieldedTipAmount.swift | 37 ++ .../ShieldedTipRecipientHistory.swift | 32 + .../Core/Services/ShieldedService.swift | 44 +- .../Core/Views/CoreContentView.swift | 5 +- .../Core/Views/IdentitiesContentView.swift | 3 + .../Core/Views/SendTransactionView.swift | 2 +- .../Core/Views/WalletDetailView.swift | 2 +- .../Core/Views/WalletKeyHealthSheet.swift | 3 + .../SwiftExampleApp/SwiftExampleAppApp.swift | 4 + .../Views/CreateIdentityView.swift | 2 +- .../Views/DashPay/DashPayProfileView.swift | 51 ++ .../Views/DashPay/DashPayTabView.swift | 149 ++++- .../Views/DashPay/ShieldedTipSubmission.swift | 84 +++ .../Views/IdentityDetailView.swift | 47 +- .../SearchWalletsForIdentitiesView.swift | 15 +- .../Views/StorageExplorerView.swift | 8 + .../Views/StorageModelListViews.swift | 34 + .../Views/StorageRecordDetailViews.swift | 23 + .../ShieldedRebindRequestTests.swift | 30 + .../ShieldedTipSubmissionTests.swift | 98 +++ .../DashLegacySchemaMigrationTests.swift | 54 ++ .../DashModelMigrationTests.swift | 21 + .../DashPayPersistenceTests.swift | 110 +++- .../ShieldedAccountSnapshotTests.swift | 24 + .../ShieldedTipAmountTests.swift | 24 + packages/swift-sdk/schema-models.json | 3 +- scripts/check-storage-explorer.sh | 17 +- 113 files changed, 6802 insertions(+), 273 deletions(-) create mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt create mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt create mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt create mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt create mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt create mode 100644 packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt create mode 100644 packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt create mode 100644 packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt create mode 100644 packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs create mode 100644 packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs create mode 100644 packages/rs-platform-wallet-storage/tests/sqlite_profile_address_encoding.rs create mode 100644 packages/rs-platform-wallet/docs/SHIELDED_TIPS.md create mode 100644 packages/rs-platform-wallet/src/wallet/shielded/tips.rs create mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift create mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift create mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift create mode 100644 packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift create mode 100644 packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift create mode 100644 packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedTipSubmissionTests.swift create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt index 35b30f96085..ca481c5d891 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt @@ -35,6 +35,9 @@ class AppContainer(private val context: Context) { val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + val shieldedTipSubmissions = + org.dashfoundation.example.ui.dashpay.ShieldedTipSubmissions(applicationScope) + val database: DashDatabase = DashDatabase.create(context) val dataStore = context.preferencesStore diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt index cab86124046..274cdd57f01 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt @@ -23,6 +23,9 @@ data class DashPayProfile( val displayName: String?, val publicMessage: String?, val avatarUrl: String?, + val corePaymentAddress: String? = null, + val platformPaymentAddress: String? = null, + val shieldedAddress: String? = null, ) /** Parse a `getProfile` / `getContactProfile` JSON object, or null. */ @@ -32,6 +35,9 @@ fun parseDashPayProfile(json: String?): DashPayProfile? { displayName = obj.optStringOrNull("displayName"), publicMessage = obj.optStringOrNull("publicMessage"), avatarUrl = obj.optStringOrNull("avatarUrl"), + corePaymentAddress = obj.optStringOrNull("corePaymentAddress"), + platformPaymentAddress = obj.optStringOrNull("platformPaymentAddress"), + shieldedAddress = obj.optStringOrNull("shieldedAddress"), ) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt index 2f81559246e..abc8ebd6d9d 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt @@ -12,6 +12,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api @@ -39,14 +40,20 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController +import java.math.BigDecimal import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import org.dashfoundation.dashsdk.tokens.PaymentAddressUpdate import org.dashfoundation.example.di.LocalAppContainer import org.dashfoundation.example.ui.components.FormSection import org.dashfoundation.example.ui.components.LabeledContent import org.dashfoundation.example.ui.components.SubmitButton import org.dashfoundation.example.util.Base58 +import org.dashfoundation.example.util.DashAddress +import org.dashfoundation.example.util.DashAddressType import org.dashfoundation.example.util.generateQrBitmap import org.dashfoundation.example.util.hexToBytes @@ -72,7 +79,25 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController val walletId = identity?.walletId val wallet = remember(manager, walletId) { walletId?.let { manager?.wallet(forWalletId = it) } } + // Derived from the live identity's index, not Room's placeholder 0 (see DashPayTabScreen); + // Room's index is only a key so a discovery re-slot reruns the lookup. + val tipAccount by produceState(initialValue = null, wallet, manager, identityIdHex, identity?.identityIndex) { + value = wallet?.let { w -> + runCatching { w.identityIndex(idBytes)?.let { index -> manager?.shieldedTipAccountIndex(index) } } + .getOrNull() + } + } + val tipBalance by remember(walletId, tipAccount) { + val account = tipAccount + if (walletId == null || account == null) flowOf(0L) + else container.database.shieldedDao().observeNotesByWalletAccount(walletId, account) + .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } + }.collectAsStateWithLifecycle(initialValue = 0L) + var profile by remember { mutableStateOf(null) } + val publishedTipAddress = profile?.shieldedAddress?.let { raw -> + manager?.let { m -> runCatching { DashAddress.encodeOrchard(raw.hexToBytes(), m.network) }.getOrNull() } + } var profileExists by remember { mutableStateOf(false) } var qrUri by remember { mutableStateOf(null) } var qrError by remember { mutableStateOf(null) } @@ -87,6 +112,7 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController var displayNameField by remember { mutableStateOf("") } var publicMessageField by remember { mutableStateOf("") } var avatarUrlField by remember { mutableStateOf("") } + var shieldedAddressField by remember { mutableStateOf("") } var isSaving by remember { mutableStateOf(false) } var saveError by remember { mutableStateOf(null) } @@ -132,6 +158,7 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController displayNameField = profile?.displayName.orEmpty() publicMessageField = profile?.publicMessage.orEmpty() avatarUrlField = profile?.avatarUrl.orEmpty() + shieldedAddressField = publishedTipAddress.orEmpty() saveError = null } isEditing = !isEditing @@ -172,6 +199,31 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController label = { Text("Avatar URL") }, singleLine = true, ) + TextButton(enabled = !isSaving && container.shieldedService.isAvailable, onClick = { + val m = manager ?: return@TextButton + val wid = walletId ?: return@TextButton + isSaving = true + saveError = null + scope.launch { + try { + shieldedAddressField = requireNotNull(DashAddress.encodeOrchard(m.prepareShieldedTipAddress(wid, idBytes), m.network)) + } catch (e: Exception) { + saveError = e.message ?: "Could not prepare tip account" + } finally { + isSaving = false + } + } + }, modifier = Modifier.testTag("dashpay.profile.useTipAccount")) { + Text("Use this wallet’s dedicated tip account") + } + Text("The address is published only when you save.", style = MaterialTheme.typography.bodySmall) + OutlinedTextField( + value = shieldedAddressField, + onValueChange = { shieldedAddressField = it }, + modifier = Modifier.fillMaxWidth().testTag("dashpay.profile.shieldedAddress"), + label = { Text("Shielded tip address") }, + supportingText = { Text("Paste an external receiving address, or leave blank to disable tips. External funds are managed by the receiving wallet.") }, + ) saveError?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } @@ -194,6 +246,15 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController avatarUrl = avatarUrlField.trim().ifEmpty { null }, doCreate = !profileExists, signerHandle = m.signerHandle, + shieldedAddress = when (val address = shieldedAddressField.trim()) { + publishedTipAddress.orEmpty() -> PaymentAddressUpdate.Keep + "" -> PaymentAddressUpdate.Remove + else -> { + val parsed = DashAddress.parse(address, m.network) as? DashAddressType.Orchard + ?: throw IllegalArgumentException("Enter a shielded address for this network") + PaymentAddressUpdate.Set(parsed.raw43) + } + }, ) loadProfile() isEditing = false @@ -224,6 +285,19 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController } } + if (!isEditing) { + FormSection(title = "Shielded tips") { + Text("This wallet’s tip balance: ${BigDecimal.valueOf(tipBalance, 11).stripTrailingZeros().toPlainString()} DASH") + val address = publishedTipAddress + if (address == null) { + Text("Tips are not enabled.") + } else { + SelectionContainer { Text(address, style = MaterialTheme.typography.bodySmall) } + Text("This receiving address is public and associated with your username. Removing it does not revoke previously shared copies.", style = MaterialTheme.typography.bodySmall) + } + } + } + FormSection(title = "Identity") { Text( Base58.encode(idBytes), diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt index 983beec2f0e..f73e35df786 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt @@ -26,6 +26,8 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SheetValue +import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -37,7 +39,9 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -159,6 +163,7 @@ fun DashPayTabScreen(navController: NavHostController) { val appUiState = container.appUiState var claimSheetUri by remember { mutableStateOf(null) } var showClaimSheet by remember { mutableStateOf(false) } + var showTipSheet by remember { mutableStateOf(false) } val pendingInvite by appUiState.pendingInviteUri.collectAsStateWithLifecycle() val claimInFlight by appUiState.invitationClaimInFlight.collectAsStateWithLifecycle() // The parked URI is NOT cleared at seeding: it stays in AppUiState (the @@ -320,7 +325,62 @@ fun DashPayTabScreen(navController: NavHostController) { onError = { unlockError = it }, ) + val tipManager = manager + val tipWalletId = identity.walletId + // The tip account follows the live identity's derivation index, not + // Room's non-null `identityIndex`: its 0 is a placeholder for an identity + // with no recoverable index and would alias identity 0's tip pool. + // produceState keeps its last value when its keys change, so each result + // is tagged with the inputs it was resolved for and a result for another + // identity or wallet is never offered while the new lookup runs. Room's + // index is only a key: discovery re-slotting a placeholder rewrites it. + val tipAccountKey = listOf(managed, tipManager, identityHex, identity.identityIndex) + val taggedTipAccount by produceState, Result>?>( + initialValue = null, managed, tipManager, identityHex, identity.identityIndex, + ) { + value = tipAccountKey to runCatching { + val index = requireNotNull(managed) { "Wallet is not loaded" } + .identityIndex(identity.identityId) + ?: error("Tip account requires a recoverable identity index") + requireNotNull(tipManager).shieldedTipAccountIndex(index) + } + } + val tipAccountResult = taggedTipAccount + ?.takeIf { (key, _) -> key == tipAccountKey } + ?.second + val tipAccount = tipAccountResult?.getOrNull() + val tipSubmission = tipWalletId?.let { + container.shieldedTipSubmissions.forWallet(network.ffiValue, it.toHex()) + } + val tipSending by rememberUpdatedState(tipSubmission?.busy == true) + val tipSheetState = rememberModalBottomSheetState( + confirmValueChange = { value -> value != SheetValue.Hidden || !tipSending }, + ) + if (showTipSheet && managed != null && tipManager != null && tipWalletId != null && tipAccount != null && tipSubmission != null) { + ModalBottomSheet( + sheetState = tipSheetState, + onDismissRequest = { if (!tipSubmission.busy) showTipSheet = false }, + ) { + ShieldedTipSheet(tipManager, managed, tipWalletId, tipAccount, tipSubmission) + } + } FormSection(title = "DashPay") { + if (container.shieldedService.isAvailable) { + EntityRow( + icon = Icons.AutoMirrored.Filled.Send, + title = "Send shielded tip", + onClick = { + when (val result = tipAccountResult) { + null -> unlockError = "The tip account is still loading" + else -> result.fold( + onSuccess = { showTipSheet = true }, + onFailure = { unlockError = it.message ?: "Could not open shielded tips" }, + ) + } + }, + modifier = Modifier.testTag("dashpay.sendShieldedTip"), + ) + } EntityRow( icon = Icons.Default.Group, title = "Contacts", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt new file mode 100644 index 00000000000..e21e1ca8522 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt @@ -0,0 +1,24 @@ +package org.dashfoundation.example.ui.dashpay + +import org.dashfoundation.dashsdk.errors.DashSdkError + +/** + * Permit a fresh user review only for failures known not to have executed a tip. + * On the tip path, Rust maps selection/build/recipient-check failures to + * WalletOperation. Broadcast ambiguity maps to ShieldedSpendUnconfirmed, and + * successful post-broadcast bookkeeping is best-effort (never WalletOperation). + * Unknown exceptions, including JNI failures and cancellation, remain locked. + */ +internal fun canReviewShieldedTipAfterFailure(error: Exception): Boolean = when (error) { + is IllegalArgumentException, + is DashSdkError.InvalidParameter, + is DashSdkError.PlatformWallet.InvalidHandle, + is DashSdkError.PlatformWallet.NotFound, + is DashSdkError.PlatformWallet.SigningKeyUnavailable, + is DashSdkError.PlatformWallet.WalletOperation, + is DashSdkError.PlatformWallet.ShieldedNoRecordedAnchor, + is DashSdkError.PlatformWallet.ShieldedBroadcastFailed -> true + // ErrorInvalidParameter is a preflight-only FFI failure on this call path. + is DashSdkError.PlatformWallet.Generic -> error.nativeCode == 2 + else -> false +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt new file mode 100644 index 00000000000..c5418cdde79 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt @@ -0,0 +1,123 @@ +package org.dashfoundation.example.ui.dashpay + +import android.content.Context +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Checkbox +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import java.math.BigDecimal +import kotlinx.coroutines.launch +import org.dashfoundation.dashsdk.tokens.ShieldedTipRecipient +import org.dashfoundation.dashsdk.tokens.ShieldedTipRecipientHistory +import org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet +import org.dashfoundation.dashsdk.wallet.PlatformWalletManager +import org.dashfoundation.example.ui.components.SubmitButton +import org.dashfoundation.example.util.Base58 +import org.dashfoundation.example.util.DashAddress + +/** Username tipping uses the same verified recipient and confirmation boundary as Swift. */ +@Composable +fun ShieldedTipSheet(manager: PlatformWalletManager, wallet: ManagedPlatformWallet, walletId: ByteArray, tipAccount: Int, submission: ShieldedTipSubmission) { + val scope = rememberCoroutineScope() + val context = LocalContext.current + val history = remember(context) { + ShieldedTipRecipientHistory(context.getSharedPreferences("dashpay.tipRecipients", Context.MODE_PRIVATE)) + } + var changedRecipient by remember { mutableStateOf(null) } + var username by remember { mutableStateOf("") } + var amount by remember { mutableStateOf("") } + var recipient by remember { mutableStateOf(null) } + var confirmedAmount by remember { mutableStateOf(null) } + var resolving by remember { mutableStateOf(false) } + val busy = resolving || submission.busy + val submitted = submission.submitted + var spendTips by remember { mutableStateOf(false) } + var message by remember { mutableStateOf(null) } + + changedRecipient?.let { changed -> + AlertDialog( + onDismissRequest = { changedRecipient = null }, + title = { Text("Tip recipient changed") }, + text = { Text("The identity or shielded address for this username differs from your previous confirmation. Verify the change with the recipient before continuing.") }, + confirmButton = { + TextButton(onClick = { recipient = changed; changedRecipient = null }) { Text("Review new recipient") } + }, + dismissButton = { + TextButton(onClick = { changedRecipient = null }) { Text("Cancel") } + }, + ) + } + + Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text("Send a shielded tip") + OutlinedTextField(username, { username = it; recipient = null }, label = { Text("Username") }, enabled = !busy && !submitted) + OutlinedTextField(amount, { amount = it; recipient = null }, label = { Text("Amount (DASH)") }, enabled = !busy && !submitted) + Row { + Checkbox(checked = spendTips, enabled = !busy && !submitted, + onCheckedChange = { spendTips = it; recipient = null }) + Text("Spend from my dedicated tip account") + } + recipient?.let { + Text("Recipient: ${Base58.encode(it.identityId)}") + DashAddress.encodeOrchard(it.address, manager.network)?.let { address -> + SelectionContainer { Text(address) } + } + Text("Send $amount DASH from your ${if (spendTips) "tip" else "main shielded"} account to $username?") + } + (message ?: submission.message)?.let { Text(it) } + if (submission.status == ShieldedTipSubmission.Status.Sent) { + TextButton(onClick = { submission.startNewTip() }) { Text("Start a new tip") } + } + SubmitButton( + text = if (recipient == null) "Review tip" else "Confirm and send", + isLoading = busy, enabled = !busy && !submitted && changedRecipient == null, modifier = Modifier.fillMaxWidth(), + ) { + val selected = recipient + if (selected != null) { + val sendUsername = username.trim() + val sendAmount = requireNotNull(confirmedAmount) + val sendAccount = if (spendTips) tipAccount else 0 + recipient = null + submission.submit { + history.confirm(manager.network, walletId, sendUsername, selected) + manager.sendShieldedTip(walletId, sendUsername, selected, sendAmount, account = sendAccount) + } + } else { + resolving = true + message = null + scope.launch { + try { + val credits = BigDecimal(amount.trim()).movePointRight(11).longValueExact() + require(credits > 0) { "Enter a positive amount" } + confirmedAmount = credits + val resolved = wallet.dashpay.resolveShieldedTip(username.trim()) + if (history.hasChanged(manager.network, walletId, username, resolved)) { + changedRecipient = resolved + } else { + recipient = resolved + } + } catch (e: Exception) { + message = e.message ?: "Unable to review tip" + recipient = null + } finally { resolving = false } + } + } + } + } +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt new file mode 100644 index 00000000000..af37ff54ca6 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt @@ -0,0 +1,57 @@ +package org.dashfoundation.example.ui.dashpay + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch + +/** Application-owned submissions survive sheet dismissal, navigation and activity recreation. */ +class ShieldedTipSubmissions(private val scope: CoroutineScope) { + private val wallets = mutableMapOf() + + /** Called on the main thread; one guard per network/wallet, across all of its identities. */ + fun forWallet(network: Int, walletId: String): ShieldedTipSubmission = + wallets.getOrPut("$network:$walletId") { ShieldedTipSubmission(scope) } +} + +/** Main-thread state. A cancelled UI must never imply that blocking JNI stopped broadcasting. */ +class ShieldedTipSubmission(private val scope: CoroutineScope) { + enum class Status { Ready, Sending, Sent, Uncertain } + + var status by mutableStateOf(Status.Ready) + private set + var message by mutableStateOf(null) + private set + val busy: Boolean get() = status == Status.Sending + val submitted: Boolean get() = status != Status.Ready + + fun submit(send: suspend () -> Unit) { + if (submitted) return + // Lock synchronously, before launching, so two UI events cannot submit twice. + status = Status.Sending + message = null + scope.launch { + try { + send() + status = Status.Sent + message = "Shielded tip sent." + } catch (error: Exception) { + status = if (canReviewShieldedTipAfterFailure(error)) Status.Ready else Status.Uncertain + message = if (status == Status.Uncertain) { + "The tip may have been sent. Check shielded activity before sending again. ${error.message.orEmpty()}" + } else { + error.message ?: "Unable to send tip" + } + if (error is kotlinx.coroutines.CancellationException) throw error + } + } + } + + /** Starting another payment requires an explicit action after a confirmed successful return. */ + fun startNewTip() { + if (status != Status.Sent) return + status = Status.Ready + message = null + } +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt index a92013c0bd8..631cb2a6d24 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt @@ -140,6 +140,21 @@ fun SearchWalletsForIdentitiesScreen(navController: NavHostController) { walletHandle = wallet.handle, mnemonicResolverHandle = mgr.mnemonicResolverHandle, ) + // Rebind after every successful scan, not only when new ids + // came back: discovery can also promote an already-known + // identity into its verified slot (not reported in `found`), + // and its dedicated tip account needs registering too. + // Rust adds tip accounts itself, so the default [0] request + // suffices; a bind failure stays non-fatal. + if (container.shieldedService.isAvailable) { + try { + mgr.bindShielded(wallet.walletId) + } catch (error: kotlinx.coroutines.CancellationException) { + throw error + } catch (error: Exception) { + android.util.Log.w("IdentityDiscovery", "Identities found; shielded bind failed", error) + } + } summary = "Found ${found.size} identity(ies)." if (found.isEmpty()) { previewPaths = mgr.identityRegistration.previewRegistrationKeys( diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt index e1c133c12f2..6bf60e9c40c 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt @@ -197,8 +197,8 @@ fun SendTransactionScreen( val hasShielded = remember { Sdk.hasShielded() } val shieldedBalance by remember(walletIdHex) { if (hasShielded) { - container.database.shieldedDao().observeUnspentNotesByWallet(walletId) - .map { notes -> notes.sumOf { it.value } } + container.database.shieldedDao().observeNotesByWalletAccount(walletId, 0) + .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } } else { MutableStateFlow(0L) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt index 50b42461858..1ea3555b1b0 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt @@ -129,8 +129,8 @@ fun WalletDetailScreen( val hasShielded = remember { Sdk.hasShielded() } val shieldedBalance by remember(walletIdHex) { if (hasShielded) { - container.database.shieldedDao().observeUnspentNotesByWallet(walletId) - .map { notes -> notes.sumOf { it.value } } + container.database.shieldedDao().observeNotesByWalletAccount(walletId, 0) + .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } } else { MutableStateFlow(0L) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt new file mode 100644 index 00000000000..a75fc08352e --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt @@ -0,0 +1,41 @@ +package org.dashfoundation.example.ui.dashpay + +import java.util.concurrent.CancellationException +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ShieldedTipFailureTest { + @Test + fun permitsFreshReviewAfterDefinitiveFailures() { + val errors = listOf( + IllegalArgumentException("amount must be positive"), + DashSdkError.InvalidParameter("invalid account"), + DashSdkError.PlatformWallet.Generic(2, "invalid memo"), + DashSdkError.PlatformWallet.InvalidHandle("closed"), + DashSdkError.PlatformWallet.NotFound("wallet removed"), + DashSdkError.PlatformWallet.SigningKeyUnavailable("unlock wallet"), + DashSdkError.PlatformWallet.WalletOperation("The tip recipient changed; review and confirm again"), + DashSdkError.PlatformWallet.WalletOperation("insufficient notes"), + DashSdkError.PlatformWallet.ShieldedNoRecordedAnchor("sync first"), + DashSdkError.PlatformWallet.ShieldedBroadcastFailed("consensus rejected"), + ) + errors.forEach { assertTrue(it.toString(), canReviewShieldedTipAfterFailure(it)) } + } + + @Test + fun retainsLockForAmbiguousAndUnclassifiedOutcomes() { + val errors = listOf( + DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed("no result proof"), + DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed("no relay verdict"), + DashSdkError.Timeout("timed out"), + DashSdkError.NetworkError("connection lost"), + DashSdkError.PlatformWallet.Generic(999, "unknown native error"), + RuntimeException("JNI failure"), + CancellationException("cancelled"), + IllegalStateException("unexpected state"), + ) + errors.forEach { assertFalse(it.toString(), canReviewShieldedTipAfterFailure(it)) } + } +} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt new file mode 100644 index 00000000000..e3d0d102a84 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt @@ -0,0 +1,85 @@ +package org.dashfoundation.example.ui.dashpay + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.ExperimentalCoroutinesApi +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ShieldedTipSubmissionTest { + @Test + fun dismissAndReopenCannotSubmitAgainWhileNativeSendRuns() = runTest { + val submissions = ShieldedTipSubmissions(backgroundScope) + val payment = submissions.forWallet(1, "wallet") + val nativeFinished = CompletableDeferred() + var sends = 0 + payment.submit { sends++; nativeFinished.await() } + assertTrue(payment.busy) + // Even a second click before the first coroutine starts is ignored. + payment.submit { sends++ } + runCurrent() + val sheetScope = CoroutineScope(coroutineContext + SupervisorJob()) + sheetScope.cancel() + val reopened = submissions.forWallet(1, "wallet") + assertSame(payment, reopened) + reopened.submit { sends++ } + assertEquals(1, sends) + nativeFinished.complete(Unit) + runCurrent() + assertEquals(ShieldedTipSubmission.Status.Sent, reopened.status) + assertFalse(reopened.busy) + reopened.submit { sends++ } + runCurrent() + assertEquals(1, sends) + reopened.startNewTip() + reopened.submit { sends++ } + runCurrent() + assertEquals(2, sends) + } + + @Test + fun uncertainOutcomeStaysLockedAcrossReopeningAndNewTipAction() = runTest { + val submissions = ShieldedTipSubmissions(backgroundScope) + val payment = submissions.forWallet(1, "wallet") + payment.submit { throw IllegalStateException("JNI outcome lost") } + runCurrent() + val reopened = submissions.forWallet(1, "wallet") + assertEquals(ShieldedTipSubmission.Status.Uncertain, reopened.status) + reopened.startNewTip() + var retried = false + reopened.submit { retried = true } + runCurrent() + assertFalse(retried) + assertTrue(reopened.submitted) + assertFalse(reopened.busy) + } + + @Test + fun definitivePreflightFailureAllowsFreshReview() = runTest { + val payment = ShieldedTipSubmission(backgroundScope) + payment.submit { throw IllegalArgumentException("invalid amount") } + runCurrent() + assertEquals(ShieldedTipSubmission.Status.Ready, payment.status) + assertEquals("invalid amount", payment.message) + var retried = false + payment.submit { retried = true } + runCurrent() + assertTrue(retried) + } + + @Test + fun walletAndNetworkGuardsAreIndependent() = runTest { + val submissions = ShieldedTipSubmissions(backgroundScope) + submissions.forWallet(1, "a").submit { } + assertFalse(submissions.forWallet(2, "a").submitted) + assertFalse(submissions.forWallet(1, "b").submitted) + } +} diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt index 19797f2678a..704e2ed2954 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseMigrationTest.kt @@ -28,6 +28,65 @@ class DashDatabaseMigrationTest { private val dbName = "migration-test.db" + @Test + fun migrate16To17PreservesProfilesAndSweepState() { + migrateProfilesAndSweepState(16) + } + + @Test + fun migrate10To17PreservesProfilesThroughEveryMigration() { + migrateProfilesAndSweepState(10) + } + + private fun migrateProfilesAndSweepState(fromVersion: Int) { + helper.createDatabase(dbName, fromVersion).apply { + execSQL("INSERT INTO identities (identityId, balance, revision, isLocal, identityType, createdAt, lastUpdated, networkRaw, identityIndex) VALUES (x'0A', 0, 0, 1, 'User', 0, 0, 1, 0)") + execSQL("INSERT INTO dashpay_profiles (networkRaw, identityId, displayName, createdAt, lastUpdated) VALUES (1, x'0A', 'Alice', 0, 0)") + execSQL("INSERT INTO dashpay_contact_profiles (networkRaw, ownerIdentityId, contactIdentityId, displayName, checkedAtMs, createdAt, lastUpdated) VALUES (1, x'0A', x'0B', 'Bob', 123, 0, 0)") + execSQL("INSERT INTO wallets (walletId, walletGroupId, networkRaw, name, birthHeight, syncedHeight, lastSynced, isImported, createdAt, lastUpdated) VALUES (x'01', x'02', 1, 'w', 0, 0, 0, 0, 0, 0)") + execSQL("INSERT INTO pending_inputs (outpoint, inputIndex, spendingTxid, walletId, createdAt) VALUES (x'0301', 0, x'02', x'01', 0)") + if (fromVersion >= 11) { + execSQL("UPDATE wallets SET lastAppliedChainLockHeight = 4321") + execSQL("UPDATE pending_inputs SET isSweptTombstone = 1, winnerMinedHeight = 1234") + } + close() + } + val db = helper.runMigrationsAndValidate( + dbName, + 17, + true, + DashDatabase.MIGRATION_10_11, + DashDatabase.MIGRATION_11_12, + DashDatabase.MIGRATION_12_13, + DashDatabase.MIGRATION_13_14, + DashDatabase.MIGRATION_14_15, + DashDatabase.MIGRATION_15_16, + DashDatabase.MIGRATION_16_17, + ) + for ((table, name) in listOf("dashpay_profiles" to "Alice", "dashpay_contact_profiles" to "Bob")) { + db.query("SELECT displayName, corePaymentAddress, platformPaymentAddress, shieldedAddress FROM $table").use { cursor -> + assertTrue(cursor.moveToFirst()) + assertEquals(name, cursor.getString(0)) + assertTrue(cursor.isNull(1) && cursor.isNull(2) && cursor.isNull(3)) + } + db.execSQL("UPDATE $table SET shieldedAddress = ?", arrayOf(ByteArray(43) { 0x45 })) + db.query("SELECT shieldedAddress FROM $table").use { cursor -> + assertTrue(cursor.moveToFirst()) + org.junit.Assert.assertArrayEquals(ByteArray(43) { 0x45 }, cursor.getBlob(0)) + } + } + db.query("SELECT isSweptTombstone, winnerMinedHeight FROM pending_inputs").use { cursor -> + assertTrue(cursor.moveToFirst()) + assertEquals(if (fromVersion >= 11) 1 else 0, cursor.getInt(0)) + if (fromVersion >= 11) assertEquals(1234, cursor.getInt(1)) else assertTrue(cursor.isNull(1)) + } + db.query("SELECT lastAppliedChainLockHeight FROM wallets").use { cursor -> + assertTrue(cursor.moveToFirst()) + if (fromVersion >= 11) assertEquals(4321, cursor.getInt(0)) else assertTrue(cursor.isNull(0)) + } + db.close() + } + /** * v2 → v3 adds the `dashpay_contact_profiles` and `dashpay_payments` * tables (additive — no reshapes). Pre-existing v2 data must survive @@ -746,7 +805,7 @@ class DashDatabaseMigrationTest { helper.createDatabase(dbName, 4).close() helper.runMigrationsAndValidate( dbName, - 16, + 17, true, DashDatabase.MIGRATION_4_5, DashDatabase.MIGRATION_5_6, @@ -760,16 +819,17 @@ class DashDatabaseMigrationTest { DashDatabase.MIGRATION_13_14, DashDatabase.MIGRATION_14_15, DashDatabase.MIGRATION_15_16, + DashDatabase.MIGRATION_16_17, ).close() } - /** The full chain from v1 must also land on a valid v16 schema. */ + /** The full chain from v1 must also land on a valid v17 schema. */ @Test fun migrateAllTheWayFrom1() { helper.createDatabase(dbName, 1).close() helper.runMigrationsAndValidate( dbName, - 16, + 17, true, DashDatabase.MIGRATION_1_2, DashDatabase.MIGRATION_2_3, @@ -786,6 +846,7 @@ class DashDatabaseMigrationTest { DashDatabase.MIGRATION_13_14, DashDatabase.MIGRATION_14_15, DashDatabase.MIGRATION_15_16, + DashDatabase.MIGRATION_16_17, ).close() } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt index 60f99620a5e..3d55a791b26 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/DashpayNative.kt @@ -139,6 +139,12 @@ internal object DashpayNative { avatarBytes: ByteArray?, doCreate: Boolean, signerHandle: Long, + coreAddressAction: Int, + coreAddress: ByteArray?, + platformAddressAction: Int, + platformAddress: ByteArray?, + shieldedAddressAction: Int, + shieldedAddress: ByteArray?, ): String? /** diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt index fb82e03ccb3..070df65f3fe 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt @@ -16,6 +16,17 @@ package org.dashfoundation.dashsdk.ffi * non-shielded build throws [UnsatisfiedLinkError]. */ internal object FundingNative { + external fun tipAccountIndex(identityIndex: Int): Int + external fun prepareShieldedTipAddress( + manager: Long, walletId: ByteArray, resolver: Long, identityId: ByteArray, + ): ByteArray + external fun resolveShieldedTip(wallet: Long, username: String): ByteArray + external fun sendShieldedTip( + manager: Long, walletId: ByteArray, resolver: Long, account: Int, + username: String, expectedId: ByteArray, expectedAddress: ByteArray, + amount: Long, memo: String?, + ) + external fun shieldedIdentityDebitRecoveryRecords( managerHandle: Long, diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt index ae4d7946395..c9c18a68858 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt @@ -527,7 +527,7 @@ abstract class NativePersistenceBridge { /** * One `IdentityEntryFFI` upsert. DPNS labels + acquired-at timestamps * ride as parallel arrays. Descriptor - * `([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;)I`. + * `([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I`. */ @Suppress("LongParameterList") open fun onPersistIdentityUpsert( @@ -551,6 +551,9 @@ abstract class NativePersistenceBridge { dashpayAvatarFingerprint: ByteArray, dashpayAvatarFingerprintPresent: Boolean, dashpayPublicMessage: String?, + dashpayCorePaymentAddress: ByteArray? = null, + dashpayPlatformPaymentAddress: ByteArray? = null, + dashpayShieldedAddress: ByteArray? = null, ): Int = 0 /** One identity-id removal. Descriptor `([B[B)I`. */ @@ -761,7 +764,7 @@ abstract class NativePersistenceBridge { /** * One `ContactProfileRowFFI` delta riding an identity upsert * (`IdentityEntryFFI.contact_profiles`). Descriptor - * `([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;J)I`. + * `([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;J[B[B[B)I`. * * [isPresent] `true` ⇒ upsert the cached contact-profile row for * `(ownerId, contactId)`; `false` ⇒ tombstone — the contact removed @@ -785,6 +788,9 @@ abstract class NativePersistenceBridge { avatarFingerprintPresent: Boolean, publicMessage: String?, checkedAtMs: Long, + corePaymentAddress: ByteArray? = null, + platformPaymentAddress: ByteArray? = null, + shieldedAddress: ByteArray? = null, ): Int = 0 // ── Asset locks ─────────────────────────────────────────────────── @@ -1396,6 +1402,7 @@ class IdentityRestoreData( * re-fetches every contact. */ @JvmField val contactProfiles: Array, + @JvmField val dashpayProfile: ContactProfileRestoreData? = null, ) /** @@ -1428,6 +1435,9 @@ class ContactProfileRestoreData( @JvmField val avatarFingerprint: ByteArray?, @JvmField val publicMessage: String?, @JvmField val checkedAtMs: Long, + @JvmField val corePaymentAddress: ByteArray? = null, + @JvmField val platformPaymentAddress: ByteArray? = null, + @JvmField val shieldedAddress: ByteArray? = null, ) /** diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt index 0b3445a5397..89fcbc89ce5 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabase.kt @@ -190,9 +190,12 @@ import org.dashfoundation.dashsdk.persistence.entities.WalletManagerMetadataEnti * `onLoadPrivateContactScanState`, so a relaunch resumes the private contact * request sync where it stopped. Empty after the migration: the first sync * reads the store from its start, as every sync did before. + * + * Version 17 adds nullable Core, Platform, and shielded payment addresses + * to cached owner and contact profiles. */ @Database( - version = 16, + version = 17, exportSchema = true, entities = [ WalletEntity::class, @@ -730,6 +733,17 @@ abstract class DashDatabase : RoomDatabase() { } } + /** v16 → v17: optional public payment addresses on cached profiles. */ + val MIGRATION_16_17: Migration = object : Migration(16, 17) { + override fun migrate(db: SupportSQLiteDatabase) { + for (table in listOf("dashpay_profiles", "dashpay_contact_profiles")) { + for (column in listOf("corePaymentAddress", "platformPaymentAddress", "shieldedAddress")) { + db.execSQL("ALTER TABLE `$table` ADD COLUMN `$column` BLOB") + } + } + } + } + /** * v15 -> v16: the two private contact request scan state tables, see * the version-16 class doc above. Created empty. @@ -783,6 +797,7 @@ abstract class DashDatabase : RoomDatabase() { MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, + MIGRATION_16_17, ) .build() diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index b33f99a467d..0373fd39fcb 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -1727,6 +1727,9 @@ class PlatformWalletPersistenceHandler( dashpayAvatarFingerprint: ByteArray, dashpayAvatarFingerprintPresent: Boolean, dashpayPublicMessage: String?, + dashpayCorePaymentAddress: ByteArray?, + dashpayPlatformPaymentAddress: ByteArray?, + dashpayShieldedAddress: ByteArray?, ): Int = guarded { stage(walletId) { db -> val ownerWallet = if (walletIdIsSome) identityWalletId else walletId @@ -1841,6 +1844,9 @@ class PlatformWalletPersistenceHandler( avatarHash = if (dashpayAvatarHashPresent) dashpayAvatarHash else null, avatarFingerprint = if (dashpayAvatarFingerprintPresent) dashpayAvatarFingerprint else null, + corePaymentAddress = dashpayCorePaymentAddress, + platformPaymentAddress = dashpayPlatformPaymentAddress, + shieldedAddress = dashpayShieldedAddress, lastUpdated = now(), ), ) @@ -2339,6 +2345,9 @@ class PlatformWalletPersistenceHandler( avatarFingerprintPresent: Boolean, publicMessage: String?, checkedAtMs: Long, + corePaymentAddress: ByteArray?, + platformPaymentAddress: ByteArray?, + shieldedAddress: ByteArray?, ): Int = guarded { stage(walletId) { db -> // Owner identity must exist (networkRaw is read off it). In the @@ -2361,6 +2370,9 @@ class PlatformWalletPersistenceHandler( avatarUrl = avatarUrl, avatarHash = avatarHash.takeIf { avatarHashPresent }, avatarFingerprint = avatarFingerprint.takeIf { avatarFingerprintPresent }, + corePaymentAddress = corePaymentAddress, + platformPaymentAddress = platformPaymentAddress, + shieldedAddress = shieldedAddress, checkedAtMs = checkedAtMs, lastUpdated = now(), ), @@ -3141,6 +3153,9 @@ class PlatformWalletPersistenceHandler( avatarFingerprint = cp.avatarFingerprint, publicMessage = cp.publicMessage, checkedAtMs = cp.checkedAtMs, + corePaymentAddress = cp.corePaymentAddress, + platformPaymentAddress = cp.platformPaymentAddress, + shieldedAddress = cp.shieldedAddress, ) }.toTypedArray() IdentityRestoreData( @@ -3157,6 +3172,17 @@ class PlatformWalletPersistenceHandler( ignoredSenders = ignoredRows, payments = paymentRows, contactProfiles = contactProfileRows, + dashpayProfile = database.dashpayDao().getProfile(idRow.networkRaw, idRow.identityId)?.let { p -> + ContactProfileRestoreData( + contactId = idRow.identityId, + displayName = p.displayName, bio = p.bio, avatarUrl = p.avatarUrl, + avatarHash = p.avatarHash, avatarFingerprint = p.avatarFingerprint, + publicMessage = p.publicMessage, checkedAtMs = 0, + corePaymentAddress = p.corePaymentAddress, + platformPaymentAddress = p.platformPaymentAddress, + shieldedAddress = p.shieldedAddress, + ) + }, ) }.toTypedArray() } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt index bb72b816457..669f5274936 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayContactProfileEntity.kt @@ -67,6 +67,9 @@ data class DashpayContactProfileEntity( val avatarHash: ByteArray? = null, /** 8-byte perceptual hash. */ val avatarFingerprint: ByteArray? = null, + val corePaymentAddress: ByteArray? = null, + val platformPaymentAddress: ByteArray? = null, + val shieldedAddress: ByteArray? = null, /** * Wall-clock ms of the last fetch attempt on the Rust side * (`ContactProfileEntry.checked_at_ms`) — drives the self-heal diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt index 6d8a8806839..a956ef22cc8 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/DashpayProfileEntity.kt @@ -44,6 +44,9 @@ data class DashpayProfileEntity( val avatarHash: ByteArray? = null, /** 8-byte perceptual hash. */ val avatarFingerprint: ByteArray? = null, + val corePaymentAddress: ByteArray? = null, + val platformPaymentAddress: ByteArray? = null, + val shieldedAddress: ByteArray? = null, val createdAt: Date = Date(), val lastUpdated: Date = Date(), ) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt index 1dfb441d1b0..0733d30a557 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/services/ShieldedService.kt @@ -208,7 +208,9 @@ class ShieldedService(private val database: DashDatabase) { _state.value = ShieldedSyncState() _shieldedBalance.value = database.shieldedDao() .observeUnspentNotesByWallet(walletId) - .map { notes -> notes.sumOf { it.value } } + // Rust also scans dedicated tip accounts; ordinary wallet balances only + // include the accounts selected by this service's caller. + .map { notes -> notes.filter { it.accountIndex in sortedAccounts }.sumOf { it.value } } try { manager.configureShielded(dbPath) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt index 4060881efa7..fc476498df8 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/Dashpay.kt @@ -37,6 +37,13 @@ class Dashpay internal constructor(private val walletHandle: Long, private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, ) { + /** Fetch and validate the current recipient through proof-verified DPNS and profile reads. */ + suspend fun resolveShieldedTip(username: String): ShieldedTipRecipient = gate.op { + val bytes = mapNativeErrors { org.dashfoundation.dashsdk.ffi.FundingNative.resolveShieldedTip(walletHandle, username) } + check(bytes.size == 75) { "Invalid recipient response" } + ShieldedTipRecipient(bytes.copyOfRange(0, 32), bytes.copyOfRange(32, 75)) + } + /** * Send a contact request to [recipientIdentityId], signing the document * state-transition with [signerHandle] and keying the contact crypto @@ -768,11 +775,17 @@ class Dashpay internal constructor(private val walletHandle: Long, avatarBytes: ByteArray? = null, doCreate: Boolean, signerHandle: Long, + corePaymentAddress: PaymentAddressUpdate = PaymentAddressUpdate.Keep, + platformPaymentAddress: PaymentAddressUpdate = PaymentAddressUpdate.Keep, + shieldedAddress: PaymentAddressUpdate = PaymentAddressUpdate.Keep, ): String? = gate.op { mapNativeErrors { DashpayNative.createOrUpdateProfile( walletHandle, identityId, displayName, publicMessage, avatarUrl, avatarBytes, doCreate, signerHandle, + corePaymentAddress.action, corePaymentAddress.bytes, + platformPaymentAddress.action, platformPaymentAddress.bytes, + shieldedAddress.action, shieldedAddress.bytes, ) } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt new file mode 100644 index 00000000000..2284dfa2b0c --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/PaymentAddressUpdate.kt @@ -0,0 +1,8 @@ +package org.dashfoundation.dashsdk.tokens + +/** Explicit partial-update semantics for a public profile payment address. */ +sealed class PaymentAddressUpdate(internal val action: Int, internal val bytes: ByteArray?) { + data object Keep : PaymentAddressUpdate(0, null) + class Set(bytes: ByteArray) : PaymentAddressUpdate(1, bytes.copyOf()) + data object Remove : PaymentAddressUpdate(2, null) +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt new file mode 100644 index 00000000000..5ba1d253d31 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt @@ -0,0 +1,16 @@ +package org.dashfoundation.dashsdk.tokens + +/** Verified recipient snapshot to bind payment confirmation to an identity and address. */ +class ShieldedTipRecipient(identityId: ByteArray, address: ByteArray) { + private val identityBytes = identityId.copyOf() + private val addressBytes = address.copyOf() + val identityId: ByteArray get() = identityBytes.copyOf() + val address: ByteArray get() = addressBytes.copyOf() + init { + require(identityBytes.size == 32) + require(addressBytes.size == 43) + } + override fun equals(other: Any?): Boolean = other is ShieldedTipRecipient && + identityBytes.contentEquals(other.identityBytes) && addressBytes.contentEquals(other.addressBytes) + override fun hashCode(): Int = 31 * identityBytes.contentHashCode() + addressBytes.contentHashCode() +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt new file mode 100644 index 00000000000..ad29af2cf00 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt @@ -0,0 +1,40 @@ +package org.dashfoundation.dashsdk.tokens + +import android.content.SharedPreferences +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.dashfoundation.dashsdk.Network +import org.dashfoundation.dashsdk.persistence.normalizeDpnsLabel + +/** + * Local record of recipients explicitly confirmed by this wallet's user. + * Mirrors the Swift tip sheet's persistent recipient-change warning. This + * record only informs confirmation; Rust still verifies the recipient before sending. + */ +class ShieldedTipRecipientHistory(private val preferences: SharedPreferences) { + fun hasChanged( + network: Network, walletId: ByteArray, username: String, recipient: ShieldedTipRecipient, + ): Boolean { + val previous = preferences.getString(key(network, walletId, username), null) ?: return false + return previous != snapshot(recipient) + } + + /** Call only after explicit confirmation, before submitting the payment. */ + suspend fun confirm( + network: Network, walletId: ByteArray, username: String, recipient: ShieldedTipRecipient, + ) = withContext(Dispatchers.IO) { + check(preferences.edit().putString(key(network, walletId, username), snapshot(recipient)).commit()) { + "Could not save recipient confirmation" + } + } + + private fun key(network: Network, walletId: ByteArray, username: String): String { + val label = username.trim().lowercase().removeSuffix(".dash") + return "${network.ffiValue}:${walletId.hex()}:${normalizeDpnsLabel(label)}.dash" + } + + private fun snapshot(recipient: ShieldedTipRecipient): String = + "${recipient.identityId.hex()}:${recipient.address.hex()}" + + private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) } +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt index 5a01e25f73d..b1bc061accc 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/ManagedPlatformWallet.kt @@ -1269,6 +1269,29 @@ class ManagedPlatformWallet internal constructor( } } + /** + * The HD derivation index of one managed identity, or null when the wallet + * holds no recoverable index for it (a watched or index-less identity). + * Per-identity state derived from the index — the dedicated shielded tip + * account — must treat null as "unavailable" rather than fall back to 0, + * which is identity 0's slot. Room's `IdentityEntity.identityIndex` is + * non-null and stores 0 as a placeholder, so it cannot answer this. + */ + suspend fun identityIndex(identityId: ByteArray): Int? = withContext(Dispatchers.IO) { + mapNativeErrors { + val identityHandle = translateManagedIdentityNotFoundToZero { + TokensNative.getManagedIdentity(handle, identityId) + } + if (identityHandle == 0L) return@mapNativeErrors null + try { + val index = WalletManagerNative.managedIdentityGetIdentityIndex(identityHandle) + if (index < 0) null else index.toInt() + } finally { + TokensNative.managedIdentityDestroy(identityHandle) + } + } + } + /** * The advisory "why not" reason a withdrawal preflight records when the * account can't fund one — port of the `success_with_message` reason the diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index ab4207b1213..f3aae892125 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -2027,6 +2027,27 @@ class PlatformWalletManager( // the caller must NOT retry (the spent notes stay reserved Rust-side // until a later shielded sync resolves them). + /** Dedicated account index derived by Rust's wallet convention. */ + fun shieldedTipAccountIndex(identityIndex: Int): Int = mapNativeErrors { FundingNative.tipAccountIndex(identityIndex) } + + suspend fun prepareShieldedTipAddress(walletId: ByteArray, identityId: ByteArray): ByteArray = teardownGate.op { + mapNativeErrors { FundingNative.prepareShieldedTipAddress(managerHandle, walletId, mnemonicResolver.nativeHandle, identityId) } + } + + /** Send only if fresh resolution still matches the recipient shown in confirmation. */ + suspend fun sendShieldedTip( + walletId: ByteArray, username: String, + recipient: org.dashfoundation.dashsdk.tokens.ShieldedTipRecipient, + amount: Long, account: Int = 0, memo: String? = null, + ): Unit = teardownGate.op { + require(amount > 0) { "amount must be positive, got $amount" } + require(account >= 0) { "account must be non-negative, got $account" } + mapNativeErrors { + FundingNative.sendShieldedTip(managerHandle, walletId, mnemonicResolver.nativeHandle, + account, username, recipient.identityId, recipient.address, amount, memo) + } + } + /** * Shielded → shielded transfer (Type 16) — port of Swift's * `PlatformWalletManager.shieldedTransfer(walletId:account:recipientRaw43:amount:memo:)` diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt index ac1ae6f77ae..406921c256f 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt @@ -242,8 +242,9 @@ class DashDatabaseTest { // 12 → 13 the contract bounds kind, 13 → 14 the token // once-per-identity distribution block, 14 → 15 the DashPay // backfill record columns on `wallets`, and 15 → 16 the private - // contact request scan state tables. - assertEquals(16, db.openHelper.readableDatabase.version) + // contact request scan state tables. 16 → 17 adds profile + // payment addresses. + assertEquals(17, db.openHelper.readableDatabase.version) val indexes = mutableSetOf() db.openHelper.readableDatabase.query("PRAGMA index_list('pending_inputs')").use { c -> val nameColumn = c.getColumnIndexOrThrow("name") diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index 6a40c939b72..521982befd8 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -912,6 +912,9 @@ class PlatformWalletPersistenceHandlerTest { dashpayAvatarFingerprint = ByteArray(8), dashpayAvatarFingerprintPresent = false, dashpayPublicMessage = "hi", + dashpayCorePaymentAddress = ByteArray(21) { 1 }, + dashpayPlatformPaymentAddress = ByteArray(21) { 2 }, + dashpayShieldedAddress = ByteArray(43) { 3 }, ) handler.onChangesetEnd(walletId, success = true) @@ -930,6 +933,9 @@ class PlatformWalletPersistenceHandlerTest { assertNotNull(profile) assertEquals("Alice", profile!!.displayName) assertEquals("hi", profile.publicMessage) + assertTrue(ByteArray(21) { 1 }.contentEquals(profile.corePaymentAddress)) + assertTrue(ByteArray(21) { 2 }.contentEquals(profile.platformPaymentAddress)) + assertTrue(ByteArray(43) { 3 }.contentEquals(profile.shieldedAddress)) assertNotNull(profile.avatarHash) assertNull(profile.avatarFingerprint) } @@ -5036,6 +5042,9 @@ class PlatformWalletPersistenceHandlerTest { avatarFingerprintPresent = false, publicMessage = "yo", checkedAtMs = 1_700_000_111_000, + corePaymentAddress = ByteArray(21) { 1 }, + platformPaymentAddress = ByteArray(21) { 2 }, + shieldedAddress = ByteArray(43) { 3 }, ) handler.onChangesetEnd(walletId, success = true) } @@ -5164,9 +5173,18 @@ class PlatformWalletPersistenceHandlerTest { ), ) + db.dashpayDao().upsertProfile( + org.dashfoundation.dashsdk.persistence.entities.DashpayProfileEntity( + networkRaw = testnet, identityId = ownerId, + displayName = "Alice", shieldedAddress = ByteArray(43) { 7 }, + ), + ) val list = handler.onLoadWalletList() assertEquals(1, list.size) val identity = list[0].identities.single() + assertEquals("Alice", identity.dashpayProfile?.displayName) + assertTrue(ByteArray(43) { 7 }.contentEquals(identity.dashpayProfile?.shieldedAddress)) + assertEquals(1, identity.payments.size) val payment = identity.payments[0] @@ -5179,6 +5197,9 @@ class PlatformWalletPersistenceHandlerTest { assertEquals(1, identity.contactProfiles.size) val profile = identity.contactProfiles[0] + assertTrue(ByteArray(21) { 1 }.contentEquals(profile.corePaymentAddress)) + assertTrue(ByteArray(21) { 2 }.contentEquals(profile.platformPaymentAddress)) + assertTrue(ByteArray(43) { 3 }.contentEquals(profile.shieldedAddress)) assertTrue(contactId.contentEquals(profile.contactId)) assertEquals("Bob", profile.displayName) assertNull(profile.bio) diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt new file mode 100644 index 00000000000..a5ebd51c380 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt @@ -0,0 +1,58 @@ +package org.dashfoundation.dashsdk.tokens + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.test.runTest +import org.dashfoundation.dashsdk.Network +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class ShieldedTipRecipientHistoryTest { + private val preferences = ApplicationProvider.getApplicationContext() + .getSharedPreferences("tip-recipient-history-test", Context.MODE_PRIVATE) + private val walletId = ByteArray(32) { 1 } + private val recipient = ShieldedTipRecipient(ByteArray(32) { 2 }, ByteArray(43) { 3 }) + private val history get() = ShieldedTipRecipientHistory(preferences) + + @Before + fun reset() { + preferences.edit().clear().commit() + } + + @Test + fun confirmationSurvivesReopeningAndCanonicalSpellings() = runTest { + assertFalse(history.hasChanged(Network.TESTNET, walletId, "Alice", recipient)) + history.confirm(Network.TESTNET, walletId, " Alice.DASH ", recipient) + assertFalse(history.hasChanged(Network.TESTNET, walletId, "a11ce", recipient)) + val changed = ShieldedTipRecipient(recipient.identityId, ByteArray(43) { 4 }) + assertTrue(history.hasChanged(Network.TESTNET, walletId, "a11ce.dash", changed)) + } + + @Test + fun detectsBothIdentityAndAddressReplacementWithoutChangingThePin() = runTest { + history.confirm(Network.TESTNET, walletId, "Alice", recipient) + val newIdentity = ShieldedTipRecipient(ByteArray(32) { 4 }, recipient.address) + val newAddress = ShieldedTipRecipient(recipient.identityId, ByteArray(43) { 5 }) + assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", newIdentity)) + assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", newAddress)) + assertFalse(history.hasChanged(Network.TESTNET, walletId, "Alice", recipient)) + history.confirm(Network.TESTNET, walletId, "Alice", newAddress) + assertFalse(history.hasChanged(Network.TESTNET, walletId, "Alice", newAddress)) + assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", recipient)) + } + + @Test + fun isolatesNetworksWalletsAndUsernames() = runTest { + history.confirm(Network.TESTNET, walletId, "Alice", recipient) + val changed = ShieldedTipRecipient(ByteArray(32) { 4 }, recipient.address) + assertFalse(history.hasChanged(Network.MAINNET, walletId, "Alice", changed)) + assertFalse(history.hasChanged(Network.TESTNET, ByteArray(32) { 6 }, "Alice", changed)) + assertFalse(history.hasChanged(Network.TESTNET, walletId, "Bob", changed)) + assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", changed)) + } +} diff --git a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs index 6c83f4d459e..5ac265a66c7 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs @@ -4,7 +4,7 @@ use std::ffi::CStr; use std::os::raw::c_char; use std::ptr; -use platform_wallet::{DashPayProfile, ProfileUpdate}; +use platform_wallet::{DashPayProfile, PaymentAddressUpdate, ProfileUpdate}; use rs_sdk_ffi::{SignerHandle, VTableSigner}; use crate::check_ptr; @@ -14,6 +14,35 @@ use crate::runtime::block_on_worker; use crate::types::*; use crate::{unwrap_option_or_return, unwrap_result_or_return}; +/// Payment address update: action 0 keeps, 1 sets, and 2 removes the property. +/// For action 1, `bytes` must point to `len` readable bytes for the call duration. +#[repr(C)] +pub struct PaymentAddressUpdateFFI { + pub action: u32, + pub bytes: *const u8, + pub len: usize, +} + +unsafe fn decode_address_update( + input: *const PaymentAddressUpdateFFI, +) -> Result { + if input.is_null() { + return Ok(PaymentAddressUpdate::Keep); + } + let input = &*input; + match input.action { + 0 => Ok(PaymentAddressUpdate::Keep), + 2 => Ok(PaymentAddressUpdate::Remove), + 1 if !input.bytes.is_null() && matches!(input.len, 21 | 43) => Ok( + PaymentAddressUpdate::Set(std::slice::from_raw_parts(input.bytes, input.len).to_vec()), + ), + _ => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "Invalid payment address update".to_string(), + )), + } +} + /// Flat FFI view of a [`DashPayProfile`]. #[repr(C)] pub struct DashPayProfileFFI { @@ -24,6 +53,12 @@ pub struct DashPayProfileFFI { pub avatar_hash: [u8; 32], pub avatar_fingerprint_is_some: bool, pub avatar_fingerprint: [u8; 8], + pub core_payment_address_is_some: bool, + pub core_payment_address: [u8; 21], + pub platform_payment_address_is_some: bool, + pub platform_payment_address: [u8; 21], + pub shielded_address_is_some: bool, + pub shielded_address: [u8; 43], } impl DashPayProfileFFI { @@ -36,6 +71,12 @@ impl DashPayProfileFFI { avatar_hash: [0u8; 32], avatar_fingerprint_is_some: false, avatar_fingerprint: [0u8; 8], + core_payment_address_is_some: false, + core_payment_address: [0; 21], + platform_payment_address_is_some: false, + platform_payment_address: [0; 21], + shielded_address_is_some: false, + shielded_address: [0; 43], } } @@ -61,6 +102,33 @@ impl DashPayProfileFFI { avatar_hash, avatar_fingerprint_is_some, avatar_fingerprint, + core_payment_address_is_some: profile + .core_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + core_payment_address: profile + .core_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + platform_payment_address_is_some: profile + .platform_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + platform_payment_address: profile + .platform_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + shielded_address_is_some: profile + .shielded_address + .as_ref() + .is_some_and(|a| a.len() == 43), + shielded_address: profile + .shielded_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 43]), } } } @@ -331,14 +399,49 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_s do_create: bool, signer_handle: *mut SignerHandle, out_profile: *mut DashPayProfileFFI, +) -> PlatformWalletFFIResult { + platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( + wallet_handle, + identity_id, + display_name, + public_message, + avatar_url, + avatar_bytes, + avatar_bytes_len, + ptr::null(), + ptr::null(), + ptr::null(), + do_create, + signer_handle, + out_profile, + ) +} + +/// Create or update a profile with explicit keep/set/remove payment address operations. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( + wallet_handle: Handle, + identity_id: *const u8, + display_name: *const c_char, + public_message: *const c_char, + avatar_url: *const c_char, + avatar_bytes: *const u8, + avatar_bytes_len: usize, + core_payment_address: *const PaymentAddressUpdateFFI, + platform_payment_address: *const PaymentAddressUpdateFFI, + shielded_address: *const PaymentAddressUpdateFFI, + do_create: bool, + signer_handle: *mut SignerHandle, + out_profile: *mut DashPayProfileFFI, ) -> PlatformWalletFFIResult { check_ptr!(out_profile); - check_ptr!(signer_handle); // `DashPayProfileFFI` owns heap C-string pointer fields freed by // `dashpay_profile_ffi_free`; publish the empty sentinel before any // fallible work so an error path never leaves uninitialized stack bytes // in those pointer fields. Matches the read-side helpers in this file. *out_profile = DashPayProfileFFI::empty(); + check_ptr!(signer_handle); let id = unwrap_result_or_return!(read_identifier(identity_id)); @@ -352,6 +455,12 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_s Some(std::slice::from_raw_parts(avatar_bytes, avatar_bytes_len).to_vec()) }; + let core_payment_address = + unwrap_result_or_return!(decode_address_update(core_payment_address)); + let platform_payment_address = + unwrap_result_or_return!(decode_address_update(platform_payment_address)); + let shielded_address = unwrap_result_or_return!(decode_address_update(shielded_address)); + let signer_addr = signer_handle as usize; let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, move |wallet| { @@ -361,6 +470,9 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_s public_message, avatar_url, avatar_bytes: avatar_bytes_vec, + core_payment_address, + platform_payment_address, + shielded_address, }; block_on_worker(async move { @@ -401,6 +513,79 @@ mod tests { }) } + #[test] + fn null_signer_leaves_profile_safe_to_free() { + unsafe { + let mut out = std::mem::MaybeUninit::::uninit(); + let result = platform_wallet_create_or_update_dashpay_profile_with_signer( + 0, + ptr::null(), + ptr::null(), + ptr::null(), + ptr::null(), + ptr::null(), + 0, + false, + ptr::null_mut(), + out.as_mut_ptr(), + ); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + let mut out = out.assume_init(); + assert!(out.display_name.is_null()); + assert!(!out.shielded_address_is_some); + dashpay_profile_ffi_free(&mut out); + } + } + + #[test] + fn payment_address_updates_preserve_distinct_operations() { + unsafe { + assert!(matches!( + decode_address_update(ptr::null()).unwrap(), + PaymentAddressUpdate::Keep + )); + let mut update = PaymentAddressUpdateFFI { + action: 2, + bytes: ptr::null(), + len: 0, + }; + assert!(matches!( + decode_address_update(&update).unwrap(), + PaymentAddressUpdate::Remove + )); + update.action = 1; + assert!(decode_address_update(&update).is_err()); + let address = [7u8; 43]; + update.bytes = address.as_ptr(); + update.len = address.len(); + match decode_address_update(&update).unwrap() { + PaymentAddressUpdate::Set(bytes) => assert_eq!(bytes, address), + _ => panic!("expected set operation"), + } + update.action = 3; + assert!(decode_address_update(&update).is_err()); + } + } + + #[test] + fn profile_addresses_copy_to_owned_fixed_buffers() { + let profile = DashPayProfile { + core_payment_address: Some(vec![1; 21]), + platform_payment_address: Some(vec![2; 21]), + shielded_address: Some(vec![3; 43]), + ..Default::default() + }; + let mut ffi = DashPayProfileFFI::from_profile(&profile); + assert!(ffi.core_payment_address_is_some); + assert!(ffi.platform_payment_address_is_some); + assert!(ffi.shielded_address_is_some); + drop(profile); + assert_eq!(ffi.core_payment_address, [1; 21]); + assert_eq!(ffi.platform_payment_address, [2; 21]); + assert_eq!(ffi.shielded_address, [3; 43]); + unsafe { dashpay_profile_ffi_free(&mut ffi) }; + } + #[test] fn test_get_profile_absent_returns_false_flag() { unsafe { @@ -437,6 +622,7 @@ mod tests { avatar_hash: Some(hash), avatar_fingerprint: Some([1, 2, 3, 4, 5, 6, 7, 8]), public_message: Some("Hello world".to_string()), + ..Default::default() }); let handle = MANAGED_IDENTITY_STORAGE.insert(managed); diff --git a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs index e04c82a2ff0..5d988fb33cd 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs @@ -137,6 +137,13 @@ pub struct IdentityEntryFFI { pub dashpay_profile_avatar_fingerprint: [u8; 8], /// `true` iff the source `avatar_fingerprint` was `Some(_)`. pub dashpay_profile_avatar_fingerprint_present: bool, + pub dashpay_profile_core_payment_address: [u8; 21], + pub dashpay_profile_core_payment_address_present: bool, + pub dashpay_profile_platform_payment_address: [u8; 21], + pub dashpay_profile_platform_payment_address_present: bool, + pub dashpay_profile_shielded_address: [u8; 43], + pub dashpay_profile_shielded_address_present: bool, + /// Heap-allocated NUL-terminated UTF-8 C string for the DashPay /// profile's public message. `null` when the source field was /// `None`. Owned by this FFI struct; freed in @@ -213,6 +220,13 @@ pub struct ContactProfileRowFFI { pub avatar_fingerprint: [u8; 8], /// `true` iff the source `avatar_fingerprint` was `Some(_)`. pub avatar_fingerprint_present: bool, + pub core_payment_address: [u8; 21], + pub core_payment_address_present: bool, + pub platform_payment_address: [u8; 21], + pub platform_payment_address_present: bool, + pub shielded_address: [u8; 43], + pub shielded_address_present: bool, + /// Heap-allocated `publicMessage`; `null` when `None`. Freed in /// [`free_identity_entry_ffi`]. pub public_message: *const c_char, @@ -377,38 +391,8 @@ const _: [u8; 8] = [0u8; std::mem::align_of::()]; // than a build error. Pin the expected size here so any reshape // fails the cargo build first. // -// Expected layout on 64-bit targets (all fields in declaration -// order under `#[repr(C)]`): -// -// 0..=31 identity_id [u8; 32] -// 32..=39 balance u64 -// 40..=47 revision u64 -// 48 identity_index_is_some bool -// 49..=51 (padding to 4) -// 52..=55 identity_index u32 -// 56 status u8 -// 57 wallet_id_is_some bool -// 58..=89 wallet_id [u8; 32] -// 90..=95 (padding to 8 for pointer alignment) -// 96..=103 dpns_names *const *const c_char -// 104..=111 dpns_names_count usize -// 112..=119 dpns_names_acquired_at *const u64 -// 120 dashpay_profile_present bool -// 121..=127 (padding to 8 for pointer alignment) -// 128..=135 dashpay_profile_display_name *const c_char -// 136..=143 dashpay_profile_bio *const c_char -// 144..=151 dashpay_profile_avatar_url *const c_char -// 152..=183 dashpay_profile_avatar_hash [u8; 32] -// 184 dashpay_profile_avatar_hash_present bool -// 185..=192 dashpay_profile_avatar_fingerprint [u8; 8] -// 193 dashpay_profile_avatar_fingerprint_present bool -// 194..=199 (padding to 8 for pointer alignment) -// 200..=207 dashpay_profile_public_message *const c_char -// 208..=215 contact_profiles *const ContactProfileRowFFI -// 216..=223 contact_profiles_count usize -// -// Total size = 224, alignment = 8 (from u64 / pointer). -const _: [u8; 224] = [0u8; std::mem::size_of::()]; +// Includes three fixed-size payment addresses and their presence flags. +const _: [u8; 312] = [0u8; std::mem::size_of::()]; const _: [u8; 8] = [0u8; std::mem::align_of::()]; // --------------------------------------------------------------------------- @@ -471,6 +455,15 @@ impl IdentityEntryFFI { dashpay_profile_avatar_hash_present: profile_fields.avatar_hash_present, dashpay_profile_avatar_fingerprint: profile_fields.avatar_fingerprint, dashpay_profile_avatar_fingerprint_present: profile_fields.avatar_fingerprint_present, + dashpay_profile_core_payment_address: profile_fields.core_payment_address, + dashpay_profile_core_payment_address_present: profile_fields + .core_payment_address_present, + dashpay_profile_platform_payment_address: profile_fields.platform_payment_address, + dashpay_profile_platform_payment_address_present: profile_fields + .platform_payment_address_present, + dashpay_profile_shielded_address: profile_fields.shielded_address, + dashpay_profile_shielded_address_present: profile_fields.shielded_address_present, + dashpay_profile_public_message: profile_fields.public_message, contact_profiles, contact_profiles_count, @@ -493,6 +486,13 @@ struct DashPayProfileFields { avatar_hash_present: bool, avatar_fingerprint: [u8; 8], avatar_fingerprint_present: bool, + core_payment_address: [u8; 21], + core_payment_address_present: bool, + platform_payment_address: [u8; 21], + platform_payment_address_present: bool, + shielded_address: [u8; 43], + shielded_address_present: bool, + public_message: *const c_char, } @@ -508,6 +508,13 @@ impl DashPayProfileFields { avatar_hash_present: false, avatar_fingerprint: [0u8; 8], avatar_fingerprint_present: false, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [0; 43], + shielded_address_present: false, + public_message: ptr::null(), } } @@ -535,6 +542,34 @@ impl DashPayProfileFields { avatar_hash_present, avatar_fingerprint, avatar_fingerprint_present, + core_payment_address: profile + .core_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + core_payment_address_present: profile + .core_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + platform_payment_address: profile + .platform_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + platform_payment_address_present: profile + .platform_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + shielded_address: profile + .shielded_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 43]), + shielded_address_present: profile + .shielded_address + .as_ref() + .is_some_and(|a| a.len() == 43), + public_message: optional_c_string(profile.public_message.as_deref()), } } @@ -634,6 +669,13 @@ fn allocate_contact_profile_rows( avatar_hash_present: false, avatar_fingerprint: [0u8; 8], avatar_fingerprint_present: false, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [0; 43], + shielded_address_present: false, + public_message: ptr::null(), checked_at_ms: entry.checked_at_ms, }); @@ -657,6 +699,34 @@ fn allocate_contact_profile_rows( avatar_hash_present, avatar_fingerprint, avatar_fingerprint_present, + core_payment_address: profile + .core_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + core_payment_address_present: profile + .core_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + platform_payment_address: profile + .platform_payment_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 21]), + platform_payment_address_present: profile + .platform_payment_address + .as_ref() + .is_some_and(|a| a.len() == 21), + shielded_address: profile + .shielded_address + .as_deref() + .and_then(|a| a.try_into().ok()) + .unwrap_or([0; 43]), + shielded_address_present: profile + .shielded_address + .as_ref() + .is_some_and(|a| a.len() == 43), + public_message: optional_c_string(profile.public_message.as_deref()), checked_at_ms: entry.checked_at_ms, }); @@ -1050,6 +1120,7 @@ mod tests { avatar_hash: Some([0xAB; 32]), avatar_fingerprint: Some([0xCD; 8]), public_message: None, + ..Default::default() }), dashpay_payments: Default::default(), contact_profiles: Default::default(), @@ -1102,6 +1173,7 @@ mod tests { avatar_hash: Some([0x11; 32]), avatar_fingerprint: None, public_message: None, + ..Default::default() }), checked_at_ms: 111, }, diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 8495c4464ac..5e6aac742f4 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -7180,6 +7180,9 @@ fn build_wallet_identity_bucket( unsafe { restore_dashpay_payments(spec, &mut managed) }; unsafe { restore_dashpay_ignored(spec, &mut managed) }; unsafe { restore_contact_profiles(spec, &mut managed) }; + if let Some(profile) = unsafe { spec.dashpay_profile.as_ref() } { + *managed.dashpay_profile_mut() = Some(unsafe { profile_from_restore_row(profile) }); + } bucket.insert(spec.identity_index, managed); } @@ -7340,6 +7343,42 @@ fn is_valid_avatar_url(url: &str) -> bool { !url.is_empty() && url.len() <= MAX_AVATAR_URL_LEN && url.starts_with("https://") } +/// Copy a host-owned profile row, retaining the avatar URL validation used for +/// cached contact profiles. The host frees the buffers after restoration returns. +/// +/// # Safety +/// The row's string pointers must be null or readable NUL-terminated strings. +unsafe fn profile_from_restore_row( + row: &ContactProfileRestoreEntryFFI, +) -> platform_wallet::DashPayProfile { + let opt_string = |ptr: *const std::os::raw::c_char| -> Option { + if ptr.is_null() { + None + } else { + CStr::from_ptr(ptr).to_str().ok().map(str::to_string) + } + }; + platform_wallet::DashPayProfile { + display_name: opt_string(row.display_name), + bio: opt_string(row.bio), + avatar_url: opt_string(row.avatar_url).filter(|u| is_valid_avatar_url(u)), + avatar_hash: row.avatar_hash_present.then_some(row.avatar_hash), + avatar_fingerprint: row + .avatar_fingerprint_present + .then_some(row.avatar_fingerprint), + public_message: opt_string(row.public_message), + core_payment_address: row + .core_payment_address_present + .then(|| row.core_payment_address.to_vec()), + platform_payment_address: row + .platform_payment_address_present + .then(|| row.platform_payment_address.to_vec()), + shielded_address: row + .shielded_address_present + .then(|| row.shielded_address.to_vec()), + } +} + /// Fold a slice of [`ContactProfileRestoreEntryFFI`] rows into /// the managed identity's contact-profile cache. Split out from /// [`restore_contact_profiles`] so the c-string decode + avatar-url @@ -7353,43 +7392,11 @@ unsafe fn apply_contact_profile_rows( rows: &[ContactProfileRestoreEntryFFI], managed: &mut ManagedIdentity, ) { - use platform_wallet::{ContactProfileEntry, DashPayProfile}; - - let opt_string = |ptr: *const std::os::raw::c_char| -> Option { - if ptr.is_null() { - None - } else { - CStr::from_ptr(ptr).to_str().ok().map(str::to_string) - } - }; - for row in rows { - let avatar_hash = if row.avatar_hash_present { - Some(row.avatar_hash) - } else { - None - }; - let avatar_fingerprint = if row.avatar_fingerprint_present { - Some(row.avatar_fingerprint) - } else { - None - }; - // Re-validate the public, attacker-controlled avatar URL; drop - // just the URL field (keep the rest of the profile) if it no - // longer passes the `https://` / length rule. - let avatar_url = opt_string(row.avatar_url).filter(|u| is_valid_avatar_url(u)); - managed.dashpay_contact_profiles_mut().insert( Identifier::from(row.contact_id), - ContactProfileEntry { - profile: Some(DashPayProfile { - display_name: opt_string(row.display_name), - bio: opt_string(row.bio), - avatar_url, - avatar_hash, - avatar_fingerprint, - public_message: opt_string(row.public_message), - }), + platform_wallet::ContactProfileEntry { + profile: Some(profile_from_restore_row(row)), checked_at_ms: row.checked_at_ms, }, ); @@ -9575,6 +9582,155 @@ mod tests { "both host allocations freed" ); } + /// The owned DashPay profile a host supplies on the wallet-restore load + /// callback reaches the restored `ManagedIdentity` with every field, + /// including the three payment addresses, and is an owned copy: the free + /// callback scribbles over the host buffers before anything is asserted. A + /// null profile pointer restores no profile. + #[test] + fn owned_dashpay_profile_hydrates_through_the_load_callback() { + use crate::wallet_restore_types::{ContactProfileRestoreEntryFFI, IdentityRestoreEntryFFI}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Host { + strings: Vec>, + profile: ContactProfileRestoreEntryFFI, + identities: Vec, + wallet: WalletRestoreEntryFFI, + frees: AtomicUsize, + } + fn c_buf(text: &str) -> Box<[u8]> { + let mut bytes = text.as_bytes().to_vec(); + bytes.push(0); + bytes.into_boxed_slice() + } + fn identity(id: u8, index: u32) -> IdentityRestoreEntryFFI { + IdentityRestoreEntryFFI { + identity_id: [id; 32], + balance: 7, + revision: 1, + identity_index: index, + status: 2, + dpns_names: std::ptr::null(), + dpns_names_count: 0, + contested_dpns_names: std::ptr::null(), + contested_dpns_names_count: 0, + keys: std::ptr::null(), + keys_count: 0, + contacts: std::ptr::null(), + contacts_count: 0, + payments: std::ptr::null(), + payments_count: 0, + ignored_senders: std::ptr::null(), + ignored_senders_count: 0, + contact_profiles: std::ptr::null(), + contact_profiles_count: 0, + dashpay_profile: std::ptr::null(), + } + } + unsafe extern "C" fn load_wallet( + context: *mut c_void, + entries: *mut *const WalletRestoreEntryFFI, + count: *mut usize, + ) -> i32 { + let host = &mut *(context as *mut Host); + host.strings = ["Alice", "bio text", "https://example.com/a.png", "hello"] + .into_iter() + .map(c_buf) + .collect(); + host.profile = ContactProfileRestoreEntryFFI { + contact_id: [0; 32], + display_name: host.strings[0].as_ptr().cast(), + bio: host.strings[1].as_ptr().cast(), + avatar_url: host.strings[2].as_ptr().cast(), + avatar_hash: [0xA1; 32], + avatar_hash_present: true, + avatar_fingerprint: [0xF1; 8], + avatar_fingerprint_present: true, + core_payment_address: [0xC1; 21], + core_payment_address_present: true, + platform_payment_address: [0xD1; 21], + platform_payment_address_present: true, + shielded_address: [0xE1; 43], + shielded_address_present: true, + public_message: host.strings[3].as_ptr().cast(), + checked_at_ms: 0, + }; + let mut with_profile = identity(0x11, 0); + with_profile.dashpay_profile = &host.profile; + host.identities = vec![with_profile, identity(0x22, 1)]; + host.wallet = WalletRestoreEntryFFI { + wallet_id: [42; 32], + identities: host.identities.as_ptr(), + identities_count: host.identities.len(), + ..Default::default() + }; + *entries = &host.wallet; + *count = 1; + 0 + } + unsafe extern "C" fn free_wallet( + context: *mut c_void, + _entries: *const WalletRestoreEntryFFI, + _count: usize, + ) { + let host = &mut *(context as *mut Host); + // Anything Rust still borrowed would now read as garbage. + for buf in &mut host.strings { + let len = buf.len(); + buf[..len - 1].fill(b'X'); + } + host.profile.avatar_hash = [0; 32]; + host.profile.core_payment_address = [0; 21]; + host.profile.platform_payment_address = [0; 21]; + host.profile.shielded_address = [0; 43]; + host.frees.fetch_add(1, Ordering::SeqCst); + } + + let host = Box::leak(Box::new(Host { + strings: Vec::new(), + profile: unsafe { std::mem::zeroed() }, + identities: Vec::new(), + wallet: WalletRestoreEntryFFI::default(), + frees: AtomicUsize::new(0), + })); + let persister = FFIPersister::new(PersistenceCallbacks { + context: (host as *mut Host).cast(), + on_load_wallet_list_fn: Some(load_wallet), + on_load_wallet_list_free_fn: Some(free_wallet), + ..Default::default() + }); + let snapshot = persister.load().expect("host snapshot"); + assert_eq!(host.frees.load(Ordering::SeqCst), 1, "host buffers freed"); + + let bucket = &snapshot.wallets[&[42; 32]] + .identity_manager + .wallet_identities[&[42; 32]]; + let profile = bucket[&0] + .dashpay() + .profile + .clone() + .expect("owned profile restored"); + assert_eq!( + profile, + platform_wallet::DashPayProfile { + display_name: Some("Alice".into()), + bio: Some("bio text".into()), + avatar_url: Some("https://example.com/a.png".into()), + avatar_hash: Some([0xA1; 32]), + avatar_fingerprint: Some([0xF1; 8]), + public_message: Some("hello".into()), + core_payment_address: Some(vec![0xC1; 21]), + platform_payment_address: Some(vec![0xD1; 21]), + shielded_address: Some(vec![0xE1; 43]), + } + ); + assert!( + bucket[&1].dashpay().profile.is_none(), + "a null profile pointer restores no profile" + ); + } + unsafe extern "C" fn noop_free_wallets( _ctx: *mut c_void, _entries: *const WalletRestoreEntryFFI, @@ -13831,6 +13987,13 @@ mod tests { avatar_hash_present: true, avatar_fingerprint: [0x22; 8], avatar_fingerprint_present: true, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [3; 43], + shielded_address_present: true, + public_message: public_message.as_ptr(), checked_at_ms: 1_700_000_000_000, }, @@ -13843,6 +14006,13 @@ mod tests { avatar_hash_present: false, avatar_fingerprint: [0u8; 8], avatar_fingerprint_present: false, + core_payment_address: [0; 21], + core_payment_address_present: false, + platform_payment_address: [0; 21], + platform_payment_address_present: false, + shielded_address: [0; 43], + shielded_address_present: false, + public_message: std::ptr::null(), checked_at_ms: 1_700_000_000_001, }, @@ -13867,6 +14037,7 @@ mod tests { ); assert_eq!(alice_profile.avatar_hash, Some([0x11; 32])); assert_eq!(alice_profile.avatar_fingerprint, Some([0x22; 8])); + assert_eq!(alice_profile.shielded_address, Some(vec![3; 43])); assert!(alice_profile.bio.is_none()); let bob = managed diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 2c28e59d1ad..e7c0daca4f0 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -749,6 +749,48 @@ pub(crate) fn catch_spend_panic( ) } +/// Post-panic guidance for exports that move no funds. Paired with +/// `ErrorWalletOperation` in [`catch_query_panic`]. +const QUERY_PANIC_GUIDANCE: &str = "No funds were moved; the call may be retried."; + +/// [`catch_panic_to_code`] specialized for exports that spend nothing (address +/// preparation, recipient resolution). A panic there is a plain failure of this +/// call, so it maps to [`PlatformWalletFFIResultCode::ErrorWalletOperation`] and +/// the host may retry. The boundary matters as much as on the spend path: an +/// unwind that reaches the `extern "C"` frame aborts the process before the JNI +/// guard on the far side can translate it. +fn catch_query_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorWalletOperation, + QUERY_PANIC_GUIDANCE, + body, + ) +} + +/// Test-only fault injection for the tip exports: while set, the worker future +/// of each guarded tip call panics before it touches the wallet, so a test can +/// prove the real `extern "C"` entry point (not just the helper) contains the +/// unwind. Process-global because the future runs on a tokio worker thread; +/// consulted only by the three tip exports. +#[cfg(test)] +static INJECT_TIP_WORKER_PANIC: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +#[cfg(test)] +fn maybe_inject_tip_worker_panic() { + if INJECT_TIP_WORKER_PANIC.load(std::sync::atomic::Ordering::SeqCst) { + panic!("injected tip worker panic"); + } +} + +#[cfg(not(test))] +#[inline(always)] +fn maybe_inject_tip_worker_panic() {} + /// Post-panic guidance for the asset-lock funding exports. Paired with /// `ErrorTransactionBroadcastUnconfirmed` in [`catch_funding_panic`]. const FUNDING_PANIC_GUIDANCE: &str = "The asset lock may or may not have been broadcast — do \ @@ -2346,6 +2388,219 @@ pub(crate) fn resolve_shielded_coordinator( } } +/// Derive and register the identity's dedicated tip account, without publishing it. +/// All ID pointers must reference 32 bytes; `out_address` must reference 43 writable bytes. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_tip_address( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + identity_id_bytes: *const u8, + out_address: *mut u8, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(identity_id_bytes); + check_ptr!(out_address); + std::ptr::write_bytes(out_address, 0, 43); + let wallet_id: [u8; 32] = std::slice::from_raw_parts(wallet_id_bytes, 32) + .try_into() + .unwrap(); + let identity_id = match crate::types::read_identifier(identity_id_bytes) { + Ok(id) => id, + Err(e) => return e.into(), + }; + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(value) => value, + Err(e) => return e, + }; + let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( + mnemonic_resolver_handle, + &wallet_id, + ) { + Ok(value) => value, + Err(e) => return e, + }; + // The worker call and its result mapping sit inside the panic boundary; + // the raw output write happens outside it, only on success, so a panic + // leaves the zeroed buffer untouched. + let mut address = [0u8; 43]; + let result = catch_query_panic( + "shielded tip address preparation", + || match block_on_worker(async move { + maybe_inject_tip_worker_panic(); + wallet + .prepare_shielded_tip_address(seed.as_ref(), &identity_id, &coordinator) + .await + }) { + Ok(bytes) => { + address = bytes; + PlatformWalletFFIResult::ok() + } + Err(e) => e.into(), + }, + ); + if result.code == PlatformWalletFFIResultCode::Success { + std::ptr::copy_nonoverlapping(address.as_ptr(), out_address, 43); + } + result +} + +/// Resolve a username using verified current DPNS and profile documents. +/// Outputs are 32-byte identity ID and 43-byte Orchard address buffers. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_resolve_shielded_tip( + wallet_handle: Handle, + username: *const c_char, + out_identity_id: *mut u8, + out_address: *mut u8, +) -> PlatformWalletFFIResult { + check_ptr!(username); + check_ptr!(out_identity_id); + check_ptr!(out_address); + std::ptr::write_bytes(out_identity_id, 0, 32); + std::ptr::write_bytes(out_address, 0, 43); + let username = match CStr::from_ptr(username).to_str() { + Ok(s) => s.to_owned(), + Err(e) => return e.into(), + }; + let mut identity_id = [0u8; 32]; + let mut address = [0u8; 43]; + let result = catch_query_panic("shielded tip resolution", || { + // Clone under the registry guard, then release it: the resolution makes + // DPNS and profile network requests, and holding the global wallet + // registry lock across them would block handle creation and teardown + // for unrelated wallets. + let identity = + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()); + let result = identity.map(|identity| { + block_on_worker(async move { + maybe_inject_tip_worker_panic(); + identity.dashpay().resolve_shielded_tip(&username).await + }) + }); + match result { + Some(Ok(recipient)) => { + identity_id = recipient.identity_id.to_buffer(); + address = recipient.address; + PlatformWalletFFIResult::ok() + } + Some(Err(e)) => e.into(), + None => PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::NotFound, + "Wallet not found", + ), + } + }); + if result.code == PlatformWalletFFIResultCode::Success { + std::ptr::copy_nonoverlapping(identity_id.as_ptr(), out_identity_id, 32); + std::ptr::copy_nonoverlapping(address.as_ptr(), out_address, 43); + } + result +} + +/// Send a tip only if fresh resolution matches the recipient the user confirmed. +/// ID/address pointers must reference 32/43 readable bytes respectively. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + username: *const c_char, + expected_identity_id: *const u8, + expected_address: *const u8, + amount: u64, + memo_text: *const c_char, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(mnemonic_resolver_handle); + check_ptr!(username); + check_ptr!(expected_identity_id); + check_ptr!(expected_address); + let username = match CStr::from_ptr(username).to_str() { + Ok(s) => s.to_owned(), + Err(e) => return e.into(), + }; + let wallet_id: [u8; 32] = std::slice::from_raw_parts(wallet_id_bytes, 32) + .try_into() + .unwrap(); + let identity_id = match crate::types::read_identifier(expected_identity_id) { + Ok(id) => id, + Err(e) => return e.into(), + }; + let address: [u8; 43] = std::slice::from_raw_parts(expected_address, 43) + .try_into() + .unwrap(); + let memo_str = match crate::dashpay_profile::decode_opt_c_str(memo_text) { + Ok(value) => value, + Err(e) => return e, + }; + let memo = match encode_memo_text(memo_str.as_deref()) { + Ok(value) => value, + Err(e) => return e, + }; + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(value) => value, + Err(e) => return e, + }; + let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( + mnemonic_resolver_handle, + &wallet_id, + ) { + Ok(value) => value, + Err(e) => return e, + }; + catch_spend_panic("shielded tip", || { + let result = block_on_worker(async move { + maybe_inject_tip_worker_panic(); + let recipient = platform_wallet::ShieldedTipRecipient { + identity_id, + address, + }; + let prover = CachedOrchardProver::new(); + let result = wallet + .send_shielded_tip( + &coordinator, + seed.as_ref(), + account, + &username, + &recipient, + amount, + memo, + &prover, + ) + .await; + poke_sync_on_unconfirmed(&result, handle); + result + }); + map_spend_result(result, "shielded tip") + }) +} + +/// Return the dedicated ZIP-32 tip account for a wallet identity derivation index. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_shielded_tip_account_index( + identity_index: u32, + out_account: *mut u32, +) -> PlatformWalletFFIResult { + check_ptr!(out_account); + *out_account = 0; + match platform_wallet::wallet::shielded::tips::shielded_tip_account_index(identity_index) { + Ok(account) => { + *out_account = account; + PlatformWalletFFIResult::ok() + } + Err(e) => e.into(), + } +} + +/// Whether an account is reserved for explicitly selected DashPay tip activity. +#[no_mangle] +pub extern "C" fn platform_wallet_is_shielded_tip_account(account: u32) -> bool { + platform_wallet::wallet::shielded::is_shielded_tip_account(account) +} + #[cfg(test)] mod tests { use super::*; @@ -2897,6 +3152,208 @@ mod tests { ); } + /// A fixed BIP-39 phrase the test resolver answers for every wallet id; + /// the wallet under test is created from the same phrase so the resolved + /// seed matches it. + const TIP_TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon \ + abandon abandon abandon abandon about"; + + unsafe extern "C" fn resolve_tip_test_mnemonic( + _ctx: *const std::ffi::c_void, + _wallet_id: *const u8, + out: *mut c_char, + cap: usize, + out_len: *mut usize, + ) -> i32 { + let phrase = TIP_TEST_MNEMONIC.as_bytes(); + assert!(cap >= phrase.len()); + std::ptr::copy_nonoverlapping(phrase.as_ptr(), out.cast::(), phrase.len()); + *out_len = phrase.len(); + rs_sdk_ffi::mnemonic_resolver_result::SUCCESS + } + + unsafe extern "C" fn destroy_tip_test_resolver(_ctx: *mut std::ffi::c_void) {} + + /// A manager with a configured shielded store and one wallet created from + /// `TIP_TEST_MNEMONIC`: the state a tip export needs to get past every + /// argument check and into its guarded worker call. + fn tip_test_manager() -> (Handle, [u8; 32], std::path::PathBuf) { + let handle = recovery_test_manager(); + let path = + std::env::temp_dir().join(format!("shielded-ffi-tip-{}-{handle}", std::process::id())); + std::fs::create_dir_all(&path).expect("temporary store directory"); + let wallet_id = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |manager| { + runtime().block_on(async { + manager + .configure_shielded(path.join("tree.sqlite")) + .await + .expect("configure shielded store"); + manager + .create_wallet_from_mnemonic( + TIP_TEST_MNEMONIC, + key_wallet::Network::Testnet, + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("register wallet") + .wallet_id() + }) + }) + .expect("live manager"); + (handle, wallet_id, path) + } + + /// The real exports contain a worker panic instead of letting it unwind into + /// the `extern "C"` frame: this drives the exported entry points themselves, + /// so deleting a guard at a call site fails here even while the helper-level + /// tests below stay green. One test covers all three exports because the + /// injection flag is process-global. + #[test] + fn exported_tip_entry_points_contain_a_worker_panic() { + use std::sync::atomic::Ordering::SeqCst; + + let (handle, wallet_id, path) = tip_test_manager(); + let mut vtable = rs_sdk_ffi::MnemonicResolverVTable { + resolve: resolve_tip_test_mnemonic, + destroy: destroy_tip_test_resolver, + }; + let mut resolver = MnemonicResolverHandle { + ctx: std::ptr::null_mut(), + vtable: &mut vtable, + }; + let username = std::ffi::CString::new("alice").expect("username"); + let identity_id = [0x21u8; 32]; + let address = [0x43u8; 43]; + + INJECT_TIP_WORKER_PANIC.store(true, SeqCst); + + // Spending export: the ambiguous, do-not-retry contract. + let mut send = unsafe { + platform_wallet_manager_send_shielded_tip( + handle, + wallet_id.as_ptr(), + &mut resolver, + 0, + username.as_ptr(), + identity_id.as_ptr(), + address.as_ptr(), + 1_000, + std::ptr::null(), + ) + }; + assert_eq!( + send.code, + PlatformWalletFFIResultCode::ErrorShieldedSpendUnconfirmed + ); + let message = message_of(&send); + assert!( + message.contains("injected tip worker panic") && message.contains("do NOT retry"), + "{message}" + ); + + // Non-spending exports: a retryable failure with the outputs left zeroed. + let mut out_address = [0xAAu8; 43]; + let mut prepare = unsafe { + platform_wallet_manager_prepare_shielded_tip_address( + handle, + wallet_id.as_ptr(), + &mut resolver, + identity_id.as_ptr(), + out_address.as_mut_ptr(), + ) + }; + assert_eq!( + prepare.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&prepare); + assert!( + message.contains("injected tip worker panic") && message.contains("may be retried"), + "{message}" + ); + assert_eq!( + out_address, [0u8; 43], + "no address may escape a failed call" + ); + + let mut wallet_handle = NULL_HANDLE; + let mut got = unsafe { + crate::manager::platform_wallet_manager_get_wallet( + handle, + &wallet_id, + &mut wallet_handle, + ) + }; + assert_eq!(got.code, PlatformWalletFFIResultCode::Success); + let mut out_identity = [0xAAu8; 32]; + let mut out_recipient = [0xAAu8; 43]; + let mut resolve = unsafe { + platform_wallet_resolve_shielded_tip( + wallet_handle, + username.as_ptr(), + out_identity.as_mut_ptr(), + out_recipient.as_mut_ptr(), + ) + }; + assert_eq!( + resolve.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + assert!(message_of(&resolve).contains("injected tip worker panic")); + assert_eq!(out_identity, [0u8; 32]); + assert_eq!(out_recipient, [0u8; 43]); + + INJECT_TIP_WORKER_PANIC.store(false, SeqCst); + unsafe { + crate::platform_wallet_ffi_result_free(&mut send); + crate::platform_wallet_ffi_result_free(&mut prepare); + crate::platform_wallet_ffi_result_free(&mut resolve); + crate::platform_wallet_ffi_result_free(&mut got); + let mut destroyed = crate::wallet::platform_wallet_destroy(wallet_handle); + crate::platform_wallet_ffi_result_free(&mut destroyed); + let mut destroyed = platform_wallet_manager_destroy(handle); + crate::platform_wallet_ffi_result_free(&mut destroyed); + } + let _ = std::fs::remove_dir_all(path); + } + + #[test] + fn catch_query_panic_maps_a_panic_to_a_retryable_wallet_operation() { + let result = catch_query_panic("shielded tip resolution", || { + panic!("tokio worker panicked"); + }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&result); + assert!( + message.contains("shielded tip resolution panicked") + && message.contains("tokio worker panicked") + && message.contains("may be retried"), + "{message}" + ); + } + + #[test] + fn should_contain_tip_worker_panic_as_uncertain_spend() { + let result = catch_spend_panic("shielded tip", || { + let result = block_on_worker(async { + panic!("tip worker failed after possible broadcast"); + #[allow(unreachable_code)] + Ok(()) + }); + map_spend_result(result, "shielded tip") + }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedSpendUnconfirmed + ); + assert!(message_of(&result).contains("do NOT retry")); + } + /// A panic inside the CoinJoin-drain funding export must NOT unwind into the `extern "C"` /// frame (that aborts the Android process before the JNI layer's own guard can translate it /// into a Java exception). It becomes `ErrorTransactionBroadcastUnconfirmed` — the diff --git a/packages/rs-platform-wallet-ffi/src/shielded_sync.rs b/packages/rs-platform-wallet-ffi/src/shielded_sync.rs index 3cdf55f5e1e..4d94d18e345 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_sync.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_sync.rs @@ -890,6 +890,89 @@ fn map_shielded_error(error: PlatformWalletError, operation: &str) -> PlatformWa } } +/// Snapshot the effective bound accounts, including discovered and restored tip +/// accounts. An unbound wallet returns an empty array. The caller must release +/// a nonempty result with `platform_wallet_manager_free_shielded_account_indices`. +/// +/// # Safety +/// `wallet_id_bytes` must point to 32 readable bytes; both output pointers must +/// be writable. Returned indices are valid until freed by the caller. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_account_indices( + handle: Handle, + wallet_id_bytes: *const u8, + out_indices: *mut *mut u32, + out_count: *mut usize, +) -> PlatformWalletFFIResult { + check_ptr!(out_indices); + check_ptr!(out_count); + *out_indices = std::ptr::null_mut(); + *out_count = 0; + check_ptr!(wallet_id_bytes); + let mut wallet_id = [0; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + let option = PLATFORM_WALLET_MANAGER_STORAGE.with_item(handle, |manager| { + runtime().block_on(async { + match manager.get_wallet(&wallet_id).await { + Some(wallet) => Some(wallet.shielded_account_indices().await), + None => None, + } + }) + }); + let Some(indices) = unwrap_option_or_return!(option) else { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + "wallet not found", + ); + }; + if !indices.is_empty() { + *out_count = indices.len(); + *out_indices = Box::into_raw(indices.into_boxed_slice()) as *mut u32; + } + PlatformWalletFFIResult::ok() +} + +/// Release an account snapshot returned by the matching getter. Null is a no-op. +/// +/// # Safety +/// A nonnull pointer and count must be an unfreed pair from +/// `platform_wallet_manager_shielded_account_indices`. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_free_shielded_account_indices( + indices: *mut u32, + count: usize, +) { + if !indices.is_null() { + drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut( + indices, count, + ))); + } +} + +#[cfg(test)] +mod account_indices_tests { + use super::*; + + #[test] + fn invalid_handle_clears_account_snapshot_outputs() { + let mut indices = std::ptr::NonNull::::dangling().as_ptr(); + let mut count = 99; + let wallet_id = [0; 32]; + unsafe { + let result = platform_wallet_manager_shielded_account_indices( + 0, + wallet_id.as_ptr(), + &mut indices, + &mut count, + ); + assert_ne!(result.code, PlatformWalletFFIResultCode::Success); + assert!(indices.is_null()); + assert_eq!(count, 0); + platform_wallet_manager_free_shielded_account_indices(indices, count); + } + } +} + #[cfg(test)] mod recovery_error_tests { use super::*; diff --git a/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs b/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs index e5cfdfa0dab..b230dba9d7a 100644 --- a/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs +++ b/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs @@ -358,6 +358,8 @@ pub struct IdentityRestoreEntryFFI { /// identity has no cached contact profiles. pub contact_profiles: *const ContactProfileRestoreEntryFFI, pub contact_profiles_count: usize, + /// Optional owned DashPay profile; contact_id is ignored. + pub dashpay_profile: *const ContactProfileRestoreEntryFFI, } /// One DashPay payment-history row to rehydrate into @@ -388,7 +390,7 @@ pub struct PaymentRestoreEntryFFI { /// the managed identity's contact-profile cache (keyed by the contact's identity /// id) at load. Mirrors the persist-side /// [`crate::identity_persistence::ContactProfileRowFFI`] field-for-field -/// (the leading `contact_id` key, the five public profile fields with +/// (the leading `contact_id` key, the public profile fields with /// their `_present` byte-array flags, and the trailing `checked_at_ms` /// self-heal timestamp). /// @@ -420,6 +422,13 @@ pub struct ContactProfileRestoreEntryFFI { pub avatar_fingerprint: [u8; 8], /// `true` iff the source `avatar_fingerprint` was `Some(_)`. pub avatar_fingerprint_present: bool, + pub core_payment_address: [u8; 21], + pub core_payment_address_present: bool, + pub platform_payment_address: [u8; 21], + pub platform_payment_address_present: bool, + pub shielded_address: [u8; 43], + pub shielded_address_present: bool, + /// NUL-terminated `publicMessage`, or null when `None`. pub public_message: *const std::os::raw::c_char, /// Wall-clock ms of the last fetch attempt — the diff --git a/packages/rs-platform-wallet-storage/SCHEMA.md b/packages/rs-platform-wallet-storage/SCHEMA.md index 94485778a6c..49f0c4045cd 100644 --- a/packages/rs-platform-wallet-storage/SCHEMA.md +++ b/packages/rs-platform-wallet-storage/SCHEMA.md @@ -132,6 +132,7 @@ erDiagram BLOB wallet_id FK "NULL = orphan identity (no parent wallet yet)" INTEGER identity_index "BIP-32 index; NULL for out-of-wallet identities" BLOB entry_blob "bincode-encoded IdentityEntry" + INTEGER entry_format "V021: 0 = pre-payment-address record, 1 = current" } IDENTITY_KEYS { @@ -153,6 +154,7 @@ erDiagram DASHPAY_PROFILES { BLOB identity_id PK "one row per identity" BLOB profile_blob "bincode-encoded DashPayProfile" + INTEGER profile_format "V021: 0 = pre-payment-address record, 1 = current" } DASHPAY_PAYMENTS_OVERLAY { @@ -488,6 +490,13 @@ every identity-scoped child writer, so a changeset carrying both an upsert and a removal for one identity commits instead of pulling the FK parent out from under its own child inserts. +`entry_format` (V021) stamps the bincode shape of `entry_blob`: 0 is the +record written before `DashPayProfile` gained its payment addresses, 1 the +current one. The writer always stamps 1; the reader dispatches on the stamp +(`schema::identity_profile_encoding::decode_identity`), so rows written +before V021 stay readable until they are rewritten. The DEFAULT is 1 and the +migration stamps the rows it finds 0, so only pre-V021 rows are ever legacy. + - PK: `identity_id`. - FK: `wallet_id → wallets(wallet_id) ON DELETE CASCADE` (nullable). - Index: `idx_identities_wallet(wallet_id)`. @@ -620,6 +629,11 @@ DELETE rather than a NULL blob — the row is absent, not nulled. `apply` writes these rows, but `load()` does not return them today; `DashPaySyncManager` rebuilds the canonical profile from Platform. +`profile_format` (V021) stamps the bincode shape of `profile_blob` the same +way `identities.entry_format` does (0 = pre-payment-address record, 1 = +current); `schema::identity_profile_encoding::decode_profile` is the stamped +reader for the day `load()` grows one. + - PK: `identity_id` (single-row-per-identity). - FK: `identity_id → identities(identity_id) ON DELETE CASCADE`. @@ -851,3 +865,4 @@ table-rebuild migration, as V004 does. | V018 | `V018__identity_hard_delete.rs` | Retires identity tombstoning. Adds `cascade_children_on_identity_delete` (brooms `identity_keys` / `contacts` / `ignored_senders` / `pending_contact_crypto` by the deleted identity id, covering the rows no live FK reaches) plus its access-path indexes `idx_contacts_owner`, `idx_ignored_senders_owner`, and `idx_pending_contact_crypto_owner`; purges every already-tombstoned identity and its dependents; drops `identities.tombstoned`. | | V019 | `V019__asset_lock_operation_id.rs` | Adds the nullable `asset_locks.operation_id BLOB` column (CHECK: NULL or exactly 16 bytes) that correlates a wallet-drain operation with its funding outpoint; the lifecycle blob is untouched. Adds the unique partial index `asset_locks_wallet_operation_id` on `(wallet_id, operation_id) WHERE operation_id IS NOT NULL` and the `asset_locks_operation_id_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `operation_id`. Purely additive; existing rows read back NULL. | | V020 | `V020__asset_lock_shielded_recipient.rs` | Adds the nullable `asset_locks.shielded_recipient BLOB` column (CHECK: NULL or exactly 43 bytes, the raw Orchard address) recording the recipient a shielded asset-lock funding was built to pay, so a resume after restart pays that recipient and refuses another; the lifecycle blob is untouched. Adds the `asset_locks_shielded_recipient_immutable` BEFORE UPDATE trigger, which aborts any change to a non-NULL `shielded_recipient`. Purely additive; existing rows read back NULL and keep accepting the resuming caller's recipient. | +| V021 | `V021__profile_address_encoding.rs` | Adds the encoding stamps `identities.entry_format` and `dashpay_profiles.profile_format` (`INTEGER NOT NULL DEFAULT 1 CHECK IN (0, 1)`) and stamps every row present at migration time 0. `DashPayProfile` gained the core, platform and shielded payment addresses, which widens the positional bincode record embedded in both blobs; the stamp routes each row to the decoder for the shape it carries (`schema::identity_profile_encoding`). | diff --git a/packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs b/packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs new file mode 100644 index 00000000000..2b98b77cd6a --- /dev/null +++ b/packages/rs-platform-wallet-storage/migrations/V021__profile_address_encoding.rs @@ -0,0 +1,19 @@ +//! Stamp the bincode encoding of `identities.entry_blob` and +//! `dashpay_profiles.profile_blob`. +//! +//! Payment addresses (core, platform, shielded) extend `DashPayProfile`, which +//! is embedded positionally in both blobs, so a record written before this +//! migration decodes only against the pre-address shape. The stamp says which +//! shape a row carries: 0 is the pre-address record, 1 the current one, and +//! `schema::identity_profile_encoding` holds the decoder for each. +//! +//! Every row present when the migration runs is stamped 0. The column DEFAULT +//! is 1, so a later insert that does not name the column is read as the shape +//! the current writer produces; the CHECK refuses a stamp no decoder knows. +pub fn migration() -> String { + "ALTER TABLE identities ADD COLUMN entry_format INTEGER NOT NULL DEFAULT 1 CHECK(entry_format IN (0, 1)); + UPDATE identities SET entry_format = 0; + ALTER TABLE dashpay_profiles ADD COLUMN profile_format INTEGER NOT NULL DEFAULT 1 CHECK(profile_format IN (0, 1)); + UPDATE dashpay_profiles SET profile_format = 0;" + .to_string() +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/mod.rs b/packages/rs-platform-wallet-storage/src/sqlite/mod.rs index 6ed1f6a26ee..a179d6336a7 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/mod.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/mod.rs @@ -51,3 +51,6 @@ pub use persister::{prune_backups_in, PruneReport, RetentionPolicy, SqlitePersis pub use reports::{CommitReport, DeleteWalletReport}; #[doc(inline)] pub use schema::core_pool::OwningAccount; + +// Versioned blob readers are useful to hosts inspecting pre-migration backups. +pub use schema::{dashpay::decode_profile, identities::decode_identity}; diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs index 88fc75b1ea7..fb3c80c452e 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/blob.rs @@ -1,6 +1,9 @@ //! BLOB-column codec helpers: thin `bincode::serde` wrappers so every //! `_blob` column uses one encoding path. Schema evolution is gated by the -//! refinery migration version — no per-blob revision tag. +//! refinery migration version — no per-blob revision tag, except the +//! `entry_format` / `profile_format` row stamps V021 added for the two +//! blobs that embed the widened `DashPayProfile` record (see +//! `identity_profile_encoding`). //! //! [`encode_outpoint`] / [`decode_outpoint`] encode `dashcore::OutPoint` //! the same way for the `outpoint` PK columns. The key is variable-width, diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs index dad012fd907..af1e3134791 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs @@ -45,10 +45,18 @@ use platform_wallet::wallet::platform_wallet::WalletId; use crate::sqlite::error::WalletStorageError; use crate::sqlite::schema::blob; use crate::sqlite::schema::blob::impl_persistable_blob; +use crate::sqlite::schema::identity_profile_encoding::decode_identity; // PUBLIC material only: DashPay overlay types reaching `_blob` columns. impl_persistable_blob!(DashPayProfile, PaymentEntry); +// `profile_blob` carries an encoding stamp (`profile_format`, V021): 0 is the +// pre-payment-address `DashPayProfile` shape, 1 the current one. Every write +// stamps 1; nothing in the crate reads the column back yet (see the module +// doc), so the stamped decoder is exported for hosts and for the day `load()` +// grows a reader. +pub use super::identity_profile_encoding::decode_profile; + /// Both tables are keyed by identity only; their FK to /// `identities(identity_id)` cascades via the `wallets → identities` chain. /// `wallet_id` feeds the precondition check only — no column. @@ -69,9 +77,10 @@ pub fn apply( let mut delete_stmt = tx.prepare_cached("DELETE FROM dashpay_profiles WHERE identity_id = ?1")?; let mut insert_stmt = tx.prepare_cached( - "INSERT INTO dashpay_profiles (identity_id, profile_blob) \ - VALUES (?1, ?2) \ - ON CONFLICT(identity_id) DO UPDATE SET profile_blob = excluded.profile_blob", + "INSERT INTO dashpay_profiles (identity_id, profile_blob, profile_format) \ + VALUES (?1, ?2, 1) \ + ON CONFLICT(identity_id) DO UPDATE SET \ + profile_blob = excluded.profile_blob, profile_format = 1", )?; for (identity_id, profile) in profiles { match profile { @@ -121,6 +130,11 @@ pub fn apply( /// order the two mean: the snapshot is the round's view of the identity, the /// overlay is the round's view of the payments that moved. /// +/// The row is decoded through its `entry_format` stamp (a pre-V021 row is +/// the legacy shape) and written back in the current shape stamped 1 in the +/// same statement, so a payment-only rewrite never leaves current bytes +/// under a legacy stamp or reads legacy bytes as the current record. +/// /// A missing `identities` row is not an error here. The FK would have /// rejected the overlay insert above, so by this point the row exists for /// every identity in `payments` unless it was deleted inside this same @@ -130,28 +144,30 @@ fn patch_payments_into_entry_blobs( payments: &BTreeMap>, ) -> Result<(), WalletStorageError> { let mut read = tx.prepare_cached( - "SELECT length(entry_blob), entry_blob FROM identities WHERE identity_id = ?1", + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ + WHERE identity_id = ?1", + )?; + let mut write = tx.prepare_cached( + "UPDATE identities SET entry_blob = ?2, entry_format = 1 WHERE identity_id = ?1", )?; - let mut write = - tx.prepare_cached("UPDATE identities SET entry_blob = ?2 WHERE identity_id = ?1")?; for (identity_id, by_tx) in payments { if by_tx.is_empty() { continue; } - let stored: Option<(i64, Vec)> = read + let stored: Option<(i64, Vec, i64)> = read .query_row(params![identity_id.as_slice()], |row| { - Ok((row.get(0)?, row.get(1)?)) + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) }) .map(Some) .or_else(|e| match e { rusqlite::Error::QueryReturnedNoRows => Ok(None), other => Err(other), })?; - let Some((len, payload)) = stored else { + let Some((len, payload, format)) = stored else { continue; }; blob::check_size(len)?; - let mut entry: IdentityEntry = blob::decode(&payload)?; + let mut entry: IdentityEntry = decode_identity(&payload, format)?; for (tx_id, row) in by_tx { entry.dashpay_payments.insert(tx_id.clone(), row.clone()); } diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs index d29c622f5eb..a3d23dd3458 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs @@ -22,6 +22,11 @@ use crate::sqlite::schema::blob::impl_persistable_blob; // PUBLIC material only: identity snapshot reaching the `entry_blob` column. impl_persistable_blob!(IdentityEntry); +// `entry_blob` carries an encoding stamp (`entry_format`, V021): 0 is the +// pre-payment-address `IdentityEntry` shape, 1 the current one. Every write +// stamps 1; the stamped reader keeps rows written before V021 decodable. +pub use super::identity_profile_encoding::decode_identity; + /// Write the changeset's inserted / updated identities. /// /// The insert half of a two-part apply: [`apply_removals`] must run for @@ -49,12 +54,13 @@ pub fn apply_upserts( // upsert without erroring), preserving the resident blob and index. // `IS` is the NULL-safe match for the nullable column. let mut stmt = tx.prepare_cached( - "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob) \ - VALUES (?1, ?2, ?3, ?4) \ + "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob, entry_format) \ + VALUES (?1, ?2, ?3, ?4, 1) \ ON CONFLICT(identity_id) DO UPDATE SET \ wallet_id = COALESCE(identities.wallet_id, excluded.wallet_id), \ identity_index = excluded.identity_index, \ - entry_blob = excluded.entry_blob \ + entry_blob = excluded.entry_blob, \ + entry_format = 1 \ WHERE identities.wallet_id IS NULL OR identities.wallet_id IS excluded.wallet_id", )?; let wallet_id_param = wallet_id_to_param(wallet_id); @@ -280,7 +286,7 @@ pub fn fetch( // the identity-id row can't leak through; sentinel matches orphan rows. let wallet_id_param = wallet_id_to_param(wallet_id); let mut stmt = conn.prepare( - "SELECT length(entry_blob), entry_blob FROM identities \ + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ WHERE identity_id = ?1 AND wallet_id IS ?2", )?; let mut rows = stmt.query(params![&identity_id[..], wallet_id_param])?; @@ -289,7 +295,7 @@ pub fn fetch( Some(row) => { blob::check_size(row.get::<_, i64>(0)?)?; let payload: Vec = row.get(1)?; - Ok(Some(blob::decode(&payload)?)) + Ok(Some(decode_identity(&payload, row.get(2)?)?)) } } } @@ -351,7 +357,7 @@ pub fn load_state_with_ctx( // unowned bucket. A plain `=` could not express the second case at all. let wallet_id_param = wallet_id_to_param(wallet_id); let mut stmt = conn.prepare( - "SELECT identity_id, length(entry_blob), entry_blob, identity_index \ + "SELECT identity_id, length(entry_blob), entry_blob, identity_index, entry_format \ FROM identities WHERE wallet_id IS ?1 ORDER BY identity_id", )?; // The ignored-senders TABLE is the authoritative ignore record (every @@ -366,7 +372,7 @@ pub fn load_state_with_ctx( blob::check_size(row.get::<_, i64>(1)?)?; let payload: Vec = row.get(2)?; let typed_identity_index: Option = row.get(3)?; - let entry: IdentityEntry = blob::decode(&payload)?; + let entry: IdentityEntry = decode_identity(&payload, row.get(4)?)?; // Cross-check the decoded blob against the typed columns it was // selected by (mirrors the accounts / identity_keys readers): the // blob must name the same identity, and its own wallet_id (when set) @@ -572,8 +578,9 @@ pub fn ensure_exists( let payload = blob::encode(&stub)?; let wallet_id_param = wallet_id_to_param(wallet_id); conn.execute( - "INSERT OR IGNORE INTO identities (identity_id, wallet_id, identity_index, entry_blob) \ - VALUES (?1, ?2, NULL, ?3)", + "INSERT OR IGNORE INTO identities \ + (identity_id, wallet_id, identity_index, entry_blob, entry_format) \ + VALUES (?1, ?2, NULL, ?3, 1)", params![&identity_id[..], wallet_id_param, payload], )?; Ok(()) diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs new file mode 100644 index 00000000000..1a392663409 --- /dev/null +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/identity_profile_encoding.rs @@ -0,0 +1,259 @@ +//! Frozen pre-V021 profile records, and the stamped decoders that route each +//! `identities.entry_blob` / `dashpay_profiles.profile_blob` row to the shape +//! it carries. Do not edit the legacy field order. +//! +//! `DashPayProfile` gained its payment addresses as trailing `Option` fields. +//! Under `bincode::serde` a struct is a fixed-arity positional record, so a +//! record written before the widening is never "short": the trailing fields +//! are simply absent, and decoding it against the current shape reads the +//! next field's bytes as an address. The row stamp (V021) is what says which +//! shape to decode; `serde(default)` on the new fields serves map formats +//! such as JSON only. +use super::blob; +use crate::sqlite::error::WalletStorageError; +use dpp::fee::Credits; +use dpp::prelude::{Identifier, Revision}; +use platform_wallet::changeset::IdentityEntry; +use platform_wallet::wallet::identity::types::block_time::BlockTime; +use platform_wallet::wallet::identity::PaymentEntry; +use platform_wallet::{ContactProfileEntry, DashPayProfile, DpnsNameInfo, IdentityStatus}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(serde::Serialize, serde::Deserialize)] +struct LegacyProfile { + display_name: Option, + bio: Option, + avatar_url: Option, + avatar_hash: Option<[u8; 32]>, + avatar_fingerprint: Option<[u8; 8]>, + public_message: Option, +} +impl From for DashPayProfile { + fn from(p: LegacyProfile) -> Self { + Self { + display_name: p.display_name, + bio: p.bio, + avatar_url: p.avatar_url, + avatar_hash: p.avatar_hash, + avatar_fingerprint: p.avatar_fingerprint, + public_message: p.public_message, + ..Default::default() + } + } +} +impl From for LegacyProfile { + fn from(p: DashPayProfile) -> Self { + Self { + display_name: p.display_name, + bio: p.bio, + avatar_url: p.avatar_url, + avatar_hash: p.avatar_hash, + avatar_fingerprint: p.avatar_fingerprint, + public_message: p.public_message, + } + } +} +#[derive(serde::Serialize, serde::Deserialize)] +struct LegacyContactProfile { + profile: Option, + checked_at_ms: u64, +} +#[derive(serde::Serialize, serde::Deserialize)] +struct LegacyIdentityEntry { + pub id: Identifier, + pub balance: Credits, + pub revision: Revision, + pub identity_index: Option, + pub last_updated_balance_block_time: Option, + pub last_synced_keys_block_time: Option, + pub dpns_names: Vec, + pub contested_dpns_names: Vec, + pub status: IdentityStatus, + pub wallet_id: Option<[u8; 32]>, + pub dashpay_profile: Option, + pub dashpay_payments: BTreeMap, + pub contact_profiles: BTreeMap, + pub ignored_senders: BTreeSet, +} +impl From for IdentityEntry { + fn from(old: LegacyIdentityEntry) -> Self { + IdentityEntry { + id: old.id, + balance: old.balance, + revision: old.revision, + identity_index: old.identity_index, + last_updated_balance_block_time: old.last_updated_balance_block_time, + last_synced_keys_block_time: old.last_synced_keys_block_time, + dpns_names: old.dpns_names, + contested_dpns_names: old.contested_dpns_names, + status: old.status, + wallet_id: old.wallet_id, + dashpay_profile: old.dashpay_profile.map(Into::into), + dashpay_payments: old.dashpay_payments, + contact_profiles: old + .contact_profiles + .into_iter() + .map(|(id, entry)| { + ( + id, + ContactProfileEntry { + profile: entry.profile.map(Into::into), + checked_at_ms: entry.checked_at_ms, + }, + ) + }) + .collect(), + ignored_senders: old.ignored_senders, + } + } +} +impl From for LegacyIdentityEntry { + fn from(entry: IdentityEntry) -> Self { + Self { + id: entry.id, + balance: entry.balance, + revision: entry.revision, + identity_index: entry.identity_index, + last_updated_balance_block_time: entry.last_updated_balance_block_time, + last_synced_keys_block_time: entry.last_synced_keys_block_time, + dpns_names: entry.dpns_names, + contested_dpns_names: entry.contested_dpns_names, + status: entry.status, + wallet_id: entry.wallet_id, + dashpay_profile: entry.dashpay_profile.map(Into::into), + dashpay_payments: entry.dashpay_payments, + contact_profiles: entry + .contact_profiles + .into_iter() + .map(|(id, entry)| { + ( + id, + LegacyContactProfile { + profile: entry.profile.map(Into::into), + checked_at_ms: entry.checked_at_ms, + }, + ) + }) + .collect(), + ignored_senders: entry.ignored_senders, + } + } +} + +// Test-only: production never writes the legacy shapes, but migration +// fixtures have to produce the bytes a pre-V021 writer produced. PUBLIC +// material only, like the current shapes they mirror. +#[cfg(any(test, feature = "__test-helpers"))] +super::blob::impl_persistable_blob!(LegacyProfile, LegacyIdentityEntry); + +/// The bytes a pre-V021 writer stored for `profile`: the record without the +/// payment-address fields. For fixtures of databases written before V021. +#[cfg(any(test, feature = "__test-helpers"))] +pub fn encode_legacy_profile(profile: &DashPayProfile) -> Result, WalletStorageError> { + blob::encode(&LegacyProfile::from(profile.clone())) +} + +/// The bytes a pre-V021 writer stored for `entry`: its own and its contacts' +/// profiles in the pre-payment-address shape. For fixtures of databases +/// written before V021. +#[cfg(any(test, feature = "__test-helpers"))] +pub fn encode_legacy_identity(entry: &IdentityEntry) -> Result, WalletStorageError> { + blob::encode(&LegacyIdentityEntry::from(entry.clone())) +} + +/// Decode a `dashpay_profiles.profile_blob` using its V021 `profile_format` +/// stamp: zero is the pre-address shape, one includes payment addresses. Never +/// fall back to the legacy shape after a current-format decoding error. +pub fn decode_profile(payload: &[u8], format: i64) -> Result { + match format { + 0 => blob::decode::(payload).map(Into::into), + 1 => blob::decode(payload), + _ => Err(WalletStorageError::blob_decode( + "unsupported profile encoding", + )), + } +} + +/// Decode an `identities.entry_blob` using its `entry_format` stamp, preserving +/// the pre-address owned and contact profile shapes for format zero. +pub fn decode_identity(payload: &[u8], format: i64) -> Result { + match format { + 1 => blob::decode(payload), + 0 => blob::decode::(payload).map(Into::into), + _ => Err(WalletStorageError::blob_decode( + "unsupported identity profile encoding", + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn old_profile() -> DashPayProfile { + DashPayProfile { + display_name: Some("Alice".into()), + bio: Some("hello".into()), + public_message: Some("hello".into()), + ..Default::default() + } + } + + #[test] + fn should_decode_standalone_profiles_by_format_without_fallback() { + let legacy = encode_legacy_profile(&old_profile()).unwrap(); + let mut profile = decode_profile(&legacy, 0).unwrap(); + assert_eq!(profile, old_profile()); + assert!(profile.core_payment_address.is_none()); + assert!(profile.platform_payment_address.is_none()); + assert!(profile.shielded_address.is_none()); + assert!(decode_profile(&legacy, 1).is_err()); + profile.shielded_address = Some(vec![9; 43]); + let current = blob::encode(&profile).unwrap(); + assert_eq!(decode_profile(¤t, 1).unwrap(), profile); + assert!(decode_profile(¤t, 0).is_err()); + assert!(decode_profile(¤t, 2).is_err()); + assert!(decode_profile(¤t[..current.len() - 1], 1).is_err()); + } + + /// The legacy identity record round-trips through the stamped decoder + /// with every field after the embedded profiles intact: the profile is + /// positional, so a shape mismatch would shift `dashpay_payments`, + /// `contact_profiles` and `ignored_senders`, not just drop an address. + #[test] + fn should_read_old_owned_and_contact_profiles_without_losing_following_fields() { + let id = Identifier::from([1; 32]); + let entry = IdentityEntry { + id, + balance: 123, + revision: 2, + identity_index: Some(0), + last_updated_balance_block_time: None, + last_synced_keys_block_time: None, + dpns_names: vec![], + contested_dpns_names: vec![], + status: IdentityStatus::Unknown, + wallet_id: Some([2; 32]), + dashpay_profile: Some(old_profile()), + dashpay_payments: BTreeMap::new(), + contact_profiles: [( + id, + ContactProfileEntry { + profile: Some(old_profile()), + checked_at_ms: 321, + }, + )] + .into(), + ignored_senders: [Identifier::from([3; 32])].into(), + }; + let legacy = encode_legacy_identity(&entry).unwrap(); + assert_eq!(decode_identity(&legacy, 0).unwrap(), entry); + // Current bytes carry three more `None`s per embedded profile. + let current = blob::encode(&entry).unwrap(); + assert_eq!(current.len(), legacy.len() + 6); + assert_eq!(decode_identity(¤t, 1).unwrap(), entry); + assert!(decode_identity(¤t[..current.len() - 1], 1).is_err()); + assert!(decode_identity(¤t, 2).is_err()); + assert!(decode_identity(&legacy, 2).is_err()); + } +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs index 88bff87e377..b3747c5713d 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/mod.rs @@ -4,7 +4,10 @@ //! columns (heights, hashes, outpoints, flags); `_blob` columns carry the //! full sub-changeset entry via [`blob::encode`] / [`blob::decode`]. Schema //! evolution is gated by the refinery migration version — blobs carry no -//! inline revision tag. +//! inline revision tag. The two exceptions are the identity and DashPay +//! profile blobs, whose rows carry an encoding stamp column (V021) because +//! the positional `DashPayProfile` record grew payment addresses; see +//! [`identity_profile_encoding`]. pub mod accounts; pub mod asset_locks; @@ -16,6 +19,7 @@ pub mod dashpay; pub mod dpns_name_states; pub mod identities; pub mod identity_keys; +pub mod identity_profile_encoding; pub mod identity_scan_states; pub mod invitations; pub mod pending_contact_crypto; diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs index 9021f02dc55..59d3c070432 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_identity_index_uniqueness.rs @@ -15,6 +15,7 @@ use common::{ ensure_identity, ensure_wallet_meta, fresh_persister, fresh_persister_with_mode, wid, }; +use dpp::identity::accessors::IdentityGettersV0; use dpp::prelude::Identifier; use platform_wallet::changeset::{ IdentityChangeSet, IdentityEntry, PersistenceError, PersistenceErrorKind, @@ -558,6 +559,35 @@ fn a_buffered_removal_frees_its_slot_for_a_later_store() { assert!(!row_exists(&p, &iid(0x01))); } +/// Discovery re-slots an identity restored at a placeholder index into the +/// index its key derivation proved, and the new snapshot carries only the +/// changed `identity_index`. Buffered behind the old-slot snapshot, the +/// merged write must take the new index: otherwise the flush writes the +/// stale slot back and the freed slot refuses its rightful owner. +#[test] +fn a_buffered_reslot_moves_the_identity_and_frees_its_old_slot() { + let (p, _tmp, _path) = fresh_persister_with_mode(FlushMode::Manual); + let w = wid(0xBA); + ensure_wallet_meta(&p, &w); + p.store(w, identity_cs([identity_entry(0x01, Some(0))], [])) + .expect("placeholder snapshot at slot 0"); + p.store(w, identity_cs([identity_entry(0x01, Some(5))], [])) + .expect("adoption into the verified slot"); + p.store(w, identity_cs([identity_entry(0x02, Some(0))], [])) + .expect("the freed slot admits its rightful owner"); + + p.flush(w).expect("the merged changeset is consistent"); + assert_eq!(live_occupant(&p, &w, 5), Some([0x01; 32])); + assert_eq!(live_occupant(&p, &w, 0), Some([0x02; 32])); + + // A reopened persister reads the same placement back. + let state = p.load().expect("reload"); + let bucket = &state.wallets[&w].identity_manager.wallet_identities[&w]; + assert_eq!(bucket[&5].identity.id(), iid(0x01)); + assert_eq!(bucket[&5].identity_index, Some(5)); + assert_eq!(bucket[&0].identity.id(), iid(0x02)); +} + /// One wallet's rejected flush is one wallet's problem: `commit_writes` /// gives every dirty wallet its own transaction, so a neighbour's /// legitimate writes land in the same pass. diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs index 58cc3c18f3b..66e11696aae 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_persist_roundtrip.rs @@ -677,6 +677,7 @@ fn tc012_dashpay_overlay_roundtrip() { avatar_hash: None, avatar_fingerprint: None, public_message: Some("public".into()), + ..Default::default() }; let payment = PaymentEntry::new_sent(Identifier::from([0x66; 32]), 7_500, Some("lunch".into())); diff --git a/packages/rs-platform-wallet-storage/tests/sqlite_profile_address_encoding.rs b/packages/rs-platform-wallet-storage/tests/sqlite_profile_address_encoding.rs new file mode 100644 index 00000000000..8c049eb348b --- /dev/null +++ b/packages/rs-platform-wallet-storage/tests/sqlite_profile_address_encoding.rs @@ -0,0 +1,335 @@ +#![allow(clippy::field_reassign_with_default)] + +//! A database written before V021 keeps its identity and DashPay profile rows +//! readable: the migration stamps the rows it finds 0, the stamped decoders +//! route them to the pre-payment-address record, and a rewrite stamps 1. +//! The fixture is written at V007 (the last published pre-rehydration +//! schema), so the whole V008 -> V021 chain runs over the legacy bytes. + +use std::collections::BTreeMap; + +use dpp::identity::accessors::IdentityGettersV0; +use dpp::prelude::Identifier; +use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry}; +use platform_wallet::wallet::identity::PaymentEntry; +use platform_wallet::{ContactProfileEntry, DashPayProfile, IdentityStatus}; +use platform_wallet_storage::sqlite::schema::identity_profile_encoding::{ + encode_legacy_identity, encode_legacy_profile, +}; +use platform_wallet_storage::sqlite::schema::{blob, dashpay, identities}; +use platform_wallet_storage::sqlite::{decode_identity, decode_profile, migrations}; +use rusqlite::{params, Connection}; + +const WALLET_ID: [u8; 32] = [0x62; 32]; + +fn old_profile() -> DashPayProfile { + DashPayProfile { + display_name: Some("Alice".into()), + bio: Some("hello".into()), + public_message: Some("hello".into()), + ..Default::default() + } +} + +fn entry(id: Identifier) -> IdentityEntry { + IdentityEntry { + id, + balance: 123, + revision: 2, + identity_index: Some(0), + last_updated_balance_block_time: None, + last_synced_keys_block_time: None, + dpns_names: vec![], + contested_dpns_names: vec![], + status: IdentityStatus::Unknown, + wallet_id: Some(WALLET_ID), + dashpay_profile: Some(old_profile()), + dashpay_payments: BTreeMap::new(), + contact_profiles: [( + id, + ContactProfileEntry { + profile: Some(old_profile()), + checked_at_ms: 321, + }, + )] + .into(), + ignored_senders: [Identifier::from([3; 32])].into(), + } +} + +fn stamps(conn: &Connection) -> (i64, i64) { + let entry_format = conn + .query_row("SELECT entry_format FROM identities", [], |row| row.get(0)) + .unwrap(); + let profile_format = conn + .query_row("SELECT profile_format FROM dashpay_profiles", [], |row| { + row.get(0) + }) + .unwrap(); + (entry_format, profile_format) +} + +fn stored_profile(conn: &Connection) -> DashPayProfile { + let (payload, format): (Vec, i64) = conn + .query_row( + "SELECT profile_blob, profile_format FROM dashpay_profiles", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + decode_profile(&payload, format).unwrap() +} + +/// Rows a pre-V021 writer stored are stamped 0 by the migration and decode +/// to the pre-address shape through both readers; a rewrite stamps them 1 +/// and the new fields round-trip; an insert that omits the stamp is read as +/// the current shape. +#[test] +fn pre_v019_rows_stay_readable_and_rewrites_restamp() { + let id = Identifier::from([1; 32]); + let old = entry(id); + + let mut conn = Connection::open_in_memory().unwrap(); + conn.pragma_update(None, "foreign_keys", true).unwrap(); + migrations::runner() + .set_target(refinery::Target::Version(7)) + .run(&mut conn) + .unwrap(); + conn.execute( + "INSERT INTO wallet_metadata (wallet_id, network, birth_height) VALUES (?1, 'testnet', 0)", + params![WALLET_ID.as_slice()], + ) + .unwrap(); + conn.execute( + "INSERT INTO identities (identity_id, wallet_id, wallet_index, entry_blob, tombstoned) \ + VALUES (?1, ?2, 0, ?3, 0)", + params![ + id.as_slice(), + WALLET_ID.as_slice(), + encode_legacy_identity(&old).unwrap() + ], + ) + .unwrap(); + conn.execute( + "INSERT INTO dashpay_profiles (identity_id, profile_blob) VALUES (?1, ?2)", + params![ + id.as_slice(), + encode_legacy_profile(&old_profile()).unwrap() + ], + ) + .unwrap(); + + migrations::run(&mut conn).unwrap(); + + assert_eq!(stamps(&conn), (0, 0), "rows present at V021 are legacy"); + assert_eq!(stored_profile(&conn), old_profile()); + let restored = identities::fetch(&conn, &WALLET_ID, &id.to_buffer()) + .unwrap() + .unwrap(); + assert_eq!(restored, old); + assert!(restored + .dashpay_profile + .as_ref() + .unwrap() + .shielded_address + .is_none()); + // The reader the runtime restores from dispatches on the stamp too: a + // legacy row decoded against the current shape would fail this load. + let state = identities::load_state(&conn, &WALLET_ID).unwrap(); + let managed = &state.wallet_identities[&WALLET_ID][&0]; + assert_eq!(managed.identity.id(), id); + assert_eq!(managed.identity.balance(), 123); + + // Rewriting the rows through the live writers stamps them current. + let mut current = restored; + current.dashpay_profile.as_mut().unwrap().shielded_address = Some(vec![9; 43]); + let tx = conn.transaction().unwrap(); + identities::apply_upserts( + &tx, + &WALLET_ID, + &IdentityChangeSet { + identities: [(id, current.clone())].into(), + ..Default::default() + }, + ) + .unwrap(); + dashpay::apply( + &tx, + &WALLET_ID, + Some(&BTreeMap::from([(id, current.dashpay_profile.clone())])), + None, + ) + .unwrap(); + tx.commit().unwrap(); + assert_eq!(stamps(&conn), (1, 1)); + assert_eq!( + stored_profile(&conn), + current.dashpay_profile.clone().unwrap() + ); + assert_eq!( + identities::fetch(&conn, &WALLET_ID, &id.to_buffer()) + .unwrap() + .unwrap(), + current + ); + let encoded = blob::encode(¤t).unwrap(); + assert_eq!(decode_identity(&encoded, 1).unwrap(), current); + + // The stamp DEFAULT follows the writer: an insert that omits it reads as + // the current shape, so only rows the migration found are ever legacy. + let other = Identifier::from([7; 32]); + conn.execute( + "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob) \ + VALUES (?1, ?2, 1, ?3)", + params![ + other.as_slice(), + WALLET_ID.as_slice(), + blob::encode(&IdentityEntry { + id: other, + identity_index: Some(1), + ..current.clone() + }) + .unwrap() + ], + ) + .unwrap(); + let format: i64 = conn + .query_row( + "SELECT entry_format FROM identities WHERE identity_id = ?1", + [other.as_slice()], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(format, 1); + assert_eq!( + identities::fetch(&conn, &WALLET_ID, &other.to_buffer()) + .unwrap() + .unwrap() + .dashpay_profile + .unwrap() + .shielded_address, + Some(vec![9; 43]) + ); +} + +/// A stamp no decoder knows is refused at the schema, not misread. +#[test] +fn unknown_stamp_is_rejected_by_the_check_constraint() { + let mut conn = Connection::open_in_memory().unwrap(); + migrations::run(&mut conn).unwrap(); + conn.execute( + "INSERT INTO wallets (wallet_id, network, birth_height) VALUES (?1, 'testnet', 0)", + params![WALLET_ID.as_slice()], + ) + .unwrap(); + let id = Identifier::from([4; 32]); + let err = conn + .execute( + "INSERT INTO identities (identity_id, wallet_id, identity_index, entry_blob, entry_format) \ + VALUES (?1, ?2, NULL, ?3, 2)", + params![id.as_slice(), WALLET_ID.as_slice(), blob::encode(&entry(id)).unwrap()], + ) + .unwrap_err(); + assert!(err.to_string().contains("CHECK"), "{err}"); +} + +/// Literal bytes of a pre-V021 `profile_blob`, written out by hand from the +/// `bincode::serde` standard encoding of the six-field record (no struct +/// declaration involved), so a reorder of the frozen legacy record cannot +/// regenerate the fixture and its decoder in step. Every field holds a +/// distinct value, so a positional shift misreads at least one of them. +#[test] +fn literal_pre_v019_profile_bytes_decode_positionally() { + let mut bytes = vec![0x01, 0x02, b'A', b'l']; // display_name: Some("Al") + bytes.extend([0x01, 0x01, b'b']); // bio: Some("b") + bytes.push(0x00); // avatar_url: None + bytes.push(0x01); // avatar_hash: Some([0x11; 32]) + bytes.extend([0x11; 32]); + bytes.push(0x01); // avatar_fingerprint: Some([0x22; 8]) + bytes.extend([0x22; 8]); + bytes.extend([0x01, 0x01, b'm']); // public_message: Some("m") + + let decoded = decode_profile(&bytes, 0).unwrap(); + assert_eq!( + decoded, + DashPayProfile { + display_name: Some("Al".into()), + bio: Some("b".into()), + avatar_url: None, + avatar_hash: Some([0x11; 32]), + avatar_fingerprint: Some([0x22; 8]), + public_message: Some("m".into()), + ..Default::default() + } + ); + // The legacy writer the migration fixture uses produces the same bytes. + assert_eq!(encode_legacy_profile(&decoded).unwrap(), bytes); + // Read as the current shape, the same row is not a valid record. + assert_ne!(decode_profile(&bytes, 1).ok(), Some(decoded)); +} + +/// A payment-only round (the `dashpay_payments_overlay` path) rewrites the +/// identity blob too. On a row the migration stamped 0 it must decode the +/// legacy record and write the current one stamped 1, so both identity +/// readers still see every profile field plus the new payment. +#[test] +fn payment_only_rewrite_of_a_legacy_identity_restamps_it() { + let id = Identifier::from([5; 32]); + let old = entry(id); + + let mut conn = Connection::open_in_memory().unwrap(); + conn.pragma_update(None, "foreign_keys", true).unwrap(); + migrations::runner() + .set_target(refinery::Target::Version(7)) + .run(&mut conn) + .unwrap(); + conn.execute( + "INSERT INTO wallet_metadata (wallet_id, network, birth_height) VALUES (?1, 'testnet', 0)", + params![WALLET_ID.as_slice()], + ) + .unwrap(); + conn.execute( + "INSERT INTO identities (identity_id, wallet_id, wallet_index, entry_blob, tombstoned) \ + VALUES (?1, ?2, 0, ?3, 0)", + params![ + id.as_slice(), + WALLET_ID.as_slice(), + encode_legacy_identity(&old).unwrap() + ], + ) + .unwrap(); + migrations::run(&mut conn).unwrap(); + let format = |conn: &Connection| -> i64 { + conn.query_row("SELECT entry_format FROM identities", [], |row| row.get(0)) + .unwrap() + }; + assert_eq!(format(&conn), 0); + + let payment = PaymentEntry::new_sent(Identifier::from([6; 32]), 42_000, Some("tip".into())); + let tx = conn.transaction().unwrap(); + dashpay::apply( + &tx, + &WALLET_ID, + None, + Some(&BTreeMap::from([( + id, + BTreeMap::from([("ab".repeat(32), payment.clone())]), + )])), + ) + .unwrap(); + tx.commit().unwrap(); + + assert_eq!(format(&conn), 1, "the rewritten blob is the current shape"); + let mut expected = old; + expected.dashpay_payments.insert("ab".repeat(32), payment); + assert_eq!( + identities::fetch(&conn, &WALLET_ID, &id.to_buffer()) + .unwrap() + .unwrap(), + expected + ); + let state = identities::load_state(&conn, &WALLET_ID).unwrap(); + let managed = &state.wallet_identities[&WALLET_ID][&0]; + assert_eq!(managed.identity.id(), id); + assert_eq!(managed.identity.balance(), 123); +} diff --git a/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md new file mode 100644 index 00000000000..c184b7b4ecb --- /dev/null +++ b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md @@ -0,0 +1,85 @@ +# DashPay shielded tips + +DashPay profiles can publish a reusable Orchard receiving address. A payer resolves +DPNS to an identity, fetches its profile with proof verification, confirms the +recipient, and sends an ordinary shielded transfer. No contact request or payment +notification document is necessary. + +## Address format and updates + +`profile.shieldedAddress` contains 43 raw bytes: the 11-byte diversifier followed +by the 32-byte diversified transmission key. Text encoding, network prefix, and +checksum belong to the user interface. External addresses with any valid +diversifier are supported. The profile does not prove ownership of the address. + +`DashPayProfile` exposes `core_payment_address`, `platform_payment_address`, and +`shielded_address`. The transparent fields use their existing 21-byte storage +form. `ProfileUpdate` uses `PaymentAddressUpdate::Keep`, `Set(bytes)`, or `Remove` +for each address. An unrelated edit preserves all payment addresses. Clients +validate Orchard decoding before publication and payment; an invalid shielded +address does not prevent displaying the rest of the profile. + +Publication checks the connected chain's DashPay contract before submitting an +address field. A bundled schema alone does not demonstrate network activation. + +## Dedicated local accounts + +The wallet reserves ZIP-32 account indices `0x40000000..0x80000000` for DashPay +tips. A wallet-owned identity at derivation index `i` uses account +`0x40000000 + i`; identity indices outside the lower half are rejected by the tip +helper. Ordinary account allocation must stay below `0x40000000`. Use +`shielded_tip_account_index` and `is_shielded_tip_account` instead of duplicating +these constants in applications. + +Call `PlatformWallet::prepare_shielded_tip_address(seed, identity_id, coordinator)` +to obtain the default address of this account. The helper binds its viewing keys +to the synchronization coordinator and flushes persistence before returning. It +does not publish the address; publication remains an explicit profile operation. +Repeated preparation derives the same account and address. An identity without a +wallet derivation index can publish an external address instead. + +Tip accounts have distinct viewing keys. Hosts must exclude them from ordinary +receive, balance, and automatic spending choices, as the example apps do. +`shielded_balances()` returns all bound accounts separately, including tip +accounts; it does not apply this policy. Spending a tip balance is an explicit +host action. +The generic shielded transfer API still accepts an explicitly selected account. +A published address is publicly associated with the profile; account separation +does not eliminate correlations introduced by later transfers or provide a +blanket guarantee against future cryptographic attacks. + +Address preparation requires an existing shielded bind. Bind the host's ordinary +accounts first; preparation preserves them while adding the dedicated account. + +## Restoration and address changes + +On seed restoration, discover the wallet's identities before binding and scanning +shielded accounts. Seed-backed `bind_shielded` adds each discovered identity's tip +account even if the caller supplies only account zero. This does not depend on the +current profile: removal or replacement of a published address does not remove +received funds from recovery. After discovering more identities in an existing +session, bind again. Newly bound accounts start with their own scan watermark at +zero, so the next synchronization scans their history while retaining the shared +commitment tree and previously synchronized accounts. + +Seedless binding includes persisted tip viewing keys, including retired accounts. +If a newly discovered identity's key is missing, it returns `false` so the host can +perform seed-backed binding. Address rotation within a tip account uses a new +diversifier; the account viewing key detects both old and new addresses. Removing +publication neither revokes old address copies nor stops their monitoring. + +An externally supplied address is not automatically owned by this wallet. Its +funds, viewing keys, and recovery belong to the external wallet. + +## Resolving and paying + +Use `wallet.identity().dashpay().resolve_shielded_tip(username)` to obtain a fresh +`ShieldedTipRecipient`. Display the resolved identity and address for confirmation. +`wallet.send_shielded_tip(...)` takes that confirmed recipient, re-resolves the +name and profile, and refuses payment if either changed. It never switches to a +transparent destination. This is a snapshot check: the submitted payment always +uses the address that was confirmed, even if the profile changes afterward. + +Tips to a public profile address are anonymous from the receiver's perspective +unless the payer provides additional context. This feature does not implement +per-contact addresses or authenticated sender attribution. diff --git a/packages/rs-platform-wallet/src/changeset/changeset.rs b/packages/rs-platform-wallet/src/changeset/changeset.rs index 23d416973a3..acbd65ec69b 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -1131,9 +1131,10 @@ impl Merge for IdentityKeysChangeSet { /// /// `IdentityChangeSet::merge` does NOT resolve `identities` vs /// `removed` for the same key — both fields are extended -/// independently. Apply runs inserts before removes, so a merged -/// changeset that contains both an insert and a tombstone for the -/// same identity will end up "removed". Same hazard as +/// independently. Apply runs removes first and drops the snapshots of +/// removed identities, so a merged changeset that contains both an +/// insert and a tombstone for the same identity will end up "removed". +/// Same hazard as /// [`ContactChangeSet`]; same mitigation: every current emitter /// produces only one of {insert, tombstone} per key per mutation. #[derive(Debug, Clone, Default, PartialEq)] @@ -1172,6 +1173,13 @@ impl Merge for IdentityChangeSet { // equivalent. We use LWW for consistency with the // other scalars in this block. existing.wallet_id = entry.wallet_id; + // `identity_index` follows the latest snapshot too. It is + // not immutable: discovery re-slots an identity restored + // at a placeholder index into the index its key derivation + // proved (`IdentityManager::adopt_into_wallet`). Keeping + // the first value would flush the stale slot and leave it + // occupied for the identity that legitimately owns it. + existing.identity_index = entry.identity_index; // DashPay profile: last-write-wins. Same policy as // every other Option scalar in this block — // every mutation snapshot copies the current diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..eee0fd9aa89 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -95,6 +95,19 @@ pub enum PlatformWalletError { #[error("Identity already exists: {0}")] IdentityAlreadyExists(Identifier), + /// A key derivation proved `identity_id` at `identity_index`, but this + /// wallet already holds a different identity in that slot. One of the two + /// records is stale; nothing was moved or persisted. + #[error( + "Identity {identity_id} is verified at index {identity_index}, but that slot holds \ + identity {occupant}" + )] + IdentityIndexOccupied { + identity_id: Identifier, + identity_index: u32, + occupant: Identifier, + }, + #[error("Identity not found: {0}")] IdentityNotFound(Identifier), diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index 13005d9c445..46e61eda796 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -91,8 +91,9 @@ pub use wallet::identity::{ derive_contact_payment_addresses, derive_contact_xpub, pubkey_binds_expected_key_data, unmask_account_reference, BlockTime, ContactProfileEntry, ContactRequest, ContactXpubData, DashPayProfile, DashPayState, DpnsFetch, DpnsNameInfo, EstablishedContact, IdentityLocation, - IdentityManager, IdentityStatus, KeyStorage, ManagedIdentity, PrivateContact, PrivateKeyData, - ProfileUpdate, RegistrationIndex, DEFAULT_CONTACT_GAP_LIMIT, + IdentityManager, IdentityStatus, KeyStorage, ManagedIdentity, PaymentAddressUpdate, + PrivateContact, PrivateKeyData, ProfileUpdate, RegistrationIndex, ShieldedTipRecipient, + DEFAULT_CONTACT_GAP_LIMIT, }; pub use wallet::masternode_withdrawal::{ MasternodeWithdrawalKey, MasternodeWithdrawalKeys, MasternodeWithdrawalRequest, @@ -126,3 +127,12 @@ pub use key_wallet_manager; // the crate can pass it to `ManagedIdentity` mutation methods // (`set_dashpay_profile`, `record_dashpay_payment`, `add_identity`, …). pub use wallet::persister::WalletPersister; + +pub use wallet::identity::types::dashpay::profile::{ + valid_transparent_payment_address, validated_shielded_address, +}; + +#[cfg(feature = "shielded")] +pub use wallet::shielded::tips::{ + is_shielded_tip_account, shielded_tip_account_index, SHIELDED_TIP_ACCOUNT_BASE, +}; diff --git a/packages/rs-platform-wallet/src/wallet/apply.rs b/packages/rs-platform-wallet/src/wallet/apply.rs index 81512cad78a..6dcda5ac4cb 100644 --- a/packages/rs-platform-wallet/src/wallet/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/apply.rs @@ -159,16 +159,22 @@ impl PlatformWalletInfo { removed, } = id_cs; - for (_id, entry) in identities { - self.identity_manager.apply_identity_entry(entry); - } // Best-effort removals across both buckets. Routed // through `remove_for_apply` so the manager's side-index // stays in lockstep with the buckets without us having to - // reach in and touch the index from out here. + // reach in and touch the index from out here. Removal wins over + // a same-batch snapshot, so removals go first and their + // snapshots are dropped: a removed identity's last placement + // must not hold a slot a surviving entry takes over. for removed_id in &removed { self.identity_manager.remove_for_apply(removed_id); } + self.identity_manager.apply_identity_entries( + identities + .into_iter() + .filter(|(id, _)| !removed.contains(id)) + .map(|(_, entry)| entry), + ); } // 2a'. Identity-scan verdict. Replayed rather than dropped: unlike the @@ -1641,6 +1647,225 @@ mod tests { assert_eq!(restored.identity.revision(), 5); } + fn slotted_entry(id_byte: u8, wallet_id: Option<[u8; 32]>, index: u32) -> IdentityEntry { + let managed = ManagedIdentity::new(make_test_identity(id_byte, 0), index); + let mut entry = IdentityEntry::from_managed(&managed); + entry.wallet_id = wallet_id; + entry.identity_index = wallet_id.map(|_| index); + entry + } + + fn apply_entries( + info: &mut PlatformWalletInfo, + wallet: &mut Wallet, + entries: impl IntoIterator, + ) { + let mut cs = IdentityChangeSet::default(); + for entry in entries { + cs.identities.insert(entry.id, entry); + } + info.apply_changeset(wallet, wrap_id(cs)).expect("apply"); + } + + fn assert_slot(info: &PlatformWalletInfo, wallet_id: [u8; 32], index: u32, id_byte: u8) { + use dpp::identity::accessors::IdentityGettersV0; + let id = Identifier::from([id_byte; 32]); + let slotted = &info.identity_manager.wallet_identities[&wallet_id][&index]; + assert_eq!(slotted.identity.id(), id, "slot {index}"); + let found = info + .identity_manager + .managed_identity(&id) + .expect("present"); + assert_eq!(found.identity_index, Some(index)); + assert_eq!(found.wallet_id, Some(wallet_id)); + } + + /// Replaying a re-slot (A@0 → A@5) must move A, so a later B@0 takes the + /// freed slot instead of overwriting A — applied one by one or merged + /// into a batch that visits B (lower id) before A. + #[test] + fn apply_follows_identity_reslot_into_its_verified_index() { + let w = [0xAB; 32]; + for merged in [false, true] { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 0)]); + if merged { + apply_entries( + &mut info, + &mut wallet, + [slotted_entry(9, Some(w), 5), slotted_entry(1, Some(w), 0)], + ); + } else { + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 5)]); + apply_entries(&mut info, &mut wallet, [slotted_entry(1, Some(w), 0)]); + } + assert_eq!(info.identity_manager.identity_count(), 2, "merged={merged}"); + assert_slot(&info, w, 5, 9); + assert_slot(&info, w, 0, 1); + } + } + + /// An observed identity adopted into the wallet replays into its slot. + #[test] + fn apply_promotes_an_observed_identity_into_the_wallet() { + let w = [0xAB; 32]; + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, None, 0)]); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 3)]); + assert_eq!(info.identity_manager.identity_count(), 1); + assert_slot(&info, w, 3, 9); + } + + /// A new entry claiming a slot another identity still holds is skipped + /// rather than discarding the occupant. + #[test] + fn apply_does_not_insert_over_an_occupied_slot() { + let w = [0xAB; 32]; + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 0)]); + apply_entries(&mut info, &mut wallet, [slotted_entry(1, Some(w), 0)]); + assert_slot(&info, w, 0, 9); + assert!(info + .identity_manager + .managed_identity(&Identifier::from([1; 32])) + .is_none()); + } + + /// A batch removing an identity frees its slot for a new entry in the + /// same batch. + #[test] + fn apply_removal_frees_the_slot_for_a_same_batch_entry() { + let w = [0xAB; 32]; + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, [slotted_entry(9, Some(w), 3)]); + let mut cs = IdentityChangeSet::default(); + let entry = slotted_entry(1, Some(w), 3); + cs.identities.insert(entry.id, entry); + cs.removed.insert(Identifier::from([9; 32])); + info.apply_changeset(&mut wallet, wrap_id(cs)) + .expect("apply"); + assert_eq!(info.identity_manager.identity_count(), 1); + assert_slot(&info, w, 3, 1); + } + + /// Merge per-mutation changesets the way a Manual-flush buffer does. + fn merged(changesets: impl IntoIterator) -> IdentityChangeSet { + use crate::changeset::Merge; + let mut all = IdentityChangeSet::default(); + for cs in changesets { + all.merge(cs); + } + all + } + + fn snapshot(entry: IdentityEntry) -> IdentityChangeSet { + let mut cs = IdentityChangeSet::default(); + cs.identities.insert(entry.id, entry); + cs + } + + /// Replay a merged batch twice; both applications must reach the state + /// the mutations produced. + fn replay_twice( + seed: impl IntoIterator + Clone, + batch: IdentityChangeSet, + check: impl Fn(&PlatformWalletInfo), + ) { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + apply_entries(&mut info, &mut wallet, seed); + for _ in 0..2 { + info.apply_changeset(&mut wallet, wrap_id(batch.clone())) + .expect("apply"); + check(&info); + } + } + + /// A moved to 5, then removed, then B added at 5: the merged batch keeps + /// A's snapshot beside its tombstone, which must not keep B out. + #[test] + fn should_place_an_entry_in_the_slot_of_a_removed_identity() { + let w = [0xAB; 32]; + let mut removal = IdentityChangeSet::default(); + removal.removed.insert(Identifier::from([9; 32])); + let batch = merged([ + snapshot(slotted_entry(9, Some(w), 5)), + removal, + snapshot(slotted_entry(1, Some(w), 5)), + ]); + replay_twice([slotted_entry(9, Some(w), 0)], batch, |info| { + assert_eq!(info.identity_manager.identity_count(), 1); + assert_slot(info, w, 5, 1); + }); + } + + /// A@0/B@1 swapped through free slot 2 merges into A@1/B@0, which replay + /// must install even though each move waits on the other. + #[test] + fn should_replay_a_merged_slot_swap() { + let w = [0xAB; 32]; + let batch = merged([ + snapshot(slotted_entry(9, Some(w), 2)), + snapshot(slotted_entry(1, Some(w), 0)), + snapshot(slotted_entry(9, Some(w), 1)), + ]); + replay_twice( + [slotted_entry(9, Some(w), 0), slotted_entry(1, Some(w), 1)], + batch, + |info| { + assert_eq!(info.identity_manager.identity_count(), 2); + assert_slot(info, w, 1, 9); + assert_slot(info, w, 0, 1); + assert!(info.identity_manager.out_of_wallet_identities.is_empty()); + }, + ); + } + + /// A move blocked by an identity the batch leaves in place keeps its slot. + #[test] + fn should_keep_a_move_blocked_by_a_stationary_identity_in_place() { + let w = [0xAB; 32]; + replay_twice( + [slotted_entry(9, Some(w), 0), slotted_entry(1, Some(w), 1)], + snapshot(slotted_entry(9, Some(w), 1)), + |info| { + assert_slot(info, w, 0, 9); + assert_slot(info, w, 1, 1); + }, + ); + } + + /// A swap whose slot a third entry also claims (an inconsistent batch) + /// is not staged, so no identity is stranded outside the wallet. + #[test] + fn should_not_stage_a_swap_whose_slot_is_claimed_twice() { + let w = [0xAB; 32]; + let batch = merged([ + snapshot(slotted_entry(1, Some(w), 1)), + snapshot(slotted_entry(3, Some(w), 0)), + snapshot(slotted_entry(2, Some(w), 0)), + ]); + replay_twice( + [ + slotted_entry(1, Some(w), 0), + slotted_entry(3, Some(w), 1), + slotted_entry(2, Some(w), 5), + ], + batch, + |info| { + assert_eq!(info.identity_manager.identity_count(), 3); + assert!(info.identity_manager.out_of_wallet_identities.is_empty()); + assert_slot(info, w, 0, 1); + assert_slot(info, w, 1, 3); + assert_slot(info, w, 5, 2); + }, + ); + } + /// A contact tombstone for a present (non-orphan) owner /// must drop the matching pending request. #[test] @@ -1703,6 +1928,8 @@ mod tests { avatar_hash: Some([0xaa; 32]), avatar_fingerprint: Some([0xbb; 8]), public_message: Some("hello world".into()), + shielded_address: Some(vec![0xcc; 43]), + ..Default::default() }; // Mutate A (persists internally via noop persister). diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index 37eb12adeff..e64b77354ff 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -37,6 +37,7 @@ pub use state::{ pub use types::dashpay::profile::{calculate_avatar_hash, calculate_dhash_fingerprint}; pub use types::{ ContactProfileEntry, ContactRequest, DashPayProfile, DashpayAddressMatch, DpnsFetch, - DpnsNameInfo, EstablishedContact, IdentityStatus, KeyStorage, PaymentDirection, PaymentEntry, - PaymentStatus, PrivateKeyData, ProfileUpdate, + DpnsNameInfo, EstablishedContact, IdentityStatus, KeyStorage, PaymentAddressUpdate, + PaymentDirection, PaymentEntry, PaymentStatus, PrivateKeyData, ProfileUpdate, + ShieldedTipRecipient, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs index 0e8596bed0a..56c1b716aff 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs @@ -7,6 +7,7 @@ use key_wallet::bip32::ExtendedPrivKey; use crate::error::PlatformWalletError; use crate::wallet::identity::network::contact_requests::budget_spent; use crate::BlockTime; +use crate::wallet::identity::state::VerifiedPlacement; use super::*; @@ -449,16 +450,38 @@ impl IdentityWallet { "Wallet info not found in wallet manager".to_string(), ) })?; - let is_new = info_guard.identity_manager.identity(&identity_id).is_none(); - if is_new { - // Stored below, with its verified keys, as one - // changeset. - info_guard.identity_manager.add_identity_unstored( - identity.clone(), - identity_index, - wallet_id, - )?; - } + // The key hash at `identity_index` proved the index: add + // the identity there, or move an identity known from + // elsewhere into that slot (stored below, with its + // verified keys, as one changeset). A slot held by a different + // identity (whether the incoming one is new or known) + // means one of the two local records is stale. + // Skip this index without touching either identity, mark + // it unanswered so the next launch rescans, and keep + // walking: aborting here would also stop the stale + // record from reaching its own verified slot higher up + // the walk, which is what frees this one. + let is_new = match info_guard.identity_manager.place_verified_identity( + identity.clone(), + identity_index, + wallet_id, + ) { + Ok(placement) => placement == VerifiedPlacement::Added, + Err(e @ PlatformWalletError::IdentityIndexOccupied { .. }) => { + drop(wm_guard); + tracing::warn!( + index = identity_index, + error = %e, + "identity discovery: verified slot holds another identity; \ + leaving both untouched and rescanning later" + ); + tally.record_sighting(); + tally.record_conflict(identity_index); + identity_index += 1; + continue; + } + Err(e) => return Err(e), + }; if let Some(managed) = info_guard .identity_manager @@ -723,6 +746,9 @@ struct ScanTally { /// together, because to a later launch they are the same fact: an index /// nobody answered. aborted_at_index: Option, + /// Indices whose verified identity could not be placed because its slot + /// holds a different local identity. Unanswered for the verdict. + conflicted_indices: Vec, } impl ScanTally { @@ -763,16 +789,22 @@ impl ScanTally { self.aborted_at_index = Some(index); } + /// Platform answered at `index`, but the identity could not be placed + /// because its verified slot holds a different local identity. The index + /// counts as unanswered (so the verdict is incomplete and a later launch + /// rescans) without touching the probe counters: Platform did answer. + fn record_conflict(&mut self, index: u32) { + self.conflicted_indices.push(index); + } + /// Every index this scan did not answer, ascending — unanswered probes /// plus the index a local fault abandoned it at. fn unanswered_indices(&self) -> Vec { let mut indices = self.failed_indices.clone(); - if let Some(index) = self.aborted_at_index { - if !indices.contains(&index) { - indices.push(index); - indices.sort_unstable(); - } - } + indices.extend(self.aborted_at_index); + indices.extend(self.conflicted_indices.iter().copied()); + indices.sort_unstable(); + indices.dedup(); indices } @@ -1326,6 +1358,22 @@ mod tests { ); } + /// A verified identity whose slot holds another local identity is skipped, + /// not a fault: the walk goes on (the hit still resets the gap counter), + /// no probe counter moves, and the index is unanswered so the next launch + /// rescans instead of trusting a complete verdict. + #[test] + fn a_slot_conflict_keeps_walking_and_leaves_the_scan_incomplete() { + let mut tally = run_scan(5, [Ok(None), Ok(None)]); + tally.record_sighting(); + tally.record_conflict(2); + assert!(tally.should_continue(3), "the hit resets the gap counter"); + let verdict = tally.verdict(0, 3); + assert!(!verdict.complete); + assert_eq!(verdict.failed_indices, vec![2]); + assert_eq!(tally.failed_probes, 0, "Platform answered the probe"); + } + /// A local fault at an index that ALSO went unanswered is recorded once. #[test] fn an_abort_at_an_already_unanswered_index_is_not_duplicated() { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs index c0d63b5afe3..75178a8f9ac 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs @@ -249,14 +249,16 @@ impl IdentityWallet { "Wallet info not found in wallet manager".to_string(), ) })?; - if info.identity_manager.identity(&identity_id).is_none() { - // Stored below, with its verified keys, as one changeset. - info.identity_manager.add_identity_unstored( - identity.clone(), - identity_index, - wallet_id, - )?; - } + // The probe at `identity_index` proved the index: add the identity + // there, or move an identity known from elsewhere into that slot; + // either is stored below, with its verified keys, as one changeset. + // A slot held by another identity refuses here, before status or + // keys are touched, so nothing contradictory is stored. + info.identity_manager.place_verified_identity( + identity.clone(), + identity_index, + wallet_id, + )?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { // Fold the freshly fetched on-chain state into an diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 14e82b28e91..128de299600 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -150,6 +150,7 @@ impl DashPayView<'_, B> { { // 1. The DashPay data contract (process-wide cache). let dashpay_contract = super::dashpay_contract()?; + self.validate_payment_address_update(&input).await?; // 2. The profile fields, with avatar hashes computed from any raw bytes. let fields = profile_fields(input)?; @@ -211,6 +212,7 @@ impl DashPayView<'_, B> { { // 1. The DashPay contract (process-wide cache). let dashpay_contract = super::dashpay_contract()?; + self.validate_payment_address_update(&input).await?; // 2. The profile fields; avatar hashes are computed only when new // bytes are provided. The SDK merges them onto the on-platform @@ -304,9 +306,22 @@ fn profile_fields(input: ProfileUpdate) -> Result [(&'static str, &crate::PaymentAddressUpdate); 3] { + [ + ("corePaymentAddress", &input.core_payment_address), + ("platformPaymentAddress", &input.platform_payment_address), + ("shieldedAddress", &input.shielded_address), + ] +} + /// Parse a profile document's property map into a [`DashPayProfile`]. /// Empty strings are normalized to `None`. `avatarHash`/`avatarFingerprint` /// are read via `as_bytes_slice` so both `Bytes` and the sized `Bytes32` @@ -336,6 +351,21 @@ fn profile_from_properties(props: &std::collections::BTreeMap) -> avatar_hash, avatar_fingerprint, public_message, + core_payment_address: props + .get("corePaymentAddress") + .and_then(|v| v.as_bytes_slice().ok()) + .filter(|bytes| crate::valid_transparent_payment_address(bytes)) + .map(|bytes| bytes.to_vec()), + platform_payment_address: props + .get("platformPaymentAddress") + .and_then(|v| v.as_bytes_slice().ok()) + .filter(|bytes| crate::valid_transparent_payment_address(bytes)) + .map(|bytes| bytes.to_vec()), + shielded_address: props + .get("shieldedAddress") + .and_then(|v| v.as_bytes_slice().ok()) + .and_then(crate::validated_shielded_address) + .map(|bytes| bytes.to_vec()), } } @@ -825,3 +855,402 @@ mod tests { assert!(cache[&id].profile.is_none()); } } + +impl DashPayView<'_, B> { + /// Fetch a fresh, proof-verified profile, bypassing the contact cache. + pub async fn fetch_profile( + &self, + identity_id: &Identifier, + ) -> Result, PlatformWalletError> { + let contract = super::dashpay_contract()?; + Ok(self + .sdk + .get_profiles(&contract, &[*identity_id]) + .await? + .remove(identity_id) + .map(|doc| profile_from_properties(doc.properties()))) + } + + /// Resolve the current DPNS owner and its current shielded tip address. + pub async fn resolve_shielded_tip( + &self, + username: &str, + ) -> Result { + let identity_id = self.sdk.resolve_dpns_name(username).await?.ok_or_else(|| { + PlatformWalletError::InvalidIdentityData("Username was not found".to_string()) + })?; + let address = self + .fetch_profile(&identity_id) + .await? + .and_then(|profile| profile.shielded_address) + .and_then(|bytes| crate::validated_shielded_address(&bytes)) + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "This profile has no valid shielded tip address".to_string(), + ) + })?; + Ok(crate::ShieldedTipRecipient { + identity_id, + address, + }) + } + + async fn validate_payment_address_update( + &self, + input: &crate::ProfileUpdate, + ) -> Result<(), PlatformWalletError> { + use crate::PaymentAddressUpdate; + use dash_sdk::platform::Fetch; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; + use dpp::prelude::DataContract; + let updates = payment_address_updates(input); + if updates + .iter() + .all(|(_, patch)| !matches!(patch, PaymentAddressUpdate::Set(_))) + { + return Ok(()); + } + for (field, patch) in updates { + if let PaymentAddressUpdate::Set(bytes) = patch { + let valid = if field == "shieldedAddress" { + crate::validated_shielded_address(bytes).is_some() + } else { + crate::valid_transparent_payment_address(bytes) + }; + if !valid { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "Invalid or unsupported {field}" + ))); + } + } + } + // The bundled latest schema does not prove the connected chain has + // activated it. Fetch the actual contract before submitting new fields. + let contract = DataContract::fetch( + &self.sdk, + dpp::data_contracts::SystemDataContract::Dashpay.id(), + ) + .await? + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "DashPay contract is not available".to_string(), + ) + })?; + let profile = contract + .document_type_for_name("profile") + .map_err(|e| PlatformWalletError::InvalidIdentityData(e.to_string()))?; + for (field, patch) in updates { + if matches!(patch, PaymentAddressUpdate::Set(_)) + && !profile.properties().contains_key(field) + { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "The connected network does not support {field} yet" + ))); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod address_patch_tests { + use super::*; + use crate::{PaymentAddressUpdate, ProfileUpdate}; + + #[tokio::test] + async fn should_allow_removal_without_contract_activation_but_reject_unsupported_set() { + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); + let contract = load_system_data_contract( + SystemDataContract::Dashpay, + PlatformVersion::get(13).unwrap(), + ) + .unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::Dashpay.id(), Some(contract)) + .await + .unwrap(); + let (wm, wallet_id, generation, _) = crate::test_support::funded_wallet_manager( + key_wallet::account::StandardAccountType::BIP44Account, + ) + .await; + let spv = Arc::new(crate::spv::SpvRuntime::new( + wm.clone(), + Arc::new(crate::events::PlatformEventManager::new(vec![])), + )); + let wallet = crate::PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wm, + generation, + Arc::new(tokio::sync::Notify::new()), + Arc::new(crate::wallet::persister::NoPlatformPersistence), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let remove = ProfileUpdate { + display_name: Some("Alice II".into()), + core_payment_address: PaymentAddressUpdate::Remove, + platform_payment_address: PaymentAddressUpdate::Remove, + shielded_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + wallet + .identity() + .dashpay() + .validate_payment_address_update(&remove) + .await + .unwrap(); + let fields = profile_fields(remove).unwrap(); + assert_eq!(fields.display_name.as_deref(), Some("Alice II")); + assert_eq!(fields.core_payment_address, PaymentAddressUpdate::Remove); + assert_eq!( + fields.platform_payment_address, + PaymentAddressUpdate::Remove + ); + assert_eq!(fields.shielded_address, PaymentAddressUpdate::Remove); + // Removal must not bypass activation checks on a simultaneously set field. + let mixed = ProfileUpdate { + core_payment_address: PaymentAddressUpdate::Set(vec![0; 21]), + shielded_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + let error = wallet + .identity() + .dashpay() + .validate_payment_address_update(&mixed) + .await + .unwrap_err(); + assert!(error + .to_string() + .contains("does not support corePaymentAddress")); + } + + #[test] + fn should_ignore_invalid_addresses_without_losing_profile() { + let profile = profile_from_properties(&std::collections::BTreeMap::from([ + ("displayName".into(), Value::Text("Alice".into())), + ("shieldedAddress".into(), Value::Bytes(vec![255; 43])), + ("corePaymentAddress".into(), Value::Bytes(vec![255; 21])), + ])); + assert_eq!(profile.display_name.as_deref(), Some("Alice")); + assert!(profile.shielded_address.is_none()); + assert!(profile.core_payment_address.is_none()); + } + + #[cfg(feature = "shielded")] + #[test] + fn should_accept_external_addresses_with_nondefault_diversifiers() { + let keys = crate::wallet::shielded::OrchardKeySet::from_seed( + &[9; 64], + key_wallet::Network::Testnet, + 7, + ) + .unwrap(); + let raw = keys.address_at(19).to_raw_address_bytes(); + assert_ne!(raw, keys.default_address.to_raw_address_bytes()); + let profile = profile_from_properties(&std::collections::BTreeMap::from([( + "shieldedAddress".into(), + Value::Bytes(raw.to_vec()), + )])); + assert_eq!(profile.shielded_address, Some(raw.to_vec())); + assert!(crate::validated_shielded_address(&raw[..42]).is_none()); + } +} + +#[cfg(all(test, feature = "shielded"))] +mod tip_resolution_tests { + use super::*; + use crate::wallet::shielded::{ + CachedOrchardProver, FileBackedShieldedStore, NetworkShieldedCoordinator, OrchardKeySet, + }; + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents, SdkBuilder}; + use dpp::{ + document::{Document, DocumentV0}, + system_data_contracts::{load_system_data_contract, SystemDataContract}, + version::PlatformVersion, + }; + + // Exercise both SDK queries through the real wallet API. No expectations + // permit a send/broadcast: a changed or invalid destination must stop first. + #[tokio::test] + async fn should_resolve_fresh_profiles_and_refuse_changed_tip_destinations() { + let original_owner = Identifier::from([1; 32]); + let new_owner = Identifier::from([2; 32]); + let keys = OrchardKeySet::from_seed(&[42; 64], key_wallet::Network::Testnet, 9).unwrap(); + let original_address = keys.default_address.to_raw_address_bytes(); + let changed_address = keys.address_at(7).to_raw_address_bytes(); + for (owner, address, expected_error) in [ + (original_owner, Some(original_address.to_vec()), "bound"), + ( + new_owner, + Some(original_address.to_vec()), + "recipient changed", + ), + ( + original_owner, + Some(changed_address.to_vec()), + "recipient changed", + ), + (original_owner, None, "no valid shielded tip address"), + ( + original_owner, + Some(vec![255; 43]), + "no valid shielded tip address", + ), + ] { + let dir = std::env::temp_dir().join(format!( + "tip-resolution-{}-{}", + std::process::id(), + rand::random::() + )); + std::fs::create_dir_all(&dir).unwrap(); + let mut sdk = SdkBuilder::new_mock() + .with_network(key_wallet::Network::Testnet) + .with_version(PlatformVersion::latest()) + .with_dump_dir(&dir) + .build() + .unwrap(); + let dpns = + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::DPNS.id(), Some(dpns.clone())) + .await + .unwrap(); + let domain = Document::V0(DocumentV0 { + id: Identifier::from([3; 32]), + owner_id: owner, + revision: Some(1), + properties: [( + "records".into(), + Value::Map(vec![( + Value::Text("identity".into()), + Value::Identifier(owner.to_buffer()), + )]), + )] + .into(), + ..Default::default() + }); + let query = DocumentQuery { + data_contract: Arc::new(dpns), + document_type_name: "domain".into(), + where_clauses: vec![ + WhereClause { + field: "normalizedParentDomainName".into(), + operator: WhereOperator::Equal, + value: Value::Text("dash".into()), + }, + WhereClause { + field: "normalizedLabel".into(), + operator: WhereOperator::Equal, + value: Value::Text("a11ce".into()), + }, + ], + select: dash_sdk::drive::query::SelectProjection::documents(), + time_range_clauses: vec![], + integer_range_clauses: vec![], + group_by: vec![], + having: vec![], + order_by_clauses: vec![], + limit: 1, + offset: None, + start: None, + sub_queries: vec![], + }; + sdk.mock() + .expect_fetch_many::( + query, + Some([(domain.id(), Some(domain))].into()), + ) + .await + .unwrap(); + let profile = Document::V0(DocumentV0 { + id: Identifier::from([4; 32]), + owner_id: owner, + revision: Some(1), + properties: address + .map(|bytes| ("shieldedAddress".into(), Value::Bytes(bytes))) + .into_iter() + .collect(), + ..Default::default() + }); + // The `$ownerId In [owner]` query `Sdk::get_profiles` sends. + let contract = super::super::dashpay_contract().unwrap(); + let profile_query = DocumentQuery::new(contract, "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![owner.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + sdk.mock() + .expect_fetch_many::( + profile_query, + Some([(profile.id(), Some(profile))].into()), + ) + .await + .unwrap(); + let sdk = Arc::new(sdk); + let (wm, wallet_id, generation, _) = crate::test_support::funded_wallet_manager( + key_wallet::account::StandardAccountType::BIP44Account, + ) + .await; + let spv = Arc::new(crate::spv::SpvRuntime::new( + wm.clone(), + Arc::new(crate::events::PlatformEventManager::new(vec![])), + )); + let wallet = crate::PlatformWallet::new( + sdk.clone(), + wallet_id, + wm, + generation, + Arc::new(tokio::sync::Notify::new()), + Arc::new(crate::wallet::persister::NoPlatformPersistence), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let path = dir.join("tree.sqlite"); + let store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + let coordinator = Arc::new(NetworkShieldedCoordinator::new( + sdk, + key_wallet::Network::Testnet, + path, + store, + )); + let confirmed = crate::ShieldedTipRecipient { + identity_id: original_owner, + address: original_address, + }; + let error = wallet + .send_shielded_tip( + &coordinator, + &[42; 64], + 0, + "Alice.dash", + &confirmed, + 1000, + [0; 36], + &CachedOrchardProver::new(), + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains(expected_error), + "expected {expected_error}, got {error}" + ); + drop(coordinator); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs index 03f8ed10004..38b221d4ab4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs @@ -36,7 +36,10 @@ impl IdentityManager { /// /// Idempotent: applying the same entry twice produces the same state /// as applying it once. If the identity already exists in either - /// bucket, the scalar fields are updated in place; balance/revision + /// bucket, it first moves to the wallet slot the entry carries (a + /// re-slot by [`Self::adopt_into_wallet`]) unless another identity + /// holds that slot (placement follows the latest entry applied, as in + /// `IdentityChangeSet::merge`), and the scalar fields are updated; balance/revision /// are gated on `entry.revision >= existing.identity.revision()` /// matching the merge policy on `IdentityChangeSet`. DPNS labels and /// contested DPNS labels are complete canonical snapshots and are @@ -46,6 +49,20 @@ impl IdentityManager { let id = entry.id; + // Follow a re-slot (placeholder index 0 to its verified index, or an + // observed identity adopted into the wallet) before updating in place. + if self.identity(&id).is_some() { + if let Some((wallet_id, index)) = entry.wallet_id.zip(entry.identity_index) { + if let Err(error) = self.adopt_into_wallet(&id, wallet_id, index) { + tracing::warn!( + identity = %id, + %error, + "keeping identity at its current slot during apply", + ); + } + } + } + // Updating an existing identity — find it across both buckets. if let Some(existing) = self.locate_mut(&id) { if entry.revision >= existing.identity.revision() { @@ -107,6 +124,18 @@ impl IdentityManager { ); return; }; + // Inserting would discard the occupant while its reverse-index + // entry kept pointing here. + if let Some(occupant) = self.slot_holder(&wallet_id, registration_index) { + tracing::warn!( + identity = %id, + %occupant, + wallet_id = %hex::encode(wallet_id), + registration_index, + "skipping wallet-owned identity entry whose slot is occupied during apply", + ); + return; + } let mut managed = ManagedIdentity::new(identity, registration_index); managed.last_updated_balance_block_time = entry.last_updated_balance_block_time; @@ -162,6 +191,116 @@ impl IdentityManager { } } + /// Restore a batch of entries independently of their order. Known + /// identities are applied first, each deferred while its target slot is + /// still held by another identity that the batch moves out, and new ones + /// are inserted last: a re-slot A@0 → A@5 frees slot 0 for a new B@0 + /// whichever entry is visited first. Moves that only wait on each other + /// (A@0/B@1 becoming A@1/B@0) are staged out of the wallet and then + /// placed; a move blocked by an identity that stays put is applied in + /// place. + pub(crate) fn apply_identity_entries( + &mut self, + entries: impl IntoIterator, + ) { + let (mut pending, fresh): (Vec<_>, Vec<_>) = entries + .into_iter() + .partition(|entry| self.identity(&entry.id).is_some()); + while !pending.is_empty() { + let (blocked, ready): (Vec<_>, Vec<_>) = pending + .into_iter() + .partition(|entry| self.blocker(entry).is_some()); + let progressed = !ready.is_empty(); + for entry in ready { + self.apply_identity_entry(entry); + } + pending = blocked; + if !progressed { + let cycle = self.cycle_members(&pending); + if cycle.is_empty() { + break; + } + for id in &cycle { + self.stage_out_of_wallet(id); + } + } + } + for entry in pending.into_iter().chain(fresh) { + self.apply_identity_entry(entry); + } + } + + /// The other identity holding the slot `entry` places its identity in. + fn blocker(&self, entry: &IdentityEntry) -> Option { + entry + .wallet_id + .zip(entry.identity_index) + .and_then(|(wallet_id, index)| self.slot_holder(&wallet_id, index)) + .filter(|holder| *holder != entry.id) + } + + /// Blocked moves on a closed cycle: following blockers through the other + /// blocked moves leads back to the start. Empty when another blocked move + /// waits on a cycle member: that slot is claimed twice (only an + /// inconsistent batch does this), and staging could strand the loser + /// outside the wallet. + fn cycle_members(&self, pending: &[IdentityEntry]) -> Vec { + let blockers: BTreeMap = pending + .iter() + .filter_map(|entry| Some((entry.id, self.blocker(entry)?))) + .collect(); + let cycle: Vec = blockers + .keys() + .copied() + .filter(|start| { + let mut current = *start; + for _ in 0..blockers.len() { + match blockers.get(¤t) { + Some(next) if next == start => return true, + Some(next) => current = *next, + None => return false, + } + } + false + }) + .collect(); + let contested = blockers + .iter() + .any(|(id, blocker)| !cycle.contains(id) && cycle.contains(blocker)); + if contested { + Vec::new() + } else { + cycle + } + } + + /// Park an in-wallet identity in the observed bucket, freeing its slot; + /// applying its entry then adopts it back into its target slot. + fn stage_out_of_wallet(&mut self, identity_id: &Identifier) { + let Some(IdentityLocation::InWallet { + wallet_id, + registration_index, + }) = self.location_index().get(identity_id).copied() + else { + return; + }; + if let Some(managed) = self + .wallet_identities + .get_mut(&wallet_id) + .and_then(|bucket| bucket.remove(®istration_index)) + { + self.out_of_wallet_identities.insert(*identity_id, managed); + self.location_index_insert(*identity_id, IdentityLocation::OutOfWallet); + } + } + + fn slot_holder(&self, wallet_id: &[u8; 32], index: u32) -> Option { + self.wallet_identities + .get(wallet_id) + .and_then(|bucket| bucket.get(&index)) + .map(|occupant| occupant.identity.id()) + } + /// Restore a single [`IdentityKeyEntry`] onto the matching /// `ManagedIdentity`. /// diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs index 294e836f9d8..bce2e3cd8db 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs @@ -4,7 +4,9 @@ //! Every mutation here persists a corresponding //! [`IdentityChangeSet`](crate::changeset::IdentityChangeSet) via //! the supplied [`WalletPersister`], except -//! [`IdentityManager::add_identity_unstored`], whose caller stores. +//! [`IdentityManager::add_identity_unstored`], +//! [`IdentityManager::place_verified_identity`] and +//! [`IdentityManager::adopt_into_wallet`], whose callers store. use super::{IdentityLocation, IdentityManager}; use crate::changeset::{IdentityChangeSet, IdentityEntry, PlatformWalletChangeSet}; @@ -16,6 +18,15 @@ use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::Identity; use dpp::prelude::Identifier; +/// How [`IdentityManager::place_verified_identity`] placed an identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VerifiedPlacement { + /// Newly added to the wallet bucket. + Added, + /// Already known; moved into (or confirmed at) the verified slot. + Adopted, +} + impl IdentityManager { /// Create a new identity manager pub fn new() -> Self { @@ -31,7 +42,10 @@ impl IdentityManager { /// onto the value at insert time. /// /// Errors if an identity with the same id already exists in either - /// bucket. + /// bucket, or with [`PlatformWalletError::IdentityIndexOccupied`] if the + /// slot already holds a different identity (inserting would silently + /// discard the occupant while its reverse-index entry kept pointing at + /// the slot). Nothing is changed or persisted on either error. /// /// Persists the resulting changeset via `persister` and returns `()`. pub fn add_identity( @@ -90,6 +104,17 @@ impl IdentityManager { if self.identity(&identity_id).is_some() { return Err(PlatformWalletError::IdentityAlreadyExists(identity_id)); } + if let Some(occupant) = self + .wallet_identities + .get(&wallet_id) + .and_then(|bucket| bucket.get(&identity_index)) + { + return Err(PlatformWalletError::IdentityIndexOccupied { + identity_id, + identity_index, + occupant: occupant.identity.id(), + }); + } let mut managed_identity = ManagedIdentity::new(identity, identity_index); // Denormalize the bucket keys onto the value so callers that @@ -142,6 +167,101 @@ impl IdentityManager { } } + /// Place an identity a key derivation just proved at `identity_index` in + /// `wallet_id`'s bucket: add it when unknown, otherwise move it into that + /// slot (see [`Self::adopt_into_wallet`]). Identity load and discovery both + /// go through here before they touch status or keys, so a refused + /// placement changes nothing. Like [`Self::add_identity_unstored`] it + /// does not persist: the caller stores the identity's snapshot with its + /// verified keys as one changeset. + pub(crate) fn place_verified_identity( + &mut self, + identity: Identity, + identity_index: u32, + wallet_id: WalletId, + ) -> Result { + let identity_id = identity.id(); + if self.identity(&identity_id).is_none() { + self.add_identity_unstored(identity, identity_index, wallet_id)?; + Ok(VerifiedPlacement::Added) + } else { + self.adopt_into_wallet(&identity_id, wallet_id, identity_index)?; + Ok(VerifiedPlacement::Adopted) + } + } + + /// Move an already-known identity into `wallet_id`'s bucket at the + /// `identity_index` a key derivation just proved for it. + /// + /// Identity load and discovery find identities by deriving this wallet's + /// MASTER key at an index, so the index they report is verified. An + /// identity first seen another way (observed out-of-wallet, or restored + /// with a host placeholder index) must take that verified slot rather than + /// just gaining a `wallet_id`: an index-less wallet identity is persisted + /// without its index, and hosts that cannot store "unknown" restore it as + /// index 0, which per-identity derivations (the dedicated tip account) + /// would then attribute to identity 0. + /// + /// Does not persist; the caller's following snapshot write carries the + /// updated `wallet_id` / `identity_index`. Fails with + /// [`PlatformWalletError::IdentityIndexOccupied`], changing nothing, when + /// the slot already holds a different identity. + pub fn adopt_into_wallet( + &mut self, + identity_id: &Identifier, + wallet_id: WalletId, + identity_index: u32, + ) -> Result<(), PlatformWalletError> { + let target = IdentityLocation::InWallet { + wallet_id, + registration_index: identity_index, + }; + let current = self + .location_index() + .get(identity_id) + .copied() + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + if current != target { + if let Some(other) = self + .wallet_identities + .get(&wallet_id) + .and_then(|bucket| bucket.get(&identity_index)) + .filter(|other| other.identity.id() != *identity_id) + { + return Err(PlatformWalletError::IdentityIndexOccupied { + identity_id: *identity_id, + identity_index, + occupant: other.identity.id(), + }); + } + let managed = match current { + IdentityLocation::OutOfWallet => self.out_of_wallet_identities.remove(identity_id), + IdentityLocation::InWallet { + wallet_id, + registration_index, + } => self + .wallet_identities + .get_mut(&wallet_id) + .and_then(|bucket| bucket.remove(®istration_index)), + } + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + self.wallet_identities + .entry(wallet_id) + .or_default() + .insert(identity_index, managed); + self.location_index_insert(*identity_id, target); + } + if let Some(managed) = self + .wallet_identities + .get_mut(&wallet_id) + .and_then(|bucket| bucket.get_mut(&identity_index)) + { + managed.wallet_id = Some(wallet_id); + managed.identity_index = Some(identity_index); + } + Ok(()) + } + /// Add an identity to the out-of-wallet (observed read-only) bucket. /// /// There is no separate `WatchedIdentity` type; observed identities diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs index 236f259e4b2..a794fd0c297 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs @@ -29,6 +29,7 @@ mod accessors; mod apply; mod lifecycle; +pub use lifecycle::VerifiedPlacement; use super::managed_identity::ManagedIdentity; use crate::changeset::{IdentityManagerStartState, IdentityScanStateEntry}; @@ -230,6 +231,7 @@ impl IdentityManager { #[cfg(test)] mod tests { use super::*; + use crate::error::PlatformWalletError; use crate::wallet::persister::{NoPlatformPersistence, WalletPersister}; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::Identity; @@ -277,6 +279,173 @@ mod tests { assert_eq!(manager.highest_registration_index(&wallet_id), Some(0)); } + #[derive(Default)] + struct CountingPersistence { + stores: std::sync::atomic::AtomicUsize, + } + impl crate::changeset::PlatformWalletPersistence for CountingPersistence { + fn store( + &self, + _wallet_id: WalletId, + _changeset: crate::changeset::PlatformWalletChangeSet, + ) -> Result<(), crate::changeset::PersistenceError> { + self.stores + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + } + fn flush(&self, _wallet_id: WalletId) -> Result<(), crate::changeset::PersistenceError> { + Ok(()) + } + fn load( + &self, + ) -> Result + { + Ok(Default::default()) + } + } + + /// Load and discovery prove an index by derivation and place the identity + /// through `place_verified_identity` before touching status or keys. An + /// identity already known (observed, or restored at a placeholder slot) + /// moves into the verified slot as `Adopted`, which discovery does not + /// report as newly discovered. A slot held by a different identity is a + /// typed refusal that changes and persists nothing. + #[test] + fn verified_placement_adopts_known_identities_and_refuses_occupied_slots() { + use std::sync::atomic::Ordering; + let mut manager = IdentityManager::new(); + let wallet_id: WalletId = [9u8; 32]; + let counter = Arc::new(CountingPersistence::default()); + let p = WalletPersister::new(wallet_id, Arc::clone(&counter) as _); + + let fresh = Identifier::from([5u8; 32]); + assert_eq!( + manager + .place_verified_identity(create_test_identity(fresh), 2, wallet_id) + .unwrap(), + VerifiedPlacement::Added + ); + + // Promotion of an observed identity: no new id is reported. + let observed = Identifier::from([1u8; 32]); + manager + .add_out_of_wallet_identity(create_test_identity(observed), &p) + .unwrap(); + assert_eq!( + manager + .place_verified_identity(create_test_identity(observed), 4, wallet_id) + .unwrap(), + VerifiedPlacement::Adopted + ); + assert!(manager.out_of_wallet_identities.is_empty()); + let managed = manager.identity(&observed).expect("present"); + assert_eq!(managed.identity_index, Some(4)); + assert_eq!(managed.wallet_id, Some(wallet_id)); + assert_eq!(manager.identity_index(&observed), Some(4)); + + // A host-placeholder slot 0 is corrected to the verified index. + let placeholder = Identifier::from([2u8; 32]); + manager + .add_identity(create_test_identity(placeholder), 0, wallet_id, &p) + .unwrap(); + manager + .adopt_into_wallet(&placeholder, wallet_id, 7) + .unwrap(); + let bucket = &manager.wallet_identities[&wallet_id]; + assert!(!bucket.contains_key(&0)); + assert_eq!(bucket[&7].identity.id(), placeholder); + assert_eq!(manager.identity_index(&placeholder), Some(7)); + // Already in place: a no-op success. + manager + .adopt_into_wallet(&placeholder, wallet_id, 7) + .unwrap(); + + // Never evict a different identity from the target slot, and persist + // nothing on the refusal. + let other = Identifier::from([3u8; 32]); + manager + .add_out_of_wallet_identity(create_test_identity(other), &p) + .unwrap(); + let stores_before = counter.stores.load(Ordering::SeqCst); + let refused = + manager.place_verified_identity(create_test_identity(other), 7, wallet_id); + assert!( + matches!( + refused, + Err(PlatformWalletError::IdentityIndexOccupied { + identity_id, + identity_index: 7, + occupant, + }) if identity_id == other && occupant == placeholder + ), + "{refused:?}" + ); + assert_eq!(counter.stores.load(Ordering::SeqCst), stores_before); + assert_eq!(manager.identity_index(&other), None); + assert!(manager.identity(&other).unwrap().wallet_id.is_none()); + assert_eq!(manager.identity_index(&placeholder), Some(7)); + assert!(matches!( + manager.adopt_into_wallet(&Identifier::from([4u8; 32]), wallet_id, 9), + Err(PlatformWalletError::IdentityNotFound(_)) + )); + } + + /// An unknown identity verified at a slot that already holds a different + /// identity (a restored placeholder, say) must not overwrite it: the + /// occupant's state would be discarded while its reverse-index entry kept + /// resolving to the newcomer. Refused with the typed error, changing and + /// persisting nothing, through `add_identity` and the shared placement. + #[test] + fn an_unknown_identity_cannot_take_an_occupied_slot() { + use std::sync::atomic::Ordering; + let mut manager = IdentityManager::new(); + let wallet_id: WalletId = [9u8; 32]; + let counter = Arc::new(CountingPersistence::default()); + let p = WalletPersister::new(wallet_id, Arc::clone(&counter) as _); + + let occupant = Identifier::from([0xB0; 32]); + manager + .add_identity(create_test_identity(occupant), 0, wallet_id, &p) + .unwrap(); + let newcomer = Identifier::from([0xA0; 32]); + let stores_before = counter.stores.load(Ordering::SeqCst); + + for attempt in [ + manager.add_identity(create_test_identity(newcomer), 0, wallet_id, &p), + manager + .place_verified_identity(create_test_identity(newcomer), 0, wallet_id) + .map(|_| ()), + ] { + assert!( + matches!( + attempt, + Err(PlatformWalletError::IdentityIndexOccupied { + identity_id, + identity_index: 0, + occupant: held, + }) if identity_id == newcomer && held == occupant + ), + "{attempt:?}" + ); + } + + assert_eq!(counter.stores.load(Ordering::SeqCst), stores_before); + assert_eq!( + manager.identity(&occupant).map(|m| m.identity.id()), + Some(occupant) + ); + assert!(manager.identity(&newcomer).is_none()); + assert_eq!(manager.identity_index(&occupant), Some(0)); + let bucket = &manager.wallet_identities[&wallet_id]; + assert_eq!(bucket.len(), 1); + assert_eq!(bucket[&0].identity.id(), occupant); + // A free slot is still fine. + manager + .add_identity(create_test_identity(newcomer), 1, wallet_id, &p) + .unwrap(); + assert_eq!(manager.identity_index(&newcomer), Some(1)); + } + #[test] fn test_add_out_of_wallet_identity() { let mut manager = IdentityManager::new(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs index 05f321ec6ef..26b9b9cb21b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs @@ -12,3 +12,4 @@ pub use managed_identity::{BlockTime, DashPayState, ManagedIdentity, PrivateCont pub use manager::IdentityLocation; pub use manager::IdentityManager; pub use manager::RegistrationIndex; +pub use manager::VerifiedPlacement; diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs index 339520651d7..a0bd1440c38 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs @@ -10,5 +10,5 @@ pub use established_contact::EstablishedContact; pub use payment::{DashpayAddressMatch, PaymentDirection, PaymentEntry, PaymentStatus}; pub use profile::{ calculate_avatar_hash, calculate_dhash_fingerprint, ContactProfileEntry, DashPayProfile, - ProfileUpdate, + PaymentAddressUpdate, ProfileUpdate, ShieldedTipRecipient, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs index ab661278f99..34ff43c3fe5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs @@ -37,6 +37,17 @@ pub struct DashPayProfile { pub avatar_fingerprint: Option<[u8; 8]>, /// Public message broadcast to contacts. pub public_message: Option, + /// Core P2PKH/P2SH storage address (type byte plus HASH160, 21 bytes). + /// The address defaults support map formats such as JSON. Positional + /// bincode records require the storage layer's versioned legacy decoder. + #[cfg_attr(feature = "serde", serde(default))] + pub core_payment_address: Option>, + /// Platform P2PKH/P2SH storage address (21 bytes). + #[cfg_attr(feature = "serde", serde(default))] + pub platform_payment_address: Option>, + /// Complete raw Orchard address (11-byte diversifier + 32-byte pk_d). + #[cfg_attr(feature = "serde", serde(default))] + pub shielded_address: Option>, } /// A cached **contact** profile, keyed by the contact's identity id on the @@ -79,6 +90,43 @@ pub struct ProfileUpdate { /// includes them in the document, then drops the bytes. /// `None` = no avatar / remove avatar. pub avatar_bytes: Option>, + pub core_payment_address: PaymentAddressUpdate, + pub platform_payment_address: PaymentAddressUpdate, + pub shielded_address: PaymentAddressUpdate, +} + +/// Explicit patch semantics: omission must never remove a published address. +pub use dash_sdk::platform::dashpay::PaymentAddressUpdate; + +/// Recipient shown at confirmation. Re-resolve before sending and compare both +/// fields so a changed DPNS owner or profile cannot silently redirect a tip. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShieldedTipRecipient { + pub identity_id: dpp::prelude::Identifier, + pub address: [u8; 43], +} + +/// Decode a raw Orchard recipient using the same decoder as shielded transfers. +/// Without shielded support an address must never be advertised as payable. +pub fn validated_shielded_address(bytes: &[u8]) -> Option<[u8; 43]> { + #[cfg(feature = "shielded")] + { + let raw: [u8; 43] = bytes.try_into().ok()?; + Option::::from( + grovedb_commitment_tree::PaymentAddress::from_raw_address_bytes(&raw), + ) + .map(|_| raw) + } + #[cfg(not(feature = "shielded"))] + { + let _ = bytes; + None + } +} + +/// Storage-form transparent address validation, matching the DashPay trigger. +pub fn valid_transparent_payment_address(bytes: &[u8]) -> bool { + bytes.len() == 21 && matches!(bytes.first(), Some(0x00 | 0x01)) } /// Compute SHA-256 hash of image bytes (DIP-15 `avatarHash` field). diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs index c6623c5a8b2..2d7e674e051 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs @@ -12,6 +12,7 @@ pub mod key_storage; pub use block_time::BlockTime; pub use dashpay::{ ContactProfileEntry, ContactRequest, DashPayProfile, DashpayAddressMatch, EstablishedContact, - PaymentDirection, PaymentEntry, PaymentStatus, ProfileUpdate, + PaymentAddressUpdate, PaymentDirection, PaymentEntry, PaymentStatus, ProfileUpdate, + ShieldedTipRecipient, }; pub use key_storage::{DpnsFetch, DpnsNameInfo, IdentityStatus, KeyStorage, PrivateKeyData}; diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index c67a5462f70..15244935ebe 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -434,6 +434,15 @@ pub struct PlatformWallet { /// wallet handles share the one lock. #[cfg(feature = "shielded")] pub(crate) shield_guard: Arc>, + /// Serializes changes to the bound shielded account set. A bind + /// replaces the registration with the accounts it was given, so a + /// caller that reads the current set and binds an augmented copy (tip + /// preparation) must not interleave with another bind, or the other + /// bind's ordinary accounts are dropped and their live state purged. + /// Taken at the top of every bind entry point and by + /// `shielded_add_account`, before `shield_guard`. + #[cfg(feature = "shielded")] + pub(crate) shielded_config_lock: Arc>, /// Set once this wallet has been removed from the manager, to stop /// a handle that outlives the removal from binding shielded state /// back onto the coordinator. Callers resolve an @@ -833,6 +842,8 @@ impl PlatformWallet { #[cfg(feature = "shielded")] shield_guard: Arc::new(tokio::sync::Mutex::new(())), #[cfg(feature = "shielded")] + shielded_config_lock: Arc::new(tokio::sync::Mutex::new(())), + #[cfg(feature = "shielded")] shielded_detached: Arc::new(std::sync::atomic::AtomicBool::new(false)), #[cfg(feature = "shielded")] private_payment_restores: Arc::default(), @@ -871,6 +882,19 @@ impl PlatformWallet { seed: &[u8], accounts: &[u32], coordinator: &Arc, + ) -> Result<(), PlatformWalletError> { + let _config = self.shielded_config_lock.lock().await; + self.bind_shielded_locked(seed, accounts, coordinator).await + } + + /// [`Self::bind_shielded`] for a caller already holding + /// `shielded_config_lock`. + #[cfg(feature = "shielded")] + pub(crate) async fn bind_shielded_locked( + &self, + seed: &[u8], + accounts: &[u32], + coordinator: &Arc, ) -> Result<(), PlatformWalletError> { use super::shielded::{AccountViewingKeys, OrchardKeySet, SubwalletId}; let required = crate::changeset::PersistenceCapabilities::SHIELDED_FVK_RESTART; @@ -897,12 +921,29 @@ impl PlatformWallet { // snapshot predates a Clear. let snapshot_generation = coordinator.clear_generation(); let network = self.sdk.network; + let mut accounts: std::collections::BTreeSet = accounts.iter().copied().collect(); + accounts.extend(self.discovered_tip_accounts().await?); + // Keep retired tip accounts scanning, including identities removed from + // the local manager after their address was published. + let start = self + .persister + .load() + .map_err(|e| PlatformWalletError::Persistence(e.to_string()))?; + accounts.extend( + start + .shielded + .viewing_keys + .keys() + .filter(|id| { + id.wallet_id == self.wallet_id + && super::shielded::is_shielded_tip_account(id.account_index) + }) + .map(|id| id.account_index), + ); let mut account_views: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for &account in accounts { - // `accounts` may contain duplicates; the BTreeMap - // dedups by definition. The full keyset (with its - // `SpendAuthorizingKey`) is dropped at the end of + for &account in &accounts { + // The full keyset (with its `SpendAuthorizingKey`) is dropped at the end of // this iteration — only the viewing half survives. let ks = OrchardKeySet::from_seed(seed, network, account)?; account_views.insert(account, ks.viewing_keys()); @@ -920,11 +961,6 @@ impl PlatformWallet { // treat it like the malformed-row case below: surface it rather // than silently mixing two keys' state. The recovery is a // shielded Clear, which drops both sides at once. - let start = self.persister.load().map_err(|e| { - PlatformWalletError::ShieldedBuildError(format!( - "persister load failed while binding shielded viewing keys: {e}" - )) - })?; for (account, views) in &account_views { let id = SubwalletId::new(self.wallet_id, *account); if let Some(persisted) = start.shielded.viewing_keys.get(&id) { @@ -989,6 +1025,7 @@ impl PlatformWallet { coordinator: &Arc, ) -> Result { use super::shielded::{AccountViewingKeys, SubwalletId}; + let _config = self.shielded_config_lock.lock().await; let required = crate::changeset::PersistenceCapabilities::SHIELDED_FVK_RESTART; let capabilities = self.persister.persistence_capabilities(); if !capabilities.contains(required) { @@ -1014,9 +1051,25 @@ impl PlatformWallet { "persister load failed while rebinding shielded viewing keys: {e}" )) })?; + let mut accounts: std::collections::BTreeSet = accounts.iter().copied().collect(); + // Newly discovered identities require their tip accounts too. Missing + // FVKs must trigger seed-backed binding: skipping them would report a + // successful restart while silently omitting recoverable tip history. + accounts.extend(self.discovered_tip_accounts().await?); + accounts.extend( + start + .shielded + .viewing_keys + .keys() + .filter(|id| { + id.wallet_id == self.wallet_id + && super::shielded::is_shielded_tip_account(id.account_index) + }) + .map(|id| id.account_index), + ); let mut account_views: std::collections::BTreeMap = std::collections::BTreeMap::new(); - for &account in accounts { + for &account in &accounts { let id = SubwalletId::new(self.wallet_id, account); let Some(fvk_bytes) = start.shielded.viewing_keys.get(&id) else { return Ok(false); @@ -1288,6 +1341,9 @@ impl PlatformWallet { ))); } self.ensure_shielded_attached()?; + // Serialized with the binds: tip preparation rebinds a snapshot of + // the account set, which would drop an account inserted mid-way. + let _config = self.shielded_config_lock.lock().await; // Everything that calls into the host — the snapshot read below // and the viewing-key write further down — stays OUTSIDE the key // slot's lock. A host callback invoked while this write guard is @@ -2905,6 +2961,8 @@ impl Clone for PlatformWallet { #[cfg(feature = "shielded")] shield_guard: self.shield_guard.clone(), #[cfg(feature = "shielded")] + shielded_config_lock: self.shielded_config_lock.clone(), + #[cfg(feature = "shielded")] shielded_detached: self.shielded_detached.clone(), #[cfg(feature = "shielded")] private_payment_restores: self.private_payment_restores.clone(), diff --git a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs index a535e52fff4..c35fb651964 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs @@ -52,6 +52,8 @@ pub mod prover; pub mod seed_pool; pub mod store; pub mod sync; +pub mod tips; +pub use tips::{is_shielded_tip_account, shielded_tip_account_index, SHIELDED_TIP_ACCOUNT_BASE}; #[cfg(test)] mod viewing_key_bind_tests; #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs index 6cdb39536f8..010015e32e9 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs @@ -281,3 +281,33 @@ fn shield_memo_round_trips_through_ovk_recovery() { "the OVK-recovered memo must decode back to the original text" ); } + +#[test] +fn should_restore_tip_notes_without_exposing_personal_notes_to_tip_viewing_key() { + use crate::wallet::shielded::shielded_tip_account_index; + let seed = [0x67; 64]; + let tip_index = shielded_tip_account_index(0).unwrap(); + let tips = OrchardKeySet::from_seed(&seed, Network::Testnet, tip_index).unwrap(); + let restored = OrchardKeySet::from_seed(&seed, Network::Testnet, tip_index).unwrap(); + let personal = OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + // Rotation is just another address of the dedicated account. Both remain + // discoverable without a saved diversifier index or a current profile. + for recipient in [tips.default_address, tips.address_at(17)] { + let wire = make_own_ovk_wire_note( + recipient, + tips.outgoing_viewing_key.clone(), + 123_456, + [0; 36], + ); + assert!(try_decrypt_note_with_memo(&restored.prepared_ivk(), &wire).is_some()); + assert!(try_decrypt_note_with_memo(&personal.prepared_ivk(), &wire).is_none()); + } + let personal_wire = make_own_ovk_wire_note( + personal.default_address, + personal.outgoing_viewing_key.clone(), + 456_789, + [0; 36], + ); + assert!(try_decrypt_note_with_memo(&tips.prepared_ivk(), &personal_wire).is_none()); + assert!(try_recover_outgoing_note(&tips.outgoing_viewing_key, &personal_wire).is_none()); +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs new file mode 100644 index 00000000000..b699b2efd53 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -0,0 +1,317 @@ +//! Dedicated DashPay tip accounts. Account selection is wallet policy, not +//! consensus: external Orchard addresses remain valid profile values. +//! +//! Reserve the upper half of the ZIP-32 account space for tips. A wallet-owned +//! identity at index i uses account 0x40000000 + i. Ordinary accounts use the +//! lower half. This mapping never depends on a username, the current profile, +//! or local allocation history: identity discovery followed by shielded bind +//! reconstructs it even after publication was removed. Address rotation uses +//! another diversifier in the same account, so all old addresses remain covered. + +use super::NetworkShieldedCoordinator; +use crate::wallet::platform_wallet::PlatformWallet; +use crate::{PlatformWalletError, ShieldedTipRecipient}; +use dpp::prelude::Identifier; +use std::sync::Arc; + +pub const SHIELDED_TIP_ACCOUNT_BASE: u32 = 0x4000_0000; + +pub fn shielded_tip_account_index(identity_index: u32) -> Result { + if identity_index >= SHIELDED_TIP_ACCOUNT_BASE { + return Err(PlatformWalletError::ShieldedKeyDerivation( + "Identity index exceeds the dedicated tip account range".to_string(), + )); + } + Ok(SHIELDED_TIP_ACCOUNT_BASE + identity_index) +} + +pub fn is_shielded_tip_account(account: u32) -> bool { + (SHIELDED_TIP_ACCOUNT_BASE..0x8000_0000).contains(&account) +} + +/// Prove `identity_index` with the seed: the identity must carry the MASTER +/// authentication key this wallet derives at that index (the key discovery and +/// registration both use). Fails closed when no key matches, including when +/// no public keys were restored. +fn verify_identity_index( + seed: &[u8], + network: key_wallet::Network, + identity_index: u32, + identity: &dpp::identity::Identity, +) -> Result<(), PlatformWalletError> { + use crate::wallet::identity::network::{ + derive_identity_auth_key_hash_from_master, MASTER_KEY_INDEX, + }; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::methods::hash::IdentityPublicKeyHashMethodsV0; + + let master = key_wallet::bip32::ExtendedPrivKey::new_master(network, seed) + .map_err(|e| PlatformWalletError::ShieldedKeyDerivation(e.to_string()))?; + let expected = derive_identity_auth_key_hash_from_master( + &master, + network, + identity_index, + MASTER_KEY_INDEX, + )?; + let verified = identity + .public_keys() + .values() + .any(|key| key.public_key_hash().ok() == Some(expected)); + if verified { + Ok(()) + } else { + Err(PlatformWalletError::InvalidIdentityData(format!( + "Identity index {identity_index} is not verified for this wallet; \ + rediscover the identity before using its tip account" + ))) + } +} + +impl PlatformWallet { + pub(crate) async fn discovered_tip_accounts(&self) -> Result, PlatformWalletError> { + let wm = self.wallet_manager.read().await; + let info = wm + .get_wallet_info(&self.wallet_id()) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())))?; + // An identity outside this convention can still use ordinary accounts + // or publish an external address; it must not block wallet-wide sync. + Ok(info + .identity_manager + .managed_identities() + .filter(|identity| identity.wallet_id == Some(self.wallet_id())) + .filter_map(|identity| identity.identity_index) + .filter_map(|index| shielded_tip_account_index(index).ok()) + .collect()) + } + + /// Prepare a dedicated receiving account without publishing anything. Full + /// bind persists its viewing key and registers it with the coordinator before + /// callers can publish the returned address. Repeated calls are idempotent. + /// Requires an existing shielded bind so preparing a tip account cannot + /// silently replace the host's ordinary account configuration. + pub async fn prepare_shielded_tip_address( + &self, + seed: &[u8], + identity_id: &Identifier, + coordinator: &Arc, + ) -> Result<[u8; 43], PlatformWalletError> { + // Do not publish a key from a mis-associated mnemonic. A first bind + // has no persisted FVK against which to detect a wrong seed. + let root = key_wallet::wallet::root_extended_keys::RootExtendedPrivKey::new_master(seed) + .map_err(|e| PlatformWalletError::ShieldedKeyDerivation(e.to_string()))?; + let public = root.to_root_extended_pub_key(); + drop(root); + let scoped_id = key_wallet::Wallet::compute_wallet_id_from_root_extended_pub_key( + &public, + Some(self.sdk.network), + ); + let legacy_id = + key_wallet::Wallet::compute_wallet_id_from_root_extended_pub_key(&public, None); + if self.wallet_id() != scoped_id && self.wallet_id() != legacy_id { + return Err(PlatformWalletError::ShieldedKeyDerivation( + "The supplied seed does not belong to this wallet".to_string(), + )); + } + let account = { + let wm = self.wallet_manager.read().await; + let info = wm.get_wallet_info(&self.wallet_id()).ok_or_else(|| { + PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())) + })?; + let identity = info + .identity_manager + .managed_identity(identity_id) + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + if identity.wallet_id != Some(self.wallet_id()) { + return Err(PlatformWalletError::InvalidIdentityData( + "Tip account requires a wallet-owned identity".to_string(), + )); + } + let index = identity.identity_index.ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "Tip account requires a recoverable identity index".to_string(), + ) + })?; + // A restored index is metadata, and hosts that cannot represent + // "unknown" have restored a placeholder 0 for wallet-attached + // identities. Publishing then would hand out identity 0's tip + // address, so require the seed to reproduce this identity's + // MASTER key at the claimed index before allocating its account. + verify_identity_index(seed, self.sdk.network, index, &identity.identity)?; + shielded_tip_account_index(index)? + }; + // Read the bound set and bind the augmented copy as one step: a bind + // replaces the registration, so another bind landing in between + // would have its ordinary accounts dropped by this stale snapshot. + let _config = self.shielded_config_lock.lock().await; + let mut accounts = self.shielded_account_indices().await; + if accounts.is_empty() { + return Err(PlatformWalletError::ShieldedNotBound); + } + #[cfg(test)] + test_hooks::after_snapshot(self).await; + accounts.push(account); + self.bind_shielded_locked(seed, &accounts, coordinator) + .await?; + self.persister() + .flush() + .map_err(|e| PlatformWalletError::Persistence(e.to_string()))?; + self.shielded_default_address(account) + .await + .ok_or(PlatformWalletError::ShieldedNotBound) + } + + /// Refuse to spend from a dedicated tip account whose slot holds an identity + /// the seed does not prove to be at that index. Hosts select the source + /// account from the identity's recorded index, and a host-restored + /// placeholder index 0 would otherwise spend identity 0's tip pool on + /// another identity's behalf. A tip account whose slot is empty (a retired + /// identity's) has no such ambiguity and stays spendable. + async fn verify_tip_account_owner( + &self, + seed: &[u8], + account: u32, + ) -> Result<(), PlatformWalletError> { + let index = account - SHIELDED_TIP_ACCOUNT_BASE; + let wm = self.wallet_manager.read().await; + let info = wm + .get_wallet_info(&self.wallet_id()) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())))?; + let Some(owner) = info + .identity_manager + .wallet_identities + .get(&self.wallet_id()) + .and_then(|bucket| bucket.get(&index)) + else { + return Ok(()); + }; + verify_identity_index(seed, self.sdk.network, index, &owner.identity) + } + + /// Send only to the identity/address pair that the user confirmed. A changed + /// name owner or profile requires a new confirmation; there is no fallback to + /// a transparent rail. Network changes after this check cannot change the + /// destination, which remains the explicitly confirmed raw address. + #[allow(clippy::too_many_arguments)] + pub async fn send_shielded_tip( + &self, + coordinator: &Arc, + seed: &[u8], + account: u32, + username: &str, + expected_recipient: &ShieldedTipRecipient, + amount: u64, + memo: [u8; 36], + prover: P, + ) -> Result<(), PlatformWalletError> { + if is_shielded_tip_account(account) { + self.verify_tip_account_owner(seed, account).await?; + } + let current = self + .identity() + .dashpay() + .resolve_shielded_tip(username) + .await?; + if current != *expected_recipient { + return Err(PlatformWalletError::InvalidIdentityData( + "The tip recipient changed; review and confirm the payment again".to_string(), + )); + } + self.shielded_transfer_to( + coordinator, + seed, + account, + ¤t.address, + amount, + memo, + prover, + ) + .await + } +} + +/// Test-only pause point between tip preparation's account snapshot and +/// its bind, keyed by wallet instance (shared by its clones) so parallel +/// tests built from the same mnemonic do not interfere. +#[cfg(test)] +pub(crate) mod test_hooks { + use super::PlatformWallet; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + use tokio::sync::oneshot; + + type Hook = (oneshot::Sender<()>, oneshot::Receiver<()>); + static AFTER_SNAPSHOT: Mutex>> = Mutex::new(None); + + fn key(wallet: &PlatformWallet) -> usize { + Arc::as_ptr(&wallet.shielded_config_lock) as usize + } + + /// Arm the pause for `wallet`. Returns a receiver that fires when + /// preparation reaches the pause, and the sender that resumes it. + pub(crate) fn pause_after_snapshot( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = oneshot::channel(); + AFTER_SNAPSHOT + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(key(wallet), (reached_tx, resume_rx)); + (reached_rx, resume_tx) + } + + pub(crate) async fn after_snapshot(wallet: &PlatformWallet) { + let hook = AFTER_SNAPSHOT + .lock() + .unwrap() + .as_mut() + .and_then(|hooks| hooks.remove(&key(wallet))); + if let Some((reached, resume)) = hook { + let _ = reached.send(()); + let _ = resume.await; + } + } +} + +#[cfg(test)] +mod tests { + use super::super::OrchardKeySet; + use super::*; + use key_wallet::Network; + + #[test] + fn should_derive_distinct_recoverable_tip_accounts() { + let seed = [42u8; 64]; + let ordinary = OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + let index = shielded_tip_account_index(0).unwrap(); + let tip = OrchardKeySet::from_seed(&seed, Network::Testnet, index).unwrap(); + let restored = OrchardKeySet::from_seed( + &seed, + Network::Testnet, + shielded_tip_account_index(0).unwrap(), + ) + .unwrap(); + let other = OrchardKeySet::from_seed( + &seed, + Network::Testnet, + shielded_tip_account_index(1).unwrap(), + ) + .unwrap(); + assert_ne!( + ordinary.full_viewing_key.to_bytes(), + tip.full_viewing_key.to_bytes() + ); + assert_ne!( + tip.default_address.to_raw_address_bytes(), + other.default_address.to_raw_address_bytes() + ); + assert_eq!( + tip.full_viewing_key.to_bytes(), + restored.full_viewing_key.to_bytes() + ); + assert!(!is_shielded_tip_account(0)); + assert!(is_shielded_tip_account(index)); + assert!(shielded_tip_account_index(SHIELDED_TIP_ACCOUNT_BASE).is_err()); + } +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 0f2b2cadada..a86d983f594 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -38,6 +38,8 @@ use crate::wallet::shielded::{ #[derive(Default)] struct CapturingPersistence { stored: Mutex>, + durability_events: Mutex>, + fail_flush: std::sync::atomic::AtomicBool, serve: Mutex>>, serve_subwallets: Mutex>, load_calls: Mutex, @@ -112,11 +114,18 @@ impl PlatformWalletPersistence for CapturingPersistence { _wallet_id: WalletId, changeset: PlatformWalletChangeSet, ) -> Result<(), PersistenceError> { + self.durability_events.lock().unwrap().push("store"); self.stored.lock().expect("stored lock").push(changeset); Ok(()) } fn flush(&self, _wallet_id: WalletId) -> Result<(), PersistenceError> { + self.durability_events.lock().unwrap().push("flush"); + if self.fail_flush.load(std::sync::atomic::Ordering::SeqCst) { + return Err(PersistenceError::backend(std::io::Error::other( + "injected flush failure", + ))); + } Ok(()) } @@ -1162,3 +1171,615 @@ async fn fresh_address_and_own_check_follow_the_bound_account() { ); assert_eq!(wallet.is_own_shielded_address(1, &fresh).await, None); } + +/// A profile is not a recovery record. Identity discovery alone must restore +/// the reserved account, even when the owner removed the tip address entirely. +/// The MASTER authentication key this seed derives for `identity_index` on +/// testnet, as an identity public-key map: what discovery and registration +/// leave on a wallet-owned identity, and what tip preparation verifies. +fn seed_master_key( + seed: &[u8], + identity_index: u32, +) -> BTreeMap { + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel}; + use dpp::platform_value::BinaryData; + let master = key_wallet::bip32::ExtendedPrivKey::new_master(Network::Testnet, seed).unwrap(); + let derived = crate::wallet::identity::network::derive_ecdsa_identity_auth_keypair_from_master( + &master, + Network::Testnet, + identity_index, + crate::wallet::identity::network::MASTER_KEY_INDEX, + ) + .unwrap(); + BTreeMap::from([( + 0, + IdentityPublicKey::V0(IdentityPublicKeyV0 { + id: 0, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::MASTER, + contract_bounds: None, + key_type: KeyType::ECDSA_SECP256K1, + read_only: false, + data: BinaryData::new(derived.public_key.to_vec()), + disabled_at: None, + }), + )]) +} + +/// Cold reload of a host that cannot store "index unknown": a wallet-attached +/// identity whose index was lost comes back at placeholder slot 0 while +/// identity 0's tip account (and its funds) is retained and bound. Tip +/// preparation must refuse it instead of handing out identity 0's address, +/// and must accept it once rediscovery proves its real index. +#[tokio::test] +async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified() { + use crate::shielded_tip_account_index; + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(); + let persister = Arc::new(CapturingPersistence::default()); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + persister.clone(), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + // Restored at the host's placeholder 0, but its keys are identity 5's. + let id = Identifier::from([0x55; 32]); + { + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed, 5), + balance: 0, + revision: 0, + }), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir("tips_placeholder_index")); + let identity_zero_tips = shielded_tip_account_index(0).unwrap(); + wallet + .bind_shielded(&seed, &[0, identity_zero_tips], &coordinator) + .await + .unwrap(); + let identity_zero_address = wallet + .shielded_default_address(identity_zero_tips) + .await + .unwrap(); + + let refused = wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await; + assert!( + matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), + "{refused:?}" + ); + // Spending selects the source account from the same recorded index, so + // sending from identity 0's tip account on this identity's behalf is + // refused too, before any network resolution or proving. + let recipient = crate::ShieldedTipRecipient { + identity_id: Identifier::from([0x77; 32]), + address: [0; 43], + }; + let spend = |account: u32| { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + let recipient = recipient.clone(); + async move { + wallet + .send_shielded_tip( + &coordinator, + &seed, + account, + "recipient.dash", + &recipient, + 1_000, + [0; 36], + &super::CachedOrchardProver::new(), + ) + .await + } + }; + let refused_spend = spend(identity_zero_tips).await; + assert!( + matches!(refused_spend, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), + "{refused_spend:?}" + ); + + // Rediscovery proves index 5 and re-slots the identity. + { + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .adopt_into_wallet(&id, wallet.wallet_id(), 5) + .unwrap(); + } + let address = wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + .unwrap(); + assert_ne!(address, identity_zero_address); + assert_eq!( + wallet + .shielded_default_address(shielded_tip_account_index(5).unwrap()) + .await + .unwrap(), + address + ); + // Its own tip account now passes the ownership check (the mock SDK then + // fails the recipient lookup), and identity 0's slot is empty, so that + // retired-style account is no longer attributed to this identity. + let own = spend(shielded_tip_account_index(5).unwrap()).await; + assert!( + !matches!(own, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), + "{own:?}" + ); +} + +#[tokio::test] +async fn should_restore_tip_account_from_identity_discovery_and_register_for_sync() { + use crate::shielded_tip_account_index; + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let id = Identifier::from([0x33; 32]); + let account = shielded_tip_account_index(3).unwrap(); + let mut original = None; + for session in 0..2 { + let persister = Arc::new(CapturingPersistence::default()); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + persister.clone(), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + { + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed, 3), + balance: 0, + revision: 0, + }), + 3, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + { + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: Identifier::from([0x44; 32]), + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }), + crate::SHIELDED_TIP_ACCOUNT_BASE, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir(&format!("tips_restore_{session}"))); + // Fresh database, no viewing keys, no published profile, and caller + // only knows about ordinary account zero. + assert!(!wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + // Upgrading an existing wallet can leave account zero persisted while + // identity discovery introduces a tip account without an FVK. Seedless + // success here would suppress the host's seed fallback and lose scans + // for that identity's tip history. + let ordinary = super::OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + persister.serve_viewing_keys(BTreeMap::from([( + SubwalletId::new(wallet.wallet_id(), 0), + ordinary.full_viewing_key.to_bytes().to_vec(), + )])); + assert!(!wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + assert!(!wallet.is_shielded_bound().await); + assert!(wallet + .prepare_shielded_tip_address(&[0x11; 64], &id, &coordinator) + .await + .is_err()); + assert!(matches!( + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await, + Err(crate::PlatformWalletError::ShieldedNotBound) + )); + assert!(!wallet.is_shielded_bound().await); + assert!(persister.captured_viewing_keys().is_empty()); + assert!(coordinator.registered_subwallets().await.is_empty()); + wallet + .bind_shielded(&seed, &[0], &coordinator) + .await + .unwrap(); + assert!(coordinator + .registered_subwallets() + .await + .contains(&SubwalletId::new(wallet.wallet_id(), account))); + assert!(wallet + .prepare_shielded_tip_address(&[0x11; 64], &id, &coordinator) + .await + .is_err()); + // A queued FVK is insufficient: no publishable address may escape a + // failed durability barrier, even though bind installed keys in memory. + persister.durability_events.lock().unwrap().clear(); + persister + .fail_flush + .store(true, std::sync::atomic::Ordering::SeqCst); + assert!(matches!( + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await, + Err(crate::PlatformWalletError::Persistence(_)) + )); + assert_eq!( + *persister.durability_events.lock().unwrap(), + ["store", "flush"] + ); + assert!(wallet.shielded_default_address(account).await.is_some()); + persister + .fail_flush + .store(false, std::sync::atomic::Ordering::SeqCst); + persister.durability_events.lock().unwrap().clear(); + let address = wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + .unwrap(); + assert!(wallet + .prepare_shielded_tip_address(&seed, &Identifier::from([0x44; 32]), &coordinator) + .await + .is_err()); + assert_eq!( + *persister.durability_events.lock().unwrap(), + ["store", "flush"] + ); + assert_ne!(wallet.shielded_default_address(0).await.unwrap(), address); + assert_eq!( + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + .unwrap(), + address + ); + assert!(persister + .captured_viewing_keys() + .contains_key(&SubwalletId::new(wallet.wallet_id(), account))); + if let Some(first) = original { + assert_eq!(first, address); + } else { + original = Some(address); + } + } +} + +#[tokio::test] +async fn should_rebind_retired_tip_accounts_without_profile_or_identity() { + let seed = [0x42; 64]; + let account = crate::shielded_tip_account_index(7).unwrap(); + let persister = Arc::new(CapturingPersistence::default()); + let wallet = platform_wallet_with(Arc::clone(&persister)).await; + let keys = super::OrchardKeySet::from_seed(&seed, Network::Testnet, account).unwrap(); + let ordinary = super::OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + persister.serve_viewing_keys(BTreeMap::from([ + ( + SubwalletId::new(wallet.wallet_id(), 0), + ordinary.full_viewing_key.to_bytes().to_vec(), + ), + ( + SubwalletId::new(wallet.wallet_id(), account), + keys.full_viewing_key.to_bytes().to_vec(), + ), + ])); + let coordinator = coordinator_at(&temp_dir("retired_tips")); + assert!(wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + assert_eq!( + wallet.shielded_default_address(account).await.unwrap(), + keys.default_address.to_raw_address_bytes() + ); + assert!(coordinator + .registered_subwallets() + .await + .contains(&SubwalletId::new(wallet.wallet_id(), account))); +} + +/// A host rebind passes only ordinary accounts (FFI and host SDKs cap the +/// request at 64 entries); Rust adds every persisted tip account itself. With +/// more than 64 tip accounts on record, a `[0]` request must still bind them +/// all, both seedlessly and from the seed, and the resulting +/// `shielded_account_indices` snapshot exceeds the request cap, which is why +/// hosts must not echo it back as a bind request. +#[tokio::test] +async fn should_bind_more_than_64_persisted_tip_accounts_from_an_ordinary_request() { + let seed = [0x42; 64]; + let tips: Vec = (0..70) + .map(|index| crate::shielded_tip_account_index(index).unwrap()) + .collect(); + for (tag, seeded) in [("many_tips_persisted", false), ("many_tips_seeded", true)] { + let persister = Arc::new(CapturingPersistence::default()); + let wallet = platform_wallet_with(Arc::clone(&persister)).await; + let mut rows = BTreeMap::new(); + for &account in std::iter::once(&0).chain(tips.iter()) { + let keys = + super::OrchardKeySet::from_seed(&seed, wallet.sdk().network, account).unwrap(); + rows.insert( + SubwalletId::new(wallet.wallet_id(), account), + keys.full_viewing_key.to_bytes().to_vec(), + ); + } + persister.serve_viewing_keys(rows); + let coordinator = coordinator_at(&temp_dir(tag)); + if seeded { + wallet + .bind_shielded(&seed, &[0], &coordinator) + .await + .unwrap(); + } else { + assert!(wallet + .bind_shielded_from_persisted(&[0], &coordinator) + .await + .unwrap()); + } + let bound = wallet.shielded_account_indices().await; + assert_eq!(bound.len(), 71, "{tag}"); + assert!( + bound.len() > 64, + "{tag}: the snapshot exceeds the request cap" + ); + let ordinary: Vec = bound + .iter() + .copied() + .filter(|&account| !super::is_shielded_tip_account(account)) + .collect(); + assert_eq!(ordinary, vec![0], "{tag}"); + let registered = coordinator.registered_subwallets().await; + for &account in &tips { + assert!( + registered.contains(&SubwalletId::new(wallet.wallet_id(), account)), + "{tag}: tip account {account} registered for sync" + ); + } + } +} + +/// A wallet bound to account 0 whose identity at index 2 can prepare a tip +/// address, for racing preparation against other account-set writers. +async fn tip_race_fixture( + tag: &str, +) -> ( + PlatformWallet, + [u8; 64], + dpp::prelude::Identifier, + Arc, +) { + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; + let seed = key_wallet::Mnemonic::from_phrase(phrase) + .unwrap() + .to_seed(""); + let (wallet_manager, wallet_id, _, _) = + crate::test_support::mnemonic_wallet_manager(phrase).await; + let generation = wallet_manager + .read() + .await + .get_wallet_info(&wallet_id) + .unwrap() + .generation + .clone(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + Arc::clone(&wallet_manager), + Arc::new(crate::events::PlatformEventManager::new(Vec::new())), + )); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(); + let persister = Arc::new(CapturingPersistence::default()); + let wallet = PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wallet_manager, + generation, + Arc::new(tokio::sync::Notify::new()), + persister.clone(), + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + let id = Identifier::from([0x66; 32]); + { + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id, + public_keys: seed_master_key(&seed, 2), + balance: 0, + revision: 0, + }), + 2, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } + let coordinator = coordinator_at(&temp_dir(tag)); + wallet + .bind_shielded(&seed, &[0], &coordinator) + .await + .unwrap(); + (wallet, seed, id, coordinator) +} + +/// Pause tip preparation right after its account snapshot, run `writer` +/// against the same wallet, and require the writer to wait for preparation. +async fn race_tip_preparation( + wallet: &PlatformWallet, + seed: [u8; 64], + id: dpp::prelude::Identifier, + coordinator: &Arc, + writer: F, +) where + F: FnOnce(PlatformWallet) -> Fut, + Fut: std::future::Future> + Send + 'static, +{ + let (reached, resume) = super::tips::test_hooks::pause_after_snapshot(wallet); + let preparing = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + }) + }; + reached.await.expect("preparation reached its snapshot"); + let mut writing = tokio::spawn(writer(wallet.clone())); + // Unserialized, the writer finishes now and the resumed preparation then + // rebinds its stale {0} plus the tip account, dropping account 1. + let finished_early = + tokio::time::timeout(std::time::Duration::from_millis(500), &mut writing).await; + assert!( + finished_early.is_err(), + "an account-set writer must wait for tip preparation's read-modify-write" + ); + resume.send(()).unwrap(); + preparing.await.unwrap().expect("tip address prepared"); + writing.await.unwrap().expect("account-set writer succeeds"); +} + +/// Tip preparation reads the bound account set and binds it plus the tip +/// account. A bind of ordinary accounts landing between those two steps must +/// not be undone by the stale snapshot: preparation is paused right after its +/// snapshot while another task binds accounts 0 and 1, and account 1 must +/// still be bound and registered once both finish. +#[tokio::test] +async fn should_keep_an_ordinary_account_bound_during_tip_preparation() { + use crate::shielded_tip_account_index; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_bind").await; + let tip = shielded_tip_account_index(2).unwrap(); + let bind_coordinator = Arc::clone(&coordinator); + race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { + wallet + .bind_shielded(&seed, &[0, 1], &bind_coordinator) + .await + }) + .await; + + let bound = wallet.shielded_account_indices().await; + for account in [0, 1, tip] { + assert!( + bound.contains(&account), + "account {account} bound: {bound:?}" + ); + } + let registered = coordinator.registered_subwallets().await; + for account in [0, 1, tip] { + assert!( + registered.contains(&SubwalletId::new(wallet.wallet_id(), account)), + "account {account} registered" + ); + } +} + +/// `shielded_add_account` writes the same account set, so it must not land +/// between preparation's snapshot and its bind either, or that bind replaces +/// the key map without the added account. +#[tokio::test] +async fn should_keep_an_added_account_during_tip_preparation() { + use crate::shielded_tip_account_index; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_add").await; + let tip = shielded_tip_account_index(2).unwrap(); + race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { + wallet.shielded_add_account(&seed, 1).await + }) + .await; + + let bound = wallet.shielded_account_indices().await; + for account in [0, 1, tip] { + assert!( + bound.contains(&account), + "account {account} bound: {bound:?}" + ); + } +} diff --git a/packages/rs-sdk/src/platform/dashpay/mod.rs b/packages/rs-sdk/src/platform/dashpay/mod.rs index 83352890a63..b987c03cf8f 100644 --- a/packages/rs-sdk/src/platform/dashpay/mod.rs +++ b/packages/rs-sdk/src/platform/dashpay/mod.rs @@ -35,7 +35,7 @@ pub use private_contact_request::{ PRIVATE_CONTACT_REQUEST_AUTO_ACCEPT_PROOF_MIN_LEN, PRIVATE_CONTACT_REQUEST_DOCUMENT_TYPE_NAME, PRIVATE_CONTACT_REQUEST_SHIELDED_ADDRESS_LEN, PRIVATE_CONTACT_REQUEST_SIGNING_KEY_TYPES, }; -pub use profile::ProfileFields; +pub use profile::{PaymentAddressUpdate, ProfileFields}; use crate::{Error, Sdk}; use dpp::prelude::Identifier; diff --git a/packages/rs-sdk/src/platform/dashpay/profile.rs b/packages/rs-sdk/src/platform/dashpay/profile.rs index e0469af7f03..f45effe172c 100644 --- a/packages/rs-sdk/src/platform/dashpay/profile.rs +++ b/packages/rs-sdk/src/platform/dashpay/profile.rs @@ -40,8 +40,8 @@ pub(crate) const MAX_PROFILE_OWNERS_PER_QUERY: usize = 100; /// /// `avatar_hash` and `avatar_fingerprint` are computed by the caller from the /// avatar image bytes. An update that changes `avatar_url` must set both hashes -/// with it, and an update sets the two hashes together. A field cannot be -/// cleared. +/// with it, and an update sets the two hashes together. Only the payment +/// addresses can be cleared, through [`PaymentAddressUpdate::Remove`]. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ProfileFields { /// Display name (1 to 25 chars per DIP-15) @@ -54,6 +54,25 @@ pub struct ProfileFields { pub avatar_hash: Option<[u8; 32]>, /// dHash perceptual fingerprint of the avatar image pub avatar_fingerprint: Option<[u8; 8]>, + /// `corePaymentAddress`: version byte and HASH160 + pub core_payment_address: PaymentAddressUpdate, + /// `platformPaymentAddress`: version byte and HASH160 + pub platform_payment_address: PaymentAddressUpdate, + /// `shieldedAddress`: raw 43-byte Orchard address + pub shielded_address: PaymentAddressUpdate, +} + +/// A change to one profile payment address. The default leaves a published +/// address alone, so omitting the field never removes it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum PaymentAddressUpdate { + /// Leave the address as it is + #[default] + Keep, + /// Publish these address bytes + Set(Vec), + /// Remove the published address + Remove, } impl ProfileFields { @@ -78,6 +97,21 @@ impl ProfileFields { Value::Bytes(fingerprint.to_vec()), ); } + for (field, update) in [ + ("corePaymentAddress", self.core_payment_address), + ("platformPaymentAddress", self.platform_payment_address), + ("shieldedAddress", self.shielded_address), + ] { + match update { + PaymentAddressUpdate::Keep => {} + PaymentAddressUpdate::Set(bytes) => { + properties.insert(field.to_string(), Value::Bytes(bytes)); + } + PaymentAddressUpdate::Remove => { + properties.remove(field); + } + } + } properties } } @@ -439,6 +473,71 @@ mod tests { } /// A supplied avatar hash and fingerprint replace the existing ones. + /// Each payment address is kept, replaced or removed on its own, and an + /// update that names none of them keeps all three. + #[test] + fn should_keep_replace_and_remove_payment_addresses_independently() { + let (id, owner) = (Identifier::new([0xD2; 32]), Identifier::new([0x0F; 32])); + let contract = dashpay_contract(); + let original = ProfileFields { + display_name: Some("Alice".into()), + core_payment_address: PaymentAddressUpdate::Set(vec![0; 21]), + platform_payment_address: PaymentAddressUpdate::Set(vec![1; 21]), + shielded_address: PaymentAddressUpdate::Set(vec![2; 43]), + ..Default::default() + } + .overlay(BTreeMap::new()); + let existing = profile_document(id, owner, original.clone(), Some(1)); + + let renamed = ProfileFields { + display_name: Some("Alice II".into()), + ..Default::default() + }; + let renamed = replacement_document(&existing, renamed, &contract).unwrap(); + for field in [ + "corePaymentAddress", + "platformPaymentAddress", + "shieldedAddress", + ] { + assert_eq!( + renamed.properties().get(field).map(Value::to_bytes), + original.get(field).map(Value::to_bytes), + "{field}" + ); + } + + let changed = ProfileFields { + shielded_address: PaymentAddressUpdate::Set(vec![3; 43]), + core_payment_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + let changed = replacement_document(&renamed, changed, &contract).unwrap(); + let merged = changed.properties(); + assert!(!merged.contains_key("corePaymentAddress")); + assert_eq!( + merged.get("platformPaymentAddress").map(Value::to_bytes), + Some(Ok(vec![1; 21])) + ); + assert_eq!( + merged.get("shieldedAddress").map(Value::to_bytes), + Some(Ok(vec![3; 43])) + ); + assert_eq!(text(merged, "displayName"), Some("Alice II")); + } + + /// Removing an address on create just leaves it out. + #[test] + fn should_omit_a_removed_payment_address_on_create() { + let fields = ProfileFields { + display_name: Some("Alice".into()), + shielded_address: PaymentAddressUpdate::Remove, + ..Default::default() + }; + let properties = fields.overlay(BTreeMap::new()); + assert_eq!(properties.len(), 1); + assert_eq!(text(&properties, "displayName"), Some("Alice")); + } + #[test] fn should_replace_the_avatar_when_supplied() { let replaced = ProfileFields { diff --git a/packages/rs-unified-sdk-jni/src/dashpay.rs b/packages/rs-unified-sdk-jni/src/dashpay.rs index b240a4f261a..ae5fabe16de 100644 --- a/packages/rs-unified-sdk-jni/src/dashpay.rs +++ b/packages/rs-unified-sdk-jni/src/dashpay.rs @@ -661,6 +661,12 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DashpayNative_createO avatar_bytes: JByteArray, do_create: jboolean, signer_handle: jlong, + core_action: jint, + core_address: JByteArray, + platform_action: jint, + platform_address: JByteArray, + shielded_action: jint, + shielded_address: JByteArray, ) -> jstring { guard(&mut env, ptr::null_mut(), |env| { let Some(id) = read_id32(env, &identity_id, "identityId") else { @@ -691,9 +697,34 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DashpayNative_createO } }; + let address_bytes = [&core_address, &platform_address, &shielded_address] + .into_iter() + .map(|address| { + if address.is_null() { + Ok(Vec::new()) + } else { + env.convert_byte_array(address) + } + }) + .collect::, _>>(); + let address_bytes = match address_bytes { + Ok(bytes) => bytes, + Err(_) => { + crate::support::throw_sdk_exception(env, 1, "Unreadable payment address"); + return ptr::null_mut(); + } + }; + let actions = [core_action, platform_action, shielded_action]; + let updates: [_; 3] = std::array::from_fn(|index| { + platform_wallet_ffi::dashpay_profile::PaymentAddressUpdateFFI { + action: actions[index] as u32, + bytes: address_bytes[index].as_ptr(), + len: address_bytes[index].len(), + } + }); let mut profile = DashPayProfileFFI::empty(); let result = unsafe { - platform_wallet_ffi::platform_wallet_create_or_update_dashpay_profile_with_signer( + platform_wallet_ffi::platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( wallet_handle as Handle, id.as_ptr(), display.as_ref().map_or(ptr::null(), |c| c.as_ptr()), @@ -701,6 +732,9 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_DashpayNative_createO url.as_ref().map_or(ptr::null(), |c| c.as_ptr()), avatar.as_ref().map_or(ptr::null(), |v| v.as_ptr()), avatar.as_ref().map_or(0, |v| v.len()), + &updates[0], + &updates[1], + &updates[2], do_create != 0, signer_handle as *mut SignerHandle, &mut profile as *mut DashPayProfileFFI, diff --git a/packages/rs-unified-sdk-jni/src/funding.rs b/packages/rs-unified-sdk-jni/src/funding.rs index 1c7bff45acc..4aa6cdf3a50 100644 --- a/packages/rs-unified-sdk-jni/src/funding.rs +++ b/packages/rs-unified-sdk-jni/src/funding.rs @@ -1259,3 +1259,155 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_shielde let _ = take_pwffi_error(env, result); }) } + +/// Dedicated tip account preparation; returns the complete raw Orchard address. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_prepareShieldedTipAddress( + mut env: JNIEnv, + _class: JClass, + manager: jlong, + wallet_id: JByteArray, + resolver: jlong, + identity_id: JByteArray, +) -> jni::sys::jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + let Some(wid) = read_id32(env, &wallet_id, "walletId") else { + return ptr::null_mut(); + }; + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return ptr::null_mut(); + }; + let mut address = [0; 43]; + let result = unsafe { + platform_wallet_ffi::platform_wallet_manager_prepare_shielded_tip_address( + manager as Handle, + wid.as_ptr(), + resolver as *mut MnemonicResolverHandle, + id.as_ptr(), + address.as_mut_ptr(), + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + env.byte_array_from_slice(&address) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Current verified recipient: 32-byte identity ID followed by 43-byte address. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_resolveShieldedTip( + mut env: JNIEnv, + _class: JClass, + wallet: jlong, + username: JString, +) -> jni::sys::jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + let username = match read_cstring_opt(env, &username, "username") { + Ok(Some(name)) => name, + _ => { + throw_sdk_exception(env, 1, "username is required"); + return ptr::null_mut(); + } + }; + let mut recipient = [0; 75]; + let result = unsafe { + platform_wallet_ffi::platform_wallet_resolve_shielded_tip( + wallet as Handle, + username.as_ptr(), + recipient.as_mut_ptr(), + recipient.as_mut_ptr().add(32), + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + env.byte_array_from_slice(&recipient) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + +/// Revalidates the confirmed recipient before spending. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShieldedTip( + mut env: JNIEnv, + _class: JClass, + manager: jlong, + wallet_id: JByteArray, + resolver: jlong, + account: jint, + username: JString, + expected_id: JByteArray, + expected_address: JByteArray, + amount: jlong, + memo: JString, +) { + guard(&mut env, (), |env| { + if account < 0 || amount <= 0 { + throw_sdk_exception(env, 1, "Invalid account or amount"); + return; + } + let Some(wid) = read_id32(env, &wallet_id, "walletId") else { + return; + }; + let Some(id) = read_id32(env, &expected_id, "expectedIdentityId") else { + return; + }; + let Some(address) = read_recipient43(env, &expected_address) else { + return; + }; + let username = match read_cstring_opt(env, &username, "username") { + Ok(Some(name)) => name, + _ => { + throw_sdk_exception(env, 1, "username is required"); + return; + } + }; + let memo = match read_cstring_opt(env, &memo, "memo") { + Ok(value) => value, + Err(()) => return, + }; + let result = unsafe { + platform_wallet_ffi::platform_wallet_manager_send_shielded_tip( + manager as Handle, + wid.as_ptr(), + resolver as *mut MnemonicResolverHandle, + account as u32, + username.as_ptr(), + id.as_ptr(), + address.as_ptr(), + amount as u64, + memo.as_ref().map_or(ptr::null(), |m| m.as_ptr()), + ) + }; + let _ = take_pwffi_error(env, result); + }) +} + +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_tipAccountIndex( + mut env: JNIEnv, + _class: JClass, + identity_index: jint, +) -> jint { + guard(&mut env, -1, |env| { + if identity_index < 0 { + throw_sdk_exception(env, 1, "identity index must be non-negative"); + return -1; + } + let mut account = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_shielded_tip_account_index( + identity_index as u32, + &mut account, + ) + }; + if take_pwffi_error(env, result) { + return -1; + } + account as jint + }) +} diff --git a/packages/rs-unified-sdk-jni/src/persistence.rs b/packages/rs-unified-sdk-jni/src/persistence.rs index 86a38c3329e..84b4ebac257 100644 --- a/packages/rs-unified-sdk-jni/src/persistence.rs +++ b/packages/rs-unified-sdk-jni/src/persistence.rs @@ -1739,13 +1739,28 @@ unsafe fn persist_identity_upsert( let public_message = cstr_opt(env, e.dashpay_profile_public_message)?; let avatar_hash = env.byte_array_from_slice(&e.dashpay_profile_avatar_hash)?; let avatar_fp = env.byte_array_from_slice(&e.dashpay_profile_avatar_fingerprint)?; + let core_payment_address = if e.dashpay_profile_core_payment_address_present { + JObject::from(env.byte_array_from_slice(&e.dashpay_profile_core_payment_address)?) + } else { + JObject::null() + }; + let platform_payment_address = if e.dashpay_profile_platform_payment_address_present { + JObject::from(env.byte_array_from_slice(&e.dashpay_profile_platform_payment_address)?) + } else { + JObject::null() + }; + let shielded_address = if e.dashpay_profile_shielded_address_present { + JObject::from(env.byte_array_from_slice(&e.dashpay_profile_shielded_address)?) + } else { + JObject::null() + }; let code = env .call_method( bridge, "onPersistIdentityUpsert", "([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;\ - Ljava/lang/String;[BZ[BZLjava/lang/String;)I", + Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I", &[ wid.into(), (&identity_id).into(), @@ -1767,6 +1782,9 @@ unsafe fn persist_identity_upsert( (&avatar_fp).into(), JValue::Bool(e.dashpay_profile_avatar_fingerprint_present as u8), (&public_message).into(), + (&core_payment_address).into(), + (&platform_payment_address).into(), + (&shielded_address).into(), ], )? .i()?; @@ -1790,11 +1808,26 @@ unsafe fn persist_identity_upsert( let public_message = cstr_opt(env, row.public_message)?; let avatar_hash = env.byte_array_from_slice(&row.avatar_hash)?; let avatar_fp = env.byte_array_from_slice(&row.avatar_fingerprint)?; + let core_payment_address = if row.core_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.core_payment_address)?) + } else { + JObject::null() + }; + let platform_payment_address = if row.platform_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.platform_payment_address)?) + } else { + JObject::null() + }; + let shielded_address = if row.shielded_address_present { + JObject::from(env.byte_array_from_slice(&row.shielded_address)?) + } else { + JObject::null() + }; env.call_method( bridge, "onPersistContactProfileDelta", "([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;\ - [BZ[BZLjava/lang/String;J)I", + [BZ[BZLjava/lang/String;J[B[B[B)I", &[ wid.into(), (&identity_id).into(), @@ -1809,6 +1842,9 @@ unsafe fn persist_identity_upsert( JValue::Bool(row.avatar_fingerprint_present as u8), (&public_message).into(), JValue::Long(row.checked_at_ms as i64), + (&core_payment_address).into(), + (&platform_payment_address).into(), + (&shielded_address).into(), ], )? .i() @@ -2667,6 +2703,7 @@ struct IdentityRestoreStaged { ignored_senders: Vec<[u8; 32]>, payments: Vec, contact_profiles: Vec, + dashpay_profile: Option, } /// Staged DashPay payment-history row: FFI struct with `txid` / `memo` @@ -2695,6 +2732,21 @@ struct ContactProfileRestoreStaged { public_message: Option, } +fn seal_profile(profile: ContactProfileRestoreStaged) -> ContactProfileRestoreEntryFFI { + let ContactProfileRestoreStaged { + mut row, + display_name, + bio, + avatar_url, + public_message, + } = profile; + row.display_name = opt_cstring_into_raw(display_name); + row.bio = opt_cstring_into_raw(bio); + row.avatar_url = opt_cstring_into_raw(avatar_url); + row.public_message = opt_cstring_into_raw(public_message); + row +} + /// Staged DashPay contact-restore row: FFI struct with every pointer /// field still null / 0 until sealed, plus the owned buffers that back /// them. Mirrors the Swift `buildIdentityRestoreBuffer` contact block: @@ -2888,6 +2940,7 @@ fn seal_wallet_entries(staged: Vec) -> Vec = keys .into_iter() @@ -2960,26 +3013,12 @@ fn seal_wallet_entries(staged: Vec) -> Vec = - contact_profiles - .into_iter() - .map( - |ContactProfileRestoreStaged { - mut row, - display_name, - bio, - avatar_url, - public_message, - }| { - row.display_name = opt_cstring_into_raw(display_name); - row.bio = opt_cstring_into_raw(bio); - row.avatar_url = opt_cstring_into_raw(avatar_url); - row.public_message = - opt_cstring_into_raw(public_message); - row - }, - ) - .collect(); + contact_profiles.into_iter().map(seal_profile).collect(); (entry.contact_profiles, entry.contact_profiles_count) = vec_into_raw(contact_profiles); entry @@ -3845,6 +3884,18 @@ fn build_identity_restore( contact_profiles.push(cp); } + let owned_profile = env + .get_field( + holder, + "dashpayProfile", + "Lorg/dashfoundation/dashsdk/ffi/ContactProfileRestoreData;", + )? + .l()?; + let dashpay_profile = if owned_profile.is_null() { + None + } else { + Some(build_contact_profile_restore(env, &owned_profile)?) + }; let entry = IdentityRestoreEntryFFI { identity_id, balance, @@ -3865,6 +3916,7 @@ fn build_identity_restore( ignored_senders_count: 0, contact_profiles: ptr::null(), contact_profiles_count: 0, + dashpay_profile: ptr::null(), }; Ok(IdentityRestoreStaged { entry, @@ -3873,6 +3925,7 @@ fn build_identity_restore( ignored_senders, payments, contact_profiles, + dashpay_profile, }) } @@ -3941,6 +3994,24 @@ fn build_contact_profile_restore( Err(_) => ([0u8; 8], false), }; + let bytes = read_bytes_field_vec(env, holder, "corePaymentAddress")?; + let (core_payment_address, core_payment_address_present) = + match <[u8; 21]>::try_from(bytes.as_slice()) { + Ok(value) => (value, true), + Err(_) => ([0; 21], false), + }; + let bytes = read_bytes_field_vec(env, holder, "platformPaymentAddress")?; + let (platform_payment_address, platform_payment_address_present) = + match <[u8; 21]>::try_from(bytes.as_slice()) { + Ok(value) => (value, true), + Err(_) => ([0; 21], false), + }; + let bytes = read_bytes_field_vec(env, holder, "shieldedAddress")?; + let (shielded_address, shielded_address_present) = match <[u8; 43]>::try_from(bytes.as_slice()) + { + Ok(value) => (value, true), + Err(_) => ([0; 43], false), + }; Ok(ContactProfileRestoreStaged { row: ContactProfileRestoreEntryFFI { contact_id, @@ -3951,6 +4022,12 @@ fn build_contact_profile_restore( avatar_hash_present, avatar_fingerprint, avatar_fingerprint_present, + core_payment_address, + core_payment_address_present, + platform_payment_address, + platform_payment_address_present, + shielded_address, + shielded_address_present, public_message: ptr::null(), checked_at_ms, }, @@ -4307,6 +4384,16 @@ unsafe extern "C" fn tramp_load_wallet_list_free( e.identities_count, )); for ident in idents.iter() { + if !ident.dashpay_profile.is_null() { + let profile = Box::from_raw( + ident.dashpay_profile as *mut ContactProfileRestoreEntryFFI, + ); + free_raw_cstring(profile.display_name); + free_raw_cstring(profile.bio); + free_raw_cstring(profile.avatar_url); + free_raw_cstring(profile.public_message); + } + if !ident.keys.is_null() && ident.keys_count > 0 { let keys: Box<[IdentityKeyRestoreFFI]> = Box::from_raw(std::ptr::slice_from_raw_parts_mut( @@ -5253,13 +5340,13 @@ const BRIDGE_METHOD_TABLE: &[(&str, &str)] = &[ ( "onPersistIdentityUpsert", "([B[BJJZIBZ[B[Ljava/lang/String;[JZLjava/lang/String;Ljava/lang/String;\ - Ljava/lang/String;[BZ[BZLjava/lang/String;)I", + Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I", ), ("onPersistIdentityRemoval", "([B[B)I"), ( "onPersistContactProfileDelta", "([B[B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;\ - [BZ[BZLjava/lang/String;J)I", + [BZ[BZLjava/lang/String;J[B[B[B)I", ), ("onPersistIdentityKeyUpsert", IDENTITY_KEY_UPSERT_DESCRIPTOR), ("onPersistIdentityKeyRemoval", "([B[BI)I"), diff --git a/packages/rs-unified-sdk-jni/src/tokens.rs b/packages/rs-unified-sdk-jni/src/tokens.rs index 438c10a45cf..7616e3be820 100644 --- a/packages/rs-unified-sdk-jni/src/tokens.rs +++ b/packages/rs-unified-sdk-jni/src/tokens.rs @@ -1583,6 +1583,42 @@ pub(crate) fn profile_to_json(profile: &DashPayProfileFFI) -> String { .collect(); fields.push(format!("\"avatarFingerprint\":{}", json_string(&hex))); } + if profile.core_payment_address_is_some { + fields.push(format!( + "\"corePaymentAddress\":{}", + json_string( + &profile + .core_payment_address + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ) + )); + } + if profile.platform_payment_address_is_some { + fields.push(format!( + "\"platformPaymentAddress\":{}", + json_string( + &profile + .platform_payment_address + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ) + )); + } + if profile.shielded_address_is_some { + fields.push(format!( + "\"shieldedAddress\":{}", + json_string( + &profile + .shielded_address + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ) + )); + } format!("{{{}}}", fields.join(",")) } @@ -2082,7 +2118,19 @@ mod tests { profile.avatar_hash[31] = 0x01; profile.avatar_fingerprint_is_some = true; profile.avatar_fingerprint = [0x10, 0x20, 0, 0, 0, 0, 0, 0xFF]; + profile.core_payment_address_is_some = true; + profile.core_payment_address = [1; 21]; + profile.platform_payment_address_is_some = true; + profile.platform_payment_address = [2; 21]; + profile.shielded_address_is_some = true; + profile.shielded_address = [3; 43]; let json = profile_to_json(&profile); + assert!(json.contains(&format!("\"corePaymentAddress\":\"{}\"", "01".repeat(21)))); + assert!(json.contains(&format!( + "\"platformPaymentAddress\":\"{}\"", + "02".repeat(21) + ))); + assert!(json.contains(&format!("\"shieldedAddress\":\"{}\"", "03".repeat(43)))); // 32-byte hash: 0xAB … 0x01 → "ab" prefix, "01" suffix (64 hex chars). assert!(json.contains("\"avatarHash\":\"ab"), "got {json}"); assert!(json.contains("01\""), "hash suffix; got {json}"); diff --git a/packages/swift-sdk/SCHEMA_RELEASES.md b/packages/swift-sdk/SCHEMA_RELEASES.md index bc9c7f29453..7c6213f711a 100644 --- a/packages/swift-sdk/SCHEMA_RELEASES.md +++ b/packages/swift-sdk/SCHEMA_RELEASES.md @@ -4,8 +4,13 @@ SwiftData schemas become supported history when a build reaches App Store distribution. TestFlight uploads capture provenance and a synthetic SQLite fixture, but do not by themselves register a released schema. The accepted frozen V1 remains unchanged. Historical V2 is now reconstructed from `52e8d4ec68f0c772313fa1bbef223fb1eabbf1cc`; all 35 entity hashes and the -model checksum match the observed App Store 9.0.2 database. Active models are -V3. Other intermediate development shapes remain unsupported. +model checksum match the observed App Store 9.0.2 database. App Store schemas +3.0.0 and 4.0.0 are published; `DashSchemaV3` and `DashSchemaV4` are bound to +`DashSchemaSnapshotV3` and `DashSchemaSnapshotV4`. Active models are V5, which +adds the optional asset-lock shielded funding recipient, private contact request +scan positions and private shielded addresses, and the +`PersistentDashpayPaymentAddresses` entity. Published V4 retains its optional +asset-lock operation id. Other intermediate development shapes remain unsupported. The old V2 fixture was generated from September 8 sources containing 13 properties added on August 28, after the August 27 App Store release. The @@ -15,26 +20,23 @@ separate from archive-captured releases. This identifies a matching model source, not the confirmed build commit of Apple's binary. V2 is reserved: automated release capture must not register another shape under that number. -The main migration plan is historical V2 → V3. Accepted V1 has a separate -V1 → V3 plan: V1 already contains the 13 properties missing from historical +The main migration plan is historical V2 → V3 → V4 → V5. Accepted V1 has a separate +V1 → V3 → V4 → V5 plan: V1 already contains the 13 properties missing from historical V2, so a V1 → V2 → V3 chain could discard values. Routing uses model metadata and runs after recovery; a version label alone never selects an unknown beta schema. The former live V2 is accepted only when its complete graph matches -current V3 exactly, entity hashes and checksum alike. That alias therefore -lasts only until the next live-graph change: after it, every store still -labelled `2.0.0` with the former live shape becomes `unsupported-v2` and fails -closed. Check internal devices still carrying that label before the next -shape change and migrate or deliberately reset them then, rather than -discovering them afterwards as failed opens. +the published V3 snapshot exactly, entity hashes and checksum alike; any other +store labelled `2.0.0` is `unsupported-v2` and fails closed. The route decision is logged as `store_migration_route` with the validated `source_version`, `source_checksum` and one of `new-store`, `accepted-v1-to-v3`, `historical-v2-to-v3`, `previous-live-v2-current-shape`, `unsupported-v2`, `published-v3-to-v4`, `published-v4-to-v5`, -`labelled-current-v5`, `ordinary-current-plan` or, from the -bridge, `legacy-v1-bridge-to-v3`. Resolving a frozen schema's identity builds -a temporary store, so it is memoized per process and consulted only where a -label is undecidable without it (`1.0.0`, `2.0.0`); a `3.0.0` label takes the +`labelled-current-v5`, `ordinary-current-plan` or, from the bridge, +`legacy-v1-bridge-to-v3` (each route continues through the registered stages to +the live version). Resolving a frozen schema's identity builds a temporary store, +so it is memoized per process and consulted only where a label is undecidable +without it (`1.0.0`, `2.0.0`); `3.0.0`, `4.0.0` and `5.0.0` labels take the default plan without any probe, and a probe failure on the undecidable labels refuses the open with the probe's own error while leaving the store untouched. @@ -138,9 +140,9 @@ The run failed before upload, so this provenance establishes a tested source layout rather than proof of publication. Regression tests exercise the public factory, data/default preservation, writes, reopen, and failure recovery. -Keep the bridge for installations that skip the V3 app release. When advancing -to V4, bind `DashSchemaV3` to its released snapshot and retain the legacy-to-V3 -step before the normal V3-to-current plan. The bridge must never automatically +Keep the bridge for installations that skip the V3 app release. `DashSchemaV3` +is bound to its released snapshot, and the bridge keeps it as its fixed target +before the normal V3-to-current plan. The bridge must never automatically follow the latest live model graph. The release observer's one-time `bootstrap` only records its observation baseline; it neither runs this migration nor proves V1's App Store provenance. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift index cad4a7bab20..1214428de61 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashLegacyStoreSQLite.swift @@ -215,18 +215,52 @@ enum DashLegacyStoreSQLite { } for (name, table) in before.tables { guard let next = after.tables[name] else { throw Failure.unsupported("Migration removed table \(name)") } - let names = table.columns.keys.sorted() - for name in names { - guard let nextColumn = next.columns[name], nextColumn.declaredType == table.columns[name]?.declaredType else { + // Compare columns by entity name, not ordinal: adding an entity + // renumbers the ones sorted after it, which renames generated + // columns such as `Z13TOKENBALANCES` to `Z14TOKENBALANCES`. + let oldColumns = try ordinalKeyedColumns(table, entities: before.entities) + let newColumns = try ordinalKeyedColumns(next, entities: after.entities) + let keys = oldColumns.keys.sorted() + for key in keys { + guard let nextColumn = newColumns[key], nextColumn.declaredType == oldColumns[key]?.declaredType else { throw Failure.unsupported("Migration removed or converted a column in \(table.actual)") } } - let oldDigest = try rowsDigest(old, table: table, names: names, entities: before.entities) - let newDigest = try rowsDigest(new, table: next, names: names, entities: after.entities) + let oldDigest = try rowsDigest(old, table: table, names: keys.compactMap { oldColumns[$0]?.normalized }, + entities: before.entities) + let newDigest = try rowsDigest(new, table: next, names: keys.compactMap { newColumns[$0]?.normalized }, + entities: after.entities) guard oldDigest == newDigest else { throw Failure.unsupported("Migration changed existing data in \(name)") } } } + /// Re-key a table's columns so the entity ordinal Core Data embeds in a + /// generated column name (`Z`, e.g. a to-many inverse's + /// foreign key) is replaced by the entity's name. Attribute columns are + /// `Z` plus a property name, which cannot start with a digit, so only + /// generated columns match. Used for cross-store comparison only: the + /// persisted recovery evidence keeps `layout`'s keys unchanged so journals + /// written by earlier builds still verify. + private static func ordinalKeyedColumns(_ table: Table, entities: [Int64: String]) throws -> [String: Column] { + var keyed: [String: Column] = [:] + for (name, column) in table.columns { + var key = name + if name.hasPrefix("Z"), !name.hasPrefix("Z_") { + let suffix = name.dropFirst() + let digits = suffix.prefix(while: { $0.isNumber }) + if !digits.isEmpty { + guard let number = Int64(digits), let entity = entities[number] else { + throw Failure.unsupported("Unknown entity ordinal in column \(table.actual)") + } + key = "Z{" + entity + "}" + suffix.dropFirst(digits.count) + } + } + guard keyed[key] == nil else { throw Failure.unsupported("Ambiguous Core Data column name") } + keyed[key] = column + } + return keyed + } + private static func layout(_ connection: Connection) throws -> Layout { var entities: [Int64: String] = [:] try connection.query("SELECT Z_ENT, Z_NAME FROM Z_PRIMARYKEY") { diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift index d41f20aba2a..985f4cb7656 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/DashModelContainer.swift @@ -96,7 +96,8 @@ public enum DashModelContainer { PersistentTrackedMasternode.self, PersistentIdentityBalanceMetadata.self, PersistentPrivateContactRequestsPosition.self, - PersistentPrivateShieldedAddress.self + PersistentPrivateShieldedAddress.self, + PersistentDashpayPaymentAddresses.self ] } @@ -399,6 +400,8 @@ public enum DashSchemaV4: VersionedSchema { /// Current schema: an asset lock records the optional Orchard recipient of its /// shielded funding, and the private contact request sync keeps its scan state /// (each identity's read position and its private contacts' shielded addresses). +/// DashPay payment addresses are stored in their own entity, leaving the +/// published profile entities unchanged. public enum DashSchemaV5: VersionedSchema { public static var versionIdentifier: Schema.Version { Schema.Version(5, 0, 0) } public static var models: [any PersistentModel.Type] { DashModelContainer.modelTypes } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift index 3106c69cc04..5bbbf4173b3 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayContactProfile.swift @@ -11,7 +11,7 @@ import SwiftData /// without re-fetching on every launch. The cache is /// relationship-independent — it serves established contacts, pending /// incoming-request senders, and (later) ignored senders from one table, -/// matching the Rust map. It holds **only the five public profile +/// matching the Rust map. It holds **only the public profile /// fields** parsed from the on-chain `profile` document; it must never /// receive anything derived from the encrypted `contactInfo` path. /// @@ -176,3 +176,16 @@ extension PersistentDashpayContactProfile { } } } + +// Address metadata is stored separately so released profile/identity relationships +// retain their SwiftData schema identity across upgrades. +extension PersistentDashpayContactProfile { + private var paymentAddresses: PersistentDashpayPaymentAddresses? { + guard let modelContext else { return nil } + return try? PersistentDashpayPaymentAddresses.fetch(in: modelContext, networkRaw: networkRaw, + ownerIdentityId: ownerIdentityId, profileIdentityId: contactIdentityId) + } + public var corePaymentAddress: Data? { paymentAddresses?.corePaymentAddress } + public var platformPaymentAddress: Data? { paymentAddresses?.platformPaymentAddress } + public var shieldedAddress: Data? { paymentAddresses?.shieldedAddress } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift new file mode 100644 index 00000000000..3bf115ecba2 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift @@ -0,0 +1,63 @@ +import Foundation +import SwiftData + +/// Raw payment addresses for an owned or cached contact profile. Keeping this +/// metadata independent preserves the released profile/identity relationship schema. +@Model +public final class PersistentDashpayPaymentAddresses { + #Unique([\.networkRaw, \.ownerIdentityId, \.profileIdentityId]) + + public var networkRaw: UInt32 + public var ownerIdentityId: Data + public var profileIdentityId: Data + public var corePaymentAddress: Data? + public var platformPaymentAddress: Data? + public var shieldedAddress: Data? + + public init(networkRaw: UInt32, ownerIdentityId: Data, profileIdentityId: Data, + corePaymentAddress: Data? = nil, platformPaymentAddress: Data? = nil, + shieldedAddress: Data? = nil) { + self.networkRaw = networkRaw + self.ownerIdentityId = ownerIdentityId + self.profileIdentityId = profileIdentityId + self.corePaymentAddress = corePaymentAddress + self.platformPaymentAddress = platformPaymentAddress + self.shieldedAddress = shieldedAddress + } + + static func fetch(in context: ModelContext, networkRaw: UInt32, + ownerIdentityId: Data, profileIdentityId: Data, fetcher: any ModelFetching = LiveModelFetcher()) throws -> PersistentDashpayPaymentAddresses? { + let query = FetchDescriptor(predicate: #Predicate { + $0.networkRaw == networkRaw && $0.ownerIdentityId == ownerIdentityId && $0.profileIdentityId == profileIdentityId + }) + return try fetcher.fetch(query, in: context).first + } + + /// Called within the persister's transaction; empty metadata removes the row. + static func replace(in context: ModelContext, networkRaw: UInt32, + ownerIdentityId: Data, profileIdentityId: Data, + core: Data?, platform: Data?, shielded: Data?, + fetcher: any ModelFetching = LiveModelFetcher()) throws { + let existing = try fetch(in: context, networkRaw: networkRaw, + ownerIdentityId: ownerIdentityId, profileIdentityId: profileIdentityId, fetcher: fetcher) + if core == nil && platform == nil && shielded == nil { + if let existing { context.delete(existing) } + return + } + let row = existing ?? PersistentDashpayPaymentAddresses(networkRaw: networkRaw, + ownerIdentityId: ownerIdentityId, profileIdentityId: profileIdentityId) + row.corePaymentAddress = core + row.platformPaymentAddress = platform + row.shieldedAddress = shielded + if existing == nil { context.insert(row) } + } + + /// Delete every address row an identity owns (its own profile's and its + /// cached contacts'). Rows are keyed by id, not by relationship, so any + /// path that deletes an identity outside the persistence handler must call this. + public static func removeOwned(in context: ModelContext, networkRaw: UInt32, ownerIdentityId: Data) throws { + try context.delete(model: PersistentDashpayPaymentAddresses.self, where: #Predicate { + $0.networkRaw == networkRaw && $0.ownerIdentityId == ownerIdentityId + }) + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift index 3e6eb2dd126..f0cdf470a70 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayProfile.swift @@ -128,3 +128,16 @@ extension PersistentDashpayProfile { } } } + +// Address metadata is stored separately so released profile/identity relationships +// retain their SwiftData schema identity across upgrades. +extension PersistentDashpayProfile { + private var paymentAddresses: PersistentDashpayPaymentAddresses? { + guard let modelContext else { return nil } + return try? PersistentDashpayPaymentAddresses.fetch(in: modelContext, networkRaw: networkRaw, + ownerIdentityId: identity.identityId, profileIdentityId: identity.identityId) + } + public var corePaymentAddress: Data? { paymentAddresses?.corePaymentAddress } + public var platformPaymentAddress: Data? { paymentAddresses?.platformPaymentAddress } + public var shieldedAddress: Data? { paymentAddresses?.shieldedAddress } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift index df7543d756c..cb86445cd1c 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift @@ -466,6 +466,10 @@ extension PersistentIdentity { identityId: Data ) -> Bool { guard let row = fetch(in: context, identityId: identityId) else { return false } + // Payment-address rows reference their owner by id only, so no + // relationship cascade reaches them. + try? PersistentDashpayPaymentAddresses.removeOwned( + in: context, networkRaw: row.networkRaw, ownerIdentityId: identityId) context.delete(row) return true } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift index e7208cbe53b..5b9f17eb610 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DashPayProfile.swift @@ -26,19 +26,33 @@ public struct DashPayProfile: Sendable, Equatable { /// Perceptual dHash (8 bytes / 64 bits) of the avatar. Present /// whenever the on-chain document carried an `avatarFingerprint`. public let avatarFingerprint: Data? + /// Core address storage encoding: type byte followed by HASH160 (21 bytes). + public let corePaymentAddress: Data? + /// Platform address storage encoding: type byte followed by HASH160 (21 bytes). + public let platformPaymentAddress: Data? + /// Complete raw Orchard address: diversifier (11 bytes) and public key (32 bytes). + public let shieldedAddress: Data? + public init( displayName: String? = nil, publicMessage: String? = nil, avatarUrl: String? = nil, avatarHash: Data? = nil, - avatarFingerprint: Data? = nil + avatarFingerprint: Data? = nil, + corePaymentAddress: Data? = nil, + platformPaymentAddress: Data? = nil, + shieldedAddress: Data? = nil ) { self.displayName = displayName self.publicMessage = publicMessage self.avatarUrl = avatarUrl self.avatarHash = avatarHash self.avatarFingerprint = avatarFingerprint + self.corePaymentAddress = corePaymentAddress + self.platformPaymentAddress = platformPaymentAddress + self.shieldedAddress = shieldedAddress + } /// Copy a `DashPayProfileFFI` into a Swift-owned value. The @@ -55,12 +69,16 @@ public struct DashPayProfile: Sendable, Equatable { self.avatarFingerprint = ffi.avatar_fingerprint_is_some ? Data(fromTuple8: ffi.avatar_fingerprint) : nil + self.corePaymentAddress = ffi.core_payment_address_is_some ? Swift.withUnsafeBytes(of: ffi.core_payment_address) { Data($0) } : nil + self.platformPaymentAddress = ffi.platform_payment_address_is_some ? Swift.withUnsafeBytes(of: ffi.platform_payment_address) { Data($0) } : nil + self.shieldedAddress = ffi.shielded_address_is_some ? Swift.withUnsafeBytes(of: ffi.shielded_address) { Data($0) } : nil + } } /// Input for `ManagedPlatformWallet.createDashPayProfile` / -/// `updateDashPayProfile`. Every field is optional; fields left as -/// `nil` are simply omitted from the outgoing document. +/// `updateDashPayProfile`. Optional text/avatar fields left as `nil` +/// are omitted. Payment addresses explicitly distinguish keep, set, and remove. /// /// `avatarBytes` is the raw image payload pre-downloaded by the app /// layer. When provided, platform-wallet computes the SHA-256 hash @@ -71,17 +89,28 @@ public struct DashPayProfileUpdate: Sendable { public var publicMessage: String? public var avatarUrl: String? public var avatarBytes: Data? + public var corePaymentAddress: DashPayPaymentAddressUpdate + public var platformPaymentAddress: DashPayPaymentAddressUpdate + public var shieldedAddress: DashPayPaymentAddressUpdate + public init( displayName: String? = nil, publicMessage: String? = nil, avatarUrl: String? = nil, - avatarBytes: Data? = nil + avatarBytes: Data? = nil, + corePaymentAddress: DashPayPaymentAddressUpdate = .keep, + platformPaymentAddress: DashPayPaymentAddressUpdate = .keep, + shieldedAddress: DashPayPaymentAddressUpdate = .keep ) { self.displayName = displayName self.publicMessage = publicMessage self.avatarUrl = avatarUrl self.avatarBytes = avatarBytes + self.corePaymentAddress = corePaymentAddress + self.platformPaymentAddress = platformPaymentAddress + self.shieldedAddress = shieldedAddress + } } @@ -122,3 +151,24 @@ private extension Data { self = Swift.withUnsafeBytes(of: &value) { Data($0) } } } + +/// Explicit operation on a payment address property. +public enum DashPayPaymentAddressUpdate: Sendable, Equatable { + case keep + case set(Data) + case remove + + func withFFI(_ body: (UnsafePointer) throws -> T) rethrows -> T { + let action: UInt32 + let data: Data + switch self { + case .keep: action = 0; data = Data() + case .set(let bytes): action = 1; data = bytes + case .remove: action = 2; data = Data() + } + return try data.withUnsafeBytes { bytes in + var value = PaymentAddressUpdateFFI(action: action, bytes: bytes.baseAddress?.assumingMemoryBound(to: UInt8.self), len: UInt(data.count)) + return try withUnsafePointer(to: &value, body) + } + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index e8206d87778..871ba046716 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -3569,37 +3569,19 @@ extension ManagedPlatformWallet { publicMessage, avatarUrl ) { namePtr, msgPtr, urlPtr -> PlatformWalletFFIResult in - let bytes = avatarBytes ?? Data() - if let avatarBytes, !avatarBytes.isEmpty { - return avatarBytes.withUnsafeBytes { rawBuf -> PlatformWalletFFIResult in - let bytesPtr = rawBuf.baseAddress?.assumingMemoryBound(to: UInt8.self) - return platform_wallet_create_or_update_dashpay_profile_with_signer( - handle, - idPtr, - namePtr, - msgPtr, - urlPtr, - bytesPtr, - UInt(avatarBytes.count), - doCreate, - signerHandle, - &outProfile - ) + return update.corePaymentAddress.withFFI { core in + update.platformPaymentAddress.withFFI { platform in + update.shieldedAddress.withFFI { shielded in + (avatarBytes ?? Data()).withUnsafeBytes { bytes in + platform_wallet_create_or_update_dashpay_profile_with_addresses_with_signer( + handle, idPtr, namePtr, msgPtr, urlPtr, + bytes.baseAddress?.assumingMemoryBound(to: UInt8.self), + UInt(bytes.count), core, platform, shielded, + doCreate, signerHandle, &outProfile + ) + } + } } - } else { - _ = bytes - return platform_wallet_create_or_update_dashpay_profile_with_signer( - handle, - idPtr, - namePtr, - msgPtr, - urlPtr, - nil, - 0, - doCreate, - signerHandle, - &outProfile - ) } } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 5befbfc41ec..75477d7f35c 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -194,6 +194,23 @@ extension PlatformWalletManager { currentShieldedTreeTotal = total } + /// Effective engine account set, including automatically discovered tip accounts. + public func shieldedAccountIndices(walletId: Data) throws -> [UInt32] { + guard isConfigured, handle != NULL_HANDLE, walletId.count == 32 else { + throw PlatformWalletError.invalidParameter("Configured manager and 32-byte walletId required") + } + var indices: UnsafeMutablePointer? + var count: UInt = 0 + try walletId.withUnsafeBytes { bytes in + try platform_wallet_manager_shielded_account_indices( + handle, bytes.bindMemory(to: UInt8.self).baseAddress!, &indices, &count + ).check() + } + defer { platform_wallet_manager_free_shielded_account_indices(indices, count) } + guard let indices else { return [] } + return Array(UnsafeBufferPointer(start: indices, count: Int(count))) + } + /// Bind `walletId`'s multi-account shielded sub-wallet to the /// `PlatformWallet` — from viewing keys the persister already /// holds when possible, deriving from the mnemonic only when it @@ -1672,3 +1689,88 @@ func shieldedTreeProgressCallback( ) } } + +public struct ShieldedTipRecipient: Sendable, Equatable { + public let identityId: Data + public let address: Data +} + +extension ManagedPlatformWallet { + /// Fetch and verify the current DPNS identity and shielded tip address. + public func resolveShieldedTip(username: String) async throws -> ShieldedTipRecipient { + let handle = self.handle + return try await Task.detached(priority: .userInitiated) { + var identityId = [UInt8](repeating: 0, count: 32) + var address = [UInt8](repeating: 0, count: 43) + try username.withCString { + try platform_wallet_resolve_shielded_tip(handle, $0, &identityId, &address).check() + } + return ShieldedTipRecipient(identityId: Data(identityId), address: Data(address)) + }.value + } +} + +extension PlatformWalletManager { + /// Prepare the dedicated tip account. Publication is a separate profile update. + public func prepareShieldedTipAddress(walletId: Data, identityId: Data, resolver: MnemonicResolver) async throws -> Data { + guard walletId.count == 32, identityId.count == 32, let resolverHandle = resolver.handle else { + throw PlatformWalletError.invalidParameter("Expected wallet/identity IDs and mnemonic resolver") + } + let handle = self.handle + return try await Task.detached(priority: .userInitiated) { + try withExtendedLifetime(resolver) { + var address = [UInt8](repeating: 0, count: 43) + try walletId.withUnsafeBytes { wallet in + try identityId.withUnsafeBytes { identity in + try platform_wallet_manager_prepare_shielded_tip_address( + handle, wallet.baseAddress!.assumingMemoryBound(to: UInt8.self), resolverHandle, + identity.baseAddress!.assumingMemoryBound(to: UInt8.self), &address + ).check() + } + } + return Data(address) + } + }.value + } + + /// Recheck the confirmed recipient before building and broadcasting the payment. + public func sendShieldedTip(walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, + username: String, recipient: ShieldedTipRecipient, amount: UInt64) async throws { + guard walletId.count == 32, recipient.identityId.count == 32, recipient.address.count == 43, + let resolverHandle = resolver.handle else { + throw PlatformWalletError.invalidParameter("Invalid shielded tip recipient or wallet") + } + let handle = self.handle + try await Task.detached(priority: .userInitiated) { + try withExtendedLifetime(resolver) { + try walletId.withUnsafeBytes { wallet in + try recipient.identityId.withUnsafeBytes { identity in + try recipient.address.withUnsafeBytes { address in + try username.withCString { name in + try platform_wallet_manager_send_shielded_tip( + handle, wallet.baseAddress!.assumingMemoryBound(to: UInt8.self), resolverHandle, + account, name, identity.baseAddress!.assumingMemoryBound(to: UInt8.self), + address.baseAddress!.assumingMemoryBound(to: UInt8.self), amount, nil + ).check() + } + } + } + } + } + }.value + } +} + +extension PlatformWalletManager { + public static func shieldedTipAccountIndex(identityIndex: UInt32) throws -> UInt32 { + var account: UInt32 = 0 + try platform_wallet_shielded_tip_account_index(identityIndex, &account).check() + return account + } +} + +extension PlatformWalletManager { + public static func isShieldedTipAccount(_ account: UInt32) -> Bool { + platform_wallet_is_shielded_tip_account(account) + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 3a3568ec2f2..f2feca0fbb9 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3728,12 +3728,14 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// were dropped from the Rust side — the former moved to the UI /// layer, the latter is now derived from /// `IdentityManager.highestRegistrationIndex(...)` at read time. + @discardableResult func persistIdentities( walletId: Data, upserts: [IdentityEntrySnapshot], removed: [Data] - ) { + ) -> Bool { onQueue { + do { for entry in upserts { let identityId = entry.identityId let descriptor = FetchDescriptor( @@ -3827,7 +3829,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // shape: a missing snapshot leaves any existing row // intact. if let profile = entry.dashpayProfile { - upsertDashpayProfile(identityRow: row, profile: profile) + try upsertDashpayProfile(identityRow: row, profile: profile) } // Upsert the cached contact-profile rows for this identity. @@ -3839,7 +3841,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // contact simply MISSING from this flush is "no update" (not a // delete). An empty array leaves any existing rows intact. if !entry.contactProfiles.isEmpty { - upsertDashpayContactProfiles( + try upsertDashpayContactProfiles( identityRow: row, profiles: entry.contactProfiles ) @@ -3896,11 +3898,19 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { predicate: #Predicate { $0.identityId == identityId } ) if let existing = try? backgroundContext.fetch(descriptor).first { + try PersistentDashpayPaymentAddresses.removeOwned(in: backgroundContext, + networkRaw: existing.networkRaw, ownerIdentityId: identityId) backgroundContext.delete(existing) } } // No save() — bracketed by changesetBegin/End. + return true + } catch { + SDKLogger.event("persistence_profile_addresses_failed", category: .persistence, + severity: .error, error: error) + return false + } } // onQueue } @@ -4087,7 +4097,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { private func upsertDashpayProfile( identityRow: PersistentIdentity, profile: DashpayProfileSnapshot - ) { + ) throws { if let existing = identityRow.dashpayProfile { // Field-level refresh. Every column is overwritten on // every flush — the FFI snapshot is authoritative for @@ -4102,6 +4112,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { existing.avatarUrl = profile.avatarUrl existing.avatarHash = profile.avatarHash existing.avatarFingerprint = profile.avatarFingerprint + existing.lastUpdated = Date() } else { let row = PersistentDashpayProfile( @@ -4119,6 +4130,10 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // `PersistentIdentity.dashpayProfile`, so we don't need // to assign `identityRow.dashpayProfile = row` here. } + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: identityRow.networkRaw, ownerIdentityId: identityRow.identityId, + profileIdentityId: identityRow.identityId, core: profile.corePaymentAddress, + platform: profile.platformPaymentAddress, shielded: profile.shieldedAddress, fetcher: modelFetcher) } /// Upsert one `PersistentDashpayContactProfile` row per cached @@ -4148,7 +4163,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { private func upsertDashpayContactProfiles( identityRow: PersistentIdentity, profiles: [ContactProfileSnapshot] - ) { + ) throws { let ownerIdentityId = identityRow.identityId for profile in profiles { let contactIdentityId = profile.contactIdentityId @@ -4159,6 +4174,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { ) ) guard profile.isPresent else { + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: identityRow.networkRaw, ownerIdentityId: ownerIdentityId, + profileIdentityId: contactIdentityId, core: nil, platform: nil, shielded: nil, fetcher: modelFetcher) // Confirmed-absent: delete the stale row if one exists; a // never-persisted contact is a no-op. if let existing = try? backgroundContext.fetch(descriptor).first { @@ -4173,6 +4191,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { existing.avatarUrl = profile.avatarUrl existing.avatarHash = profile.avatarHash existing.avatarFingerprint = profile.avatarFingerprint + existing.checkedAtMs = profile.checkedAtMs existing.lastUpdated = Date() } else { @@ -4192,6 +4211,10 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // collection from the `inverse:` declaration on // `PersistentIdentity.contactProfiles`. } + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: identityRow.networkRaw, ownerIdentityId: ownerIdentityId, + profileIdentityId: contactIdentityId, core: profile.corePaymentAddress, + platform: profile.platformPaymentAddress, shielded: profile.shieldedAddress, fetcher: modelFetcher) } } @@ -5481,6 +5504,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// 8-byte DHash perceptual fingerprint. `nil` when the source /// `avatar_fingerprint_present == false`. let avatarFingerprint: Data? + var corePaymentAddress: Data? = nil + var platformPaymentAddress: Data? = nil + var shieldedAddress: Data? = nil /// Wall-clock ms of the last fetch attempt on the Rust side /// (`ContactProfileEntry.checked_at_ms`). let checkedAtMs: UInt64 @@ -5504,6 +5530,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { /// `avatarFingerprint`). `nil` when the source /// `avatar_fingerprint_present == false`. let avatarFingerprint: Data? + var corePaymentAddress: Data? = nil + var platformPaymentAddress: Data? = nil + var shieldedAddress: Data? = nil } /// Swift-side snapshot of `IdentityKeyEntryFFI` — public-key @@ -7057,6 +7086,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // that their problematic cascade children are // gone from the store. for identity in identitiesToDelete { + try PersistentDashpayPaymentAddresses.removeOwned(in: backgroundContext, + networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) backgroundContext.delete(identity) } try backgroundContext.save() @@ -7602,6 +7633,16 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } } + let paymentAddressRows: [PersistentDashpayPaymentAddresses] + do { + paymentAddressRows = try modelFetcher.fetch(FetchDescriptor(), in: backgroundContext) + } catch { + SDKLogger.event("persistence_profile_addresses_load_failed", category: .persistence, + severity: .error, error: error) + return (nil, 0, true) + } + let addressesByOwner = Dictionary(grouping: paymentAddressRows, by: \.ownerIdentityId) + // Allocate `entriesPtr` and the `LoadAllocation` here — past // the fallible SwiftData fetch above — so an early-error path // doesn't leak the entries buffer (LoadAllocation only gets @@ -7756,6 +7797,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } let identitiesBuffer = buildIdentityRestoreBuffer( identities: sortedIdentities, + addressesByOwner: addressesByOwner, allocation: allocation ) @@ -8767,6 +8809,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { private func buildIdentityRestoreBuffer( identities: [PersistentIdentity], + addressesByOwner: [Data: [PersistentDashpayPaymentAddresses]], allocation: LoadAllocation ) -> UnsafeMutablePointer? { if identities.isEmpty { @@ -9099,6 +9142,62 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { // under a wrong key (matching the abort-on-corrupt convention the // UTXO restore uses). Filtering up front also keeps the fixed- // capacity buffer fully initialized so the count stays exact. + let addressRows = (addressesByOwner[identity.identityId] ?? []).filter { $0.networkRaw == identity.networkRaw } + if let profile = identity.dashpayProfile { + let addresses = addressRows.first { $0.profileIdentityId == identity.identityId } + var row = ContactProfileRestoreEntryFFI() + copyBytes(identity.identityId, into: &row.contact_id) + if let displayName = profile.displayName, !displayName.isEmpty { + row.display_name = UnsafePointer( + duplicateCString(displayName, allocation: allocation)) + } + if let bio = profile.bio, !bio.isEmpty { + row.bio = UnsafePointer( + duplicateCString(bio, allocation: allocation)) + } + if let avatarUrl = profile.avatarUrl, !avatarUrl.isEmpty { + row.avatar_url = UnsafePointer( + duplicateCString(avatarUrl, allocation: allocation)) + } + if let publicMessage = profile.publicMessage, !publicMessage.isEmpty { + row.public_message = UnsafePointer( + duplicateCString(publicMessage, allocation: allocation)) + } + // Gate the byte arrays on presence — an absent hash / + // fingerprint must round-trip as `_present == false`, + // not as an all-zero value (which Rust would otherwise + // restore as a real `Some([0u8; N])`). + if let avatarHash = profile.avatarHash, avatarHash.count == 32 { + copyBytes(avatarHash, into: &row.avatar_hash) + row.avatar_hash_present = true + } else { + row.avatar_hash_present = false + } + if let address = addresses?.corePaymentAddress, address.count == 21 { + copyBytes(address, into: &row.core_payment_address) + row.core_payment_address_present = true + } + if let address = addresses?.platformPaymentAddress, address.count == 21 { + copyBytes(address, into: &row.platform_payment_address) + row.platform_payment_address_present = true + } + if let address = addresses?.shieldedAddress, address.count == 43 { + copyBytes(address, into: &row.shielded_address) + row.shielded_address_present = true + } + if let avatarFingerprint = profile.avatarFingerprint, + avatarFingerprint.count == 8 { + copyBytes(avatarFingerprint, into: &row.avatar_fingerprint) + row.avatar_fingerprint_present = true + } else { + row.avatar_fingerprint_present = false + } + let own = UnsafeMutablePointer.allocate(capacity: 1) + own.initialize(to: row) + entry.dashpay_profile = UnsafePointer(own) + allocation.contactProfileArrays.append((own, 1)) + } + let contactProfileRows = identity.contactProfiles.filter { $0.contactIdentityId.count == 32 } @@ -9110,6 +9209,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { capacity: contactProfileRows.count ) for (c, profile) in contactProfileRows.enumerated() { + let addresses = addressRows.first { $0.profileIdentityId == profile.contactIdentityId } var row = ContactProfileRestoreEntryFFI() copyBytes(profile.contactIdentityId, into: &row.contact_id) if let displayName = profile.displayName, !displayName.isEmpty { @@ -9138,6 +9238,18 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } else { row.avatar_hash_present = false } + if let address = addresses?.corePaymentAddress, address.count == 21 { + copyBytes(address, into: &row.core_payment_address) + row.core_payment_address_present = true + } + if let address = addresses?.platformPaymentAddress, address.count == 21 { + copyBytes(address, into: &row.platform_payment_address) + row.platform_payment_address_present = true + } + if let address = addresses?.shieldedAddress, address.count == 43 { + copyBytes(address, into: &row.shielded_address) + row.shielded_address_present = true + } if let avatarFingerprint = profile.avatarFingerprint, avatarFingerprint.count == 8 { copyBytes(avatarFingerprint, into: &row.avatar_fingerprint) @@ -10493,7 +10605,10 @@ private func persistIdentitiesCallback( publicMessage: e.dashpay_profile_public_message.map { String(cString: $0) }, avatarUrl: e.dashpay_profile_avatar_url.map { String(cString: $0) }, avatarHash: avatarHash, - avatarFingerprint: avatarFingerprint + avatarFingerprint: avatarFingerprint, + corePaymentAddress: e.dashpay_profile_core_payment_address_present ? Swift.withUnsafeBytes(of: e.dashpay_profile_core_payment_address) { Data($0) } : nil, + platformPaymentAddress: e.dashpay_profile_platform_payment_address_present ? Swift.withUnsafeBytes(of: e.dashpay_profile_platform_payment_address) { Data($0) } : nil, + shieldedAddress: e.dashpay_profile_shielded_address_present ? Swift.withUnsafeBytes(of: e.dashpay_profile_shielded_address) { Data($0) } : nil ) } else { dashpayProfile = nil @@ -10530,6 +10645,10 @@ private func persistIdentitiesCallback( avatarUrl: row.avatar_url.map { String(cString: $0) }, avatarHash: avatarHash, avatarFingerprint: avatarFingerprint, + corePaymentAddress: row.core_payment_address_present ? Swift.withUnsafeBytes(of: row.core_payment_address) { Data($0) } : nil, + platformPaymentAddress: row.platform_payment_address_present ? Swift.withUnsafeBytes(of: row.platform_payment_address) { Data($0) } : nil, + shieldedAddress: row.shielded_address_present ? Swift.withUnsafeBytes(of: row.shielded_address) { Data($0) } : nil, + checkedAtMs: row.checked_at_ms ) ) @@ -10561,12 +10680,12 @@ private func persistIdentitiesCallback( } } - handler.persistIdentities( + let success = handler.persistIdentities( walletId: walletId, upserts: upserts, removed: removed ) - return 0 + return success ? 0 : 1 } /// C shim for `on_persist_identity_keys_fn`. Same snapshot + cast diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md index 7c467d4c1c8..6ba1071ef44 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md @@ -697,3 +697,30 @@ key that carries no budget or that the identity does not have. - [SwiftExampleApp Integration](../../../SwiftExampleApp/SwiftExampleApp/Services/DashPayService.swift) - Real-world usage example - [Unit Tests](../../../SwiftTests/SwiftDashSDKTests/PlatformWalletTests.swift) - Comprehensive test examples - [Integration Tests](../../../SwiftTests/SwiftDashSDKTests/PlatformWalletIntegrationTests.swift) - Full workflow examples + +### Shielded DashPay tips + +DashPay profiles can publish `shieldedAddress`, a complete 43-byte raw Orchard +address. `DashPayProfileUpdate` uses `.keep`, `.set(Data)`, and `.remove` for +payment address changes; unrelated profile edits preserve the published address. +Wallet-generated tip addresses use a dedicated shielded account for each local +identity. Call `prepareShieldedTipAddress` and then explicitly publish the returned +address through a signed profile update. External receiving addresses may also be +published; their funds are managed and recovered by the external wallet. + +For seed restoration, discover the wallet's identities and call `bindShielded` +again. The next shielded sync automatically scans historical notes for newly +bound tip accounts; no reset is needed. Rust derives the reserved tip accounts +from the recovered identity indices, including accounts whose profile addresses +were subsequently removed. Removing a published address does not revoke copies +already shared or stop monitoring previously received tips. + +To pay a username, call `resolveShieldedTip`, show the returned identity and +address for confirmation, then call `sendShieldedTip` with that recipient. The +send operation verifies fresh resolution still matches the confirmed recipient. +A `shieldedSpendUnconfirmed` error must not be retried automatically: the payment +may already have been accepted. + +The published address is publicly associated with the username. Dedicated +accounts isolate viewing keys and ordinary receiving activity; transfers between +accounts can still introduce correlations. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift new file mode 100644 index 00000000000..8485728a627 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift @@ -0,0 +1,37 @@ +import Foundation + +/// An exact positive DASH amount. Input uses ASCII digits and a period decimal +/// separator, without grouping, signs, or exponent notation. Unsupported locale +/// separators are rejected rather than partially parsed by Foundation. +public struct ShieldedTipAmount: Equatable, Sendable { + public let credits: UInt64 + + public init?(_ input: String) { + let parts = input.split(separator: ".", omittingEmptySubsequences: false) + guard (1...2).contains(parts.count), + !parts[0].isEmpty, + parts.allSatisfy({ !$0.isEmpty && $0.utf8.allSatisfy { (48...57).contains($0) } }), + let whole = UInt64(parts[0]) else { return nil } + let fraction = parts.count == 2 ? String(parts[1]) : "" + // Additional trailing zeros are exact and safe; extra nonzero digits + // would represent a fraction of a credit. + guard fraction.dropFirst(11).allSatisfy({ $0 == "0" }) else { return nil } + let digits = String(fraction.prefix(11)) + let fractionalCredits = UInt64(digits + String(repeating: "0", count: 11 - digits.count))! + let (integralCredits, overflow) = whole.multipliedReportingOverflow(by: 100_000_000_000) + let (credits, additionOverflow) = integralCredits.addingReportingOverflow(fractionalCredits) + guard !overflow, !additionOverflow, credits > 0 else { return nil } + self.credits = credits + } + + /// Canonical confirmation text derived from the exact amount sent. + public var dashString: String { + let whole = credits / 100_000_000_000 + let fraction = credits % 100_000_000_000 + guard fraction != 0 else { return String(whole) } + var digits = String(fraction) + digits = String(repeating: "0", count: 11 - digits.count) + digits + while digits.last == "0" { digits.removeLast() } + return "\(whole).\(digits)" + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift new file mode 100644 index 00000000000..29bec556b03 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift @@ -0,0 +1,32 @@ +import Foundation + +/// Local confirmation history. This is a change warning, never an authorization +/// to pay: `sendShieldedTip` still verifies the confirmed destination on Platform. +public final class ShieldedTipRecipientHistory { + private let defaults: UserDefaults + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + public func hasChanged(network: Network, walletId: Data, username: String, + recipient: ShieldedTipRecipient) -> Bool { + guard let previous = defaults.data(forKey: key(network: network, walletId: walletId, username: username)) else { + return false + } + return previous != recipient.identityId + recipient.address + } + + /// Call only after the user explicitly confirms, including any change warning. + public func confirm(network: Network, walletId: Data, username: String, + recipient: ShieldedTipRecipient) { + defaults.set(recipient.identityId + recipient.address, + forKey: key(network: network, walletId: walletId, username: username)) + } + + private func key(network: Network, walletId: Data, username: String) -> String { + let name = PersistentDPNSName.normalize(username.trimmingCharacters(in: .whitespacesAndNewlines)) + let canonical = name.hasSuffix(".dash") ? name : name + ".dash" + return "dashpay.tipRecipient.\(network.rawValue).\(walletId.toBase58String()).\(canonical)" + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift index d76f2fe1745..61c6b393ed8 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift @@ -185,6 +185,42 @@ class ShieldedService: ObservableObject { // MARK: - Lifecycle + /// The accounts to request when rebinding from a native snapshot: only the + /// ordinary ones, defaulting to `[0]`. The snapshot also lists the dedicated + /// tip accounts Rust binds on its own (discovered and retired ones); echoing + /// them back could exceed the 64-entry bind request cap and stop later + /// discovery from registering new accounts. + static func ordinaryBindRequest(_ snapshot: [UInt32]) -> [UInt32] { + let ordinary = snapshot.filter { !PlatformWalletManager.isShieldedTipAccount($0) } + return ordinary.isEmpty ? [0] : ordinary + } + + /// Re-register newly discovered identity accounts while retaining the engine's + /// existing ordinary accounts. Binding remains independent of discovery success. + @discardableResult + func rebindAfterIdentityDiscovery( + walletManager: PlatformWalletManager, + walletId: Data, + network: Network, + resolver: MnemonicResolver + ) -> Bool { + let existing: [UInt32] + do { + existing = try walletManager.shieldedAccountIndices(walletId: walletId) + } catch { + lastError = error.localizedDescription + return false + } + let accounts = Self.ordinaryBindRequest(existing) + if boundWalletId == walletId || boundWalletId == nil { + bind(walletManager: walletManager, walletId: walletId, network: network, + resolver: resolver, accounts: accounts) + return isBound + } + return bindEngine(walletManager: walletManager, walletId: walletId, network: network, + resolver: resolver, accounts: accounts) + } + /// Bind the service to a wallet. Drives `bindShielded` on the /// Rust side first (resolver-driven mnemonic lookup, ZIP-32 /// derivation per `accounts`, per-network commitment tree @@ -274,15 +310,15 @@ class ShieldedService: ObservableObject { resolver: resolver, accounts: sortedAccounts ) + boundAccounts = try walletManager.shieldedAccountIndices(walletId: walletId) isBound = true lastError = nil - boundAccounts = sortedAccounts // Populate per-account default addresses. Best-effort — // a failure on any one account leaves that entry // missing from `addressesByAccount` (the row in the UI // shows blank) but doesn't unbind the wallet. - for account in sortedAccounts { + for account in boundAccounts { if let raw = try? walletManager.shieldedDefaultAddress( walletId: walletId, account: account @@ -297,7 +333,7 @@ class ShieldedService: ObservableObject { // the existing Receive sheet which only renders one // address. Use account 0 if bound, else the lowest // bound account. - let primary = sortedAccounts.contains(0) ? 0 : (sortedAccounts.first ?? 0) + let primary = boundAccounts.contains(0) ? 0 : (boundAccounts.first ?? 0) orchardDisplayAddress = addressesByAccount[primary] SDKLogger.event( @@ -549,7 +585,7 @@ class ShieldedService: ObservableObject { let resolver, let network else { return } - let accounts = boundAccounts.isEmpty ? [0] : boundAccounts + let accounts = Self.ordinaryBindRequest(boundAccounts) bind( walletManager: walletManager, walletId: walletId, diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift index 4c7bfa7282a..1ecdbf477dd 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift @@ -1153,7 +1153,7 @@ struct WalletRowView: View { /// as `platformBalance` (1e11 credits/DASH), so it folds into /// the same divisor in [`combinedDashAmount(coreTotal:)`]. private var shieldedBalance: UInt64 { - shieldedNotes.reduce(UInt64(0)) { $0 + $1.value } + shieldedNotes.filter { !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) }.reduce(UInt64(0)) { $0 + $1.value } } /// Combined wallet balance expressed in DASH for a precomputed @@ -1535,7 +1535,8 @@ private struct ShieldedNetworkSummaryRows: View { /// Sum of `value` over this network's unspent notes, in credits. private var totalUnspentCredits: UInt64 { allNotes.lazy - .filter { !$0.isSpent && walletIds.contains($0.walletId) } + .filter { !$0.isSpent && walletIds.contains($0.walletId) + && !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) } .reduce(UInt64(0)) { $0 &+ $1.value } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift index a5bca7088c5..b58b6b7a912 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift @@ -530,6 +530,9 @@ struct IdentitiesContentView: View { _ = keychain.deleteKeyData(identifier: payoutIdentifier) } + // Payment-address rows are keyed by owner id; no cascade reaches them. + try? PersistentDashpayPaymentAddresses.removeOwned( + in: modelContext, networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) modelContext.delete(identity) do { try modelContext.save() diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift index de48fdf33bb..c543bc43064 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift @@ -493,7 +493,7 @@ struct SendTransactionView: View { /// send source is correct for a non-`firstWallet` wallet whose /// engine binding is live but whose UI mirror is pointed elsewhere. private var shieldedBalance: UInt64 { - shieldedNotes.reduce(0) { $0 + $1.value } + shieldedNotes.filter { !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) }.reduce(0) { $0 + $1.value } } /// Mirrors `WalletDetailView.platformBalance`: BLAST-synced diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift index 9d99c593782..b740c66c18e 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift @@ -1047,7 +1047,7 @@ struct BalanceCardView: View { /// non-`firstWallet` wallet whose engine binding is live but whose UI /// mirror is pointed elsewhere. private var shieldedBalance: UInt64 { - shieldedNotes.reduce(0) { $0 + $1.value } + shieldedNotes.filter { !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) }.reduce(0) { $0 + $1.value } } /// Core-chain balance summed from one Rust in-memory account snapshot. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift index 15004a1158b..344df016871 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletKeyHealthSheet.swift @@ -418,6 +418,9 @@ enum WalletKeyHealthChecker { for cr in Array(identity.contactRequests) { modelContext.delete(cr) } + // Payment-address rows are keyed by owner id; no cascade reaches them. + try PersistentDashpayPaymentAddresses.removeOwned( + in: modelContext, networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) try modelContext.save() // PHASE 2: delete the identity itself. Its problematic diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift index 8e2f7a06862..53324c0895a 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift @@ -60,6 +60,9 @@ struct SwiftExampleAppApp: App { @StateObject private var platformBalanceSyncService = PlatformBalanceSyncService() @StateObject private var transitionState = TransitionState() @StateObject private var appUIState = AppUIState() + // Shielded tip sends outlive the sheet that starts them (see + // `ShieldedTipSubmissions`), so their state is owned here. + @StateObject private var shieldedTipSubmissions = ShieldedTipSubmissions() /// Current manager exposed to views via the env object pipeline. /// Reads from the published `activeManager` on every body @@ -150,6 +153,7 @@ struct SwiftExampleAppApp: App { .environmentObject(platformBalanceSyncService) .environmentObject(transitionState) .environmentObject(appUIState) + .environmentObject(shieldedTipSubmissions) .environment(\.modelContext, modelContainer.mainContext) .onOpenURL { url in // DashPay invitation deep link: route to the DashPay tab and diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift index 5c5d8974477..7e018e5cee0 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift @@ -1834,7 +1834,7 @@ struct CreateIdentityView: View { /// FetchDescriptor round-trip. private func shieldedPoolBalance(for walletId: Data) -> UInt64 { unspentShieldedNotes - .filter { $0.walletId == walletId } + .filter { $0.walletId == walletId && !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) } .reduce(0) { $0 + $1.value } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift index 9b3dc6e3e8d..eb52dcb01e1 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift @@ -1,6 +1,7 @@ import CoreImage.CIFilterBuiltins import SwiftDashSDK import SwiftUI +import SwiftData /// Read-only DashPay profile sheet, promoted out of /// `IdentityDetailView`'s inline card: large avatar, display name, @@ -19,6 +20,36 @@ struct DashPayProfileView: View { @State private var qrImage: UIImage? @State private var qrURI: String? @State private var qrError: String? + @State private var showSpendTips = false + @Query private var shieldedNotes: [PersistentShieldedNote] + + init(identity: PersistentIdentity, profile: DashPayProfile?, onEdit: @escaping () -> Void) { + self.identity = identity + self.profile = profile + self.onEdit = onEdit + if let walletId = identity.wallet?.walletId { + _shieldedNotes = Query(filter: PersistentShieldedNote.unspentPredicate(walletId: walletId)) + } else { + _shieldedNotes = Query(filter: #Predicate { _ in false }) + } + } + + /// The persisted row uses zero as a historical placeholder. Only Rust's + /// optional derivation metadata can distinguish that from a real index zero. + private var tipAccount: UInt32? { + guard let walletId = identity.wallet?.walletId, + let wallet = walletManager.wallet(for: walletId), + let managed = try? wallet.managedIdentity(identityId: identity.identityId), + let index = try? managed.getIdentityIndex() else { return nil } + return try? PlatformWalletManager.shieldedTipAccountIndex(identityIndex: index) + } + + private var tipBalance: UInt64 { + guard let walletId = identity.wallet?.walletId, + let account = tipAccount else { return 0 } + return shieldedNotes.filter { $0.walletId == walletId && $0.accountIndex == account && !$0.isSpent } + .reduce(UInt64(0)) { $0 &+ $1.value } + } private var displayName: String { if let name = profile?.displayName? @@ -64,6 +95,20 @@ struct DashPayProfileView: View { .listRowBackground(Color.clear) } + Section("Shielded tips") { + if let address = profile?.shieldedAddress, + let display = DashAddress.encodeOrchard(rawBytes: address, network: identity.network) { + Text(display).font(.caption).textSelection(.enabled) + } else { + Text("No tip address published") + } + Text("Dedicated account balance: \(NSDecimalNumber(decimal: Decimal(tipBalance) / 100_000_000_000).stringValue) DASH") + .font(.caption) + Button("Send from dedicated tip account") { showSpendTips = true } + .disabled(tipBalance == 0) + Text("An external receiving address is managed by its own wallet.").font(.caption).foregroundStyle(.secondary) + } + Section("Identity") { Text(identity.identityIdBase58) .font(.caption) @@ -124,6 +169,12 @@ struct DashPayProfileView: View { } } } + .sheet(isPresented: $showSpendTips) { + if let walletId = identity.wallet?.walletId, + let account = tipAccount { + SendShieldedTipSheet(walletId: walletId, account: account, sourceLabel: "dedicated tip account") + } + } .navigationTitle("Your Profile") .navigationBarTitleDisplayMode(.inline) .toolbar { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift index e7855efb305..f58bdcc6b6b 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift @@ -33,6 +33,7 @@ struct DashPayTabView: View { @State private var segment: DashPaySegment = .contacts @State private var showAddContact = false + @State private var showShieldedTip = false @State private var showAddViaQR = false /// Drives the claim sheet via `.sheet(item:)`. A fresh value (new `id`) @@ -162,6 +163,11 @@ struct DashPayTabView: View { content .navigationTitle("DashPay") .toolbar { + ToolbarItem(placement: .navigationBarTrailing) { + Button { showShieldedTip = true } label: { Image(systemName: "gift") } + .accessibilityLabel("Send shielded tip") + .disabled(walletManager.firstWallet == nil) + } ToolbarItem(placement: .navigationBarTrailing) { Button { refresh() @@ -242,6 +248,11 @@ struct DashPayTabView: View { } } } + .sheet(isPresented: $showShieldedTip) { + if let walletId = activeIdentity?.wallet?.walletId ?? walletManager.firstWallet?.walletId { + SendShieldedTipSheet(walletId: walletId) + } + } .sheet(isPresented: $showAddViaQR) { if let identity = activeIdentity { AddViaQRSheet(identity: identity) @@ -818,7 +829,10 @@ struct DashPayTabView: View { publicMessage: persisted.publicMessage, avatarUrl: persisted.avatarUrl, avatarHash: persisted.avatarHash, - avatarFingerprint: persisted.avatarFingerprint + avatarFingerprint: persisted.avatarFingerprint, + corePaymentAddress: persisted.corePaymentAddress, + platformPaymentAddress: persisted.platformPaymentAddress, + shieldedAddress: persisted.shieldedAddress ) } } @@ -1019,3 +1033,136 @@ private struct AddViaQRSheet: View { } } } + +/// Resolve first, then explicitly confirm the identity, address, and amount. +/// The send itself is owned by the app-wide `ShieldedTipSubmissions`, so a +/// dismissed or reopened sheet finds the same in-flight or uncertain state +/// instead of a fresh, unlocked one. +struct SendShieldedTipSheet: View { + let walletId: Data + var account: UInt32 = 0 + var sourceLabel: String = "ordinary shielded account" + @EnvironmentObject private var submissions: ShieldedTipSubmissions + @EnvironmentObject private var appState: AppState + + var body: some View { + SendShieldedTipSheetContent( + walletId: walletId, account: account, sourceLabel: sourceLabel, + submission: submissions.forWallet(network: appState.currentNetwork, walletId: walletId)) + } +} + +private struct SendShieldedTipSheetContent: View { + let walletId: Data + let account: UInt32 + let sourceLabel: String + @ObservedObject var submission: ShieldedTipSubmission + @EnvironmentObject private var walletManager: PlatformWalletManager + @EnvironmentObject private var appState: AppState + @Environment(\.dismiss) private var dismiss + @State private var username = "" + @State private var amount = "" + @State private var recipient: ShieldedTipRecipient? + @State private var resolving = false + @State private var error: String? + @State private var showRecipientChanged = false + + private var tipAmount: ShieldedTipAmount? { ShieldedTipAmount(amount) } + private var credits: UInt64? { tipAmount?.credits } + /// Recipient resolution is sheet-local; the send lock is the shared submission. + private var busy: Bool { resolving || submission.busy } + private var submitted: Bool { submission.submitted } + + var body: some View { + NavigationStack { + Form { + TextField("Username", text: $username) + .textInputAutocapitalization(.never).autocorrectionDisabled() + .disabled(busy || submitted) + .onChange(of: username) { _, _ in recipient = nil } + TextField("Amount in DASH", text: $amount).keyboardType(.decimalPad) + .disabled(busy || submitted) + if let recipient, !submitted { + Section("Confirm recipient") { + Text(username) + Text(recipient.identityId.toBase58String()).font(.caption).textSelection(.enabled) + Text(DashAddress.encodeOrchard(rawBytes: recipient.address, network: appState.currentNetwork) ?? "") + .font(.caption2).textSelection(.enabled) + Text("Send \(tipAmount?.dashString ?? "—") DASH from your \(sourceLabel).") + } + } + if let error { Text(error).foregroundStyle(.red) } + switch submission.status { + case .sent: + Text(submission.message ?? "Tip submitted. Check shielded activity for confirmation.") + Button("Send another tip") { + submission.startNewTip() + recipient = nil + amount = "" + } + case .uncertain: + Text(submission.message + ?? "The tip may have been sent. Check shielded activity before sending again.") + .foregroundStyle(.orange) + case .ready, .sending: + if let message = submission.message, error == nil { + Text(message).foregroundStyle(.red) + } + Button(recipient == nil ? "Review recipient" : "Confirm and send tip") { submit() } + .disabled(busy || username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || credits == nil) + } + if busy { ProgressView() } + } + .navigationTitle("Shielded tip") + .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() }.disabled(busy) } } + .interactiveDismissDisabled(busy) + .alert("Tip recipient changed", isPresented: $showRecipientChanged) { + Button("Review new recipient") {} + Button("Cancel", role: .cancel) { recipient = nil } + } message: { + Text("This username now resolves to a different identity or shielded address than your last confirmation. Verify the change with the recipient before sending.") + } + } + } + + private func submit() { + guard let wallet = walletManager.wallet(for: walletId), let credits else { return } + error = nil + let network = appState.currentNetwork + let name = username + if let recipient { + let confirmed = recipient + let manager = walletManager + let account = account + let walletId = walletId + submission.submit { + ShieldedTipRecipientHistory().confirm(network: network, walletId: walletId, + username: name, recipient: confirmed) + do { + try await manager.sendShieldedTip(walletId: walletId, resolver: MnemonicResolver(), + account: account, username: name, recipient: confirmed, amount: credits) + } catch { + // Whatever the outcome, the next attempt re-reviews the recipient. + self.recipient = nil + throw error + } + } + return + } + resolving = true + Task { @MainActor in + defer { resolving = false } + do { + let resolved = try await wallet.resolveShieldedTip(username: name) + if ShieldedTipRecipientHistory().hasChanged(network: network, walletId: walletId, + username: name, recipient: resolved) { + showRecipientChanged = true + } + recipient = resolved + } catch { + self.error = error.localizedDescription + recipient = nil + } + } + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift new file mode 100644 index 00000000000..b4be45f6a91 --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift @@ -0,0 +1,84 @@ +import Foundation +import SwiftDashSDK + +/// Application-owned tip submissions. They outlive the sheet that started +/// them: a dismissed sheet must never imply the native send stopped +/// broadcasting, and reopening from either entry point (the DashPay tab or +/// the profile) has to find the same guard. Mirrors the Kotlin example app's +/// `ShieldedTipSubmissions`. +@MainActor +final class ShieldedTipSubmissions: ObservableObject { + private var wallets: [String: ShieldedTipSubmission] = [:] + + /// One guard per network and wallet, across all of its identities. + func forWallet(network: Network, walletId: Data) -> ShieldedTipSubmission { + let key = "\(network.rawValue):\(walletId.hexString)" + if let existing = wallets[key] { return existing } + let created = ShieldedTipSubmission() + wallets[key] = created + return created + } +} + +/// Main-actor state of one wallet's shielded tip submission. +@MainActor +final class ShieldedTipSubmission: ObservableObject { + enum Status: Equatable { case ready, sending, sent, uncertain } + + @Published private(set) var status: Status = .ready + @Published private(set) var message: String? + + var busy: Bool { status == .sending } + var submitted: Bool { status != .ready } + + /// Locks synchronously, before the task starts, so two UI events cannot + /// submit twice. Returns nil when a submission already holds the lock; the + /// task is returned so tests can await the outcome. + @discardableResult + func submit(_ send: @escaping @MainActor () async throws -> Void) -> Task? { + guard !submitted else { return nil } + status = .sending + message = nil + return Task { @MainActor in + do { + try await send() + status = .sent + message = "Shielded tip sent." + } catch { + if Self.canReviewAfterFailure(error) { + status = .ready + message = error.localizedDescription + } else { + status = .uncertain + message = "The tip may have been sent. Check shielded activity before sending " + + "again. \(error.localizedDescription)" + } + } + } + } + + /// Starting another payment is an explicit action after a confirmed success. + func startNewTip() { + guard status == .sent else { return } + status = .ready + message = nil + } + + /// Only failures known not to have executed a tip permit a fresh review. + /// On the tip path Rust maps selection, build and recipient-check failures + /// to `walletOperation`, and broadcast ambiguity to + /// `shieldedSpendUnconfirmed`; anything unknown, including cancellation, + /// stays locked until shielded activity shows the outcome. + static func canReviewAfterFailure(_ error: Error) -> Bool { + guard let error = error as? PlatformWalletError else { return false } + switch error { + case .nullPointer, .invalidHandle, .invalidParameter, .invalidIdentifier, .invalidNetwork, + .walletOperation, .identityNotFound, .contactNotFound, .utf8Conversion, + .noSelectableInputs, .shieldedBroadcastFailed, .shieldedNoRecordedAnchor, + .shieldedInsufficientBalance: + return true + default: + return false + } + } +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift index 682c3393103..ed860673752 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift @@ -1163,6 +1163,8 @@ struct DashPayProfileEditorView: View { @State private var displayName: String = "" @State private var publicMessage: String = "" @State private var avatarUrl: String = "" + @State private var shieldedTipAddress: String = "" + @EnvironmentObject private var appState: AppState @State private var isSaving = false @State private var errorMessage: String? @@ -1220,6 +1222,22 @@ struct DashPayProfileEditorView: View { .foregroundColor(.secondary) } + Section { + TextField("Shielded receiving address", text: $shieldedTipAddress, axis: .vertical) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .accessibilityIdentifier("dashpay.profile.shieldedAddress") + Button("Use a dedicated tip account") { prepareTipAddress() } + .disabled(isSaving) + if !shieldedTipAddress.isEmpty { + Button("Remove tip address", role: .destructive) { shieldedTipAddress = "" } + } + } header: { + Text("Shielded tips") + } footer: { + Text("This address is public. Use a separate account for tips, or paste an address from another wallet. Save to publish. Removing it does not revoke copies already shared.") + } + if let err = errorMessage { Section { Text(err) @@ -1255,11 +1273,27 @@ struct DashPayProfileEditorView: View { displayName = existing.displayName ?? "" publicMessage = existing.publicMessage ?? "" avatarUrl = existing.avatarUrl ?? "" + shieldedTipAddress = existing.shieldedAddress.flatMap { DashAddress.encodeOrchard(rawBytes: $0, network: appState.currentNetwork) } ?? "" } } } } + private func prepareTipAddress() { + guard let walletId else { errorMessage = "This identity has no local wallet."; return } + isSaving = true + errorMessage = nil + Task { @MainActor in + defer { isSaving = false } + do { + let address = try await walletManager.prepareShieldedTipAddress( + walletId: walletId, identityId: identityId, resolver: MnemonicResolver() + ) + shieldedTipAddress = DashAddress.encodeOrchard(rawBytes: address, network: appState.currentNetwork) ?? "" + } catch { errorMessage = error.localizedDescription } + } + } + /// Submit the create / update transition. /// /// When the user enters an avatar URL, we fetch the image bytes @@ -1311,11 +1345,22 @@ struct DashPayProfileEditorView: View { avatarBytes = nil } + let tipUpdate: DashPayPaymentAddressUpdate + let tipText = shieldedTipAddress.trimmingCharacters(in: .whitespacesAndNewlines) + if tipText.isEmpty { + tipUpdate = existing?.shieldedAddress == nil ? .keep : .remove + } else if case .orchard(let address) = DashAddress.parse(tipText, network: appState.currentNetwork).type { + tipUpdate = address == existing?.shieldedAddress ? .keep : .set(address) + } else { + errorMessage = "Enter a valid shielded address for this network." + return + } let update = DashPayProfileUpdate( displayName: cleanedDisplay.isEmpty ? nil : cleanedDisplay, publicMessage: cleanedMsg.isEmpty ? nil : cleanedMsg, avatarUrl: cleanedUrl.isEmpty ? nil : cleanedUrl, - avatarBytes: avatarBytes + avatarBytes: avatarBytes, + shieldedAddress: tipUpdate ) // Resolve the wallet via the identity's `walletId`; diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift index b30bdecf72c..ead3d72f285 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift @@ -21,6 +21,7 @@ import SwiftData struct SearchWalletsForIdentitiesView: View { @EnvironmentObject var walletManager: PlatformWalletManager @EnvironmentObject var platformState: AppState + @EnvironmentObject private var shieldedService: ShieldedService @Environment(\.dismiss) private var dismiss /// Every persisted wallet, across all networks. Sorted by @@ -60,6 +61,7 @@ struct SearchWalletsForIdentitiesView: View { /// Rendered in full (no truncation) so path-derivation /// failures and similar long messages aren't cut off. let error: String? + var bindingWarning: String? = nil } /// Resolved runtime wallet for the current selection, or `nil` @@ -181,6 +183,9 @@ struct SearchWalletsForIdentitiesView: View { .fontWeight(.semibold) .foregroundColor(finding.foundCount > 0 ? .green : .secondary) } + if let warning = finding.bindingWarning { + Text(warning).font(.caption).foregroundColor(.orange) + } if let err = finding.error { // No `.lineLimit` — identity-derivation errors can // be long (full path + SECP error chain). Let @@ -361,15 +366,19 @@ struct SearchWalletsForIdentitiesView: View { startIndex: nil, // resume from cache gapLimit: nil // Rust default (IDENTITY_GAP_LIMIT) ) + // Newly discovered identities introduce deterministic tip accounts. + // Rebind before scanning so historical tips are included. + let bound = shieldedService.rebindAfterIdentityDiscovery( + walletManager: walletManager, walletId: walletId, + network: platformState.currentNetwork, resolver: MnemonicResolver()) result = WalletFinding( walletId: walletId, label: label, foundCount: found.count, - error: nil + error: nil, + bindingWarning: bound ? nil : "Identities were discovered successfully. Shielded wallet binding could not complete; retry from the Sync tab." ) - // Zero hits → ask Rust for the preview keypairs the - // scan walked so the user can eyeball / copy them. if found.isEmpty { await loadPreviewKeys(on: managed) } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift index d5565d27f42..eabeadd9ed3 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageExplorerView.swift @@ -62,6 +62,13 @@ struct StorageExplorerView: View { ) { DashpayContactProfileStorageListView(network: network) } + modelRow( + "DashPay Payment Addresses", + icon: "qrcode", + type: PersistentDashpayPaymentAddresses.self + ) { + DashpayPaymentAddressesStorageListView(network: network) + } modelRow( "DashPay Payments", icon: "arrow.left.arrow.right.circle", @@ -303,6 +310,7 @@ struct StorageExplorerView: View { directCount(PersistentDashpayProfile.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayContactRequest.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayContactProfile.self, predicate: #Predicate { $0.networkRaw == raw }) + directCount(PersistentDashpayPaymentAddresses.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayPayment.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentDashpayIgnoredSender.self, predicate: #Predicate { $0.networkRaw == raw }) directCount(PersistentPrivateContactRequestsPosition.self, predicate: #Predicate { $0.networkRaw == raw }) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift index fb8ff7e41bb..f38b1a855d6 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageModelListViews.swift @@ -569,6 +569,40 @@ struct DashpayContactProfileStorageListView: View { } } +// MARK: - PersistentDashpayPaymentAddresses + +struct DashpayPaymentAddressesStorageListView: View { + let network: Network + @Query private var records: [PersistentDashpayPaymentAddresses] + + private var filtered: [PersistentDashpayPaymentAddresses] { + records.filter { $0.networkRaw == network.rawValue } + } + + var body: some View { + let visible = filtered + List(visible) { record in + NavigationLink(destination: DashpayPaymentAddressesStorageDetailView(record: record)) { + VStack(alignment: .leading, spacing: 4) { + Text(record.profileIdentityId.toHexString()) + .font(.body).lineLimit(1).truncationMode(.middle) + Text("Owner: \(record.ownerIdentityId.toHexString())") + .font(.caption) + .foregroundColor(.secondary) + .lineLimit(1) + .truncationMode(.middle) + } + } + } + .navigationTitle("Payment Addresses (\(visible.count))") + .overlay { + if visible.isEmpty { + ContentUnavailableView("No Records", systemImage: "qrcode") + } + } + } +} + // MARK: - PersistentDashpayContactRequest /// Storage-explorer list of every DashPay contact-request row. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift index 4b2b4e0a471..f1757fff639 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/StorageRecordDetailViews.swift @@ -414,6 +414,29 @@ struct DashpayContactProfileStorageDetailView: View { } } +// MARK: - PersistentDashpayPaymentAddresses + +struct DashpayPaymentAddressesStorageDetailView: View { + let record: PersistentDashpayPaymentAddresses + + var body: some View { + Form { + Section("Profile") { + FieldRow(label: "Network", value: Network(rawValue: record.networkRaw)?.displayName ?? String(record.networkRaw)) + FieldRow(label: "Owner ID (Hex)", value: hexString(record.ownerIdentityId)) + FieldRow(label: "Profile ID (Hex)", value: hexString(record.profileIdentityId)) + } + Section("Payment Addresses (Hex)") { + FieldRow(label: "Core (21 B)", value: record.corePaymentAddress.map(hexString) ?? "—") + FieldRow(label: "Platform (21 B)", value: record.platformPaymentAddress.map(hexString) ?? "—") + FieldRow(label: "Shielded (43 B)", value: record.shieldedAddress.map(hexString) ?? "—") + } + } + .navigationTitle("Payment Addresses") + .navigationBarTitleDisplayMode(.inline) + } +} + // MARK: - PersistentDashpayPayment /// Detail view for one DashPay payment-history row. Read-only dump diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift new file mode 100644 index 00000000000..4aa64b88362 --- /dev/null +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift @@ -0,0 +1,30 @@ +import XCTest +@testable import SwiftDashSDK +@testable import SwiftExampleApp + +/// A rebind request is built from the native account snapshot, which also +/// lists the tip accounts Rust binds itself. Only ordinary accounts may go +/// back into the request, or more than 64 tip accounts would exceed the bind +/// request cap. +@MainActor +final class ShieldedRebindRequestTests: XCTestCase { + private func tipAccounts(_ count: UInt32) throws -> [UInt32] { + try (0..? + private var opened = false + func wait() async { + if opened { return } + await withCheckedContinuation { continuation = $0 } + } + func open() { + opened = true + continuation?.resume() + continuation = nil + } + } + + @MainActor + private final class Counter { + var sends = 0 + } + + func testInFlightSendRefusesASecondSubmissionAndReopeningFindsTheSameGuard() async { + let submissions = ShieldedTipSubmissions() + let walletId = Data(repeating: 0x31, count: 32) + let gate = Gate() + let counter = Counter() + + let submission = submissions.forWallet(network: .testnet, walletId: walletId) + let task = submission.submit { + counter.sends += 1 + await gate.wait() + } + XCTAssertNotNil(task) + XCTAssertTrue(submission.busy) + + // The sheet was dismissed and reopened: the owner hands back the same + // guard, which is still locked, so the second tap never sends. + let reopened = submissions.forWallet(network: .testnet, walletId: walletId) + XCTAssertTrue(reopened === submission) + XCTAssertNil(reopened.submit { counter.sends += 1 }) + + gate.open() + await task?.value + XCTAssertEqual(counter.sends, 1) + XCTAssertEqual(submission.status, .sent) + XCTAssertTrue(submission.submitted) + + // Another payment needs an explicit action after the confirmed result. + submission.startNewTip() + XCTAssertEqual(submission.status, .ready) + XCTAssertFalse(submission.submitted) + + // Another wallet on the same network has its own guard. + let other = submissions.forWallet(network: .testnet, walletId: Data(repeating: 0x32, count: 32)) + XCTAssertFalse(other === submission) + } + + func testUnconfirmedSpendStaysLockedAcrossReopenAndCannotStartANewTip() async { + let submission = ShieldedTipSubmission() + let task = submission.submit { + throw PlatformWalletError.shieldedSpendUnconfirmed("relay accepted the transition") + } + await task?.value + XCTAssertEqual(submission.status, .uncertain) + XCTAssertTrue(submission.submitted) + XCTAssertTrue(submission.message?.contains("may have been sent") == true) + + // Neither a fresh tap nor "send another" unlocks an uncertain outcome. + XCTAssertNil(submission.submit {}) + submission.startNewTip() + XCTAssertEqual(submission.status, .uncertain) + } + + func testPreflightFailureReturnsToReadyWhileUnknownFailuresLock() async { + let submission = ShieldedTipSubmission() + await submission.submit { + throw PlatformWalletError.walletOperation("insufficient shielded notes") + }?.value + XCTAssertEqual(submission.status, .ready) + XCTAssertEqual( + submission.message, + PlatformWalletError.walletOperation("insufficient shielded notes").localizedDescription) + + struct Unknown: Error {} + await submission.submit { throw Unknown() }?.value + XCTAssertEqual(submission.status, .uncertain) + XCTAssertNil(submission.submit {}) + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift index b07ad5a84f2..84f46da808a 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift @@ -794,6 +794,60 @@ final class DashLegacySchemaMigrationTests: XCTestCase { } } + /// Adding an entity renumbers every entity sorted after it, and Core Data + /// embeds the ordinal in generated column names (`Z13TOKENBALANCES` on the + /// token-balance table becomes `Z14TOKENBALANCES` once V5 adds + /// `PersistentDashpayPaymentAddresses` ahead of `PersistentIdentity`). The + /// validator must follow the entity name, while a dropped or converted + /// column is still rejected. + func testValidatorFollowsEntityRenumberingInGeneratedColumnNames() throws { + let fixture = try XCTUnwrap(Bundle.module.url( + forResource: "dash-v1", withExtension: "store", subdirectory: "Fixtures/SchemaStores")) + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let before = directory.appendingPathComponent("before.store") + try FileManager.default.copyItem(at: fixture, to: before) + + func renumbered(_ name: String, tail: String) throws -> URL { + let url = directory.appendingPathComponent(name) + try FileManager.default.copyItem(at: fixture, to: url) + let connection = try DashLegacyStoreSQLite.Connection(url, writable: true) + var tables: [String] = [] + try connection.query(""" + SELECT m.name FROM sqlite_master m WHERE m.type='table' AND m.name <> 'Z_PRIMARYKEY' + AND EXISTS (SELECT 1 FROM pragma_table_info(m.name) WHERE name='Z_ENT') + """) { tables.append(String(cString: sqlite3_column_text($0, 0))) } + var sql = """ + BEGIN; + UPDATE Z_PRIMARYKEY SET Z_ENT = Z_ENT + 1000 WHERE Z_ENT >= 8; + UPDATE Z_PRIMARYKEY SET Z_ENT = Z_ENT - 999 WHERE Z_ENT >= 1000; + INSERT INTO Z_PRIMARYKEY (Z_ENT, Z_NAME, Z_SUPER, Z_MAX) + VALUES (8, 'PersistentDashpayPaymentAddresses', 0, 0); + ALTER TABLE Z_1INVOLVEDTRANSACTIONS RENAME COLUMN Z_31INVOLVEDTRANSACTIONS TO Z_32INVOLVEDTRANSACTIONS; + """ + for table in tables { sql += "UPDATE \(table) SET Z_ENT = Z_ENT + 1 WHERE Z_ENT >= 8;\n" } + sql += tail + "\nCOMMIT;" + try connection.execute(sql) + return url + } + + XCTAssertNoThrow(try DashLegacyStoreSQLite.validatePreservation(from: before, to: try renumbered( + "renamed.store", + tail: "ALTER TABLE ZPERSISTENTTOKENBALANCE RENAME COLUMN Z13TOKENBALANCES TO Z14TOKENBALANCES;"))) + let dropIndex = "DROP INDEX IF EXISTS ZPERSISTENTTOKENBALANCE_Z13TOKENBALANCES_INDEX;" + let drop = "ALTER TABLE ZPERSISTENTTOKENBALANCE DROP COLUMN Z13TOKENBALANCES;" + for (name, tail) in [ + ("dropped.store", dropIndex + drop), + ("converted.store", dropIndex + drop + + "ALTER TABLE ZPERSISTENTTOKENBALANCE ADD COLUMN Z14TOKENBALANCES VARCHAR;"), + ] { + XCTAssertThrowsError( + try DashLegacyStoreSQLite.validatePreservation(from: before, to: try renumbered(name, tail: tail)), + name) + } + } + func testValidatorRejectsColumnTypeChangesAndPreservesTypedValues() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift index 94ee9120cf3..11516b20a9c 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift @@ -627,11 +627,32 @@ final class DashModelMigrationTests: XCTestCase { func testV3AddsKeyColumnsWithoutChangingTheFrozenBaseline() throws { let baseline = Schema(versionedSchema: DashSchemaV1.self) let live = Schema(versionedSchema: DashSchemaV3.self) + // V3 is the published snapshot; the live types must still carry the columns. + let current = DashModelContainer.schema let oldKey = try XCTUnwrap(baseline.entities.first { $0.name == "PersistentPublicKey" }) let newKey = try XCTUnwrap(live.entities.first { $0.name == "PersistentPublicKey" }) + let currentKey = try XCTUnwrap(current.entities.first { $0.name == "PersistentPublicKey" }) for column in ["totalBudget", "expiresAt", "contractBoundsKind"] { XCTAssertNil(oldKey.attributesByName[column]) XCTAssertNotNil(newKey.attributesByName[column]) + XCTAssertNotNil(currentKey.attributesByName[column]) + } + } + + func testV5AddsPaymentAddressesAndPrivateContactEntitiesToPublishedV4() throws { + let v4 = Schema(versionedSchema: DashSchemaV4.self) + let current = DashModelContainer.schema + XCTAssertEqual( + Set(current.entities.map(\.name)).subtracting(v4.entities.map(\.name)), + ["PersistentDashpayPaymentAddresses", "PersistentPrivateContactRequestsPosition", + "PersistentPrivateShieldedAddress"]) + XCTAssertEqual(Set(v4.entities.map(\.name)).subtracting(current.entities.map(\.name)), []) + for name in ["PersistentDashpayProfile", "PersistentDashpayContactProfile"] { + let published = try XCTUnwrap(v4.entities.first { $0.name == name }) + let live = try XCTUnwrap(current.entities.first { $0.name == name }) + XCTAssertEqual( + live.attributesByName.keys.sorted(), published.attributesByName.keys.sorted(), + "\(name): V5 adds no column; addresses live in their own entity") } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index 84e538c521a..a45f29bab22 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -120,14 +120,15 @@ final class DashPayContactPersistenceTests: XCTestCase { /// Apply one identity persister round carrying only the given contact /// profiles for the fixture owner — the seam `upsertDashpayContactProfiles` /// runs under. + @discardableResult private func applyContactProfiles( _ profiles: [PlatformWalletPersistenceHandler.ContactProfileSnapshot] - ) { + ) -> Bool { // Bracket the round like the FFI does: `endChangeset` is the only // atomic `save()`, so a bare `persistIdentities` would stage the writes // without committing them. handler.beginChangeset(walletId: walletId) - handler.persistIdentities( + let success = handler.persistIdentities( walletId: walletId, upserts: [ PlatformWalletPersistenceHandler.IdentityEntrySnapshot( @@ -145,7 +146,102 @@ final class DashPayContactPersistenceTests: XCTestCase { ], removed: [] ) - handler.endChangeset(walletId: walletId, success: true) + return handler.endChangeset(walletId: walletId, success: success) + } + + func testContactPaymentAddressesAreReplacedAndRemovedTogetherWithProfile() throws { + let shielded = Data(repeating: 0x33, count: 43) + applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: true, displayName: "Tips", bio: nil, + publicMessage: nil, avatarUrl: nil, avatarHash: nil, avatarFingerprint: nil, + corePaymentAddress: Data(repeating: 1, count: 21), + platformPaymentAddress: Data(repeating: 2, count: 21), + shieldedAddress: shielded, checkedAtMs: 1)]) + let first = try XCTUnwrap(fetchContactProfileRows().first) + XCTAssertEqual(first.shieldedAddress, shielded) + XCTAssertEqual(first.corePaymentAddress, Data(repeating: 1, count: 21)) + XCTAssertEqual(first.platformPaymentAddress, Data(repeating: 2, count: 21)) + applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: true, displayName: "Tips", bio: nil, + publicMessage: nil, avatarUrl: nil, avatarHash: nil, avatarFingerprint: nil, + checkedAtMs: 2)]) + let replaced = try XCTUnwrap(fetchContactProfileRows().first) + XCTAssertNil(replaced.shieldedAddress) + XCTAssertNil(replaced.corePaymentAddress) + XCTAssertNil(replaced.platformPaymentAddress) + } + + func testPaymentAddressReadFailureRejectsProfilePersistenceRound() throws { + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: PaymentAddressReadFailure()) + let saved = applyContactProfiles([.init(contactIdentityId: contactId, isPresent: true, + displayName: "Must roll back", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43), + checkedAtMs: 1)]) + XCTAssertFalse(saved) + XCTAssertTrue(try fetchContactProfileRows().isEmpty) + } + + func testPaymentAddressReadFailureRejectsWalletRestore() throws { + let context = ModelContext(container) + let wallet = PersistentWallet(walletId: walletId, network: .testnet) + context.insert(wallet) + let account = PersistentAccount(wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + account.accountExtendedPubKeyBytes = Data(repeating: 0xEE, count: 78) + context.insert(account) + try context.save() + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: PaymentAddressReadFailure()) + let (entries, count, errored) = handler.loadWalletList() + XCTAssertTrue(errored) + XCTAssertNil(entries) + XCTAssertEqual(count, 0) + } + + func testOwnedProfilePaymentAddressesSurviveRestoreBuffer() throws { + let context = ModelContext(container) + let wallet = PersistentWallet(walletId: walletId, network: .testnet) + context.insert(wallet) + let account = PersistentAccount(wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + account.accountExtendedPubKeyBytes = Data(repeating: 0xEE, count: 78) + context.insert(account) + let owner = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + owner.wallet = wallet + context.insert(PersistentDashpayProfile(identity: owner, displayName: "Tip recipient")) + try PersistentDashpayPaymentAddresses.replace(in: context, networkRaw: Network.testnet.rawValue, + ownerIdentityId: ownerId, profileIdentityId: ownerId, core: Data(repeating: 1, count: 21), + platform: Data(repeating: 2, count: 21), shielded: Data(repeating: 3, count: 43)) + try context.save() + + let (entries, count, errored) = handler.loadWalletList() + XCTAssertFalse(errored) + XCTAssertEqual(count, 1) + let buffer = try XCTUnwrap(entries) + defer { handler.loadWalletListFree(entries: UnsafeRawPointer(buffer)) } + let restored = try XCTUnwrap(buffer[0].identities?[0].dashpay_profile).pointee + XCTAssertEqual(restored.display_name.map { String(cString: $0) }, "Tip recipient") + XCTAssertTrue(restored.core_payment_address_present) + XCTAssertTrue(restored.platform_payment_address_present) + XCTAssertTrue(restored.shielded_address_present) + XCTAssertEqual(Swift.withUnsafeBytes(of: restored.shielded_address) { Data($0) }, Data(repeating: 3, count: 43)) + } + + func testTipConfirmationHistoryPersistsAndDoesNotOverwriteOnChangeCheck() throws { + let suite = "tip-history-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let original = ShieldedTipRecipient(identityId: ownerId, address: Data(repeating: 3, count: 43)) + let changed = ShieldedTipRecipient(identityId: contactId, address: original.address) + let rotated = ShieldedTipRecipient(identityId: ownerId, address: Data(repeating: 4, count: 43)) + ShieldedTipRecipientHistory(defaults: defaults).confirm(network: .testnet, walletId: walletId, + username: "Alice", recipient: original) + let restored = ShieldedTipRecipientHistory(defaults: defaults) + XCTAssertFalse(restored.hasChanged(network: .testnet, walletId: walletId, username: "a11ce.dash", recipient: original)) + XCTAssertTrue(restored.hasChanged(network: .testnet, walletId: walletId, username: "Alice", recipient: changed)) + XCTAssertTrue(restored.hasChanged(network: .testnet, walletId: walletId, username: "Alice", recipient: rotated)) + XCTAssertFalse(restored.hasChanged(network: .testnet, walletId: walletId, username: "Alice", recipient: original)) + XCTAssertFalse(restored.hasChanged(network: .mainnet, walletId: walletId, username: "Alice", recipient: changed)) + XCTAssertFalse(restored.hasChanged(network: .testnet, walletId: contactId, username: "Alice", recipient: changed)) } // MARK: Contact-profile tombstone delete @@ -1195,3 +1291,11 @@ final class DashPayPaymentFFIMarshallingTests: XCTestCase { XCTAssertEqual(payment.txid, "") } } + +private struct PaymentAddressReadFailure: ModelFetching { + struct ReadError: Error {} + func fetch(_ descriptor: FetchDescriptor, in context: ModelContext) throws -> [T] { + if T.self == PersistentDashpayPaymentAddresses.self { throw ReadError() } + return try context.fetch(descriptor) + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift new file mode 100644 index 00000000000..56598d8dabc --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedAccountSnapshotTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import SwiftDashSDK + +@MainActor +final class ShieldedAccountSnapshotTests: XCTestCase { + /// Identity discovery can precede configureShielded. Reading the current + /// account set must still succeed so the service can perform the first bind. + func testUnconfiguredShieldedWalletReturnsEmptySnapshot() async throws { + let sdk = try SDK(network: .testnet) + let manager = try PlatformWalletManager(sdk: sdk) + do { + let wallet = try await manager.createWallet( + mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + network: .testnet, + createDefaultAccounts: false) + XCTAssertEqual(try manager.shieldedAccountIndices(walletId: wallet.walletId), []) + XCTAssertThrowsError(try manager.shieldedAccountIndices(walletId: Data(repeating: 0x71, count: 32))) + await manager.shutdown() + } catch { + await manager.shutdown() + throw error + } + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift new file mode 100644 index 00000000000..cb9d1374cd4 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift @@ -0,0 +1,24 @@ +import XCTest +@testable import SwiftDashSDK + +final class ShieldedTipAmountTests: XCTestCase { + func testRejectsPartialLocaleAndMalformedAmounts() { + for text in ["1,5", "1abc", "1.5abc", "1,000.5", "1e2", "+1", "-1", " 1", "1 ", "", ".", "1.", ".5", "12", "0", "0.000000000001"] { + XCTAssertNil(ShieldedTipAmount(text), text) + } + } + + func testExactCreditsAndCanonicalConfirmation() throws { + for (input, credits, display) in [("1.5", UInt64(150_000_000_000), "1.5"), + ("001.500000000000", 150_000_000_000, "1.5"), + ("0.00000000001", 1, "0.00000000001"), + ("184467440.73709551615", UInt64.max, "184467440.73709551615")] { + let amount = try XCTUnwrap(ShieldedTipAmount(input)) + XCTAssertEqual(amount.credits, credits) + XCTAssertEqual(amount.dashString, display) + } + XCTAssertNil(ShieldedTipAmount("184467440.73709551616")) + XCTAssertNil(ShieldedTipAmount("184467441")) + XCTAssertNil(ShieldedTipAmount("18446744073709551616")) + } +} diff --git a/packages/swift-sdk/schema-models.json b/packages/swift-sdk/schema-models.json index b7714b9657d..4bb7a6198fd 100644 --- a/packages/swift-sdk/schema-models.json +++ b/packages/swift-sdk/schema-models.json @@ -38,7 +38,8 @@ "PersistentTrackedMasternode": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentTrackedMasternode.swift", "PersistentIdentityBalanceMetadata": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentityBalanceMetadata.swift", "PersistentPrivateContactRequestsPosition": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateContactRequestsPosition.swift", - "PersistentPrivateShieldedAddress": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift" + "PersistentPrivateShieldedAddress": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentPrivateShieldedAddress.swift", + "PersistentDashpayPaymentAddresses": "packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentDashpayPaymentAddresses.swift" }, "value_types": [ { diff --git a/scripts/check-storage-explorer.sh b/scripts/check-storage-explorer.sh index 55e150dc9d3..3f21948187c 100755 --- a/scripts/check-storage-explorer.sh +++ b/scripts/check-storage-explorer.sh @@ -16,13 +16,12 @@ DETAIL_VIEWS="$REPO_ROOT/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/View errors=0 -# Extract model type names from DashModelContainer.modelTypes array. +# Extract model type names from the current schema's model list and its +# shared declarations: modelTypes -> v3ModelTypes -> allModelTypes. # Matches lines like "PersistentFoo.self," and extracts "PersistentFoo". -# Scoped to the body of the `modelTypes` computed property so other -# `.self` references in the file (e.g. `migrationPlan: -# DashMigrationPlan.self` passed to ModelContainer) aren't mistaken -# for SwiftData models. -model_types=$(awk '/var modelTypes/{flag=1} flag{print} flag && /^ \}/{flag=0}' "$CONTAINER" \ +# Scope the scan to these declarations so frozen schema substitutions and +# unrelated references (e.g. DashMigrationPlan.self) aren't treated as models. +model_types=$(awk '/static func allModelTypes\(|static var (v3ModelTypes|modelTypes):/{flag=1} flag{print} flag && /^ \}/{flag=0}' "$CONTAINER" \ | grep -oE '[A-Z][A-Za-z0-9]+\.self' \ | sed 's/\.self//' \ | sort -u) @@ -53,7 +52,7 @@ fi # Check each model type is referenced in the explorer top-level view. echo "=== Checking StorageExplorerView.swift ===" for model in $model_types; do - if ! grep -q "$model" "$EXPLORER"; then + if ! grep -qw "$model" "$EXPLORER"; then echo " MISSING: $model not referenced in StorageExplorerView.swift" errors=$((errors + 1)) else @@ -66,7 +65,7 @@ echo "" # containing @Query of the model type). echo "=== Checking StorageModelListViews.swift ===" for model in $model_types; do - if ! grep -q "$model" "$LIST_VIEWS"; then + if ! grep -qw "$model" "$LIST_VIEWS"; then echo " MISSING: $model has no list view in StorageModelListViews.swift" errors=$((errors + 1)) else @@ -78,7 +77,7 @@ echo "" # Check each model type has a detail view. echo "=== Checking StorageRecordDetailViews.swift ===" for model in $model_types; do - if ! grep -q "$model" "$DETAIL_VIEWS"; then + if ! grep -qw "$model" "$DETAIL_VIEWS"; then echo " MISSING: $model has no detail view in StorageRecordDetailViews.swift" errors=$((errors + 1)) else From a61693c5fd560dba0b5e482ee4c00c0d7aa90c57 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 15 Oct 2026 00:12:30 -0500 Subject: [PATCH 02/41] fix(sdk): drop a cleared owned DashPay profile from the host caches Load now hydrates a wallet identity's cached profile back into Rust, so the Swift and Kotlin adapters' "absent snapshot means no update" reading let a profile deleted on Platform come back on every cold start. For a wallet-owned identity an absent snapshot now deletes the owner profile row (and the Swift payment-address sidecar). Out-of-wallet identities are never hydrated and keep the old behaviour. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWalletPersistenceHandler.kt | 11 ++++-- .../PlatformWalletPersistenceHandlerTest.kt | 29 +++++++++++++++ .../src/identity_persistence.rs | 9 ++--- .../PlatformWalletPersistenceHandler.swift | 33 +++++++++-------- .../DashPayPersistenceTests.swift | 35 +++++++++++++++++++ 5 files changed, 95 insertions(+), 22 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index 0373fd39fcb..cb9ff4b56e3 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -1830,9 +1830,14 @@ class PlatformWalletPersistenceHandler( ) } - // DashPay profile: present == "update the whole document"; - // absent == "no update" (never a delete). - if (dashpayProfilePresent) { + // DashPay profile: present == "update the whole document". + // Absent deletes the row for a wallet-owned identity (the load + // path hydrated it, so absent means Platform has none); for an + // out-of-wallet identity, which is never hydrated, it is "no + // update". Mirrors Swift `persistIdentities`. + if (!dashpayProfilePresent) { + if (identityIndexIsSome) db.dashpayDao().deleteProfilesByIdentity(identityId) + } else { db.dashpayDao().upsertProfile( DashpayProfileEntity( networkRaw = networkRaw, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index 521982befd8..2230bad49d0 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -940,6 +940,35 @@ class PlatformWalletPersistenceHandlerTest { assertNull(profile.avatarFingerprint) } + @Test + fun shouldDeleteOwnedProfileWhenWalletIdentitySnapshotHasNone() = runTest { + // `sync_profiles` clears a profile deleted on Platform; the cached + // row must not be hydrated back on the next cold start. + handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) + handler.onPersistAccountRegistration( + walletId, 0, 0, 0, 0, 0, ByteArray(0), ByteArray(0), ByteArray(78) { 30 }, + ) + val identityId = ByteArray(32) { 13 } + + fun persistSnapshot(profilePresent: Boolean) { + handler.onChangesetBegin(walletId) + handler.onPersistIdentityUpsert( + walletId, identityId, 1, 0, true, 0, 0, true, walletId, + emptyArray(), LongArray(0), profilePresent, "Alice", null, null, + ByteArray(32), false, ByteArray(8), false, null, + dashpayShieldedAddress = if (profilePresent) ByteArray(43) { 3 } else null, + ) + handler.onChangesetEnd(walletId, success = true) + } + + persistSnapshot(profilePresent = true) + assertNotNull(db.dashpayDao().getProfile(testnet, identityId)) + + persistSnapshot(profilePresent = false) + assertNull(db.dashpayDao().getProfile(testnet, identityId)) + assertNull(handler.onLoadWalletList().single().identities.single().dashpayProfile) + } + @Test fun identityDpnsSnapshotRemovesStaleOwnedLabels() = runTest { handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) diff --git a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs index 5d988fb33cd..68bc3ca5e93 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs @@ -98,10 +98,11 @@ pub struct IdentityEntryFFI { pub dpns_names_acquired_at: *const u64, /// `true` iff the underlying [`IdentityEntry::dashpay_profile`] /// is `Some(_)`. When `false`, all `dashpay_profile_*` pointer - /// fields are null and the byte-array fields are zeroed — Swift - /// must skip the profile upsert entirely (changeset semantics: - /// `dashpay_profile: None` means "no update" rather than - /// "delete", matching the merge policy on the Rust side). + /// fields are null and the byte-array fields are zeroed. The + /// snapshot carries the identity's current profile, so for a + /// wallet-owned identity (hydrated on load) `false` means it has + /// none and hosts delete the cached row; an out-of-wallet identity + /// is never hydrated, so hosts leave its row alone. pub dashpay_profile_present: bool, /// Heap-allocated NUL-terminated UTF-8 C string for the DashPay /// profile's display name. `null` when the source field was diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index f2feca0fbb9..dafca55af68 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3816,20 +3816,24 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { names: entry.dpnsNames ) - // Upsert the DashPay profile cache for this identity. + // Sync the DashPay profile cache for this identity. // - // Gated on `entry.dashpayProfile != nil` — a `nil` - // snapshot mirrors the FFI's - // `dashpay_profile_present == false`, which the Rust - // `IdentityChangeSet::merge` policy treats as "no - // update" (NOT delete). DashPay doesn't expose a - // user-driven "delete profile" today; if it ever does, - // the removal must arrive via a separate signal so we - // know it's intentional. Match the dpns-name handling - // shape: a missing snapshot leaves any existing row - // intact. + // The snapshot carries Rust's current profile. For a + // wallet-owned identity (`identityIndex != nil`) the load + // path hydrated this row into Rust, so a `nil` profile is + // authoritative (e.g. `sync_profiles` found it deleted on + // Platform) and the row plus its address sidecar go. + // Out-of-wallet identities are never hydrated, so for them + // `nil` only means "not fetched" and leaves the row intact. if let profile = entry.dashpayProfile { try upsertDashpayProfile(identityRow: row, profile: profile) + } else if entry.identityIndex != nil { + if let existing = row.dashpayProfile { + backgroundContext.delete(existing) + } + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: row.networkRaw, ownerIdentityId: row.identityId, + profileIdentityId: row.identityId, core: nil, platform: nil, shielded: nil, fetcher: modelFetcher) } // Upsert the cached contact-profile rows for this identity. @@ -10581,10 +10585,9 @@ private func persistIdentitiesCallback( // Walk the optional DashPay profile block. The // `dashpay_profile_present` bit is the single source of - // truth: `false` means "no update for this flush" - // (changeset-`None` semantics, NOT a delete signal), so - // we carry `dashpayProfile == nil` through to the - // handler. When the bit is set, every `*_present` + // truth: `false` (no profile) is carried through as + // `dashpayProfile == nil`, and `persistIdentities` decides + // what that means. When the bit is set, every `*_present` // sub-flag is checked individually because zero-valued // payloads (empty strings, all-zero hashes / // fingerprints) are valid contract values and the FFI diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index a45f29bab22..16e60c38c11 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -226,6 +226,41 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertEqual(Swift.withUnsafeBytes(of: restored.shielded_address) { Data($0) }, Data(repeating: 3, count: 43)) } + func testOwnedProfileAbsentFromWalletIdentitySnapshotIsNotRestored() throws { + // `sync_profiles` clears a profile deleted on Platform; the cached + // row must not be hydrated back on the next cold start. + let context = ModelContext(container) + let wallet = PersistentWallet(walletId: walletId, network: .testnet) + context.insert(wallet) + let account = PersistentAccount(wallet: wallet, accountType: 0, accountIndex: 0, accountTypeName: "standard") + account.accountExtendedPubKeyBytes = Data(repeating: 0xEE, count: 78) + context.insert(account) + try context.save() + + func persist(_ profile: PlatformWalletPersistenceHandler.DashpayProfileSnapshot?) { + handler.beginChangeset(walletId: walletId) + let success = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 0, revision: 0, identityIndex: 0, label: nil, status: 0, + walletId: walletId, dpnsNames: [], dashpayProfile: profile, contactProfiles: [])], + removed: []) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: success)) + } + persist(.init(displayName: "Tip recipient", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43))) + XCTAssertEqual(try ModelContext(container).fetchCount(FetchDescriptor()), 1) + persist(nil) + + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + let (entries, count, errored) = handler.loadWalletList() + XCTAssertFalse(errored) + XCTAssertEqual(count, 1) + let buffer = try XCTUnwrap(entries) + defer { handler.loadWalletListFree(entries: UnsafeRawPointer(buffer)) } + XCTAssertNil(try XCTUnwrap(buffer[0].identities)[0].dashpay_profile) + } + func testTipConfirmationHistoryPersistsAndDoesNotOverwriteOnChangeCheck() throws { let suite = "tip-history-" + UUID().uuidString let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) From b0f7c73819f12a6e4ccb9f43c867c01f240b0b60 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 15 Oct 2026 01:06:59 -0500 Subject: [PATCH 03/41] fix(kotlin-sdk): scope a cleared owned profile's deletion to its network Profile rows are keyed by (networkRaw, identityId) and restored by that key, so clearing one network's owned profile must not delete another network's row for the same identity id. Co-Authored-By: Claude Opus 5.5 --- .../persistence/PlatformWalletPersistenceHandler.kt | 2 +- .../dashfoundation/dashsdk/persistence/dao/DashpayDao.kt | 3 +++ .../persistence/PlatformWalletPersistenceHandlerTest.kt | 8 ++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index cb9ff4b56e3..9640be2c81e 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -1836,7 +1836,7 @@ class PlatformWalletPersistenceHandler( // out-of-wallet identity, which is never hydrated, it is "no // update". Mirrors Swift `persistIdentities`. if (!dashpayProfilePresent) { - if (identityIndexIsSome) db.dashpayDao().deleteProfilesByIdentity(identityId) + if (identityIndexIsSome) db.dashpayDao().deleteProfile(networkRaw, identityId) } else { db.dashpayDao().upsertProfile( DashpayProfileEntity( diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt index 1948639fd38..e82b0b059fc 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/DashpayDao.kt @@ -39,6 +39,9 @@ interface DashpayDao { @Query("DELETE FROM dashpay_profiles WHERE identityId = :identityId") suspend fun deleteProfilesByIdentity(identityId: ByteArray) + @Query("DELETE FROM dashpay_profiles WHERE networkRaw = :networkRaw AND identityId = :identityId") + suspend fun deleteProfile(networkRaw: Int, identityId: ByteArray) + @Query("DELETE FROM dashpay_profiles") suspend fun deleteAllProfiles() diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index 2230bad49d0..71508fd8d23 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -963,9 +963,17 @@ class PlatformWalletPersistenceHandlerTest { persistSnapshot(profilePresent = true) assertNotNull(db.dashpayDao().getProfile(testnet, identityId)) + // The same id's row on another network is not this snapshot's to clear. + val otherNetwork = testnet + 1 + db.dashpayDao().upsertProfile( + org.dashfoundation.dashsdk.persistence.entities.DashpayProfileEntity( + networkRaw = otherNetwork, identityId = identityId, + ), + ) persistSnapshot(profilePresent = false) assertNull(db.dashpayDao().getProfile(testnet, identityId)) + assertNotNull(db.dashpayDao().getProfile(otherNetwork, identityId)) assertNull(handler.onLoadWalletList().single().identities.single().dashpayProfile) } From f4bd64714025d43c79ffda63954d34c6763da82c Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 16 Oct 2026 05:06:37 -0500 Subject: [PATCH 04/41] test(wallet-storage): build the V020 profile encoding test into the integration binary v5.1-dev builds the storage integration tests as one binary (#5397); a test file outside tests/integration/ would link the whole dependency graph again as a binary of its own. Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet-storage/tests/integration/main.rs | 1 + .../tests/{ => integration}/sqlite_profile_address_encoding.rs | 0 2 files changed, 1 insertion(+) rename packages/rs-platform-wallet-storage/tests/{ => integration}/sqlite_profile_address_encoding.rs (100%) diff --git a/packages/rs-platform-wallet-storage/tests/integration/main.rs b/packages/rs-platform-wallet-storage/tests/integration/main.rs index 0f0a6c6f051..3a9ee008ccd 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/main.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/main.rs @@ -62,6 +62,7 @@ mod sqlite_open_version_gate; mod sqlite_permissions; mod sqlite_persist_roundtrip; mod sqlite_pool_reader; +mod sqlite_profile_address_encoding; mod sqlite_provider_key_accounts; mod sqlite_qa_identity_removal; mod sqlite_recovery_mode; diff --git a/packages/rs-platform-wallet-storage/tests/sqlite_profile_address_encoding.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs similarity index 100% rename from packages/rs-platform-wallet-storage/tests/sqlite_profile_address_encoding.rs rename to packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs From 7bb25f6d2270beefa672abbc33b4ff9e335c15ad Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 29 Oct 2026 08:53:00 -0500 Subject: [PATCH 05/41] docs(sdk): document payment-address patches on ProfileFields Say what Keep and Remove mean on ProfileFields and that address bytes are sent unchecked, put the avatar test's doc comment back on its test, rename the storage tests that still named V019, and stop the V4 entity test claiming V4 changes no other entity. Co-Authored-By: Claude Opus 5.5 --- .../integration/sqlite_profile_address_encoding.rs | 4 ++-- packages/rs-sdk/src/platform/dashpay/profile.rs | 11 +++++++---- .../SwiftDashSDKTests/DashModelMigrationTests.swift | 2 ++ 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs index 8c049eb348b..453cb04f5a2 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs @@ -85,7 +85,7 @@ fn stored_profile(conn: &Connection) -> DashPayProfile { /// and the new fields round-trip; an insert that omits the stamp is read as /// the current shape. #[test] -fn pre_v019_rows_stay_readable_and_rewrites_restamp() { +fn pre_v020_rows_stay_readable_and_rewrites_restamp() { let id = Identifier::from([1; 32]); let old = entry(id); @@ -239,7 +239,7 @@ fn unknown_stamp_is_rejected_by_the_check_constraint() { /// regenerate the fixture and its decoder in step. Every field holds a /// distinct value, so a positional shift misreads at least one of them. #[test] -fn literal_pre_v019_profile_bytes_decode_positionally() { +fn literal_pre_v020_profile_bytes_decode_positionally() { let mut bytes = vec![0x01, 0x02, b'A', b'l']; // display_name: Some("Al") bytes.extend([0x01, 0x01, b'b']); // bio: Some("b") bytes.push(0x00); // avatar_url: None diff --git a/packages/rs-sdk/src/platform/dashpay/profile.rs b/packages/rs-sdk/src/platform/dashpay/profile.rs index f45effe172c..406cab5c048 100644 --- a/packages/rs-sdk/src/platform/dashpay/profile.rs +++ b/packages/rs-sdk/src/platform/dashpay/profile.rs @@ -35,13 +35,16 @@ const PROFILE_DOCUMENT_TYPE: &str = "profile"; /// cardinality cap, which is also the document-query limit. pub(crate) const MAX_PROFILE_OWNERS_PER_QUERY: usize = 100; -/// The profile fields a caller sets. `None` leaves the field alone on -/// [`Sdk::update_profile`] and omits it on [`Sdk::create_profile`]. +/// The profile fields a caller sets. `None` (or [`PaymentAddressUpdate::Keep`]) +/// leaves the field alone on [`Sdk::update_profile`] and omits it on +/// [`Sdk::create_profile`]. /// /// `avatar_hash` and `avatar_fingerprint` are computed by the caller from the /// avatar image bytes. An update that changes `avatar_url` must set both hashes /// with it, and an update sets the two hashes together. Only the payment -/// addresses can be cleared, through [`PaymentAddressUpdate::Remove`]. +/// addresses can be cleared, through [`PaymentAddressUpdate::Remove`]. Address +/// bytes are sent as given; Platform enforces their length, and decoding them +/// (a transparent address type, an Orchard address) is the caller's check. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ProfileFields { /// Display name (1 to 25 chars per DIP-15) @@ -472,7 +475,6 @@ mod tests { ); } - /// A supplied avatar hash and fingerprint replace the existing ones. /// Each payment address is kept, replaced or removed on its own, and an /// update that names none of them keeps all three. #[test] @@ -538,6 +540,7 @@ mod tests { assert_eq!(text(&properties, "displayName"), Some("Alice")); } + /// A supplied avatar hash and fingerprint replace the existing ones. #[test] fn should_replace_the_avatar_when_supplied() { let replaced = ProfileFields { diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift index 11516b20a9c..0eeac2b1f1f 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashModelMigrationTests.swift @@ -639,6 +639,8 @@ final class DashModelMigrationTests: XCTestCase { } } + /// V5 adds payment-address and private-contact entities. Payment addresses + /// live in their own table, preserving the published V4 profile columns. func testV5AddsPaymentAddressesAndPrivateContactEntitiesToPublishedV4() throws { let v4 = Schema(versionedSchema: DashSchemaV4.self) let current = DashModelContainer.schema From 5d9dc1c489fa8770ca0d17accfe0bdccf07834c0 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 29 Oct 2026 09:49:01 -0500 Subject: [PATCH 06/41] fix(platform-wallet-ffi): contain profile-write panics and hold tip call owners The address-aware profile export ran `block_on_worker`, whose join error panics, straight under its `extern "C"` frame. It now runs under `catch_panic_to_code`, which moves from the shielded send module into `runtime` so builds without the shielded feature can use it. The Swift shielded-tip calls copied only the raw native handle into their detached tasks. `resolveShieldedTip` now keeps its wallet alive for the call, and the manager's prepare and send go through the shutdown admission gate, so teardown cannot destroy a handle a call is using. Co-Authored-By: Claude Opus 5.5 --- .../src/dashpay_profile.rs | 129 ++++++++++-------- .../PlatformWalletManagerShieldedSync.swift | 21 ++- 2 files changed, 84 insertions(+), 66 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs index 5ac265a66c7..230947d30f6 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs @@ -435,65 +435,76 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_a signer_handle: *mut SignerHandle, out_profile: *mut DashPayProfileFFI, ) -> PlatformWalletFFIResult { - check_ptr!(out_profile); - // `DashPayProfileFFI` owns heap C-string pointer fields freed by - // `dashpay_profile_ffi_free`; publish the empty sentinel before any - // fallible work so an error path never leaves uninitialized stack bytes - // in those pointer fields. Matches the read-side helpers in this file. - *out_profile = DashPayProfileFFI::empty(); - check_ptr!(signer_handle); - - let id = unwrap_result_or_return!(read_identifier(identity_id)); - - let display_name = unwrap_result_or_return!(decode_opt_c_str(display_name)); - let public_message = unwrap_result_or_return!(decode_opt_c_str(public_message)); - let avatar_url = unwrap_result_or_return!(decode_opt_c_str(avatar_url)); - - let avatar_bytes_vec: Option> = if avatar_bytes.is_null() || avatar_bytes_len == 0 { - None - } else { - Some(std::slice::from_raw_parts(avatar_bytes, avatar_bytes_len).to_vec()) - }; - - let core_payment_address = - unwrap_result_or_return!(decode_address_update(core_payment_address)); - let platform_payment_address = - unwrap_result_or_return!(decode_address_update(platform_payment_address)); - let shielded_address = unwrap_result_or_return!(decode_address_update(shielded_address)); - - let signer_addr = signer_handle as usize; - - let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, move |wallet| { - let identity = wallet.identity().clone(); - let input = ProfileUpdate { - display_name, - public_message, - avatar_url, - avatar_bytes: avatar_bytes_vec, - core_payment_address, - platform_payment_address, - shielded_address, - }; - - block_on_worker(async move { - let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); - if do_create { - identity - .dashpay() - .create_profile_with_external_signer(&id, input, signer) - .await - } else { - identity - .dashpay() - .update_profile_with_external_signer(&id, input, signer) - .await - } - }) - }); - let result = unwrap_option_or_return!(option); - let profile = unwrap_result_or_return!(result); - *out_profile = DashPayProfileFFI::from_profile(&profile); - PlatformWalletFFIResult::ok() + // The write broadcasts, so a panic past that point leaves its outcome + // unknown; it must not unwind through this `extern "C"` frame. + catch_panic_to_code( + "profile write", + PlatformWalletFFIResultCode::ErrorWalletOperation, + "The profile may or may not have been written; sync profiles before retrying.", + || { + check_ptr!(out_profile); + // `DashPayProfileFFI` owns heap C-string pointer fields freed by + // `dashpay_profile_ffi_free`; publish the empty sentinel before any + // fallible work so an error path never leaves uninitialized stack bytes + // in those pointer fields. Matches the read-side helpers in this file. + *out_profile = DashPayProfileFFI::empty(); + check_ptr!(signer_handle); + + let id = unwrap_result_or_return!(read_identifier(identity_id)); + + let display_name = unwrap_result_or_return!(decode_opt_c_str(display_name)); + let public_message = unwrap_result_or_return!(decode_opt_c_str(public_message)); + let avatar_url = unwrap_result_or_return!(decode_opt_c_str(avatar_url)); + + let avatar_bytes_vec: Option> = + if avatar_bytes.is_null() || avatar_bytes_len == 0 { + None + } else { + Some(std::slice::from_raw_parts(avatar_bytes, avatar_bytes_len).to_vec()) + }; + + let core_payment_address = + unwrap_result_or_return!(decode_address_update(core_payment_address)); + let platform_payment_address = + unwrap_result_or_return!(decode_address_update(platform_payment_address)); + let shielded_address = + unwrap_result_or_return!(decode_address_update(shielded_address)); + + let signer_addr = signer_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, move |wallet| { + let identity = wallet.identity().clone(); + let input = ProfileUpdate { + display_name, + public_message, + avatar_url, + avatar_bytes: avatar_bytes_vec, + core_payment_address, + platform_payment_address, + shielded_address, + }; + + block_on_worker(async move { + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + if do_create { + identity + .dashpay() + .create_profile_with_external_signer(&id, input, signer) + .await + } else { + identity + .dashpay() + .update_profile_with_external_signer(&id, input, signer) + .await + } + }) + }); + let result = unwrap_option_or_return!(option); + let profile = unwrap_result_or_return!(result); + *out_profile = DashPayProfileFFI::from_profile(&profile); + PlatformWalletFFIResult::ok() + }, + ) } #[cfg(test)] diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 75477d7f35c..bf26510be0f 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -1698,14 +1698,16 @@ public struct ShieldedTipRecipient: Sendable, Equatable { extension ManagedPlatformWallet { /// Fetch and verify the current DPNS identity and shielded tip address. public func resolveShieldedTip(username: String) async throws -> ShieldedTipRecipient { - let handle = self.handle - return try await Task.detached(priority: .userInitiated) { - var identityId = [UInt8](repeating: 0, count: 32) - var address = [UInt8](repeating: 0, count: 43) - try username.withCString { - try platform_wallet_resolve_shielded_tip(handle, $0, &identityId, &address).check() + // `deinit` destroys `handle`, so the wallet stays alive for the native call. + return try await Task.detached(priority: .userInitiated) { [self] in + try withExtendedLifetime(self) { + var identityId = [UInt8](repeating: 0, count: 32) + var address = [UInt8](repeating: 0, count: 43) + try username.withCString { + try platform_wallet_resolve_shielded_tip(handle, $0, &identityId, &address).check() + } + return ShieldedTipRecipient(identityId: Data(identityId), address: Data(address)) } - return ShieldedTipRecipient(identityId: Data(identityId), address: Data(address)) }.value } } @@ -1716,6 +1718,9 @@ extension PlatformWalletManager { guard walletId.count == 32, identityId.count == 32, let resolverHandle = resolver.handle else { throw PlatformWalletError.invalidParameter("Expected wallet/identity IDs and mnemonic resolver") } + // Admitted, so `shutdown()` waits for this call before destroying the handle. + try admitNativeOp("prepareShieldedTipAddress") + defer { finishNativeOp() } let handle = self.handle return try await Task.detached(priority: .userInitiated) { try withExtendedLifetime(resolver) { @@ -1740,6 +1745,8 @@ extension PlatformWalletManager { let resolverHandle = resolver.handle else { throw PlatformWalletError.invalidParameter("Invalid shielded tip recipient or wallet") } + try admitNativeOp("sendShieldedTip") + defer { finishNativeOp() } let handle = self.handle try await Task.detached(priority: .userInitiated) { try withExtendedLifetime(resolver) { From 1f03442396774b9691bc3644d97fb17d3472e2dd Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 29 Oct 2026 11:25:26 -0500 Subject: [PATCH 07/41] fix(sdk): leave address validation to the wallet and pin profile-write owners The profile FFI accepted only 21- or 43-byte addresses, a partial copy of the per-field check `validate_payment_address_update` already does; it now marshals the bytes and the wallet decides. The Swift profile write keeps its wallet alive through the detached native call, since `deinit` destroys the handle, and `clearAllData` deletes the payment-address rows, which identity deletion does not cascade to. Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet-ffi/src/dashpay_profile.rs | 8 +++++--- .../PlatformWallet/ManagedPlatformWallet.swift | 5 +++-- .../Sources/SwiftDashSDK/Services/DataManager.swift | 4 ++++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs index 230947d30f6..072f59c8f19 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs @@ -33,9 +33,11 @@ unsafe fn decode_address_update( match input.action { 0 => Ok(PaymentAddressUpdate::Keep), 2 => Ok(PaymentAddressUpdate::Remove), - 1 if !input.bytes.is_null() && matches!(input.len, 21 | 43) => Ok( - PaymentAddressUpdate::Set(std::slice::from_raw_parts(input.bytes, input.len).to_vec()), - ), + // The wallet validates the bytes for their field + // (`validate_payment_address_update`); this only marshals them. + 1 if !input.bytes.is_null() => Ok(PaymentAddressUpdate::Set( + std::slice::from_raw_parts(input.bytes, input.len).to_vec(), + )), _ => Err(PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorInvalidParameter, "Invalid payment address update".to_string(), diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index 871ba046716..f8be3314ffa 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -3559,8 +3559,9 @@ extension ManagedPlatformWallet { // Rust holds a `passUnretained` ctx pointer to it via `signerHandle`, // so a bare `_ = signer` keepalive can be released under -O before the // call returns. `withExtendedLifetime` keeps ARC holding it for the - // call's duration (matches the other *_with_signer wrappers). - let result: PlatformWalletFFIResult = withExtendedLifetime(signer) { + // call's duration (matches the other *_with_signer wrappers). The + // wallet is pinned the same way: its `deinit` destroys `handle`. + let result: PlatformWalletFFIResult = withExtendedLifetime((self, signer)) { idBytes.withUnsafeBufferPointer { idBp -> PlatformWalletFFIResult in let idPtr = idBp.baseAddress! diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Services/DataManager.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Services/DataManager.swift index 6192306f807..39f71aa86e8 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Services/DataManager.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Services/DataManager.swift @@ -92,6 +92,10 @@ public final class DataManager: ObservableObject { // Delete all token balances try modelContext.delete(model: PersistentTokenBalance.self) + // Payment-address rows are keyed by identity id, not by relationship, + // so deleting identities does not cascade to them. + try modelContext.delete(model: PersistentDashpayPaymentAddresses.self) + try modelContext.save() } From bc39308ff8b68be5cd98cba2a382f26ef0dceed9 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 29 Oct 2026 12:20:55 -0500 Subject: [PATCH 08/41] fix(example-apps): show an unknown tip balance as unavailable, not zero Both profile screens turned a failed tip-account lookup into a zero balance; they now say the balance is unavailable and keep the spend button disabled. In the Kotlin tip sheet the recipient-history write ran inside the native send's failure handling, so a failed preferences commit locked the sheet as an uncertain send; it now runs as a separate pre-send step whose failure returns the sheet to review. Co-Authored-By: Claude Opus 5.5 --- .../example/ui/dashpay/DashPayProfileScreen.kt | 12 +++++++++--- .../example/ui/dashpay/ShieldedTipSheet.kt | 5 +++-- .../example/ui/dashpay/ShieldedTipSubmission.kt | 14 +++++++++++++- .../ui/dashpay/ShieldedTipSubmissionTest.kt | 14 ++++++++++++++ .../Views/DashPay/DashPayProfileView.swift | 12 ++++++++---- 5 files changed, 47 insertions(+), 10 deletions(-) diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt index abc8ebd6d9d..0acd655662a 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt @@ -87,12 +87,14 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController .getOrNull() } } + // `null` when the tip account is unknown (no wallet, or the index lookup + // failed): that is not the same as an empty account. val tipBalance by remember(walletId, tipAccount) { val account = tipAccount - if (walletId == null || account == null) flowOf(0L) + if (walletId == null || account == null) flowOf(null) else container.database.shieldedDao().observeNotesByWalletAccount(walletId, account) .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } - }.collectAsStateWithLifecycle(initialValue = 0L) + }.collectAsStateWithLifecycle(initialValue = null) var profile by remember { mutableStateOf(null) } val publishedTipAddress = profile?.shieldedAddress?.let { raw -> @@ -287,7 +289,11 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController if (!isEditing) { FormSection(title = "Shielded tips") { - Text("This wallet’s tip balance: ${BigDecimal.valueOf(tipBalance, 11).stripTrailingZeros().toPlainString()} DASH") + val balance = tipBalance + Text( + if (balance == null) "This wallet’s tip balance: unavailable" + else "This wallet’s tip balance: ${BigDecimal.valueOf(balance, 11).stripTrailingZeros().toPlainString()} DASH", + ) val address = publishedTipAddress if (address == null) { Text("Tips are not enabled.") diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt index c5418cdde79..e5dcf37fdd7 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt @@ -94,8 +94,9 @@ fun ShieldedTipSheet(manager: PlatformWalletManager, wallet: ManagedPlatformWall val sendAmount = requireNotNull(confirmedAmount) val sendAccount = if (spendTips) tipAccount else 0 recipient = null - submission.submit { - history.confirm(manager.network, walletId, sendUsername, selected) + submission.submit( + beforeSend = { history.confirm(manager.network, walletId, sendUsername, selected) }, + ) { manager.sendShieldedTip(walletId, sendUsername, selected, sendAmount, account = sendAccount) } } else { diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt index af37ff54ca6..78480f6a014 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt @@ -26,12 +26,24 @@ class ShieldedTipSubmission(private val scope: CoroutineScope) { val busy: Boolean get() = status == Status.Sending val submitted: Boolean get() = status != Status.Ready - fun submit(send: suspend () -> Unit) { + /** + * [beforeSend] runs first and moves no funds, so its failure returns the + * submission to review; only a [send] failure can leave the outcome unknown. + */ + fun submit(beforeSend: suspend () -> Unit = {}, send: suspend () -> Unit) { if (submitted) return // Lock synchronously, before launching, so two UI events cannot submit twice. status = Status.Sending message = null scope.launch { + try { + beforeSend() + } catch (error: Exception) { + status = Status.Ready + message = error.message ?: "Unable to send tip" + if (error is kotlinx.coroutines.CancellationException) throw error + return@launch + } try { send() status = Status.Sent diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt index e3d0d102a84..5cbe8a48e19 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt @@ -75,6 +75,20 @@ class ShieldedTipSubmissionTest { assertTrue(retried) } + @Test + fun beforeSendFailureAllowsFreshReviewWithoutSending() = runTest { + val payment = ShieldedTipSubmission(backgroundScope) + var sends = 0 + payment.submit(beforeSend = { throw IllegalStateException("history write failed") }) { sends++ } + runCurrent() + assertEquals(ShieldedTipSubmission.Status.Ready, payment.status) + assertEquals("history write failed", payment.message) + assertEquals(0, sends) + payment.submit { sends++ } + runCurrent() + assertEquals(1, sends) + } + @Test fun walletAndNetworkGuardsAreIndependent() = runTest { val submissions = ShieldedTipSubmissions(backgroundScope) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift index eb52dcb01e1..e38d34863b6 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift @@ -44,9 +44,11 @@ struct DashPayProfileView: View { return try? PlatformWalletManager.shieldedTipAccountIndex(identityIndex: index) } - private var tipBalance: UInt64 { + /// `nil` when the tip account is unknown (no wallet, or the index lookup + /// failed): that is not the same as an empty account. + private var tipBalance: UInt64? { guard let walletId = identity.wallet?.walletId, - let account = tipAccount else { return 0 } + let account = tipAccount else { return nil } return shieldedNotes.filter { $0.walletId == walletId && $0.accountIndex == account && !$0.isSpent } .reduce(UInt64(0)) { $0 &+ $1.value } } @@ -102,10 +104,12 @@ struct DashPayProfileView: View { } else { Text("No tip address published") } - Text("Dedicated account balance: \(NSDecimalNumber(decimal: Decimal(tipBalance) / 100_000_000_000).stringValue) DASH") + Text(tipBalance.map { + "Dedicated account balance: \(NSDecimalNumber(decimal: Decimal($0) / 100_000_000_000).stringValue) DASH" + } ?? "Dedicated account balance: unavailable") .font(.caption) Button("Send from dedicated tip account") { showSpendTips = true } - .disabled(tipBalance == 0) + .disabled((tipBalance ?? 0) == 0) Text("An external receiving address is managed by its own wallet.").font(.caption).foregroundStyle(.secondary) } From 9a976106213f0c9499458939f8a70b3b05cf3e72 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 29 Oct 2026 14:01:29 -0500 Subject: [PATCH 09/41] fix(platform-wallet-ffi): bound a payment address's length before copying it The wallet checks each field's exact length; the ABI now refuses anything over 64 bytes before allocating, so a bad C or JNI caller can't ask for an arbitrary copy. Co-Authored-By: Claude Opus 5.5 --- .../rs-platform-wallet-ffi/src/dashpay_profile.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs index 072f59c8f19..888743cfb97 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs @@ -23,6 +23,10 @@ pub struct PaymentAddressUpdateFFI { pub len: usize, } +/// Transport bound for a payment address crossing the ABI. The wallet checks +/// the exact per-field length; this only refuses absurd sizes before copying. +const MAX_PAYMENT_ADDRESS_BYTES: usize = 64; + unsafe fn decode_address_update( input: *const PaymentAddressUpdateFFI, ) -> Result { @@ -35,9 +39,9 @@ unsafe fn decode_address_update( 2 => Ok(PaymentAddressUpdate::Remove), // The wallet validates the bytes for their field // (`validate_payment_address_update`); this only marshals them. - 1 if !input.bytes.is_null() => Ok(PaymentAddressUpdate::Set( - std::slice::from_raw_parts(input.bytes, input.len).to_vec(), - )), + 1 if !input.bytes.is_null() && input.len <= MAX_PAYMENT_ADDRESS_BYTES => Ok( + PaymentAddressUpdate::Set(std::slice::from_raw_parts(input.bytes, input.len).to_vec()), + ), _ => Err(PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorInvalidParameter, "Invalid payment address update".to_string(), @@ -575,6 +579,10 @@ mod tests { PaymentAddressUpdate::Set(bytes) => assert_eq!(bytes, address), _ => panic!("expected set operation"), } + let oversized = [7u8; MAX_PAYMENT_ADDRESS_BYTES + 1]; + update.bytes = oversized.as_ptr(); + update.len = oversized.len(); + assert!(decode_address_update(&update).is_err()); update.action = 3; assert!(decode_address_update(&update).is_err()); } From 2567f16e8233d7ef072ac9f8ef3d13f2332c75e6 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 30 Oct 2026 08:42:47 -0500 Subject: [PATCH 10/41] test(platform-wallet): pin that a load stores an adopted identity at its proved slot After the rebase onto #5487, placement no longer persists: load and discovery store the placed identity's snapshot with its verified keys in one changeset. Cover the adopted case, which now relies on that snapshot to carry the new wallet and index, and narrow VerifiedPlacement to the crate with the function that returns it. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/discovery.rs | 2 +- .../src/wallet/identity/network/loading.rs | 129 +++++++++++++++--- .../identity/state/manager/lifecycle.rs | 2 +- .../src/wallet/identity/state/manager/mod.rs | 5 +- .../src/wallet/identity/state/mod.rs | 2 +- 5 files changed, 112 insertions(+), 28 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs index 56c1b716aff..81b2e6a9e53 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs @@ -6,8 +6,8 @@ use key_wallet::bip32::ExtendedPrivKey; use crate::error::PlatformWalletError; use crate::wallet::identity::network::contact_requests::budget_spent; -use crate::BlockTime; use crate::wallet::identity::state::VerifiedPlacement; +use crate::BlockTime; use super::*; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs index 75178a8f9ac..b7d18930083 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs @@ -262,8 +262,8 @@ impl IdentityWallet { if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { // Fold the freshly fetched on-chain state into an - // already-known identity too — the add above only runs for - // new ones, and without this a re-load kept serving the + // already-known identity too — the placement above only + // adds new ones, and without this a re-load kept serving the // stale key set (keys added from another device never // appeared, and contact requests referencing them failed // key-index validation). Same fold `refresh_identity` @@ -731,23 +731,13 @@ mod tests { } } - /// A load that finds an identity the wallet does not hold yet stores it - /// and its keys, each with the breadcrumb verified against the seed, as - /// one changeset. No snapshot of the identity or its keys reaches the - /// store ahead of the breadcrumbs, so a store that fails between two - /// writes cannot leave watch-only key rows behind. - #[tokio::test] - async fn should_store_a_newly_loaded_identity_with_its_keys_in_one_changeset() { - struct Events; - impl EventHandler for Events {} - impl PlatformEventHandler for Events {} - - const SEED: [u8; 64] = [7; 64]; - let network = Network::Testnet; - let master = ExtendedPrivKey::new_master(network, &SEED).unwrap(); - let identity_id = Identifier::from([0x5A; 32]); - // Registered at index 0 the way registration does it: MASTER, HIGH - // and CRITICAL auth keys at key ids 0..=2, all from the seed. + /// An identity registered at index 0 the way registration does it: + /// MASTER, HIGH and CRITICAL auth keys at key ids 0..=2, all from the seed. + fn registered_at_index_zero( + master: &ExtendedPrivKey, + network: Network, + identity_id: Identifier, + ) -> Identity { let levels = [ SecurityLevel::MASTER, SecurityLevel::HIGH, @@ -757,7 +747,7 @@ mod tests { .zip(levels) .map(|(key_id, security_level)| { let derived = - derive_ecdsa_identity_auth_keypair_from_master(&master, network, 0, key_id) + derive_ecdsa_identity_auth_keypair_from_master(master, network, 0, key_id) .unwrap(); let key: IdentityPublicKey = IdentityPublicKeyV0 { id: key_id, @@ -773,12 +763,30 @@ mod tests { (key_id, key) }) .collect(); - let on_chain = Identity::V0(IdentityV0 { + Identity::V0(IdentityV0 { id: identity_id, public_keys, balance: 1_000_000, revision: 1, - }); + }) + } + + /// A load that finds an identity the wallet does not hold yet stores it + /// and its keys, each with the breadcrumb verified against the seed, as + /// one changeset. No snapshot of the identity or its keys reaches the + /// store ahead of the breadcrumbs, so a store that fails between two + /// writes cannot leave watch-only key rows behind. + #[tokio::test] + async fn should_store_a_newly_loaded_identity_with_its_keys_in_one_changeset() { + struct Events; + impl EventHandler for Events {} + impl PlatformEventHandler for Events {} + + const SEED: [u8; 64] = [7; 64]; + let network = Network::Testnet; + let master = ExtendedPrivKey::new_master(network, &SEED).unwrap(); + let identity_id = Identifier::from([0x5A; 32]); + let on_chain = registered_at_index_zero(&master, network, identity_id); let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); let probe = @@ -845,4 +853,81 @@ mod tests { ); } } + + /// A load that proves the index of an identity already known out of + /// wallet adopts it into that slot, and the identity's snapshot (now + /// carrying the wallet and index) reaches the store in the same changeset + /// as its keys: placement itself stores nothing. + #[tokio::test] + async fn should_store_an_adopted_identity_at_its_proved_slot_with_its_keys() { + struct Events; + impl EventHandler for Events {} + impl PlatformEventHandler for Events {} + + const SEED: [u8; 64] = [7; 64]; + let network = Network::Testnet; + let master = ExtendedPrivKey::new_master(network, &SEED).unwrap(); + let identity_id = Identifier::from([0x5B; 32]); + let on_chain = registered_at_index_zero(&master, network, identity_id); + + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); + let probe = + derive_load_probe_hash(ResolvedLoadKeyHashSource::Master(&master), network, 0).unwrap(); + sdk.mock() + .expect_fetch(PublicKeyHash(probe), Some(on_chain.clone())) + .await + .unwrap(); + let store = Arc::new(CapturingStore::default()); + let manager = PlatformWalletManager::new(Arc::new(sdk), store.clone(), Arc::new(Events)); + let wallet = manager + .create_wallet_from_seed_bytes( + network, + &SEED, + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .unwrap(); + let wallet_id = wallet.wallet_id(); + { + let identity = wallet.identity(); + let mut wm = identity.wallet_manager.write().await; + wm.get_wallet_info_mut(&wallet_id) + .unwrap() + .identity_manager + .add_out_of_wallet_identity(on_chain, &identity.persister) + .unwrap(); + } + store.take(); + + wallet + .identity() + .load_identity_by_index_from_master(0, &master) + .await + .unwrap() + .expect("the identity at index 0 is found"); + + let stored = store.take(); + let identity_changesets: Vec<_> = stored + .iter() + .filter(|changeset| changeset.identities.is_some() || changeset.identity_keys.is_some()) + .collect(); + assert_eq!( + identity_changesets.len(), + 1, + "the adopted identity and its keys go out together: {identity_changesets:?}" + ); + let changeset = identity_changesets[0]; + let entry = &changeset + .identities + .as_ref() + .expect("the changeset carries the identity") + .identities[&identity_id]; + assert_eq!(entry.wallet_id, Some(wallet_id)); + assert_eq!(entry.identity_index, Some(0)); + assert!(changeset + .identity_keys + .as_ref() + .is_some_and(|keys| keys.upserts.len() == 3)); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs index bce2e3cd8db..07707ea4c11 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs @@ -20,7 +20,7 @@ use dpp::prelude::Identifier; /// How [`IdentityManager::place_verified_identity`] placed an identity. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum VerifiedPlacement { +pub(crate) enum VerifiedPlacement { /// Newly added to the wallet bucket. Added, /// Already known; moved into (or confirmed at) the verified slot. diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs index a794fd0c297..c58b49a9943 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/mod.rs @@ -29,7 +29,7 @@ mod accessors; mod apply; mod lifecycle; -pub use lifecycle::VerifiedPlacement; +pub(crate) use lifecycle::VerifiedPlacement; use super::managed_identity::ManagedIdentity; use crate::changeset::{IdentityManagerStartState, IdentityScanStateEntry}; @@ -367,8 +367,7 @@ mod tests { .add_out_of_wallet_identity(create_test_identity(other), &p) .unwrap(); let stores_before = counter.stores.load(Ordering::SeqCst); - let refused = - manager.place_verified_identity(create_test_identity(other), 7, wallet_id); + let refused = manager.place_verified_identity(create_test_identity(other), 7, wallet_id); assert!( matches!( refused, diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs index 26b9b9cb21b..d63a9845254 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/mod.rs @@ -12,4 +12,4 @@ pub use managed_identity::{BlockTime, DashPayState, ManagedIdentity, PrivateCont pub use manager::IdentityLocation; pub use manager::IdentityManager; pub use manager::RegistrationIndex; -pub use manager::VerifiedPlacement; +pub(crate) use manager::VerifiedPlacement; From 4c983c24d6b20d8ccc4db03a38b6eb6b71a2852b Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 30 Oct 2026 08:42:47 -0500 Subject: [PATCH 11/41] fix(platform-wallet-ffi): contain panics in the shielded account snapshot export platform_wallet_manager_shielded_account_indices called runtime().block_on with no panic boundary, so a host calling from inside a Tokio runtime (or any panic in the lookup) unwound into the C frame and aborted. Run it under catch_query_panic, now shared from runtime.rs, and poll on a worker via block_on_worker. The outputs stay cleared on failure. Co-Authored-By: Claude Opus 5.5 --- .../rs-platform-wallet-ffi/src/runtime.rs | 27 ++++++ .../src/shielded_send.rs | 24 +----- .../src/shielded_sync.rs | 86 ++++++++++++++----- 3 files changed, 94 insertions(+), 43 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/runtime.rs b/packages/rs-platform-wallet-ffi/src/runtime.rs index ee96010db00..7af3fb933ea 100644 --- a/packages/rs-platform-wallet-ffi/src/runtime.rs +++ b/packages/rs-platform-wallet-ffi/src/runtime.rs @@ -18,6 +18,9 @@ //! on the caller, but it parks almost immediately — all the //! compute happens on the tokio worker. +#[cfg(feature = "shielded")] +use crate::error::{catch_panic_to_code, PlatformWalletFFIResult, PlatformWalletFFIResultCode}; + /// Worker thread stack size for the shared runtime. 8 MB gives proof /// verification + GroveDB comfortable headroom without meaningfully /// affecting memory footprint (we spin up a small number of workers). @@ -89,6 +92,30 @@ pub(crate) fn run_on_big_stack_thread(f: impl FnOnce() -> T + Send) -> }) } +/// Post-panic guidance for exports that move no funds. Paired with +/// `ErrorWalletOperation` in [`catch_query_panic`]. +#[cfg(feature = "shielded")] +const QUERY_PANIC_GUIDANCE: &str = "No funds were moved; the call may be retried."; + +/// [`catch_panic_to_code`] specialized for exports that spend nothing (address +/// preparation, recipient resolution). A panic there is a plain failure of this +/// call, so it maps to [`PlatformWalletFFIResultCode::ErrorWalletOperation`] and +/// the host may retry. The boundary matters as much as on the spend path: an +/// unwind that reaches the `extern "C"` frame aborts the process before the JNI +/// guard on the far side can translate it. +#[cfg(feature = "shielded")] +pub(crate) fn catch_query_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorWalletOperation, + QUERY_PANIC_GUIDANCE, + body, + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index e7c0daca4f0..754e11df8fe 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -64,7 +64,7 @@ use crate::core_wallet_types::OutPointFFI; use crate::error::*; use crate::handle::*; use crate::identity_registration_with_signer::{decode_identity_pubkeys, IdentityPubkeyFFI}; -use crate::runtime::{block_on_worker, runtime}; +use crate::runtime::{block_on_worker, catch_query_panic, runtime}; use crate::shielded_types::{ShieldedIdentityDebitRecoveryRecordFFI, ShieldedShieldPreflightFFI}; use crate::types::read_identifier; use crate::unwrap_result_or_return; @@ -749,28 +749,6 @@ pub(crate) fn catch_spend_panic( ) } -/// Post-panic guidance for exports that move no funds. Paired with -/// `ErrorWalletOperation` in [`catch_query_panic`]. -const QUERY_PANIC_GUIDANCE: &str = "No funds were moved; the call may be retried."; - -/// [`catch_panic_to_code`] specialized for exports that spend nothing (address -/// preparation, recipient resolution). A panic there is a plain failure of this -/// call, so it maps to [`PlatformWalletFFIResultCode::ErrorWalletOperation`] and -/// the host may retry. The boundary matters as much as on the spend path: an -/// unwind that reaches the `extern "C"` frame aborts the process before the JNI -/// guard on the far side can translate it. -fn catch_query_panic( - operation: &str, - body: impl FnOnce() -> PlatformWalletFFIResult, -) -> PlatformWalletFFIResult { - catch_panic_to_code( - operation, - PlatformWalletFFIResultCode::ErrorWalletOperation, - QUERY_PANIC_GUIDANCE, - body, - ) -} - /// Test-only fault injection for the tip exports: while set, the worker future /// of each guarded tip call panics before it touches the wallet, so a test can /// prove the real `extern "C"` entry point (not just the helper) contains the diff --git a/packages/rs-platform-wallet-ffi/src/shielded_sync.rs b/packages/rs-platform-wallet-ffi/src/shielded_sync.rs index 4d94d18e345..b80aa218eb5 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_sync.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_sync.rs @@ -20,7 +20,7 @@ use platform_wallet::PlatformWalletError; use crate::error::*; use crate::handle::*; -use crate::runtime::{block_on_worker, runtime}; +use crate::runtime::{block_on_worker, catch_query_panic, runtime}; use crate::shielded_types::{ ShieldedBalanceSourceFFI, ShieldedLocalAccountBalanceFFI, ShieldedLocalBalanceSnapshotFFI, ShieldedLocalBalanceStatusFFI, ShieldedSyncWalletResultFFI, @@ -911,25 +911,24 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_account_indices( check_ptr!(wallet_id_bytes); let mut wallet_id = [0; 32]; std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); - let option = PLATFORM_WALLET_MANAGER_STORAGE.with_item(handle, |manager| { - runtime().block_on(async { - match manager.get_wallet(&wallet_id).await { - Some(wallet) => Some(wallet.shielded_account_indices().await), - None => None, - } - }) - }); - let Some(indices) = unwrap_option_or_return!(option) else { - return PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorWalletOperation, - "wallet not found", - ); - }; - if !indices.is_empty() { - *out_count = indices.len(); - *out_indices = Box::into_raw(indices.into_boxed_slice()) as *mut u32; - } - PlatformWalletFFIResult::ok() + // The whole lookup runs inside the panic boundary, polled on a worker + // rather than this host thread; the outputs stay cleared on any failure. + catch_query_panic("shielded account snapshot", || { + let option = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |manager| manager.get_wallet_blocking(&wallet_id)); + let Some(wallet) = unwrap_option_or_return!(option) else { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorWalletOperation, + "wallet not found", + ); + }; + let indices = block_on_worker(async move { wallet.shielded_account_indices().await }); + if !indices.is_empty() { + *out_count = indices.len(); + *out_indices = Box::into_raw(indices.into_boxed_slice()) as *mut u32; + } + PlatformWalletFFIResult::ok() + }) } /// Release an account snapshot returned by the matching getter. Null is a no-op. @@ -952,6 +951,8 @@ pub unsafe extern "C" fn platform_wallet_manager_free_shielded_account_indices( #[cfg(test)] mod account_indices_tests { use super::*; + use crate::test_fixtures::mock_manager; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; #[test] fn invalid_handle_clears_account_snapshot_outputs() { @@ -971,6 +972,51 @@ mod account_indices_tests { platform_wallet_manager_free_shielded_account_indices(indices, count); } } + + /// A host calling from inside a Tokio runtime makes the worker helper's + /// `block_on` panic; the export must turn that into an error result with + /// cleared outputs instead of unwinding into the C frame. + #[test] + fn should_contain_a_panic_and_clear_outputs_when_called_inside_a_runtime() { + let manager = mock_manager(); + let wallet_id = runtime().block_on(async { + manager + .create_wallet_from_seed_bytes( + dashcore::Network::Testnet, + &[7; 64], + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("create mock wallet") + .wallet_id() + }); + let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(manager); + let mut indices = std::ptr::NonNull::::dangling().as_ptr(); + let mut count = 99; + let result = runtime().block_on(async { + unsafe { + platform_wallet_manager_shielded_account_indices( + handle, + wallet_id.as_ptr(), + &mut indices, + &mut count, + ) + } + }); + PLATFORM_WALLET_MANAGER_STORAGE.remove(handle); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = unsafe { CStr::from_ptr(result.message) }.to_string_lossy(); + assert!( + message.contains("shielded account snapshot panicked"), + "{message}" + ); + assert!(indices.is_null()); + assert_eq!(count, 0); + } } #[cfg(test)] From 9052a11ef4fdae2fc0e4089fb541ef37c2525a67 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 30 Oct 2026 08:42:47 -0500 Subject: [PATCH 12/41] fix(platform-wallet-ffi): re-validate payment addresses restored from the host profile_from_restore_row copied the host's payment-address buffers as-is, so a stale or corrupt SwiftData/Room row could restore an address a profile fetch would reject. Apply the wallet's transparent and Orchard validators on restore, as the avatar URL already is. Co-Authored-By: Claude Opus 5.5 --- .../rs-platform-wallet-ffi/src/persistence.rs | 93 ++++++++++++++++--- 1 file changed, 82 insertions(+), 11 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 5e6aac742f4..0d06ef1dc9b 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -7367,15 +7367,23 @@ unsafe fn profile_from_restore_row( .avatar_fingerprint_present .then_some(row.avatar_fingerprint), public_message: opt_string(row.public_message), + // Re-validated like the avatar URL: a stale or corrupt host row must + // not restore an address that a profile fetch would have rejected. core_payment_address: row .core_payment_address_present - .then(|| row.core_payment_address.to_vec()), + .then_some(row.core_payment_address) + .filter(|address| platform_wallet::valid_transparent_payment_address(address)) + .map(|address| address.to_vec()), platform_payment_address: row .platform_payment_address_present - .then(|| row.platform_payment_address.to_vec()), + .then_some(row.platform_payment_address) + .filter(|address| platform_wallet::valid_transparent_payment_address(address)) + .map(|address| address.to_vec()), shielded_address: row .shielded_address_present - .then(|| row.shielded_address.to_vec()), + .then_some(row.shielded_address) + .and_then(|address| platform_wallet::validated_shielded_address(&address)) + .map(|address| address.to_vec()), } } @@ -9582,6 +9590,67 @@ mod tests { "both host allocations freed" ); } + + /// A storage-form transparent payment address: a 0x00/0x01 version byte, + /// then a 20-byte hash. + fn transparent_address(version: u8, fill: u8) -> [u8; 21] { + let mut address = [fill; 21]; + address[0] = version; + address + } + + /// Host bytes for a shielded address, and what restore keeps of them: a + /// decodable Orchard address where shielded support is built in, and + /// nothing without it, where no shielded address is payable. + fn shielded_fixture() -> ([u8; 43], Option>) { + #[cfg(feature = "shielded")] + { + let address = OrchardKeySet::from_seed(&[42; 64], Network::Testnet, 0) + .expect("orchard keys") + .default_address + .to_raw_address_bytes(); + (address, Some(address.to_vec())) + } + #[cfg(not(feature = "shielded"))] + { + ([0xE1; 43], None) + } + } + + /// Restore re-validates each payment address as a profile fetch would, + /// dropping a wrong-version transparent address and undecodable Orchard + /// bytes from a stale or corrupt host row while keeping the rest. + #[test] + fn should_drop_invalid_payment_addresses_on_restore() { + let name = std::ffi::CString::new("Carol").unwrap(); + let row = ContactProfileRestoreEntryFFI { + contact_id: [0xDD; 32], + display_name: name.as_ptr(), + bio: std::ptr::null(), + avatar_url: std::ptr::null(), + avatar_hash: [0; 32], + avatar_hash_present: false, + avatar_fingerprint: [0; 8], + avatar_fingerprint_present: false, + core_payment_address: transparent_address(0x05, 0xC1), + core_payment_address_present: true, + platform_payment_address: transparent_address(0x01, 0xD1), + platform_payment_address_present: true, + shielded_address: [0xFF; 43], + shielded_address_present: true, + public_message: std::ptr::null(), + checked_at_ms: 0, + }; + let profile = unsafe { profile_from_restore_row(&row) }; + assert_eq!(profile.display_name.as_deref(), Some("Carol")); + assert_eq!(profile.core_payment_address, None); + assert_eq!( + profile.platform_payment_address, + Some(transparent_address(0x01, 0xD1).to_vec()) + ); + assert_eq!(profile.shielded_address, None); + } + /// The owned DashPay profile a host supplies on the wallet-restore load /// callback reaches the restored `ManagedIdentity` with every field, /// including the three payment addresses, and is an owned copy: the free @@ -9647,11 +9716,11 @@ mod tests { avatar_hash_present: true, avatar_fingerprint: [0xF1; 8], avatar_fingerprint_present: true, - core_payment_address: [0xC1; 21], + core_payment_address: transparent_address(0x00, 0xC1), core_payment_address_present: true, - platform_payment_address: [0xD1; 21], + platform_payment_address: transparent_address(0x01, 0xD1), platform_payment_address_present: true, - shielded_address: [0xE1; 43], + shielded_address: shielded_fixture().0, shielded_address_present: true, public_message: host.strings[3].as_ptr().cast(), checked_at_ms: 0, @@ -9720,9 +9789,9 @@ mod tests { avatar_hash: Some([0xA1; 32]), avatar_fingerprint: Some([0xF1; 8]), public_message: Some("hello".into()), - core_payment_address: Some(vec![0xC1; 21]), - platform_payment_address: Some(vec![0xD1; 21]), - shielded_address: Some(vec![0xE1; 43]), + core_payment_address: Some(transparent_address(0x00, 0xC1).to_vec()), + platform_payment_address: Some(transparent_address(0x01, 0xD1).to_vec()), + shielded_address: shielded_fixture().1, } ); assert!( @@ -12548,6 +12617,8 @@ mod tests { use key_wallet::transaction_checking::{BlockInfo, TransactionContext}; use key_wallet::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; use key_wallet::wallet::Wallet; + #[cfg(feature = "shielded")] + use platform_wallet::wallet::shielded::OrchardKeySet; /// Regression: restored pool addresses must be tagged with the /// WALLET's network, not the network the base58 string parses as. @@ -13991,7 +14062,7 @@ mod tests { core_payment_address_present: false, platform_payment_address: [0; 21], platform_payment_address_present: false, - shielded_address: [3; 43], + shielded_address: shielded_fixture().0, shielded_address_present: true, public_message: public_message.as_ptr(), @@ -14037,7 +14108,7 @@ mod tests { ); assert_eq!(alice_profile.avatar_hash, Some([0x11; 32])); assert_eq!(alice_profile.avatar_fingerprint, Some([0x22; 8])); - assert_eq!(alice_profile.shielded_address, Some(vec![3; 43])); + assert_eq!(alice_profile.shielded_address, shielded_fixture().1); assert!(alice_profile.bio.is_none()); let bob = managed From 2a802ab597feb6d619b8cd4814fb0ec73e3d3578 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 30 Oct 2026 08:42:47 -0500 Subject: [PATCH 13/41] fix(swift-sdk): fail identity removal when its payment-address rows can't be removed PersistentIdentity.remove swallowed the sidecar cleanup error and deleted the identity anyway, stranding address rows. It now throws without deleting. The example app saves the row deletes before touching the Keychain and rolls back on failure, so a failed removal no longer leaves a keyless identity behind. Co-Authored-By: Claude Opus 5.5 --- .../Models/PersistentIdentity.swift | 10 ++-- .../Core/Views/IdentitiesContentView.swift | 49 +++++++++---------- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift index cb86445cd1c..e95cdc03478 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Persistence/Models/PersistentIdentity.swift @@ -460,15 +460,17 @@ extension PersistentIdentity { return true } + /// Throws, deleting nothing, when the owner's payment-address rows cannot + /// be removed: they reference their owner by id only, so no relationship + /// cascade reaches them, and deleting the identity without them would + /// strand rows a later restore could pick up. @discardableResult public static func remove( in context: ModelContext, identityId: Data - ) -> Bool { + ) throws -> Bool { guard let row = fetch(in: context, identityId: identityId) else { return false } - // Payment-address rows reference their owner by id only, so no - // relationship cascade reaches them. - try? PersistentDashpayPaymentAddresses.removeOwned( + try PersistentDashpayPaymentAddresses.removeOwned( in: context, networkRaw: row.networkRaw, ownerIdentityId: identityId) context.delete(row) return true diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift index b58b6b7a912..1397be6f6f4 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/IdentitiesContentView.swift @@ -504,42 +504,41 @@ struct IdentitiesContentView: View { /// `payoutPrivateKeyIdentifier`) since those are likewise keyed /// by string identifier. /// - /// After keychain cleanup the SwiftData cascade does the rest: - /// `@Relationship(.cascade)` on `publicKeys` / `documents` drops - /// those child rows, `@Relationship(.nullify)` on `tokenBalances` + /// The Keychain identifiers are collected first, then the row deletes are + /// saved, and only after a successful save are the Keychain items + /// removed: a failed save rolls back and keeps the identity signable, + /// instead of leaving a keyless row behind. The SwiftData cascade does + /// the rest: `@Relationship(.cascade)` on `publicKeys` / `documents` + /// drops those child rows, `@Relationship(.nullify)` on `tokenBalances` /// severs the link, and the `PersistentWallet.identities` inverse /// (declared on the wallet side, also `.nullify`) naturally drops /// this identity from its owning wallet — no manual detachment - /// required. + /// required. Payment-address rows are keyed by owner id, so no cascade + /// reaches them; they are removed explicitly in the same save. private func removeIdentityLocally(_ identity: PersistentIdentity) { - let keychain = KeychainManager.shared - - for publicKey in identity.publicKeys { - if let identifier = publicKey.privateKeyKeychainIdentifier { - _ = keychain.deleteKeyData(identifier: identifier) - } - } + let keychainIdentifiers = identity.publicKeys.compactMap(\.privateKeyKeychainIdentifier) + + [ + identity.votingPrivateKeyIdentifier, + identity.ownerPrivateKeyIdentifier, + identity.payoutPrivateKeyIdentifier, + ].compactMap { $0 } - if let votingIdentifier = identity.votingPrivateKeyIdentifier { - _ = keychain.deleteKeyData(identifier: votingIdentifier) - } - if let ownerIdentifier = identity.ownerPrivateKeyIdentifier { - _ = keychain.deleteKeyData(identifier: ownerIdentifier) - } - if let payoutIdentifier = identity.payoutPrivateKeyIdentifier { - _ = keychain.deleteKeyData(identifier: payoutIdentifier) - } - - // Payment-address rows are keyed by owner id; no cascade reaches them. - try? PersistentDashpayPaymentAddresses.removeOwned( - in: modelContext, networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) - modelContext.delete(identity) do { + try PersistentDashpayPaymentAddresses.removeOwned( + in: modelContext, networkRaw: identity.networkRaw, ownerIdentityId: identity.identityId) + modelContext.delete(identity) try modelContext.save() } catch { + modelContext.rollback() platformState.showError( message: "Failed to remove identity from device: \(error.localizedDescription)" ) + return + } + + let keychain = KeychainManager.shared + for identifier in keychainIdentifiers { + _ = keychain.deleteKeyData(identifier: identifier) } } } From a14af41523aeb6f5705215fb1c6bd35958d7dac0 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 30 Oct 2026 09:21:24 -0500 Subject: [PATCH 14/41] fix(platform-wallet-ffi): resolve the tip wallet and seed inside the panic boundary The prepare and send tip exports resolved the wallet, coordinator and seed before entering their panic boundaries. Resolution blocks on the runtime, so a host calling from inside a Tokio runtime panicked across the C ABI and aborted. Prepare now resolves inside its query boundary; send resolves under a retryable preflight boundary, since nothing is spent yet, and keeps the do-not-retry contract for the spend itself. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 142 ++++++++++++++---- 1 file changed, 113 insertions(+), 29 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 754e11df8fe..0385f5711d5 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -2388,24 +2388,25 @@ pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_tip_address( Ok(id) => id, Err(e) => return e.into(), }; - let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { - Ok(value) => value, - Err(e) => return e, - }; - let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( - mnemonic_resolver_handle, - &wallet_id, - ) { - Ok(value) => value, - Err(e) => return e, - }; - // The worker call and its result mapping sit inside the panic boundary; - // the raw output write happens outside it, only on success, so a panic - // leaves the zeroed buffer untouched. + // Wallet, coordinator and seed resolution, the worker call and its result + // mapping all sit inside the panic boundary (resolution blocks on the + // runtime, which panics when the host calls from inside one); the raw + // output write happens outside it, only on success, so a panic leaves the + // zeroed buffer untouched. let mut address = [0u8; 43]; - let result = catch_query_panic( - "shielded tip address preparation", - || match block_on_worker(async move { + let result = catch_query_panic("shielded tip address preparation", || { + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(value) => value, + Err(e) => return e, + }; + let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( + mnemonic_resolver_handle, + &wallet_id, + ) { + Ok(value) => value, + Err(e) => return e, + }; + match block_on_worker(async move { maybe_inject_tip_worker_panic(); wallet .prepare_shielded_tip_address(seed.as_ref(), &identity_id, &coordinator) @@ -2416,8 +2417,8 @@ pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_tip_address( PlatformWalletFFIResult::ok() } Err(e) => e.into(), - }, - ); + } + }); if result.code == PlatformWalletFFIResultCode::Success { std::ptr::copy_nonoverlapping(address.as_ptr(), out_address, 43); } @@ -2518,16 +2519,27 @@ pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( Ok(value) => value, Err(e) => return e, }; - let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { - Ok(value) => value, - Err(e) => return e, - }; - let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( - mnemonic_resolver_handle, - &wallet_id, - ) { - Ok(value) => value, - Err(e) => return e, + // Resolution blocks on the runtime and can panic before anything is + // spent, so it runs under the retryable query boundary; only the spend + // itself takes the do-not-retry contract below. + let mut resolved = None; + let preflight = catch_query_panic("shielded tip preflight", || { + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(value) => value, + Err(e) => return e, + }; + let seed = match crate::identity_keys_from_mnemonic::resolve_seed_from_resolver( + mnemonic_resolver_handle, + &wallet_id, + ) { + Ok(value) => value, + Err(e) => return e, + }; + resolved = Some((wallet, coordinator, seed)); + PlatformWalletFFIResult::ok() + }); + let Some((wallet, coordinator, seed)) = resolved else { + return preflight; }; catch_spend_panic("shielded tip", || { let result = block_on_worker(async move { @@ -3183,6 +3195,78 @@ mod tests { (handle, wallet_id, path) } + /// A host calling from inside a Tokio runtime makes wallet resolution's + /// `block_on` panic before anything is spent. Both manager tip exports + /// must contain it as a retryable failure, with no address escaping. + #[test] + fn tip_manager_exports_contain_a_resolution_panic_inside_a_runtime() { + let (handle, wallet_id, path) = tip_test_manager(); + let mut vtable = rs_sdk_ffi::MnemonicResolverVTable { + resolve: resolve_tip_test_mnemonic, + destroy: destroy_tip_test_resolver, + }; + let mut resolver = MnemonicResolverHandle { + ctx: std::ptr::null_mut(), + vtable: &mut vtable, + }; + let username = std::ffi::CString::new("alice").expect("username"); + let identity_id = [0x21u8; 32]; + let address = [0x43u8; 43]; + let mut out_address = [0xAAu8; 43]; + + let (mut send, mut prepare) = runtime().block_on(async { + let send = unsafe { + platform_wallet_manager_send_shielded_tip( + handle, + wallet_id.as_ptr(), + &mut resolver, + 0, + username.as_ptr(), + identity_id.as_ptr(), + address.as_ptr(), + 1_000, + std::ptr::null(), + ) + }; + let prepare = unsafe { + platform_wallet_manager_prepare_shielded_tip_address( + handle, + wallet_id.as_ptr(), + &mut resolver, + identity_id.as_ptr(), + out_address.as_mut_ptr(), + ) + }; + (send, prepare) + }); + + assert_eq!(send.code, PlatformWalletFFIResultCode::ErrorWalletOperation); + let message = message_of(&send); + assert!( + message.contains("shielded tip preflight panicked") + && message.contains("may be retried"), + "{message}" + ); + assert_eq!( + prepare.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&prepare); + assert!( + message.contains("shielded tip address preparation panicked"), + "{message}" + ); + assert_eq!(out_address, [0u8; 43]); + + unsafe { + crate::platform_wallet_ffi_result_free(&mut send); + crate::platform_wallet_ffi_result_free(&mut prepare); + let mut destroyed = platform_wallet_manager_destroy(handle); + crate::platform_wallet_ffi_result_free(&mut destroyed); + } + let _ = std::fs::remove_dir_all(path); + } + /// The real exports contain a worker panic instead of letting it unwind into /// the `extern "C"` frame: this drives the exported entry points themselves, /// so deleting a guard at a call site fails here even while the helper-level From 613fa9c2a18b7708e1c1e1dd7742af8680e7ac2d Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 30 Oct 2026 09:21:24 -0500 Subject: [PATCH 15/41] fix(swift-sdk): fail an identity removal changeset when the identity fetch fails The removal callback read a failed fetch as an absent row, skipping the identity and payment-address deletes while reporting success. Let the error fail the changeset. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWallet/PlatformWalletPersistenceHandler.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index dafca55af68..aafe0adb062 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3901,7 +3901,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { let descriptor = FetchDescriptor( predicate: #Predicate { $0.identityId == identityId } ) - if let existing = try? backgroundContext.fetch(descriptor).first { + // A failed fetch fails the changeset rather than reading as an + // absent row, which would strand the identity and its sidecar. + if let existing = try backgroundContext.fetch(descriptor).first { try PersistentDashpayPaymentAddresses.removeOwned(in: backgroundContext, networkRaw: existing.networkRaw, ownerIdentityId: identityId) backgroundContext.delete(existing) From 50b940b12832785c2d958ae97090cf1e58e7be58 Mon Sep 17 00:00:00 2001 From: pasta Date: Sun, 1 Nov 2026 12:04:06 -0600 Subject: [PATCH 16/41] refactor(sdk): move the shielded-tip screens to a follow-up PR This PR now carries the wallet, storage and SDK bindings only. The tip sheets, the profile-editor tip field, the tip-account balance filters, the post-discovery rebind and the host-side recipient history and amount parsing move to the stacked follow-ups, where the decision logic they held is first moved into rs-platform-wallet. Co-Authored-By: Claude Opus 5.5 --- .../dashfoundation/example/di/AppContainer.kt | 3 - .../example/ui/dashpay/DashPayJson.kt | 6 - .../ui/dashpay/DashPayProfileScreen.kt | 80 ---------- .../example/ui/dashpay/DashPayTabScreen.kt | 60 ------- .../example/ui/dashpay/ShieldedTipFailure.kt | 24 --- .../example/ui/dashpay/ShieldedTipSheet.kt | 124 --------------- .../ui/dashpay/ShieldedTipSubmission.kt | 69 -------- .../SearchWalletsForIdentitiesScreen.kt | 15 -- .../ui/wallet/SendTransactionScreen.kt | 4 +- .../example/ui/wallet/WalletDetailScreen.kt | 4 +- .../ui/dashpay/ShieldedTipFailureTest.kt | 41 ----- .../ui/dashpay/ShieldedTipSubmissionTest.kt | 99 ------------ .../tokens/ShieldedTipRecipientHistory.kt | 40 ----- .../tokens/ShieldedTipRecipientHistoryTest.kt | 58 ------- .../PlatformWallet/ShieldedTipAmount.swift | 37 ----- .../ShieldedTipRecipientHistory.swift | 32 ---- .../Core/Services/ShieldedService.swift | 44 +----- .../Core/Views/CoreContentView.swift | 5 +- .../Core/Views/SendTransactionView.swift | 2 +- .../Core/Views/WalletDetailView.swift | 2 +- .../SwiftExampleApp/SwiftExampleAppApp.swift | 4 - .../Views/CreateIdentityView.swift | 2 +- .../Views/DashPay/DashPayProfileView.swift | 55 ------- .../Views/DashPay/DashPayTabView.swift | 149 +----------------- .../Views/DashPay/ShieldedTipSubmission.swift | 84 ---------- .../Views/IdentityDetailView.swift | 47 +----- .../SearchWalletsForIdentitiesView.swift | 15 +- .../ShieldedRebindRequestTests.swift | 30 ---- .../ShieldedTipSubmissionTests.swift | 98 ------------ .../DashPayPersistenceTests.swift | 18 --- .../ShieldedTipAmountTests.swift | 24 --- 31 files changed, 18 insertions(+), 1257 deletions(-) delete mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt delete mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt delete mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt delete mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt delete mode 100644 packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt delete mode 100644 packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt delete mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt delete mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift delete mode 100644 packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift delete mode 100644 packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift delete mode 100644 packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift delete mode 100644 packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedTipSubmissionTests.swift delete mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt index ca481c5d891..35b30f96085 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/di/AppContainer.kt @@ -35,9 +35,6 @@ class AppContainer(private val context: Context) { val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) - val shieldedTipSubmissions = - org.dashfoundation.example.ui.dashpay.ShieldedTipSubmissions(applicationScope) - val database: DashDatabase = DashDatabase.create(context) val dataStore = context.preferencesStore diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt index 274cdd57f01..cab86124046 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayJson.kt @@ -23,9 +23,6 @@ data class DashPayProfile( val displayName: String?, val publicMessage: String?, val avatarUrl: String?, - val corePaymentAddress: String? = null, - val platformPaymentAddress: String? = null, - val shieldedAddress: String? = null, ) /** Parse a `getProfile` / `getContactProfile` JSON object, or null. */ @@ -35,9 +32,6 @@ fun parseDashPayProfile(json: String?): DashPayProfile? { displayName = obj.optStringOrNull("displayName"), publicMessage = obj.optStringOrNull("publicMessage"), avatarUrl = obj.optStringOrNull("avatarUrl"), - corePaymentAddress = obj.optStringOrNull("corePaymentAddress"), - platformPaymentAddress = obj.optStringOrNull("platformPaymentAddress"), - shieldedAddress = obj.optStringOrNull("shieldedAddress"), ) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt index 0acd655662a..2f81559246e 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayProfileScreen.kt @@ -12,7 +12,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api @@ -40,20 +39,14 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController -import java.math.BigDecimal import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import org.dashfoundation.dashsdk.tokens.PaymentAddressUpdate import org.dashfoundation.example.di.LocalAppContainer import org.dashfoundation.example.ui.components.FormSection import org.dashfoundation.example.ui.components.LabeledContent import org.dashfoundation.example.ui.components.SubmitButton import org.dashfoundation.example.util.Base58 -import org.dashfoundation.example.util.DashAddress -import org.dashfoundation.example.util.DashAddressType import org.dashfoundation.example.util.generateQrBitmap import org.dashfoundation.example.util.hexToBytes @@ -79,27 +72,7 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController val walletId = identity?.walletId val wallet = remember(manager, walletId) { walletId?.let { manager?.wallet(forWalletId = it) } } - // Derived from the live identity's index, not Room's placeholder 0 (see DashPayTabScreen); - // Room's index is only a key so a discovery re-slot reruns the lookup. - val tipAccount by produceState(initialValue = null, wallet, manager, identityIdHex, identity?.identityIndex) { - value = wallet?.let { w -> - runCatching { w.identityIndex(idBytes)?.let { index -> manager?.shieldedTipAccountIndex(index) } } - .getOrNull() - } - } - // `null` when the tip account is unknown (no wallet, or the index lookup - // failed): that is not the same as an empty account. - val tipBalance by remember(walletId, tipAccount) { - val account = tipAccount - if (walletId == null || account == null) flowOf(null) - else container.database.shieldedDao().observeNotesByWalletAccount(walletId, account) - .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } - }.collectAsStateWithLifecycle(initialValue = null) - var profile by remember { mutableStateOf(null) } - val publishedTipAddress = profile?.shieldedAddress?.let { raw -> - manager?.let { m -> runCatching { DashAddress.encodeOrchard(raw.hexToBytes(), m.network) }.getOrNull() } - } var profileExists by remember { mutableStateOf(false) } var qrUri by remember { mutableStateOf(null) } var qrError by remember { mutableStateOf(null) } @@ -114,7 +87,6 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController var displayNameField by remember { mutableStateOf("") } var publicMessageField by remember { mutableStateOf("") } var avatarUrlField by remember { mutableStateOf("") } - var shieldedAddressField by remember { mutableStateOf("") } var isSaving by remember { mutableStateOf(false) } var saveError by remember { mutableStateOf(null) } @@ -160,7 +132,6 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController displayNameField = profile?.displayName.orEmpty() publicMessageField = profile?.publicMessage.orEmpty() avatarUrlField = profile?.avatarUrl.orEmpty() - shieldedAddressField = publishedTipAddress.orEmpty() saveError = null } isEditing = !isEditing @@ -201,31 +172,6 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController label = { Text("Avatar URL") }, singleLine = true, ) - TextButton(enabled = !isSaving && container.shieldedService.isAvailable, onClick = { - val m = manager ?: return@TextButton - val wid = walletId ?: return@TextButton - isSaving = true - saveError = null - scope.launch { - try { - shieldedAddressField = requireNotNull(DashAddress.encodeOrchard(m.prepareShieldedTipAddress(wid, idBytes), m.network)) - } catch (e: Exception) { - saveError = e.message ?: "Could not prepare tip account" - } finally { - isSaving = false - } - } - }, modifier = Modifier.testTag("dashpay.profile.useTipAccount")) { - Text("Use this wallet’s dedicated tip account") - } - Text("The address is published only when you save.", style = MaterialTheme.typography.bodySmall) - OutlinedTextField( - value = shieldedAddressField, - onValueChange = { shieldedAddressField = it }, - modifier = Modifier.fillMaxWidth().testTag("dashpay.profile.shieldedAddress"), - label = { Text("Shielded tip address") }, - supportingText = { Text("Paste an external receiving address, or leave blank to disable tips. External funds are managed by the receiving wallet.") }, - ) saveError?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) } @@ -248,15 +194,6 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController avatarUrl = avatarUrlField.trim().ifEmpty { null }, doCreate = !profileExists, signerHandle = m.signerHandle, - shieldedAddress = when (val address = shieldedAddressField.trim()) { - publishedTipAddress.orEmpty() -> PaymentAddressUpdate.Keep - "" -> PaymentAddressUpdate.Remove - else -> { - val parsed = DashAddress.parse(address, m.network) as? DashAddressType.Orchard - ?: throw IllegalArgumentException("Enter a shielded address for this network") - PaymentAddressUpdate.Set(parsed.raw43) - } - }, ) loadProfile() isEditing = false @@ -287,23 +224,6 @@ fun DashPayProfileScreen(identityIdHex: String, navController: NavHostController } } - if (!isEditing) { - FormSection(title = "Shielded tips") { - val balance = tipBalance - Text( - if (balance == null) "This wallet’s tip balance: unavailable" - else "This wallet’s tip balance: ${BigDecimal.valueOf(balance, 11).stripTrailingZeros().toPlainString()} DASH", - ) - val address = publishedTipAddress - if (address == null) { - Text("Tips are not enabled.") - } else { - SelectionContainer { Text(address, style = MaterialTheme.typography.bodySmall) } - Text("This receiving address is public and associated with your username. Removing it does not revoke previously shared copies.", style = MaterialTheme.typography.bodySmall) - } - } - } - FormSection(title = "Identity") { Text( Base58.encode(idBytes), diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt index f73e35df786..983beec2f0e 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/DashPayTabScreen.kt @@ -26,8 +26,6 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SheetValue -import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Scaffold import androidx.compose.material3.Text @@ -39,9 +37,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.produceState import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -163,7 +159,6 @@ fun DashPayTabScreen(navController: NavHostController) { val appUiState = container.appUiState var claimSheetUri by remember { mutableStateOf(null) } var showClaimSheet by remember { mutableStateOf(false) } - var showTipSheet by remember { mutableStateOf(false) } val pendingInvite by appUiState.pendingInviteUri.collectAsStateWithLifecycle() val claimInFlight by appUiState.invitationClaimInFlight.collectAsStateWithLifecycle() // The parked URI is NOT cleared at seeding: it stays in AppUiState (the @@ -325,62 +320,7 @@ fun DashPayTabScreen(navController: NavHostController) { onError = { unlockError = it }, ) - val tipManager = manager - val tipWalletId = identity.walletId - // The tip account follows the live identity's derivation index, not - // Room's non-null `identityIndex`: its 0 is a placeholder for an identity - // with no recoverable index and would alias identity 0's tip pool. - // produceState keeps its last value when its keys change, so each result - // is tagged with the inputs it was resolved for and a result for another - // identity or wallet is never offered while the new lookup runs. Room's - // index is only a key: discovery re-slotting a placeholder rewrites it. - val tipAccountKey = listOf(managed, tipManager, identityHex, identity.identityIndex) - val taggedTipAccount by produceState, Result>?>( - initialValue = null, managed, tipManager, identityHex, identity.identityIndex, - ) { - value = tipAccountKey to runCatching { - val index = requireNotNull(managed) { "Wallet is not loaded" } - .identityIndex(identity.identityId) - ?: error("Tip account requires a recoverable identity index") - requireNotNull(tipManager).shieldedTipAccountIndex(index) - } - } - val tipAccountResult = taggedTipAccount - ?.takeIf { (key, _) -> key == tipAccountKey } - ?.second - val tipAccount = tipAccountResult?.getOrNull() - val tipSubmission = tipWalletId?.let { - container.shieldedTipSubmissions.forWallet(network.ffiValue, it.toHex()) - } - val tipSending by rememberUpdatedState(tipSubmission?.busy == true) - val tipSheetState = rememberModalBottomSheetState( - confirmValueChange = { value -> value != SheetValue.Hidden || !tipSending }, - ) - if (showTipSheet && managed != null && tipManager != null && tipWalletId != null && tipAccount != null && tipSubmission != null) { - ModalBottomSheet( - sheetState = tipSheetState, - onDismissRequest = { if (!tipSubmission.busy) showTipSheet = false }, - ) { - ShieldedTipSheet(tipManager, managed, tipWalletId, tipAccount, tipSubmission) - } - } FormSection(title = "DashPay") { - if (container.shieldedService.isAvailable) { - EntityRow( - icon = Icons.AutoMirrored.Filled.Send, - title = "Send shielded tip", - onClick = { - when (val result = tipAccountResult) { - null -> unlockError = "The tip account is still loading" - else -> result.fold( - onSuccess = { showTipSheet = true }, - onFailure = { unlockError = it.message ?: "Could not open shielded tips" }, - ) - } - }, - modifier = Modifier.testTag("dashpay.sendShieldedTip"), - ) - } EntityRow( icon = Icons.Default.Group, title = "Contacts", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt deleted file mode 100644 index e21e1ca8522..00000000000 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailure.kt +++ /dev/null @@ -1,24 +0,0 @@ -package org.dashfoundation.example.ui.dashpay - -import org.dashfoundation.dashsdk.errors.DashSdkError - -/** - * Permit a fresh user review only for failures known not to have executed a tip. - * On the tip path, Rust maps selection/build/recipient-check failures to - * WalletOperation. Broadcast ambiguity maps to ShieldedSpendUnconfirmed, and - * successful post-broadcast bookkeeping is best-effort (never WalletOperation). - * Unknown exceptions, including JNI failures and cancellation, remain locked. - */ -internal fun canReviewShieldedTipAfterFailure(error: Exception): Boolean = when (error) { - is IllegalArgumentException, - is DashSdkError.InvalidParameter, - is DashSdkError.PlatformWallet.InvalidHandle, - is DashSdkError.PlatformWallet.NotFound, - is DashSdkError.PlatformWallet.SigningKeyUnavailable, - is DashSdkError.PlatformWallet.WalletOperation, - is DashSdkError.PlatformWallet.ShieldedNoRecordedAnchor, - is DashSdkError.PlatformWallet.ShieldedBroadcastFailed -> true - // ErrorInvalidParameter is a preflight-only FFI failure on this call path. - is DashSdkError.PlatformWallet.Generic -> error.nativeCode == 2 - else -> false -} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt deleted file mode 100644 index e5dcf37fdd7..00000000000 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSheet.kt +++ /dev/null @@ -1,124 +0,0 @@ -package org.dashfoundation.example.ui.dashpay - -import android.content.Context -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Checkbox -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.unit.dp -import java.math.BigDecimal -import kotlinx.coroutines.launch -import org.dashfoundation.dashsdk.tokens.ShieldedTipRecipient -import org.dashfoundation.dashsdk.tokens.ShieldedTipRecipientHistory -import org.dashfoundation.dashsdk.wallet.ManagedPlatformWallet -import org.dashfoundation.dashsdk.wallet.PlatformWalletManager -import org.dashfoundation.example.ui.components.SubmitButton -import org.dashfoundation.example.util.Base58 -import org.dashfoundation.example.util.DashAddress - -/** Username tipping uses the same verified recipient and confirmation boundary as Swift. */ -@Composable -fun ShieldedTipSheet(manager: PlatformWalletManager, wallet: ManagedPlatformWallet, walletId: ByteArray, tipAccount: Int, submission: ShieldedTipSubmission) { - val scope = rememberCoroutineScope() - val context = LocalContext.current - val history = remember(context) { - ShieldedTipRecipientHistory(context.getSharedPreferences("dashpay.tipRecipients", Context.MODE_PRIVATE)) - } - var changedRecipient by remember { mutableStateOf(null) } - var username by remember { mutableStateOf("") } - var amount by remember { mutableStateOf("") } - var recipient by remember { mutableStateOf(null) } - var confirmedAmount by remember { mutableStateOf(null) } - var resolving by remember { mutableStateOf(false) } - val busy = resolving || submission.busy - val submitted = submission.submitted - var spendTips by remember { mutableStateOf(false) } - var message by remember { mutableStateOf(null) } - - changedRecipient?.let { changed -> - AlertDialog( - onDismissRequest = { changedRecipient = null }, - title = { Text("Tip recipient changed") }, - text = { Text("The identity or shielded address for this username differs from your previous confirmation. Verify the change with the recipient before continuing.") }, - confirmButton = { - TextButton(onClick = { recipient = changed; changedRecipient = null }) { Text("Review new recipient") } - }, - dismissButton = { - TextButton(onClick = { changedRecipient = null }) { Text("Cancel") } - }, - ) - } - - Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Send a shielded tip") - OutlinedTextField(username, { username = it; recipient = null }, label = { Text("Username") }, enabled = !busy && !submitted) - OutlinedTextField(amount, { amount = it; recipient = null }, label = { Text("Amount (DASH)") }, enabled = !busy && !submitted) - Row { - Checkbox(checked = spendTips, enabled = !busy && !submitted, - onCheckedChange = { spendTips = it; recipient = null }) - Text("Spend from my dedicated tip account") - } - recipient?.let { - Text("Recipient: ${Base58.encode(it.identityId)}") - DashAddress.encodeOrchard(it.address, manager.network)?.let { address -> - SelectionContainer { Text(address) } - } - Text("Send $amount DASH from your ${if (spendTips) "tip" else "main shielded"} account to $username?") - } - (message ?: submission.message)?.let { Text(it) } - if (submission.status == ShieldedTipSubmission.Status.Sent) { - TextButton(onClick = { submission.startNewTip() }) { Text("Start a new tip") } - } - SubmitButton( - text = if (recipient == null) "Review tip" else "Confirm and send", - isLoading = busy, enabled = !busy && !submitted && changedRecipient == null, modifier = Modifier.fillMaxWidth(), - ) { - val selected = recipient - if (selected != null) { - val sendUsername = username.trim() - val sendAmount = requireNotNull(confirmedAmount) - val sendAccount = if (spendTips) tipAccount else 0 - recipient = null - submission.submit( - beforeSend = { history.confirm(manager.network, walletId, sendUsername, selected) }, - ) { - manager.sendShieldedTip(walletId, sendUsername, selected, sendAmount, account = sendAccount) - } - } else { - resolving = true - message = null - scope.launch { - try { - val credits = BigDecimal(amount.trim()).movePointRight(11).longValueExact() - require(credits > 0) { "Enter a positive amount" } - confirmedAmount = credits - val resolved = wallet.dashpay.resolveShieldedTip(username.trim()) - if (history.hasChanged(manager.network, walletId, username, resolved)) { - changedRecipient = resolved - } else { - recipient = resolved - } - } catch (e: Exception) { - message = e.message ?: "Unable to review tip" - recipient = null - } finally { resolving = false } - } - } - } - } -} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt deleted file mode 100644 index 78480f6a014..00000000000 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmission.kt +++ /dev/null @@ -1,69 +0,0 @@ -package org.dashfoundation.example.ui.dashpay - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.launch - -/** Application-owned submissions survive sheet dismissal, navigation and activity recreation. */ -class ShieldedTipSubmissions(private val scope: CoroutineScope) { - private val wallets = mutableMapOf() - - /** Called on the main thread; one guard per network/wallet, across all of its identities. */ - fun forWallet(network: Int, walletId: String): ShieldedTipSubmission = - wallets.getOrPut("$network:$walletId") { ShieldedTipSubmission(scope) } -} - -/** Main-thread state. A cancelled UI must never imply that blocking JNI stopped broadcasting. */ -class ShieldedTipSubmission(private val scope: CoroutineScope) { - enum class Status { Ready, Sending, Sent, Uncertain } - - var status by mutableStateOf(Status.Ready) - private set - var message by mutableStateOf(null) - private set - val busy: Boolean get() = status == Status.Sending - val submitted: Boolean get() = status != Status.Ready - - /** - * [beforeSend] runs first and moves no funds, so its failure returns the - * submission to review; only a [send] failure can leave the outcome unknown. - */ - fun submit(beforeSend: suspend () -> Unit = {}, send: suspend () -> Unit) { - if (submitted) return - // Lock synchronously, before launching, so two UI events cannot submit twice. - status = Status.Sending - message = null - scope.launch { - try { - beforeSend() - } catch (error: Exception) { - status = Status.Ready - message = error.message ?: "Unable to send tip" - if (error is kotlinx.coroutines.CancellationException) throw error - return@launch - } - try { - send() - status = Status.Sent - message = "Shielded tip sent." - } catch (error: Exception) { - status = if (canReviewShieldedTipAfterFailure(error)) Status.Ready else Status.Uncertain - message = if (status == Status.Uncertain) { - "The tip may have been sent. Check shielded activity before sending again. ${error.message.orEmpty()}" - } else { - error.message ?: "Unable to send tip" - } - if (error is kotlinx.coroutines.CancellationException) throw error - } - } - } - - /** Starting another payment requires an explicit action after a confirmed successful return. */ - fun startNewTip() { - if (status != Status.Sent) return - status = Status.Ready - message = null - } -} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt index 631cb2a6d24..a92013c0bd8 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/identity/SearchWalletsForIdentitiesScreen.kt @@ -140,21 +140,6 @@ fun SearchWalletsForIdentitiesScreen(navController: NavHostController) { walletHandle = wallet.handle, mnemonicResolverHandle = mgr.mnemonicResolverHandle, ) - // Rebind after every successful scan, not only when new ids - // came back: discovery can also promote an already-known - // identity into its verified slot (not reported in `found`), - // and its dedicated tip account needs registering too. - // Rust adds tip accounts itself, so the default [0] request - // suffices; a bind failure stays non-fatal. - if (container.shieldedService.isAvailable) { - try { - mgr.bindShielded(wallet.walletId) - } catch (error: kotlinx.coroutines.CancellationException) { - throw error - } catch (error: Exception) { - android.util.Log.w("IdentityDiscovery", "Identities found; shielded bind failed", error) - } - } summary = "Found ${found.size} identity(ies)." if (found.isEmpty()) { previewPaths = mgr.identityRegistration.previewRegistrationKeys( diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt index 6bf60e9c40c..e1c133c12f2 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt @@ -197,8 +197,8 @@ fun SendTransactionScreen( val hasShielded = remember { Sdk.hasShielded() } val shieldedBalance by remember(walletIdHex) { if (hasShielded) { - container.database.shieldedDao().observeNotesByWalletAccount(walletId, 0) - .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } + container.database.shieldedDao().observeUnspentNotesByWallet(walletId) + .map { notes -> notes.sumOf { it.value } } } else { MutableStateFlow(0L) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt index 1ea3555b1b0..50b42461858 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/WalletDetailScreen.kt @@ -129,8 +129,8 @@ fun WalletDetailScreen( val hasShielded = remember { Sdk.hasShielded() } val shieldedBalance by remember(walletIdHex) { if (hasShielded) { - container.database.shieldedDao().observeNotesByWalletAccount(walletId, 0) - .map { notes -> notes.filter { !it.isSpent }.sumOf { it.value } } + container.database.shieldedDao().observeUnspentNotesByWallet(walletId) + .map { notes -> notes.sumOf { it.value } } } else { MutableStateFlow(0L) } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt deleted file mode 100644 index a75fc08352e..00000000000 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipFailureTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -package org.dashfoundation.example.ui.dashpay - -import java.util.concurrent.CancellationException -import org.dashfoundation.dashsdk.errors.DashSdkError -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class ShieldedTipFailureTest { - @Test - fun permitsFreshReviewAfterDefinitiveFailures() { - val errors = listOf( - IllegalArgumentException("amount must be positive"), - DashSdkError.InvalidParameter("invalid account"), - DashSdkError.PlatformWallet.Generic(2, "invalid memo"), - DashSdkError.PlatformWallet.InvalidHandle("closed"), - DashSdkError.PlatformWallet.NotFound("wallet removed"), - DashSdkError.PlatformWallet.SigningKeyUnavailable("unlock wallet"), - DashSdkError.PlatformWallet.WalletOperation("The tip recipient changed; review and confirm again"), - DashSdkError.PlatformWallet.WalletOperation("insufficient notes"), - DashSdkError.PlatformWallet.ShieldedNoRecordedAnchor("sync first"), - DashSdkError.PlatformWallet.ShieldedBroadcastFailed("consensus rejected"), - ) - errors.forEach { assertTrue(it.toString(), canReviewShieldedTipAfterFailure(it)) } - } - - @Test - fun retainsLockForAmbiguousAndUnclassifiedOutcomes() { - val errors = listOf( - DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed("no result proof"), - DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed("no relay verdict"), - DashSdkError.Timeout("timed out"), - DashSdkError.NetworkError("connection lost"), - DashSdkError.PlatformWallet.Generic(999, "unknown native error"), - RuntimeException("JNI failure"), - CancellationException("cancelled"), - IllegalStateException("unexpected state"), - ) - errors.forEach { assertFalse(it.toString(), canReviewShieldedTipAfterFailure(it)) } - } -} diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt deleted file mode 100644 index 5cbe8a48e19..00000000000 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/dashpay/ShieldedTipSubmissionTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -package org.dashfoundation.example.ui.dashpay - -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.test.runCurrent -import kotlinx.coroutines.test.runTest -import kotlinx.coroutines.ExperimentalCoroutinesApi -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertSame -import org.junit.Assert.assertTrue -import org.junit.Test - -@OptIn(ExperimentalCoroutinesApi::class) -class ShieldedTipSubmissionTest { - @Test - fun dismissAndReopenCannotSubmitAgainWhileNativeSendRuns() = runTest { - val submissions = ShieldedTipSubmissions(backgroundScope) - val payment = submissions.forWallet(1, "wallet") - val nativeFinished = CompletableDeferred() - var sends = 0 - payment.submit { sends++; nativeFinished.await() } - assertTrue(payment.busy) - // Even a second click before the first coroutine starts is ignored. - payment.submit { sends++ } - runCurrent() - val sheetScope = CoroutineScope(coroutineContext + SupervisorJob()) - sheetScope.cancel() - val reopened = submissions.forWallet(1, "wallet") - assertSame(payment, reopened) - reopened.submit { sends++ } - assertEquals(1, sends) - nativeFinished.complete(Unit) - runCurrent() - assertEquals(ShieldedTipSubmission.Status.Sent, reopened.status) - assertFalse(reopened.busy) - reopened.submit { sends++ } - runCurrent() - assertEquals(1, sends) - reopened.startNewTip() - reopened.submit { sends++ } - runCurrent() - assertEquals(2, sends) - } - - @Test - fun uncertainOutcomeStaysLockedAcrossReopeningAndNewTipAction() = runTest { - val submissions = ShieldedTipSubmissions(backgroundScope) - val payment = submissions.forWallet(1, "wallet") - payment.submit { throw IllegalStateException("JNI outcome lost") } - runCurrent() - val reopened = submissions.forWallet(1, "wallet") - assertEquals(ShieldedTipSubmission.Status.Uncertain, reopened.status) - reopened.startNewTip() - var retried = false - reopened.submit { retried = true } - runCurrent() - assertFalse(retried) - assertTrue(reopened.submitted) - assertFalse(reopened.busy) - } - - @Test - fun definitivePreflightFailureAllowsFreshReview() = runTest { - val payment = ShieldedTipSubmission(backgroundScope) - payment.submit { throw IllegalArgumentException("invalid amount") } - runCurrent() - assertEquals(ShieldedTipSubmission.Status.Ready, payment.status) - assertEquals("invalid amount", payment.message) - var retried = false - payment.submit { retried = true } - runCurrent() - assertTrue(retried) - } - - @Test - fun beforeSendFailureAllowsFreshReviewWithoutSending() = runTest { - val payment = ShieldedTipSubmission(backgroundScope) - var sends = 0 - payment.submit(beforeSend = { throw IllegalStateException("history write failed") }) { sends++ } - runCurrent() - assertEquals(ShieldedTipSubmission.Status.Ready, payment.status) - assertEquals("history write failed", payment.message) - assertEquals(0, sends) - payment.submit { sends++ } - runCurrent() - assertEquals(1, sends) - } - - @Test - fun walletAndNetworkGuardsAreIndependent() = runTest { - val submissions = ShieldedTipSubmissions(backgroundScope) - submissions.forWallet(1, "a").submit { } - assertFalse(submissions.forWallet(2, "a").submitted) - assertFalse(submissions.forWallet(1, "b").submitted) - } -} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt deleted file mode 100644 index ad29af2cf00..00000000000 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistory.kt +++ /dev/null @@ -1,40 +0,0 @@ -package org.dashfoundation.dashsdk.tokens - -import android.content.SharedPreferences -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import org.dashfoundation.dashsdk.Network -import org.dashfoundation.dashsdk.persistence.normalizeDpnsLabel - -/** - * Local record of recipients explicitly confirmed by this wallet's user. - * Mirrors the Swift tip sheet's persistent recipient-change warning. This - * record only informs confirmation; Rust still verifies the recipient before sending. - */ -class ShieldedTipRecipientHistory(private val preferences: SharedPreferences) { - fun hasChanged( - network: Network, walletId: ByteArray, username: String, recipient: ShieldedTipRecipient, - ): Boolean { - val previous = preferences.getString(key(network, walletId, username), null) ?: return false - return previous != snapshot(recipient) - } - - /** Call only after explicit confirmation, before submitting the payment. */ - suspend fun confirm( - network: Network, walletId: ByteArray, username: String, recipient: ShieldedTipRecipient, - ) = withContext(Dispatchers.IO) { - check(preferences.edit().putString(key(network, walletId, username), snapshot(recipient)).commit()) { - "Could not save recipient confirmation" - } - } - - private fun key(network: Network, walletId: ByteArray, username: String): String { - val label = username.trim().lowercase().removeSuffix(".dash") - return "${network.ffiValue}:${walletId.hex()}:${normalizeDpnsLabel(label)}.dash" - } - - private fun snapshot(recipient: ShieldedTipRecipient): String = - "${recipient.identityId.hex()}:${recipient.address.hex()}" - - private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) } -} diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt deleted file mode 100644 index a5ebd51c380..00000000000 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipientHistoryTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -package org.dashfoundation.dashsdk.tokens - -import android.content.Context -import androidx.test.core.app.ApplicationProvider -import kotlinx.coroutines.test.runTest -import org.dashfoundation.dashsdk.Network -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner - -@RunWith(RobolectricTestRunner::class) -class ShieldedTipRecipientHistoryTest { - private val preferences = ApplicationProvider.getApplicationContext() - .getSharedPreferences("tip-recipient-history-test", Context.MODE_PRIVATE) - private val walletId = ByteArray(32) { 1 } - private val recipient = ShieldedTipRecipient(ByteArray(32) { 2 }, ByteArray(43) { 3 }) - private val history get() = ShieldedTipRecipientHistory(preferences) - - @Before - fun reset() { - preferences.edit().clear().commit() - } - - @Test - fun confirmationSurvivesReopeningAndCanonicalSpellings() = runTest { - assertFalse(history.hasChanged(Network.TESTNET, walletId, "Alice", recipient)) - history.confirm(Network.TESTNET, walletId, " Alice.DASH ", recipient) - assertFalse(history.hasChanged(Network.TESTNET, walletId, "a11ce", recipient)) - val changed = ShieldedTipRecipient(recipient.identityId, ByteArray(43) { 4 }) - assertTrue(history.hasChanged(Network.TESTNET, walletId, "a11ce.dash", changed)) - } - - @Test - fun detectsBothIdentityAndAddressReplacementWithoutChangingThePin() = runTest { - history.confirm(Network.TESTNET, walletId, "Alice", recipient) - val newIdentity = ShieldedTipRecipient(ByteArray(32) { 4 }, recipient.address) - val newAddress = ShieldedTipRecipient(recipient.identityId, ByteArray(43) { 5 }) - assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", newIdentity)) - assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", newAddress)) - assertFalse(history.hasChanged(Network.TESTNET, walletId, "Alice", recipient)) - history.confirm(Network.TESTNET, walletId, "Alice", newAddress) - assertFalse(history.hasChanged(Network.TESTNET, walletId, "Alice", newAddress)) - assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", recipient)) - } - - @Test - fun isolatesNetworksWalletsAndUsernames() = runTest { - history.confirm(Network.TESTNET, walletId, "Alice", recipient) - val changed = ShieldedTipRecipient(ByteArray(32) { 4 }, recipient.address) - assertFalse(history.hasChanged(Network.MAINNET, walletId, "Alice", changed)) - assertFalse(history.hasChanged(Network.TESTNET, ByteArray(32) { 6 }, "Alice", changed)) - assertFalse(history.hasChanged(Network.TESTNET, walletId, "Bob", changed)) - assertTrue(history.hasChanged(Network.TESTNET, walletId, "Alice", changed)) - } -} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift deleted file mode 100644 index 8485728a627..00000000000 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipAmount.swift +++ /dev/null @@ -1,37 +0,0 @@ -import Foundation - -/// An exact positive DASH amount. Input uses ASCII digits and a period decimal -/// separator, without grouping, signs, or exponent notation. Unsupported locale -/// separators are rejected rather than partially parsed by Foundation. -public struct ShieldedTipAmount: Equatable, Sendable { - public let credits: UInt64 - - public init?(_ input: String) { - let parts = input.split(separator: ".", omittingEmptySubsequences: false) - guard (1...2).contains(parts.count), - !parts[0].isEmpty, - parts.allSatisfy({ !$0.isEmpty && $0.utf8.allSatisfy { (48...57).contains($0) } }), - let whole = UInt64(parts[0]) else { return nil } - let fraction = parts.count == 2 ? String(parts[1]) : "" - // Additional trailing zeros are exact and safe; extra nonzero digits - // would represent a fraction of a credit. - guard fraction.dropFirst(11).allSatisfy({ $0 == "0" }) else { return nil } - let digits = String(fraction.prefix(11)) - let fractionalCredits = UInt64(digits + String(repeating: "0", count: 11 - digits.count))! - let (integralCredits, overflow) = whole.multipliedReportingOverflow(by: 100_000_000_000) - let (credits, additionOverflow) = integralCredits.addingReportingOverflow(fractionalCredits) - guard !overflow, !additionOverflow, credits > 0 else { return nil } - self.credits = credits - } - - /// Canonical confirmation text derived from the exact amount sent. - public var dashString: String { - let whole = credits / 100_000_000_000 - let fraction = credits % 100_000_000_000 - guard fraction != 0 else { return String(whole) } - var digits = String(fraction) - digits = String(repeating: "0", count: 11 - digits.count) + digits - while digits.last == "0" { digits.removeLast() } - return "\(whole).\(digits)" - } -} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift deleted file mode 100644 index 29bec556b03..00000000000 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ShieldedTipRecipientHistory.swift +++ /dev/null @@ -1,32 +0,0 @@ -import Foundation - -/// Local confirmation history. This is a change warning, never an authorization -/// to pay: `sendShieldedTip` still verifies the confirmed destination on Platform. -public final class ShieldedTipRecipientHistory { - private let defaults: UserDefaults - - public init(defaults: UserDefaults = .standard) { - self.defaults = defaults - } - - public func hasChanged(network: Network, walletId: Data, username: String, - recipient: ShieldedTipRecipient) -> Bool { - guard let previous = defaults.data(forKey: key(network: network, walletId: walletId, username: username)) else { - return false - } - return previous != recipient.identityId + recipient.address - } - - /// Call only after the user explicitly confirms, including any change warning. - public func confirm(network: Network, walletId: Data, username: String, - recipient: ShieldedTipRecipient) { - defaults.set(recipient.identityId + recipient.address, - forKey: key(network: network, walletId: walletId, username: username)) - } - - private func key(network: Network, walletId: Data, username: String) -> String { - let name = PersistentDPNSName.normalize(username.trimmingCharacters(in: .whitespacesAndNewlines)) - let canonical = name.hasSuffix(".dash") ? name : name + ".dash" - return "dashpay.tipRecipient.\(network.rawValue).\(walletId.toBase58String()).\(canonical)" - } -} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift index 61c6b393ed8..d76f2fe1745 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Services/ShieldedService.swift @@ -185,42 +185,6 @@ class ShieldedService: ObservableObject { // MARK: - Lifecycle - /// The accounts to request when rebinding from a native snapshot: only the - /// ordinary ones, defaulting to `[0]`. The snapshot also lists the dedicated - /// tip accounts Rust binds on its own (discovered and retired ones); echoing - /// them back could exceed the 64-entry bind request cap and stop later - /// discovery from registering new accounts. - static func ordinaryBindRequest(_ snapshot: [UInt32]) -> [UInt32] { - let ordinary = snapshot.filter { !PlatformWalletManager.isShieldedTipAccount($0) } - return ordinary.isEmpty ? [0] : ordinary - } - - /// Re-register newly discovered identity accounts while retaining the engine's - /// existing ordinary accounts. Binding remains independent of discovery success. - @discardableResult - func rebindAfterIdentityDiscovery( - walletManager: PlatformWalletManager, - walletId: Data, - network: Network, - resolver: MnemonicResolver - ) -> Bool { - let existing: [UInt32] - do { - existing = try walletManager.shieldedAccountIndices(walletId: walletId) - } catch { - lastError = error.localizedDescription - return false - } - let accounts = Self.ordinaryBindRequest(existing) - if boundWalletId == walletId || boundWalletId == nil { - bind(walletManager: walletManager, walletId: walletId, network: network, - resolver: resolver, accounts: accounts) - return isBound - } - return bindEngine(walletManager: walletManager, walletId: walletId, network: network, - resolver: resolver, accounts: accounts) - } - /// Bind the service to a wallet. Drives `bindShielded` on the /// Rust side first (resolver-driven mnemonic lookup, ZIP-32 /// derivation per `accounts`, per-network commitment tree @@ -310,15 +274,15 @@ class ShieldedService: ObservableObject { resolver: resolver, accounts: sortedAccounts ) - boundAccounts = try walletManager.shieldedAccountIndices(walletId: walletId) isBound = true lastError = nil + boundAccounts = sortedAccounts // Populate per-account default addresses. Best-effort — // a failure on any one account leaves that entry // missing from `addressesByAccount` (the row in the UI // shows blank) but doesn't unbind the wallet. - for account in boundAccounts { + for account in sortedAccounts { if let raw = try? walletManager.shieldedDefaultAddress( walletId: walletId, account: account @@ -333,7 +297,7 @@ class ShieldedService: ObservableObject { // the existing Receive sheet which only renders one // address. Use account 0 if bound, else the lowest // bound account. - let primary = boundAccounts.contains(0) ? 0 : (boundAccounts.first ?? 0) + let primary = sortedAccounts.contains(0) ? 0 : (sortedAccounts.first ?? 0) orchardDisplayAddress = addressesByAccount[primary] SDKLogger.event( @@ -585,7 +549,7 @@ class ShieldedService: ObservableObject { let resolver, let network else { return } - let accounts = Self.ordinaryBindRequest(boundAccounts) + let accounts = boundAccounts.isEmpty ? [0] : boundAccounts bind( walletManager: walletManager, walletId: walletId, diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift index 1ecdbf477dd..4c7bfa7282a 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/CoreContentView.swift @@ -1153,7 +1153,7 @@ struct WalletRowView: View { /// as `platformBalance` (1e11 credits/DASH), so it folds into /// the same divisor in [`combinedDashAmount(coreTotal:)`]. private var shieldedBalance: UInt64 { - shieldedNotes.filter { !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) }.reduce(UInt64(0)) { $0 + $1.value } + shieldedNotes.reduce(UInt64(0)) { $0 + $1.value } } /// Combined wallet balance expressed in DASH for a precomputed @@ -1535,8 +1535,7 @@ private struct ShieldedNetworkSummaryRows: View { /// Sum of `value` over this network's unspent notes, in credits. private var totalUnspentCredits: UInt64 { allNotes.lazy - .filter { !$0.isSpent && walletIds.contains($0.walletId) - && !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) } + .filter { !$0.isSpent && walletIds.contains($0.walletId) } .reduce(UInt64(0)) { $0 &+ $1.value } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift index c543bc43064..de48fdf33bb 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift @@ -493,7 +493,7 @@ struct SendTransactionView: View { /// send source is correct for a non-`firstWallet` wallet whose /// engine binding is live but whose UI mirror is pointed elsewhere. private var shieldedBalance: UInt64 { - shieldedNotes.filter { !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) }.reduce(0) { $0 + $1.value } + shieldedNotes.reduce(0) { $0 + $1.value } } /// Mirrors `WalletDetailView.platformBalance`: BLAST-synced diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift index b740c66c18e..9d99c593782 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/WalletDetailView.swift @@ -1047,7 +1047,7 @@ struct BalanceCardView: View { /// non-`firstWallet` wallet whose engine binding is live but whose UI /// mirror is pointed elsewhere. private var shieldedBalance: UInt64 { - shieldedNotes.filter { !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) }.reduce(0) { $0 + $1.value } + shieldedNotes.reduce(0) { $0 + $1.value } } /// Core-chain balance summed from one Rust in-memory account snapshot. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift index 53324c0895a..8e2f7a06862 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/SwiftExampleAppApp.swift @@ -60,9 +60,6 @@ struct SwiftExampleAppApp: App { @StateObject private var platformBalanceSyncService = PlatformBalanceSyncService() @StateObject private var transitionState = TransitionState() @StateObject private var appUIState = AppUIState() - // Shielded tip sends outlive the sheet that starts them (see - // `ShieldedTipSubmissions`), so their state is owned here. - @StateObject private var shieldedTipSubmissions = ShieldedTipSubmissions() /// Current manager exposed to views via the env object pipeline. /// Reads from the published `activeManager` on every body @@ -153,7 +150,6 @@ struct SwiftExampleAppApp: App { .environmentObject(platformBalanceSyncService) .environmentObject(transitionState) .environmentObject(appUIState) - .environmentObject(shieldedTipSubmissions) .environment(\.modelContext, modelContainer.mainContext) .onOpenURL { url in // DashPay invitation deep link: route to the DashPay tab and diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift index 7e018e5cee0..5c5d8974477 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift @@ -1834,7 +1834,7 @@ struct CreateIdentityView: View { /// FetchDescriptor round-trip. private func shieldedPoolBalance(for walletId: Data) -> UInt64 { unspentShieldedNotes - .filter { $0.walletId == walletId && !PlatformWalletManager.isShieldedTipAccount($0.accountIndex) } + .filter { $0.walletId == walletId } .reduce(0) { $0 + $1.value } } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift index e38d34863b6..9b3dc6e3e8d 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayProfileView.swift @@ -1,7 +1,6 @@ import CoreImage.CIFilterBuiltins import SwiftDashSDK import SwiftUI -import SwiftData /// Read-only DashPay profile sheet, promoted out of /// `IdentityDetailView`'s inline card: large avatar, display name, @@ -20,38 +19,6 @@ struct DashPayProfileView: View { @State private var qrImage: UIImage? @State private var qrURI: String? @State private var qrError: String? - @State private var showSpendTips = false - @Query private var shieldedNotes: [PersistentShieldedNote] - - init(identity: PersistentIdentity, profile: DashPayProfile?, onEdit: @escaping () -> Void) { - self.identity = identity - self.profile = profile - self.onEdit = onEdit - if let walletId = identity.wallet?.walletId { - _shieldedNotes = Query(filter: PersistentShieldedNote.unspentPredicate(walletId: walletId)) - } else { - _shieldedNotes = Query(filter: #Predicate { _ in false }) - } - } - - /// The persisted row uses zero as a historical placeholder. Only Rust's - /// optional derivation metadata can distinguish that from a real index zero. - private var tipAccount: UInt32? { - guard let walletId = identity.wallet?.walletId, - let wallet = walletManager.wallet(for: walletId), - let managed = try? wallet.managedIdentity(identityId: identity.identityId), - let index = try? managed.getIdentityIndex() else { return nil } - return try? PlatformWalletManager.shieldedTipAccountIndex(identityIndex: index) - } - - /// `nil` when the tip account is unknown (no wallet, or the index lookup - /// failed): that is not the same as an empty account. - private var tipBalance: UInt64? { - guard let walletId = identity.wallet?.walletId, - let account = tipAccount else { return nil } - return shieldedNotes.filter { $0.walletId == walletId && $0.accountIndex == account && !$0.isSpent } - .reduce(UInt64(0)) { $0 &+ $1.value } - } private var displayName: String { if let name = profile?.displayName? @@ -97,22 +64,6 @@ struct DashPayProfileView: View { .listRowBackground(Color.clear) } - Section("Shielded tips") { - if let address = profile?.shieldedAddress, - let display = DashAddress.encodeOrchard(rawBytes: address, network: identity.network) { - Text(display).font(.caption).textSelection(.enabled) - } else { - Text("No tip address published") - } - Text(tipBalance.map { - "Dedicated account balance: \(NSDecimalNumber(decimal: Decimal($0) / 100_000_000_000).stringValue) DASH" - } ?? "Dedicated account balance: unavailable") - .font(.caption) - Button("Send from dedicated tip account") { showSpendTips = true } - .disabled((tipBalance ?? 0) == 0) - Text("An external receiving address is managed by its own wallet.").font(.caption).foregroundStyle(.secondary) - } - Section("Identity") { Text(identity.identityIdBase58) .font(.caption) @@ -173,12 +124,6 @@ struct DashPayProfileView: View { } } } - .sheet(isPresented: $showSpendTips) { - if let walletId = identity.wallet?.walletId, - let account = tipAccount { - SendShieldedTipSheet(walletId: walletId, account: account, sourceLabel: "dedicated tip account") - } - } .navigationTitle("Your Profile") .navigationBarTitleDisplayMode(.inline) .toolbar { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift index f58bdcc6b6b..e7855efb305 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/DashPayTabView.swift @@ -33,7 +33,6 @@ struct DashPayTabView: View { @State private var segment: DashPaySegment = .contacts @State private var showAddContact = false - @State private var showShieldedTip = false @State private var showAddViaQR = false /// Drives the claim sheet via `.sheet(item:)`. A fresh value (new `id`) @@ -163,11 +162,6 @@ struct DashPayTabView: View { content .navigationTitle("DashPay") .toolbar { - ToolbarItem(placement: .navigationBarTrailing) { - Button { showShieldedTip = true } label: { Image(systemName: "gift") } - .accessibilityLabel("Send shielded tip") - .disabled(walletManager.firstWallet == nil) - } ToolbarItem(placement: .navigationBarTrailing) { Button { refresh() @@ -248,11 +242,6 @@ struct DashPayTabView: View { } } } - .sheet(isPresented: $showShieldedTip) { - if let walletId = activeIdentity?.wallet?.walletId ?? walletManager.firstWallet?.walletId { - SendShieldedTipSheet(walletId: walletId) - } - } .sheet(isPresented: $showAddViaQR) { if let identity = activeIdentity { AddViaQRSheet(identity: identity) @@ -829,10 +818,7 @@ struct DashPayTabView: View { publicMessage: persisted.publicMessage, avatarUrl: persisted.avatarUrl, avatarHash: persisted.avatarHash, - avatarFingerprint: persisted.avatarFingerprint, - corePaymentAddress: persisted.corePaymentAddress, - platformPaymentAddress: persisted.platformPaymentAddress, - shieldedAddress: persisted.shieldedAddress + avatarFingerprint: persisted.avatarFingerprint ) } } @@ -1033,136 +1019,3 @@ private struct AddViaQRSheet: View { } } } - -/// Resolve first, then explicitly confirm the identity, address, and amount. -/// The send itself is owned by the app-wide `ShieldedTipSubmissions`, so a -/// dismissed or reopened sheet finds the same in-flight or uncertain state -/// instead of a fresh, unlocked one. -struct SendShieldedTipSheet: View { - let walletId: Data - var account: UInt32 = 0 - var sourceLabel: String = "ordinary shielded account" - @EnvironmentObject private var submissions: ShieldedTipSubmissions - @EnvironmentObject private var appState: AppState - - var body: some View { - SendShieldedTipSheetContent( - walletId: walletId, account: account, sourceLabel: sourceLabel, - submission: submissions.forWallet(network: appState.currentNetwork, walletId: walletId)) - } -} - -private struct SendShieldedTipSheetContent: View { - let walletId: Data - let account: UInt32 - let sourceLabel: String - @ObservedObject var submission: ShieldedTipSubmission - @EnvironmentObject private var walletManager: PlatformWalletManager - @EnvironmentObject private var appState: AppState - @Environment(\.dismiss) private var dismiss - @State private var username = "" - @State private var amount = "" - @State private var recipient: ShieldedTipRecipient? - @State private var resolving = false - @State private var error: String? - @State private var showRecipientChanged = false - - private var tipAmount: ShieldedTipAmount? { ShieldedTipAmount(amount) } - private var credits: UInt64? { tipAmount?.credits } - /// Recipient resolution is sheet-local; the send lock is the shared submission. - private var busy: Bool { resolving || submission.busy } - private var submitted: Bool { submission.submitted } - - var body: some View { - NavigationStack { - Form { - TextField("Username", text: $username) - .textInputAutocapitalization(.never).autocorrectionDisabled() - .disabled(busy || submitted) - .onChange(of: username) { _, _ in recipient = nil } - TextField("Amount in DASH", text: $amount).keyboardType(.decimalPad) - .disabled(busy || submitted) - if let recipient, !submitted { - Section("Confirm recipient") { - Text(username) - Text(recipient.identityId.toBase58String()).font(.caption).textSelection(.enabled) - Text(DashAddress.encodeOrchard(rawBytes: recipient.address, network: appState.currentNetwork) ?? "") - .font(.caption2).textSelection(.enabled) - Text("Send \(tipAmount?.dashString ?? "—") DASH from your \(sourceLabel).") - } - } - if let error { Text(error).foregroundStyle(.red) } - switch submission.status { - case .sent: - Text(submission.message ?? "Tip submitted. Check shielded activity for confirmation.") - Button("Send another tip") { - submission.startNewTip() - recipient = nil - amount = "" - } - case .uncertain: - Text(submission.message - ?? "The tip may have been sent. Check shielded activity before sending again.") - .foregroundStyle(.orange) - case .ready, .sending: - if let message = submission.message, error == nil { - Text(message).foregroundStyle(.red) - } - Button(recipient == nil ? "Review recipient" : "Confirm and send tip") { submit() } - .disabled(busy || username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || credits == nil) - } - if busy { ProgressView() } - } - .navigationTitle("Shielded tip") - .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() }.disabled(busy) } } - .interactiveDismissDisabled(busy) - .alert("Tip recipient changed", isPresented: $showRecipientChanged) { - Button("Review new recipient") {} - Button("Cancel", role: .cancel) { recipient = nil } - } message: { - Text("This username now resolves to a different identity or shielded address than your last confirmation. Verify the change with the recipient before sending.") - } - } - } - - private func submit() { - guard let wallet = walletManager.wallet(for: walletId), let credits else { return } - error = nil - let network = appState.currentNetwork - let name = username - if let recipient { - let confirmed = recipient - let manager = walletManager - let account = account - let walletId = walletId - submission.submit { - ShieldedTipRecipientHistory().confirm(network: network, walletId: walletId, - username: name, recipient: confirmed) - do { - try await manager.sendShieldedTip(walletId: walletId, resolver: MnemonicResolver(), - account: account, username: name, recipient: confirmed, amount: credits) - } catch { - // Whatever the outcome, the next attempt re-reviews the recipient. - self.recipient = nil - throw error - } - } - return - } - resolving = true - Task { @MainActor in - defer { resolving = false } - do { - let resolved = try await wallet.resolveShieldedTip(username: name) - if ShieldedTipRecipientHistory().hasChanged(network: network, walletId: walletId, - username: name, recipient: resolved) { - showRecipientChanged = true - } - recipient = resolved - } catch { - self.error = error.localizedDescription - recipient = nil - } - } - } -} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift deleted file mode 100644 index b4be45f6a91..00000000000 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DashPay/ShieldedTipSubmission.swift +++ /dev/null @@ -1,84 +0,0 @@ -import Foundation -import SwiftDashSDK - -/// Application-owned tip submissions. They outlive the sheet that started -/// them: a dismissed sheet must never imply the native send stopped -/// broadcasting, and reopening from either entry point (the DashPay tab or -/// the profile) has to find the same guard. Mirrors the Kotlin example app's -/// `ShieldedTipSubmissions`. -@MainActor -final class ShieldedTipSubmissions: ObservableObject { - private var wallets: [String: ShieldedTipSubmission] = [:] - - /// One guard per network and wallet, across all of its identities. - func forWallet(network: Network, walletId: Data) -> ShieldedTipSubmission { - let key = "\(network.rawValue):\(walletId.hexString)" - if let existing = wallets[key] { return existing } - let created = ShieldedTipSubmission() - wallets[key] = created - return created - } -} - -/// Main-actor state of one wallet's shielded tip submission. -@MainActor -final class ShieldedTipSubmission: ObservableObject { - enum Status: Equatable { case ready, sending, sent, uncertain } - - @Published private(set) var status: Status = .ready - @Published private(set) var message: String? - - var busy: Bool { status == .sending } - var submitted: Bool { status != .ready } - - /// Locks synchronously, before the task starts, so two UI events cannot - /// submit twice. Returns nil when a submission already holds the lock; the - /// task is returned so tests can await the outcome. - @discardableResult - func submit(_ send: @escaping @MainActor () async throws -> Void) -> Task? { - guard !submitted else { return nil } - status = .sending - message = nil - return Task { @MainActor in - do { - try await send() - status = .sent - message = "Shielded tip sent." - } catch { - if Self.canReviewAfterFailure(error) { - status = .ready - message = error.localizedDescription - } else { - status = .uncertain - message = "The tip may have been sent. Check shielded activity before sending " - + "again. \(error.localizedDescription)" - } - } - } - } - - /// Starting another payment is an explicit action after a confirmed success. - func startNewTip() { - guard status == .sent else { return } - status = .ready - message = nil - } - - /// Only failures known not to have executed a tip permit a fresh review. - /// On the tip path Rust maps selection, build and recipient-check failures - /// to `walletOperation`, and broadcast ambiguity to - /// `shieldedSpendUnconfirmed`; anything unknown, including cancellation, - /// stays locked until shielded activity shows the outcome. - static func canReviewAfterFailure(_ error: Error) -> Bool { - guard let error = error as? PlatformWalletError else { return false } - switch error { - case .nullPointer, .invalidHandle, .invalidParameter, .invalidIdentifier, .invalidNetwork, - .walletOperation, .identityNotFound, .contactNotFound, .utf8Conversion, - .noSelectableInputs, .shieldedBroadcastFailed, .shieldedNoRecordedAnchor, - .shieldedInsufficientBalance: - return true - default: - return false - } - } -} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift index ed860673752..682c3393103 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/IdentityDetailView.swift @@ -1163,8 +1163,6 @@ struct DashPayProfileEditorView: View { @State private var displayName: String = "" @State private var publicMessage: String = "" @State private var avatarUrl: String = "" - @State private var shieldedTipAddress: String = "" - @EnvironmentObject private var appState: AppState @State private var isSaving = false @State private var errorMessage: String? @@ -1222,22 +1220,6 @@ struct DashPayProfileEditorView: View { .foregroundColor(.secondary) } - Section { - TextField("Shielded receiving address", text: $shieldedTipAddress, axis: .vertical) - .textInputAutocapitalization(.never) - .autocorrectionDisabled() - .accessibilityIdentifier("dashpay.profile.shieldedAddress") - Button("Use a dedicated tip account") { prepareTipAddress() } - .disabled(isSaving) - if !shieldedTipAddress.isEmpty { - Button("Remove tip address", role: .destructive) { shieldedTipAddress = "" } - } - } header: { - Text("Shielded tips") - } footer: { - Text("This address is public. Use a separate account for tips, or paste an address from another wallet. Save to publish. Removing it does not revoke copies already shared.") - } - if let err = errorMessage { Section { Text(err) @@ -1273,27 +1255,11 @@ struct DashPayProfileEditorView: View { displayName = existing.displayName ?? "" publicMessage = existing.publicMessage ?? "" avatarUrl = existing.avatarUrl ?? "" - shieldedTipAddress = existing.shieldedAddress.flatMap { DashAddress.encodeOrchard(rawBytes: $0, network: appState.currentNetwork) } ?? "" } } } } - private func prepareTipAddress() { - guard let walletId else { errorMessage = "This identity has no local wallet."; return } - isSaving = true - errorMessage = nil - Task { @MainActor in - defer { isSaving = false } - do { - let address = try await walletManager.prepareShieldedTipAddress( - walletId: walletId, identityId: identityId, resolver: MnemonicResolver() - ) - shieldedTipAddress = DashAddress.encodeOrchard(rawBytes: address, network: appState.currentNetwork) ?? "" - } catch { errorMessage = error.localizedDescription } - } - } - /// Submit the create / update transition. /// /// When the user enters an avatar URL, we fetch the image bytes @@ -1345,22 +1311,11 @@ struct DashPayProfileEditorView: View { avatarBytes = nil } - let tipUpdate: DashPayPaymentAddressUpdate - let tipText = shieldedTipAddress.trimmingCharacters(in: .whitespacesAndNewlines) - if tipText.isEmpty { - tipUpdate = existing?.shieldedAddress == nil ? .keep : .remove - } else if case .orchard(let address) = DashAddress.parse(tipText, network: appState.currentNetwork).type { - tipUpdate = address == existing?.shieldedAddress ? .keep : .set(address) - } else { - errorMessage = "Enter a valid shielded address for this network." - return - } let update = DashPayProfileUpdate( displayName: cleanedDisplay.isEmpty ? nil : cleanedDisplay, publicMessage: cleanedMsg.isEmpty ? nil : cleanedMsg, avatarUrl: cleanedUrl.isEmpty ? nil : cleanedUrl, - avatarBytes: avatarBytes, - shieldedAddress: tipUpdate + avatarBytes: avatarBytes ) // Resolve the wallet via the identity's `walletId`; diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift index ead3d72f285..b30bdecf72c 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SearchWalletsForIdentitiesView.swift @@ -21,7 +21,6 @@ import SwiftData struct SearchWalletsForIdentitiesView: View { @EnvironmentObject var walletManager: PlatformWalletManager @EnvironmentObject var platformState: AppState - @EnvironmentObject private var shieldedService: ShieldedService @Environment(\.dismiss) private var dismiss /// Every persisted wallet, across all networks. Sorted by @@ -61,7 +60,6 @@ struct SearchWalletsForIdentitiesView: View { /// Rendered in full (no truncation) so path-derivation /// failures and similar long messages aren't cut off. let error: String? - var bindingWarning: String? = nil } /// Resolved runtime wallet for the current selection, or `nil` @@ -183,9 +181,6 @@ struct SearchWalletsForIdentitiesView: View { .fontWeight(.semibold) .foregroundColor(finding.foundCount > 0 ? .green : .secondary) } - if let warning = finding.bindingWarning { - Text(warning).font(.caption).foregroundColor(.orange) - } if let err = finding.error { // No `.lineLimit` — identity-derivation errors can // be long (full path + SECP error chain). Let @@ -366,19 +361,15 @@ struct SearchWalletsForIdentitiesView: View { startIndex: nil, // resume from cache gapLimit: nil // Rust default (IDENTITY_GAP_LIMIT) ) - // Newly discovered identities introduce deterministic tip accounts. - // Rebind before scanning so historical tips are included. - let bound = shieldedService.rebindAfterIdentityDiscovery( - walletManager: walletManager, walletId: walletId, - network: platformState.currentNetwork, resolver: MnemonicResolver()) result = WalletFinding( walletId: walletId, label: label, foundCount: found.count, - error: nil, - bindingWarning: bound ? nil : "Identities were discovered successfully. Shielded wallet binding could not complete; retry from the Sync tab." + error: nil ) + // Zero hits → ask Rust for the preview keypairs the + // scan walked so the user can eyeball / copy them. if found.isEmpty { await loadPreviewKeys(on: managed) } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift deleted file mode 100644 index 4aa64b88362..00000000000 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/ShieldedRebindRequestTests.swift +++ /dev/null @@ -1,30 +0,0 @@ -import XCTest -@testable import SwiftDashSDK -@testable import SwiftExampleApp - -/// A rebind request is built from the native account snapshot, which also -/// lists the tip accounts Rust binds itself. Only ordinary accounts may go -/// back into the request, or more than 64 tip accounts would exceed the bind -/// request cap. -@MainActor -final class ShieldedRebindRequestTests: XCTestCase { - private func tipAccounts(_ count: UInt32) throws -> [UInt32] { - try (0..? - private var opened = false - func wait() async { - if opened { return } - await withCheckedContinuation { continuation = $0 } - } - func open() { - opened = true - continuation?.resume() - continuation = nil - } - } - - @MainActor - private final class Counter { - var sends = 0 - } - - func testInFlightSendRefusesASecondSubmissionAndReopeningFindsTheSameGuard() async { - let submissions = ShieldedTipSubmissions() - let walletId = Data(repeating: 0x31, count: 32) - let gate = Gate() - let counter = Counter() - - let submission = submissions.forWallet(network: .testnet, walletId: walletId) - let task = submission.submit { - counter.sends += 1 - await gate.wait() - } - XCTAssertNotNil(task) - XCTAssertTrue(submission.busy) - - // The sheet was dismissed and reopened: the owner hands back the same - // guard, which is still locked, so the second tap never sends. - let reopened = submissions.forWallet(network: .testnet, walletId: walletId) - XCTAssertTrue(reopened === submission) - XCTAssertNil(reopened.submit { counter.sends += 1 }) - - gate.open() - await task?.value - XCTAssertEqual(counter.sends, 1) - XCTAssertEqual(submission.status, .sent) - XCTAssertTrue(submission.submitted) - - // Another payment needs an explicit action after the confirmed result. - submission.startNewTip() - XCTAssertEqual(submission.status, .ready) - XCTAssertFalse(submission.submitted) - - // Another wallet on the same network has its own guard. - let other = submissions.forWallet(network: .testnet, walletId: Data(repeating: 0x32, count: 32)) - XCTAssertFalse(other === submission) - } - - func testUnconfirmedSpendStaysLockedAcrossReopenAndCannotStartANewTip() async { - let submission = ShieldedTipSubmission() - let task = submission.submit { - throw PlatformWalletError.shieldedSpendUnconfirmed("relay accepted the transition") - } - await task?.value - XCTAssertEqual(submission.status, .uncertain) - XCTAssertTrue(submission.submitted) - XCTAssertTrue(submission.message?.contains("may have been sent") == true) - - // Neither a fresh tap nor "send another" unlocks an uncertain outcome. - XCTAssertNil(submission.submit {}) - submission.startNewTip() - XCTAssertEqual(submission.status, .uncertain) - } - - func testPreflightFailureReturnsToReadyWhileUnknownFailuresLock() async { - let submission = ShieldedTipSubmission() - await submission.submit { - throw PlatformWalletError.walletOperation("insufficient shielded notes") - }?.value - XCTAssertEqual(submission.status, .ready) - XCTAssertEqual( - submission.message, - PlatformWalletError.walletOperation("insufficient shielded notes").localizedDescription) - - struct Unknown: Error {} - await submission.submit { throw Unknown() }?.value - XCTAssertEqual(submission.status, .uncertain) - XCTAssertNil(submission.submit {}) - } -} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index 16e60c38c11..5b2e29fd58a 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -261,24 +261,6 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertNil(try XCTUnwrap(buffer[0].identities)[0].dashpay_profile) } - func testTipConfirmationHistoryPersistsAndDoesNotOverwriteOnChangeCheck() throws { - let suite = "tip-history-" + UUID().uuidString - let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) - defer { defaults.removePersistentDomain(forName: suite) } - let original = ShieldedTipRecipient(identityId: ownerId, address: Data(repeating: 3, count: 43)) - let changed = ShieldedTipRecipient(identityId: contactId, address: original.address) - let rotated = ShieldedTipRecipient(identityId: ownerId, address: Data(repeating: 4, count: 43)) - ShieldedTipRecipientHistory(defaults: defaults).confirm(network: .testnet, walletId: walletId, - username: "Alice", recipient: original) - let restored = ShieldedTipRecipientHistory(defaults: defaults) - XCTAssertFalse(restored.hasChanged(network: .testnet, walletId: walletId, username: "a11ce.dash", recipient: original)) - XCTAssertTrue(restored.hasChanged(network: .testnet, walletId: walletId, username: "Alice", recipient: changed)) - XCTAssertTrue(restored.hasChanged(network: .testnet, walletId: walletId, username: "Alice", recipient: rotated)) - XCTAssertFalse(restored.hasChanged(network: .testnet, walletId: walletId, username: "Alice", recipient: original)) - XCTAssertFalse(restored.hasChanged(network: .mainnet, walletId: walletId, username: "Alice", recipient: changed)) - XCTAssertFalse(restored.hasChanged(network: .testnet, walletId: contactId, username: "Alice", recipient: changed)) - } - // MARK: Contact-profile tombstone delete /// A present profile upserts a row; a later `isPresent == false` tombstone diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift deleted file mode 100644 index cb9d1374cd4..00000000000 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedTipAmountTests.swift +++ /dev/null @@ -1,24 +0,0 @@ -import XCTest -@testable import SwiftDashSDK - -final class ShieldedTipAmountTests: XCTestCase { - func testRejectsPartialLocaleAndMalformedAmounts() { - for text in ["1,5", "1abc", "1.5abc", "1,000.5", "1e2", "+1", "-1", " 1", "1 ", "", ".", "1.", ".5", "12", "0", "0.000000000001"] { - XCTAssertNil(ShieldedTipAmount(text), text) - } - } - - func testExactCreditsAndCanonicalConfirmation() throws { - for (input, credits, display) in [("1.5", UInt64(150_000_000_000), "1.5"), - ("001.500000000000", 150_000_000_000, "1.5"), - ("0.00000000001", 1, "0.00000000001"), - ("184467440.73709551615", UInt64.max, "184467440.73709551615")] { - let amount = try XCTUnwrap(ShieldedTipAmount(input)) - XCTAssertEqual(amount.credits, credits) - XCTAssertEqual(amount.dashString, display) - } - XCTAssertNil(ShieldedTipAmount("184467440.73709551616")) - XCTAssertNil(ShieldedTipAmount("184467441")) - XCTAssertNil(ShieldedTipAmount("18446744073709551616")) - } -} From 5aba29a75005d2e789cb2a11bb81135563736e75 Mon Sep 17 00:00:00 2001 From: pasta Date: Sun, 1 Nov 2026 12:37:42 -0600 Subject: [PATCH 17/41] fix(platform-wallet): tie tip spending and publication to an identity's proved slot Tip preparation verified an identity's slot, released the wallet lock, and only then bound the slot's account, so discovery could move the identity in between. The native tip send also took a raw account number, leaving hosts to pick an identity's account from its recorded index. - A per-wallet identity_placement lock orders identity moves (discovery, loading, changeset apply) against tip preparation, publication and sends. - send_shielded_tip takes a ShieldedTipSource: Identity(id) spends the tip account of the slot the seed proves the identity holds; Account(n) spends an ordinary account or an empty slot's (retired) tip account. Same shape through C (ShieldedTipSourceFFI), JNI, Swift and Kotlin. - PlatformWallet::write_dashpay_profile refuses one of this wallet's tip addresses unless it was prepared this session for the identity at the slot it now holds. The unchecked DashPayView profile writes become crate-private. Co-Authored-By: Claude Opus 5.5 --- .../dashsdk/ffi/FundingNative.kt | 3 +- .../dashsdk/tokens/ShieldedTipRecipient.kt | 25 +++ .../dashsdk/wallet/PlatformWalletManager.kt | 11 +- .../src/dashpay_profile.rs | 16 +- .../src/shielded_send.rs | 79 ++++++- .../rs-platform-wallet/docs/SHIELDED_TIPS.md | 19 +- packages/rs-platform-wallet/src/lib.rs | 3 +- .../src/wallet/identity/network/discovery.rs | 4 + .../identity/network/dpns_marketplace.rs | 1 + .../identity/network/identity_handle.rs | 7 + .../src/wallet/identity/network/loading.rs | 4 +- .../src/wallet/identity/network/payments.rs | 3 + .../src/wallet/identity/network/profile.rs | 6 +- .../src/wallet/platform_wallet.rs | 65 ++++++ .../src/wallet/shielded/mod.rs | 5 +- .../src/wallet/shielded/tips.rs | 199 +++++++++++++----- .../wallet/shielded/viewing_key_bind_tests.rs | 192 +++++++++++++++-- packages/rs-unified-sdk-jni/src/funding.rs | 27 ++- .../PlatformWalletManagerShieldedSync.swift | 36 +++- .../SwiftDashSDK/PlatformWallet/README.md | 4 +- 20 files changed, 607 insertions(+), 102 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt index 070df65f3fe..5b3ae7ad0aa 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt @@ -21,8 +21,9 @@ internal object FundingNative { manager: Long, walletId: ByteArray, resolver: Long, identityId: ByteArray, ): ByteArray external fun resolveShieldedTip(wallet: Long, username: String): ByteArray + /** A non-null [sourceIdentityId] spends that identity's tip account; otherwise [sourceAccount]. */ external fun sendShieldedTip( - manager: Long, walletId: ByteArray, resolver: Long, account: Int, + manager: Long, walletId: ByteArray, resolver: Long, sourceIdentityId: ByteArray?, sourceAccount: Int, username: String, expectedId: ByteArray, expectedAddress: ByteArray, amount: Long, memo: String?, ) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt index 5ba1d253d31..353573c87a5 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/tokens/ShieldedTipRecipient.kt @@ -14,3 +14,28 @@ class ShieldedTipRecipient(identityId: ByteArray, address: ByteArray) { identityBytes.contentEquals(other.identityBytes) && addressBytes.contentEquals(other.addressBytes) override fun hashCode(): Int = 31 * identityBytes.contentHashCode() + addressBytes.contentHashCode() } + +/** + * The account a shielded tip is paid from. Rust decides which account an + * identity's source selects, from the slot the wallet seed proves it holds. + */ +sealed class ShieldedTipSource { + /** The identity's dedicated tip account. */ + class Identity(identityId: ByteArray) : ShieldedTipSource() { + private val identityBytes = identityId.copyOf() + val identityId: ByteArray get() = identityBytes.copyOf() + init { + require(identityBytes.size == 32) { "identity id must be 32 bytes, got ${identityBytes.size}" } + } + override fun equals(other: Any?): Boolean = + other is Identity && identityBytes.contentEquals(other.identityBytes) + override fun hashCode(): Int = identityBytes.contentHashCode() + } + + /** An ordinary account, or the tip account of a retired identity. */ + data class Account(val index: Int) : ShieldedTipSource() { + init { + require(index >= 0) { "account must be non-negative, got $index" } + } + } +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index f3aae892125..d5d4da7170e 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -2038,13 +2038,18 @@ class PlatformWalletManager( suspend fun sendShieldedTip( walletId: ByteArray, username: String, recipient: org.dashfoundation.dashsdk.tokens.ShieldedTipRecipient, - amount: Long, account: Int = 0, memo: String? = null, + amount: Long, source: org.dashfoundation.dashsdk.tokens.ShieldedTipSource, + memo: String? = null, ): Unit = teardownGate.op { require(amount > 0) { "amount must be positive, got $amount" } - require(account >= 0) { "account must be non-negative, got $account" } + val (sourceIdentityId, sourceAccount) = when (source) { + is org.dashfoundation.dashsdk.tokens.ShieldedTipSource.Identity -> source.identityId to 0 + is org.dashfoundation.dashsdk.tokens.ShieldedTipSource.Account -> null to source.index + } mapNativeErrors { FundingNative.sendShieldedTip(managerHandle, walletId, mnemonicResolver.nativeHandle, - account, username, recipient.identityId, recipient.address, amount, memo) + sourceIdentityId, sourceAccount, username, recipient.identityId, recipient.address, + amount, memo) } } diff --git a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs index 888743cfb97..600d28cab47 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay_profile.rs @@ -479,7 +479,7 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_a let signer_addr = signer_handle as usize; let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, move |wallet| { - let identity = wallet.identity().clone(); + let wallet = wallet.clone(); let input = ProfileUpdate { display_name, public_message, @@ -492,17 +492,9 @@ pub unsafe extern "C" fn platform_wallet_create_or_update_dashpay_profile_with_a block_on_worker(async move { let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); - if do_create { - identity - .dashpay() - .create_profile_with_external_signer(&id, input, signer) - .await - } else { - identity - .dashpay() - .update_profile_with_external_signer(&id, input, signer) - .await - } + wallet + .write_dashpay_profile(&id, input, signer, do_create) + .await }) }); let result = unwrap_option_or_return!(option); diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 0385f5711d5..daffbbb6635 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -52,7 +52,7 @@ use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; use dpp::ProtocolError; use platform_wallet::wallet::asset_lock::AssetLockFunding; use platform_wallet::wallet::shielded::CachedOrchardProver; -use platform_wallet::PlatformWalletError; +use platform_wallet::{PlatformWalletError, ShieldedTipSource}; use rs_sdk_ffi::{ MnemonicResolverCoreSigner, MnemonicResolverHandle, SignerHandle, VTableSigner, DASH_SDK_SIGNER_ERR_KEY_UNAVAILABLE_PREFIX, @@ -2478,14 +2478,46 @@ pub unsafe extern "C" fn platform_wallet_resolve_shielded_tip( result } +/// [`ShieldedTipSourceFFI::kind`]: spend the dedicated tip account of the +/// wallet identity `identity_id`. +pub const SHIELDED_TIP_SOURCE_IDENTITY: u32 = 0; +/// [`ShieldedTipSourceFFI::kind`]: spend `account` explicitly (an ordinary +/// account, or a retired identity's tip account). +pub const SHIELDED_TIP_SOURCE_ACCOUNT: u32 = 1; + +/// The account a shielded tip is paid from. The field `kind` does not use is +/// ignored. +#[repr(C)] +pub struct ShieldedTipSourceFFI { + pub kind: u32, + pub identity_id: [u8; 32], + pub account: u32, +} + +/// The wallet's [`ShieldedTipSource`] for an FFI source; the wallet decides +/// which account an identity's source selects. +fn decode_tip_source( + source: &ShieldedTipSourceFFI, +) -> Result { + match source.kind { + SHIELDED_TIP_SOURCE_IDENTITY => Ok(ShieldedTipSource::Identity(source.identity_id.into())), + SHIELDED_TIP_SOURCE_ACCOUNT => Ok(ShieldedTipSource::Account(source.account)), + _ => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "Invalid shielded tip source".to_string(), + )), + } +} + /// Send a tip only if fresh resolution matches the recipient the user confirmed. -/// ID/address pointers must reference 32/43 readable bytes respectively. +/// `source` must point to a readable [`ShieldedTipSourceFFI`]; the ID/address +/// pointers must reference 32/43 readable bytes respectively. #[no_mangle] pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( handle: Handle, wallet_id_bytes: *const u8, mnemonic_resolver_handle: *mut MnemonicResolverHandle, - account: u32, + source: *const ShieldedTipSourceFFI, username: *const c_char, expected_identity_id: *const u8, expected_address: *const u8, @@ -2494,9 +2526,14 @@ pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( ) -> PlatformWalletFFIResult { check_ptr!(wallet_id_bytes); check_ptr!(mnemonic_resolver_handle); + check_ptr!(source); check_ptr!(username); check_ptr!(expected_identity_id); check_ptr!(expected_address); + let source = match decode_tip_source(&*source) { + Ok(source) => source, + Err(e) => return e, + }; let username = match CStr::from_ptr(username).to_str() { Ok(s) => s.to_owned(), Err(e) => return e.into(), @@ -2553,7 +2590,7 @@ pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( .send_shielded_tip( &coordinator, seed.as_ref(), - account, + source, &username, &recipient, amount, @@ -2603,6 +2640,28 @@ mod tests { use platform_wallet::wallet::shielded::store::PendingRedrive; use platform_wallet::wallet::shielded::{FileBackedShieldedStore, ShieldedStore, SubwalletId}; + #[test] + fn should_decode_each_tip_source_kind_and_reject_others() { + let source = |kind| ShieldedTipSourceFFI { + kind, + identity_id: [7; 32], + account: 3, + }; + assert_eq!( + decode_tip_source(&source(SHIELDED_TIP_SOURCE_IDENTITY)).ok(), + Some(ShieldedTipSource::Identity([7; 32].into())) + ); + assert_eq!( + decode_tip_source(&source(SHIELDED_TIP_SOURCE_ACCOUNT)).ok(), + Some(ShieldedTipSource::Account(3)) + ); + let refused = decode_tip_source(&source(2)).unwrap_err(); + assert_eq!( + refused.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + } + #[test] fn encode_memo_text_none_is_empty() { let bytes = encode_memo_text(None).expect("None must encode"); @@ -3220,7 +3279,11 @@ mod tests { handle, wallet_id.as_ptr(), &mut resolver, - 0, + &ShieldedTipSourceFFI { + kind: SHIELDED_TIP_SOURCE_ACCOUNT, + identity_id: [0; 32], + account: 0, + }, username.as_ptr(), identity_id.as_ptr(), address.as_ptr(), @@ -3297,7 +3360,11 @@ mod tests { handle, wallet_id.as_ptr(), &mut resolver, - 0, + &ShieldedTipSourceFFI { + kind: SHIELDED_TIP_SOURCE_ACCOUNT, + identity_id: [0; 32], + account: 0, + }, username.as_ptr(), identity_id.as_ptr(), address.as_ptr(), diff --git a/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md index c184b7b4ecb..4ffa17dbd95 100644 --- a/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md +++ b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md @@ -38,12 +38,24 @@ does not publish the address; publication remains an explicit profile operation. Repeated preparation derives the same account and address. An identity without a wallet derivation index can publish an external address instead. +Publish through `PlatformWallet::write_dashpay_profile`. A shielded address that is +one of this wallet's bound tip addresses is published only if preparation, in this +session, proved with the seed that the identity holds the slot selecting it, and the +identity still holds that slot. Discovery can move an identity whose keys derive at +several indices, and a restored placeholder index proves nothing, so prepare the +address again after a restart or a move; preparation is idempotent. Preparation, +publication and tip sends hold a per-wallet placement lock that discovery, loading +and changeset apply take before moving an identity. An address already published +before a move keeps receiving into its old account until the profile is updated. + Tip accounts have distinct viewing keys. Hosts must exclude them from ordinary receive, balance, and automatic spending choices, as the example apps do. `shielded_balances()` returns all bound accounts separately, including tip accounts; it does not apply this policy. Spending a tip balance is an explicit host action. -The generic shielded transfer API still accepts an explicitly selected account. +The generic shielded spend APIs (transfer, unshield, withdraw, top-up) still accept an +explicitly selected account and apply none of the tip-slot checks below; use +`send_shielded_tip` with a `ShieldedTipSource` for tips. A published address is publicly associated with the profile; account separation does not eliminate correlations introduced by later transfers or provide a blanket guarantee against future cryptographic attacks. @@ -76,7 +88,10 @@ funds, viewing keys, and recovery belong to the external wallet. Use `wallet.identity().dashpay().resolve_shielded_tip(username)` to obtain a fresh `ShieldedTipRecipient`. Display the resolved identity and address for confirmation. `wallet.send_shielded_tip(...)` takes that confirmed recipient, re-resolves the -name and profile, and refuses payment if either changed. It never switches to a +name and profile, and refuses payment if either changed. Its `ShieldedTipSource` +names what pays: `Identity(id)` spends that identity's tip account, after the seed +proves the slot it holds; `Account(n)` spends an ordinary account, or the tip +account of a slot that holds no identity (a retired identity's funds). It never switches to a transparent destination. This is a snapshot check: the submitted payment always uses the address that was confirmed, even if the profile changes afterward. diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index 46e61eda796..a36d6ad2db7 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -134,5 +134,6 @@ pub use wallet::identity::types::dashpay::profile::{ #[cfg(feature = "shielded")] pub use wallet::shielded::tips::{ - is_shielded_tip_account, shielded_tip_account_index, SHIELDED_TIP_ACCOUNT_BASE, + is_shielded_tip_account, shielded_tip_account_index, ShieldedTipSource, + SHIELDED_TIP_ACCOUNT_BASE, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs index 81b2e6a9e53..c0173a3f8f9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs @@ -441,6 +441,8 @@ impl IdentityWallet { // Acquire write lock to add/enrich the identity, then emit // every per-key breadcrumb in one batched changeset. + // Placement lock first; see `identity_placement`. + let placement_guard = self.identity_placement.write().await; let mut wm_guard = self.wallet_manager.write().await; let info_guard = wm_guard @@ -469,6 +471,7 @@ impl IdentityWallet { Ok(placement) => placement == VerifiedPlacement::Added, Err(e @ PlatformWalletError::IdentityIndexOccupied { .. }) => { drop(wm_guard); + drop(placement_guard); tracing::warn!( index = identity_index, error = %e, @@ -514,6 +517,7 @@ impl IdentityWallet { })?; } drop(wm_guard); + drop(placement_guard); if is_new { discovered.push(identity.clone()); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index f54f1791730..c08233cc18b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -3945,6 +3945,7 @@ mod tests { sdk_writer: Arc::new(super::super::sdk_writer::SdkWriter::new(sdk)), dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + identity_placement: Arc::new(tokio::sync::RwLock::new(())), } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs index c8e7937b2e6..1f09ec6a89c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs @@ -534,6 +534,12 @@ pub struct IdentityWallet { /// the source rendered after process restart. pub(crate) dpns_sync_progress: Arc>>, + /// Orders moves of a wallet identity between slots (discovery, loading + /// and `PlatformWallet::apply` take it for writing) against operations + /// that act on the account a slot selects (tip preparation, tip sends and + /// tip address publication take it for reading). Taken before + /// `wallet_manager`. + pub(crate) identity_placement: Arc>, } // Manual `Debug`: the derive would require `B: Debug`, which is not part @@ -562,6 +568,7 @@ impl Clone for IdentityWallet { sdk_writer: Arc::clone(&self.sdk_writer), dpns_operation_gate: Arc::clone(&self.dpns_operation_gate), dpns_sync_progress: Arc::clone(&self.dpns_sync_progress), + identity_placement: Arc::clone(&self.identity_placement), } } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs index b7d18930083..2ba94b92660 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs @@ -241,8 +241,10 @@ impl IdentityWallet { ) .await?; - // Add the identity to the manager and enrich it. + // Add the identity to the manager and enrich it. Placement lock + // first; see `identity_placement`. { + let _placement = self.identity_placement.write().await; let mut wm = self.wallet_manager.write().await; let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { crate::error::PlatformWalletError::WalletNotFound( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs index 5060aa6295d..1913e399e2d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs @@ -13434,6 +13434,7 @@ mod tests { sdk_writer: Arc::clone(&real.sdk_writer), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), + identity_placement: Arc::clone(&real.identity_placement), } } @@ -13476,6 +13477,7 @@ mod tests { sdk_writer: Arc::clone(&real.sdk_writer), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), + identity_placement: Arc::clone(&real.identity_placement), } } @@ -13532,6 +13534,7 @@ mod tests { sdk_writer: Arc::clone(&real.sdk_writer), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), + identity_placement: Arc::clone(&real.identity_placement), } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 128de299600..03526c86408 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -139,7 +139,7 @@ impl DashPayView<'_, B> { /// All other behavior — avatar hashing, document construction, /// local cache update via the persister — is identical to the /// legacy variant. - pub async fn create_profile_with_external_signer( + pub(crate) async fn create_profile_with_external_signer( &self, identity_id: &Identifier, input: ProfileUpdate, @@ -201,7 +201,7 @@ impl DashPayView<'_, B> { /// /// Mirrors [`Self::update_profile`] but signing is routed through /// the supplied `&S: Signer`. - pub async fn update_profile_with_external_signer( + pub(crate) async fn update_profile_with_external_signer( &self, identity_id: &Identifier, input: ProfileUpdate, @@ -1236,7 +1236,7 @@ mod tip_resolution_tests { .send_shielded_tip( &coordinator, &[42; 64], - 0, + crate::ShieldedTipSource::Account(0), "Alice.dash", &confirmed, 1000, diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 15244935ebe..c7699a15b54 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -38,6 +38,9 @@ use crate::changeset::{ ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, }; use crate::error::PlatformWalletError; +#[cfg(feature = "shielded")] +use crate::validated_shielded_address; +use crate::{DashPayProfile, PaymentAddressUpdate, ProfileUpdate}; use dash_sdk::platform::transition::put_settings::PutSettings; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; @@ -443,6 +446,14 @@ pub struct PlatformWallet { /// `shielded_add_account`, before `shield_guard`. #[cfg(feature = "shielded")] pub(crate) shielded_config_lock: Arc>, + /// The tip account each identity's address was last prepared for in + /// this session, after its slot was proved with the seed. Publication + /// of a wallet tip address requires it, so an address is published only + /// for the identity and slot it was prepared for. `Arc` so cloned wallet + /// handles share it. + #[cfg(feature = "shielded")] + pub(crate) prepared_tip_accounts: + Arc>>, /// Set once this wallet has been removed from the manager, to stop /// a handle that outlives the removal from binding shielded state /// back onto the coordinator. Callers resolve an @@ -817,6 +828,7 @@ impl PlatformWallet { ), dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + identity_placement: Arc::new(tokio::sync::RwLock::new(())), }; let platform = PlatformAddressWallet::new( @@ -844,6 +856,8 @@ impl PlatformWallet { #[cfg(feature = "shielded")] shielded_config_lock: Arc::new(tokio::sync::Mutex::new(())), #[cfg(feature = "shielded")] + prepared_tip_accounts: Arc::new(std::sync::Mutex::new(BTreeMap::new())), + #[cfg(feature = "shielded")] shielded_detached: Arc::new(std::sync::atomic::AtomicBool::new(false)), #[cfg(feature = "shielded")] private_payment_restores: Arc::default(), @@ -2887,6 +2901,13 @@ impl PlatformWallet { }); { + // An identity entry can move an identity to another slot. + // Placement lock first; see `identity_placement`. + let _placement = if changeset.identities.is_some() { + Some(self.identity.identity_placement.write().await) + } else { + None + }; let mut wm = self.wallet_manager.write().await; let (wallet, info) = wm .get_wallet_mut_and_info_mut(&self.wallet_id) @@ -2963,6 +2984,8 @@ impl Clone for PlatformWallet { #[cfg(feature = "shielded")] shielded_config_lock: self.shielded_config_lock.clone(), #[cfg(feature = "shielded")] + prepared_tip_accounts: self.prepared_tip_accounts.clone(), + #[cfg(feature = "shielded")] shielded_detached: self.shielded_detached.clone(), #[cfg(feature = "shielded")] private_payment_restores: self.private_payment_restores.clone(), @@ -2970,6 +2993,48 @@ impl Clone for PlatformWallet { } } +impl PlatformWallet { + /// Create (`create`) or update `identity_id`'s DashPay profile. A + /// shielded address that is one of this wallet's dedicated tip addresses + /// must have been prepared for this identity at the slot it holds, and + /// the placement lock is held through a write that sets one, so the slot + /// cannot change before it lands. + pub async fn write_dashpay_profile( + &self, + identity_id: &Identifier, + input: ProfileUpdate, + signer: &S, + create: bool, + ) -> Result + where + S: Signer + Send + Sync, + { + let sets_shielded = matches!(input.shielded_address, PaymentAddressUpdate::Set(_)); + let _placement = if sets_shielded { + Some(self.identity.identity_placement.read().await) + } else { + None + }; + #[cfg(feature = "shielded")] + if let PaymentAddressUpdate::Set(bytes) = &input.shielded_address { + if let Some(address) = validated_shielded_address(bytes) { + self.check_tip_address_publication(identity_id, &address) + .await?; + } + } + let dashpay = self.identity.dashpay(); + if create { + dashpay + .create_profile_with_external_signer(identity_id, input, signer) + .await + } else { + dashpay + .update_profile_with_external_signer(identity_id, input, signer) + .await + } + } +} + impl std::fmt::Debug for PlatformWallet { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("PlatformWallet") diff --git a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs index c35fb651964..3c267336f2a 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs @@ -53,7 +53,10 @@ pub mod seed_pool; pub mod store; pub mod sync; pub mod tips; -pub use tips::{is_shielded_tip_account, shielded_tip_account_index, SHIELDED_TIP_ACCOUNT_BASE}; +pub use tips::{ + is_shielded_tip_account, shielded_tip_account_index, ShieldedTipSource, + SHIELDED_TIP_ACCOUNT_BASE, +}; #[cfg(test)] mod viewing_key_bind_tests; #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index b699b2efd53..7e7581a37ff 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -11,8 +11,10 @@ use super::NetworkShieldedCoordinator; use crate::wallet::platform_wallet::PlatformWallet; use crate::{PlatformWalletError, ShieldedTipRecipient}; +use dpp::identity::accessors::IdentityGettersV0; use dpp::prelude::Identifier; -use std::sync::Arc; +use grovedb_commitment_tree::PaymentAddress; +use std::sync::{Arc, PoisonError}; pub const SHIELDED_TIP_ACCOUNT_BASE: u32 = 0x4000_0000; @@ -29,6 +31,18 @@ pub fn is_shielded_tip_account(account: u32) -> bool { (SHIELDED_TIP_ACCOUNT_BASE..0x8000_0000).contains(&account) } +/// The account a tip is paid from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ShieldedTipSource { + /// The identity's dedicated tip account, at the slot the seed proves the + /// identity holds when the notes are selected. + Identity(Identifier), + /// An explicit account: an ordinary account, or the tip account of a slot + /// that holds no identity (a retired identity's funds). A slot that holds + /// an identity is spent through [`Self::Identity`] instead. + Account(u32), +} + /// Prove `identity_index` with the seed: the identity must carry the MASTER /// authentication key this wallet derives at that index (the key discovery and /// registration both use). Fails closed when no key matches, including when @@ -42,7 +56,6 @@ fn verify_identity_index( use crate::wallet::identity::network::{ derive_identity_auth_key_hash_from_master, MASTER_KEY_INDEX, }; - use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::methods::hash::IdentityPublicKeyHashMethodsV0; let master = key_wallet::bip32::ExtendedPrivKey::new_master(network, seed) @@ -112,33 +125,13 @@ impl PlatformWallet { "The supplied seed does not belong to this wallet".to_string(), )); } - let account = { - let wm = self.wallet_manager.read().await; - let info = wm.get_wallet_info(&self.wallet_id()).ok_or_else(|| { - PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())) - })?; - let identity = info - .identity_manager - .managed_identity(identity_id) - .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; - if identity.wallet_id != Some(self.wallet_id()) { - return Err(PlatformWalletError::InvalidIdentityData( - "Tip account requires a wallet-owned identity".to_string(), - )); - } - let index = identity.identity_index.ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "Tip account requires a recoverable identity index".to_string(), - ) - })?; - // A restored index is metadata, and hosts that cannot represent - // "unknown" have restored a placeholder 0 for wallet-attached - // identities. Publishing then would hand out identity 0's tip - // address, so require the seed to reproduce this identity's - // MASTER key at the claimed index before allocating its account. - verify_identity_index(seed, self.sdk.network, index, &identity.identity)?; - shielded_tip_account_index(index)? - }; + // Held until the address is returned, so the identity cannot move to + // another slot between the check below and the bind of the account + // that slot selects. Publication rechecks it (see + // `check_tip_address_publication`) because the slot can still change + // before the host publishes. + let _placement = self.identity.identity_placement.read().await; + let account = self.verified_tip_account(seed, identity_id).await?; // Read the bound set and bind the augmented copy as one step: a bind // replaces the registration, so another bind landing in between // would have its ordinary accounts dropped by this stale snapshot. @@ -155,57 +148,163 @@ impl PlatformWallet { self.persister() .flush() .map_err(|e| PlatformWalletError::Persistence(e.to_string()))?; - self.shielded_default_address(account) + let address = self + .shielded_default_address(account) .await - .ok_or(PlatformWalletError::ShieldedNotBound) + .ok_or(PlatformWalletError::ShieldedNotBound)?; + self.prepared_tip_accounts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(*identity_id, account); + Ok(address) } - /// Refuse to spend from a dedicated tip account whose slot holds an identity - /// the seed does not prove to be at that index. Hosts select the source - /// account from the identity's recorded index, and a host-restored - /// placeholder index 0 would otherwise spend identity 0's tip pool on - /// another identity's behalf. A tip account whose slot is empty (a retired - /// identity's) has no such ambiguity and stays spendable. - async fn verify_tip_account_owner( + /// The tip account of a wallet-owned identity's slot, proved with the + /// seed. A restored index is metadata, and hosts that cannot represent + /// "unknown" restore a placeholder 0 for wallet-attached identities, so + /// the seed must reproduce the identity's MASTER key at the recorded index + /// before the account that index selects is used for it. + async fn verified_tip_account( &self, seed: &[u8], - account: u32, - ) -> Result<(), PlatformWalletError> { - let index = account - SHIELDED_TIP_ACCOUNT_BASE; + identity_id: &Identifier, + ) -> Result { let wm = self.wallet_manager.read().await; let info = wm .get_wallet_info(&self.wallet_id()) .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())))?; - let Some(owner) = info + let identity = info .identity_manager - .wallet_identities - .get(&self.wallet_id()) - .and_then(|bucket| bucket.get(&index)) + .managed_identity(identity_id) + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + if identity.wallet_id != Some(self.wallet_id()) { + return Err(PlatformWalletError::InvalidIdentityData( + "Tip account requires a wallet-owned identity".to_string(), + )); + } + let index = identity.identity_index.ok_or_else(|| { + PlatformWalletError::InvalidIdentityData( + "Tip account requires a recoverable identity index".to_string(), + ) + })?; + verify_identity_index(seed, self.sdk.network, index, &identity.identity)?; + shielded_tip_account_index(index) + } + + /// The account `source` spends. An identity spends the tip account of + /// the slot the seed proves it holds. An explicit tip account is refused + /// while its slot holds an identity: the user chose that identity's + /// account by its number, and the identity in the slot may not be the one + /// they meant. + pub(crate) async fn tip_source_account( + &self, + seed: &[u8], + source: ShieldedTipSource, + ) -> Result { + match source { + ShieldedTipSource::Identity(identity_id) => { + self.verified_tip_account(seed, &identity_id).await + } + ShieldedTipSource::Account(account) if is_shielded_tip_account(account) => { + let wm = self.wallet_manager.read().await; + let info = wm.get_wallet_info(&self.wallet_id()).ok_or_else(|| { + PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())) + })?; + let occupant = info + .identity_manager + .wallet_identities + .get(&self.wallet_id()) + .and_then(|bucket| bucket.get(&(account - SHIELDED_TIP_ACCOUNT_BASE))); + match occupant { + Some(owner) => Err(PlatformWalletError::InvalidIdentityData(format!( + "Account {account} is the tip account of identity {}; \ + send from that identity instead", + owner.identity.id() + ))), + None => Ok(account), + } + } + ShieldedTipSource::Account(account) => Ok(account), + } + } + + /// Refuse to publish one of this wallet's dedicated tip addresses unless + /// preparation, in this session, proved with the seed that `identity_id` + /// holds the slot selecting that account, and the identity still holds + /// it. Discovery can move an identity whose keys derive at several + /// indices, and a restored placeholder index is not proof of a slot. + /// Addresses of ordinary accounts and of other wallets are the owner's + /// choice. Only bound accounts are recognised; preparation binds the + /// account it hands out. Callers hold the placement lock through the + /// profile write. + pub(crate) async fn check_tip_address_publication( + &self, + identity_id: &Identifier, + address: &[u8; 43], + ) -> Result<(), PlatformWalletError> { + let Some(address) = + Option::::from(PaymentAddress::from_raw_address_bytes(address)) else { return Ok(()); }; - verify_identity_index(seed, self.sdk.network, index, &owner.identity) + let owning_account = { + let keys = self.shielded_keys.read().await; + keys.as_ref().and_then(|keys| { + keys.iter() + .filter(|(account, _)| is_shielded_tip_account(**account)) + .find(|(_, views)| views.full_viewing_key.scope_for_address(&address).is_some()) + .map(|(account, _)| *account) + }) + }; + let Some(owning_account) = owning_account else { + return Ok(()); + }; + let prepared = self + .prepared_tip_accounts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(identity_id) + .copied(); + let wm = self.wallet_manager.read().await; + let current = wm + .get_wallet_info(&self.wallet_id()) + .and_then(|info| info.identity_manager.managed_identity(identity_id)) + .filter(|identity| identity.wallet_id == Some(self.wallet_id())) + .and_then(|identity| identity.identity_index) + .and_then(|index| shielded_tip_account_index(index).ok()); + if prepared == Some(owning_account) && current == Some(owning_account) { + Ok(()) + } else { + Err(PlatformWalletError::InvalidIdentityData( + "This tip address was not prepared for the identity's current tip account; \ + prepare the identity's tip address again" + .to_string(), + )) + } } /// Send only to the identity/address pair that the user confirmed. A changed /// name owner or profile requires a new confirmation; there is no fallback to /// a transparent rail. Network changes after this check cannot change the /// destination, which remains the explicitly confirmed raw address. + /// + /// The source is checked before anything is resolved or proved, and the + /// placement lock is held through the spend, so an identity's tip is paid + /// from the account of the slot it holds when its notes are selected. #[allow(clippy::too_many_arguments)] pub async fn send_shielded_tip( &self, coordinator: &Arc, seed: &[u8], - account: u32, + source: ShieldedTipSource, username: &str, expected_recipient: &ShieldedTipRecipient, amount: u64, memo: [u8; 36], prover: P, ) -> Result<(), PlatformWalletError> { - if is_shielded_tip_account(account) { - self.verify_tip_account_owner(seed, account).await?; - } + let _placement = self.identity.identity_placement.read().await; + let account = self.tip_source_account(seed, source).await?; let current = self .identity() .dashpay() diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index a86d983f594..d00f393c62b 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -1207,6 +1207,33 @@ fn seed_master_key( )]) } +/// A signer for writes that must be refused before anything is signed. +#[derive(Debug)] +struct NoSigner; + +#[async_trait::async_trait] +impl dpp::identity::signer::Signer for NoSigner { + async fn sign( + &self, + _key: &dpp::identity::IdentityPublicKey, + _data: &[u8], + ) -> Result { + unreachable!("the write is refused before signing") + } + + async fn sign_create_witness( + &self, + _key: &dpp::identity::IdentityPublicKey, + _data: &[u8], + ) -> Result { + unreachable!("the write is refused before signing") + } + + fn can_sign_with(&self, _key: &dpp::identity::IdentityPublicKey) -> bool { + false + } +} + /// Cold reload of a host that cannot store "index unknown": a wallet-attached /// identity whose index was lost comes back at placeholder slot 0 while /// identity 0's tip account (and its funds) is retained and bound. Tip @@ -1288,14 +1315,15 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), "{refused:?}" ); - // Spending selects the source account from the same recorded index, so - // sending from identity 0's tip account on this identity's behalf is - // refused too, before any network resolution or proving. + // A send from this identity selects the same recorded index, so it is + // refused too, before any network resolution or proving; and identity + // 0's tip account cannot be spent by number while a slot-0 identity + // holds it. let recipient = crate::ShieldedTipRecipient { identity_id: Identifier::from([0x77; 32]), address: [0; 43], }; - let spend = |account: u32| { + let spend = |source: crate::ShieldedTipSource| { let wallet = wallet.clone(); let coordinator = Arc::clone(&coordinator); let recipient = recipient.clone(); @@ -1304,7 +1332,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .send_shielded_tip( &coordinator, &seed, - account, + source, "recipient.dash", &recipient, 1_000, @@ -1314,11 +1342,35 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .await } }; - let refused_spend = spend(identity_zero_tips).await; + let refused_with = |result: &Result<(), crate::PlatformWalletError>, reason: &str| matches!(result, Err(crate::PlatformWalletError::InvalidIdentityData(msg)) if msg.contains(reason)); + // Nor can it publish identity 0's tip address as its own: the profile + // write refuses it before signing or any network call. + let published = wallet + .write_dashpay_profile( + &id, + crate::ProfileUpdate { + shielded_address: crate::PaymentAddressUpdate::Set(identity_zero_address.to_vec()), + ..Default::default() + }, + &NoSigner, + false, + ) + .await + .map(|_| ()); + assert!( + refused_with(&published, "not prepared for"), + "{published:?}" + ); + let refused_spend = spend(crate::ShieldedTipSource::Identity(id)).await; assert!( - matches!(refused_spend, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), + refused_with(&refused_spend, "not verified"), "{refused_spend:?}" ); + let by_number = spend(crate::ShieldedTipSource::Account(identity_zero_tips)).await; + assert!( + refused_with(&by_number, "send from that identity"), + "{by_number:?}" + ); // Rediscovery proves index 5 and re-slots the identity. { @@ -1341,13 +1393,36 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .unwrap(), address ); - // Its own tip account now passes the ownership check (the mock SDK then - // fails the recipient lookup), and identity 0's slot is empty, so that - // retired-style account is no longer attributed to this identity. - let own = spend(shielded_tip_account_index(5).unwrap()).await; + assert_eq!( + wallet + .tip_source_account(&seed, crate::ShieldedTipSource::Identity(id)) + .await + .unwrap(), + shielded_tip_account_index(5).unwrap() + ); + // The identity now passes the source check (the mock SDK then fails the + // recipient lookup). Slot 0 is empty, so its account is spendable by + // number as a retired identity's; slot 5's is not. + for source in [ + crate::ShieldedTipSource::Identity(id), + crate::ShieldedTipSource::Account(identity_zero_tips), + ] { + let passed = spend(source).await; + assert!( + !matches!( + passed, + Err(crate::PlatformWalletError::InvalidIdentityData(_)) + ), + "{source:?}: {passed:?}" + ); + } + let own_by_number = spend(crate::ShieldedTipSource::Account( + shielded_tip_account_index(5).unwrap(), + )) + .await; assert!( - !matches!(own, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), - "{own:?}" + refused_with(&own_by_number, "send from that identity"), + "{own_by_number:?}" ); } @@ -1783,3 +1858,94 @@ async fn should_keep_an_added_account_during_tip_preparation() { ); } } + +/// Discovery can move an identity whose keys derive at two indices between +/// their slots. Preparation holds the placement lock from its slot check to +/// its return, so a move waits for it; the address it returned then names the +/// old slot's account, and publishing that address for the moved identity is +/// refused until its address is prepared again. Ordinary accounts' addresses +/// and other wallets' addresses stay publishable. +#[tokio::test] +async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stale_address() { + use crate::shielded_tip_account_index; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_placement_move").await; + { + let mut wm = wallet.wallet_manager().write().await; + let managed = wm + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .managed_identity_mut(&id) + .unwrap(); + let mut second = seed_master_key(&seed, 7).remove(&0).unwrap(); + second.set_id(1); + managed.identity.add_public_key(second); + } + + let (reached, resume) = super::tips::test_hooks::pause_after_snapshot(&wallet); + let preparing = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + }) + }; + reached.await.expect("preparation reached its snapshot"); + // The move discovery and loading make, under the lock they take. + let mut moving = { + let wallet = wallet.clone(); + tokio::spawn(async move { + let _placement = wallet.identity.identity_placement.write().await; + let mut wm = wallet.wallet_manager().write().await; + wm.get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .adopt_into_wallet(&id, wallet.wallet_id(), 7) + }) + }; + let moved_early = + tokio::time::timeout(std::time::Duration::from_millis(500), &mut moving).await; + assert!( + moved_early.is_err(), + "an identity move must wait for tip preparation to return" + ); + resume.send(()).unwrap(); + let stale = preparing.await.unwrap().expect("tip address prepared"); + assert_eq!( + Some(stale), + wallet + .shielded_default_address(shielded_tip_account_index(2).unwrap()) + .await + ); + moving.await.unwrap().expect("identity moved to slot 7"); + + let refused = wallet.check_tip_address_publication(&id, &stale).await; + assert!( + matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not prepared for")), + "{refused:?}" + ); + let fresh = wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + .unwrap(); + assert_ne!(fresh, stale); + let ordinary = wallet.shielded_default_address(0).await.unwrap(); + let external = super::OrchardKeySet::from_seed( + &[9; 64], + Network::Testnet, + shielded_tip_account_index(2).unwrap(), + ) + .unwrap() + .default_address + .to_raw_address_bytes(); + for address in [fresh, ordinary, external] { + wallet + .check_tip_address_publication(&id, &address) + .await + .expect("publishable"); + } +} diff --git a/packages/rs-unified-sdk-jni/src/funding.rs b/packages/rs-unified-sdk-jni/src/funding.rs index 4aa6cdf3a50..387e0e8af76 100644 --- a/packages/rs-unified-sdk-jni/src/funding.rs +++ b/packages/rs-unified-sdk-jni/src/funding.rs @@ -1330,7 +1330,9 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_resolve }) } -/// Revalidates the confirmed recipient before spending. +/// Revalidates the confirmed recipient before spending. A non-null +/// `source_identity_id` spends that identity's dedicated tip account and +/// `source_account` is ignored; otherwise `source_account` is spent. #[no_mangle] pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShieldedTip( mut env: JNIEnv, @@ -1338,7 +1340,8 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShi manager: jlong, wallet_id: JByteArray, resolver: jlong, - account: jint, + source_identity_id: JByteArray, + source_account: jint, username: JString, expected_id: JByteArray, expected_address: JByteArray, @@ -1346,13 +1349,29 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShi memo: JString, ) { guard(&mut env, (), |env| { - if account < 0 || amount <= 0 { + if source_account < 0 || amount <= 0 { throw_sdk_exception(env, 1, "Invalid account or amount"); return; } let Some(wid) = read_id32(env, &wallet_id, "walletId") else { return; }; + let source = if source_identity_id.is_null() { + platform_wallet_ffi::ShieldedTipSourceFFI { + kind: platform_wallet_ffi::SHIELDED_TIP_SOURCE_ACCOUNT, + identity_id: [0; 32], + account: source_account as u32, + } + } else { + let Some(identity_id) = read_id32(env, &source_identity_id, "sourceIdentityId") else { + return; + }; + platform_wallet_ffi::ShieldedTipSourceFFI { + kind: platform_wallet_ffi::SHIELDED_TIP_SOURCE_IDENTITY, + identity_id, + account: 0, + } + }; let Some(id) = read_id32(env, &expected_id, "expectedIdentityId") else { return; }; @@ -1375,7 +1394,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShi manager as Handle, wid.as_ptr(), resolver as *mut MnemonicResolverHandle, - account as u32, + &source, username.as_ptr(), id.as_ptr(), address.as_ptr(), diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index bf26510be0f..5b6304bfb94 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -1695,6 +1695,33 @@ public struct ShieldedTipRecipient: Sendable, Equatable { public let address: Data } +/// The account a shielded tip is paid from. Rust decides which account an +/// identity's source selects, from the slot the wallet seed proves it holds. +public enum ShieldedTipSource: Sendable, Equatable { + /// The identity's dedicated tip account. + case identity(Data) + /// An ordinary account, or the tip account of a retired identity. + case account(UInt32) + + var ffi: ShieldedTipSourceFFI? { + var value = ShieldedTipSourceFFI() + switch self { + case .identity(let identityId): + guard identityId.count == 32 else { return nil } + value.kind = SHIELDED_TIP_SOURCE_IDENTITY + identityId.withUnsafeBytes { src in + Swift.withUnsafeMutableBytes(of: &value.identity_id) { dst in + dst.copyMemory(from: src) + } + } + case .account(let account): + value.kind = SHIELDED_TIP_SOURCE_ACCOUNT + value.account = account + } + return value + } +} + extension ManagedPlatformWallet { /// Fetch and verify the current DPNS identity and shielded tip address. public func resolveShieldedTip(username: String) async throws -> ShieldedTipRecipient { @@ -1739,16 +1766,17 @@ extension PlatformWalletManager { } /// Recheck the confirmed recipient before building and broadcasting the payment. - public func sendShieldedTip(walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, + public func sendShieldedTip(walletId: Data, resolver: MnemonicResolver, source: ShieldedTipSource, username: String, recipient: ShieldedTipRecipient, amount: UInt64) async throws { guard walletId.count == 32, recipient.identityId.count == 32, recipient.address.count == 43, - let resolverHandle = resolver.handle else { - throw PlatformWalletError.invalidParameter("Invalid shielded tip recipient or wallet") + let sourceFFI = source.ffi, let resolverHandle = resolver.handle else { + throw PlatformWalletError.invalidParameter("Invalid shielded tip source, recipient or wallet") } try admitNativeOp("sendShieldedTip") defer { finishNativeOp() } let handle = self.handle try await Task.detached(priority: .userInitiated) { + var source = sourceFFI try withExtendedLifetime(resolver) { try walletId.withUnsafeBytes { wallet in try recipient.identityId.withUnsafeBytes { identity in @@ -1756,7 +1784,7 @@ extension PlatformWalletManager { try username.withCString { name in try platform_wallet_manager_send_shielded_tip( handle, wallet.baseAddress!.assumingMemoryBound(to: UInt8.self), resolverHandle, - account, name, identity.baseAddress!.assumingMemoryBound(to: UInt8.self), + &source, name, identity.baseAddress!.assumingMemoryBound(to: UInt8.self), address.baseAddress!.assumingMemoryBound(to: UInt8.self), amount, nil ).check() } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md index 6ba1071ef44..2186860d536 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md @@ -716,7 +716,9 @@ were subsequently removed. Removing a published address does not revoke copies already shared or stop monitoring previously received tips. To pay a username, call `resolveShieldedTip`, show the returned identity and -address for confirmation, then call `sendShieldedTip` with that recipient. The +address for confirmation, then call `sendShieldedTip` with that recipient and a +`ShieldedTipSource`: `.identity(id)` pays from that identity's tip account, and +`.account(n)` from an ordinary account or a retired identity's tip account. The send operation verifies fresh resolution still matches the confirmed recipient. A `shieldedSpendUnconfirmed` error must not be retried automatically: the payment may already have been accepted. From ee5e9143f23672657770f5c56d70bd7bb44ff2df Mon Sep 17 00:00:00 2001 From: pasta Date: Sun, 1 Nov 2026 13:52:53 -0600 Subject: [PATCH 18/41] fix(swift-sdk): convert the tip source kinds to the struct's UInt32 cbindgen emits the SHIELDED_TIP_SOURCE_* constants as macros, which Swift imports as Int32. Co-Authored-By: Claude Opus 5.5 --- .../PlatformWallet/PlatformWalletManagerShieldedSync.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 5b6304bfb94..4e8f878ff94 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -1708,14 +1708,14 @@ public enum ShieldedTipSource: Sendable, Equatable { switch self { case .identity(let identityId): guard identityId.count == 32 else { return nil } - value.kind = SHIELDED_TIP_SOURCE_IDENTITY + value.kind = UInt32(SHIELDED_TIP_SOURCE_IDENTITY) identityId.withUnsafeBytes { src in Swift.withUnsafeMutableBytes(of: &value.identity_id) { dst in dst.copyMemory(from: src) } } case .account(let account): - value.kind = SHIELDED_TIP_SOURCE_ACCOUNT + value.kind = UInt32(SHIELDED_TIP_SOURCE_ACCOUNT) value.account = account } return value From d9464dc3bc766fc37d8b2c1eed0eb2f042750fd9 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 19:16:11 +0000 Subject: [PATCH 19/41] fix(platform-wallet): preserve tip metadata and ordinary send balances --- Cargo.lock | 1 + .../ui/wallet/SendTransactionScreen.kt | 5 +- .../17.json | 4314 +++++++++++++++++ .../dashsdk/persistence/dao/ShieldedDao.kt | 6 + .../dashsdk/persistence/DashDatabaseTest.kt | 26 + .../rs-platform-wallet-ffi/src/persistence.rs | 51 +- .../sqlite_profile_address_encoding.rs | 4 +- .../integration/sqlite_schema_pinning.rs | 4 +- packages/rs-platform-wallet/Cargo.toml | 3 + .../src/wallet/identity/network/profile.rs | 101 + .../wallet/identity/types/dashpay/profile.rs | 18 +- .../src/wallet/shielded/tips.rs | 8 +- .../wallet/shielded/viewing_key_bind_tests.rs | 55 +- .../PlatformWalletPersistenceHandler.swift | 2 +- .../Core/Views/SendTransactionView.swift | 12 +- ...PersistentShieldedNotePredicateTests.swift | 40 +- .../DashPayPersistenceTests.swift | 39 + 17 files changed, 4612 insertions(+), 77 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json diff --git a/Cargo.lock b/Cargo.lock index 8f31b4100ff..10f5b1b04f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5483,6 +5483,7 @@ dependencies = [ "key-wallet", "key-wallet-manager", "log", + "orchard", "platform-encryption", "rand 0.8.6", "rayon", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt index e1c133c12f2..a2a9664b029 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/wallet/SendTransactionScreen.kt @@ -192,12 +192,11 @@ fun SendTransactionScreen( } } - // Shielded credits — unspent-note sum from Room, only on a shielded - // build (same source WalletDetailScreen's Shielded row reads). + // Ordinary shielded sends spend account zero. val hasShielded = remember { Sdk.hasShielded() } val shieldedBalance by remember(walletIdHex) { if (hasShielded) { - container.database.shieldedDao().observeUnspentNotesByWallet(walletId) + container.database.shieldedDao().observeUnspentNotesByWalletAccount(walletId, 0) .map { notes -> notes.sumOf { it.value } } } else { MutableStateFlow(0L) diff --git a/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json b/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json new file mode 100644 index 00000000000..c51c1777fd2 --- /dev/null +++ b/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json @@ -0,0 +1,4314 @@ +{ + "formatVersion": 1, + "database": { + "version": 17, + "identityHash": "aa58da0a7ca53a564b0a4a9bf012000b", + "entities": [ + { + "tableName": "wallets", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `walletGroupId` BLOB NOT NULL, `networkRaw` INTEGER, `name` TEXT, `walletDescription` TEXT, `birthHeight` INTEGER NOT NULL, `syncedHeight` INTEGER NOT NULL, `lastSynced` INTEGER NOT NULL, `lastAppliedChainLockBytes` BLOB, `lastAppliedChainLockHeight` INTEGER, `dashPayBackfillFloor` INTEGER, `dashPayBackfillRewoundFrom` INTEGER, `dashPayBackfillCovered` BLOB, `isImported` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "walletGroupId", + "columnName": "walletGroupId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT" + }, + { + "fieldPath": "walletDescription", + "columnName": "walletDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "birthHeight", + "columnName": "birthHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncedHeight", + "columnName": "syncedHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSynced", + "columnName": "lastSynced", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAppliedChainLockBytes", + "columnName": "lastAppliedChainLockBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "lastAppliedChainLockHeight", + "columnName": "lastAppliedChainLockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "dashPayBackfillFloor", + "columnName": "dashPayBackfillFloor", + "affinity": "INTEGER" + }, + { + "fieldPath": "dashPayBackfillRewoundFrom", + "columnName": "dashPayBackfillRewoundFrom", + "affinity": "INTEGER" + }, + { + "fieldPath": "dashPayBackfillCovered", + "columnName": "dashPayBackfillCovered", + "affinity": "BLOB" + }, + { + "fieldPath": "isImported", + "columnName": "isImported", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_wallets_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallets_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_wallets_walletGroupId", + "unique": false, + "columnNames": [ + "walletGroupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_wallets_walletGroupId` ON `${TABLE_NAME}` (`walletGroupId`)" + } + ] + }, + { + "tableName": "accounts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `walletId` BLOB NOT NULL, `accountType` INTEGER NOT NULL, `accountIndex` INTEGER NOT NULL, `accountTypeName` TEXT NOT NULL, `balanceConfirmed` INTEGER NOT NULL, `balanceUnconfirmed` INTEGER NOT NULL, `externalHighestUsed` INTEGER NOT NULL, `internalHighestUsed` INTEGER NOT NULL, `standardTag` INTEGER NOT NULL, `registrationIndex` INTEGER NOT NULL, `keyClass` INTEGER NOT NULL, `userIdentityId` BLOB NOT NULL, `friendIdentityId` BLOB NOT NULL, `accountExtendedPubKeyBytes` BLOB, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, FOREIGN KEY(`walletId`) REFERENCES `wallets`(`walletId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountType", + "columnName": "accountType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountTypeName", + "columnName": "accountTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "balanceConfirmed", + "columnName": "balanceConfirmed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "balanceUnconfirmed", + "columnName": "balanceUnconfirmed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "externalHighestUsed", + "columnName": "externalHighestUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "internalHighestUsed", + "columnName": "internalHighestUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "standardTag", + "columnName": "standardTag", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "registrationIndex", + "columnName": "registrationIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keyClass", + "columnName": "keyClass", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "userIdentityId", + "columnName": "userIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "friendIdentityId", + "columnName": "friendIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountExtendedPubKeyBytes", + "columnName": "accountExtendedPubKeyBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_accounts_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_accounts_walletId` ON `${TABLE_NAME}` (`walletId`)" + }, + { + "name": "index_accounts_walletId_accountType_accountIndex_standardTag_registrationIndex_keyClass_userIdentityId_friendIdentityId", + "unique": true, + "columnNames": [ + "walletId", + "accountType", + "accountIndex", + "standardTag", + "registrationIndex", + "keyClass", + "userIdentityId", + "friendIdentityId" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_accounts_walletId_accountType_accountIndex_standardTag_registrationIndex_keyClass_userIdentityId_friendIdentityId` ON `${TABLE_NAME}` (`walletId`, `accountType`, `accountIndex`, `standardTag`, `registrationIndex`, `keyClass`, `userIdentityId`, `friendIdentityId`)" + }, + { + "name": "index_accounts_accountExtendedPubKeyBytes", + "unique": true, + "columnNames": [ + "accountExtendedPubKeyBytes" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_accounts_accountExtendedPubKeyBytes` ON `${TABLE_NAME}` (`accountExtendedPubKeyBytes`)" + } + ], + "foreignKeys": [ + { + "table": "wallets", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "walletId" + ], + "referencedColumns": [ + "walletId" + ] + } + ] + }, + { + "tableName": "transactions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`txid` BLOB NOT NULL, `transactionData` BLOB NOT NULL, `context` INTEGER NOT NULL, `blockHeight` INTEGER NOT NULL, `blockHash` BLOB, `blockTimestamp` INTEGER NOT NULL, `blockPosition` INTEGER NOT NULL, `hasBlockPosition` INTEGER NOT NULL, `direction` INTEGER NOT NULL, `transactionType` TEXT NOT NULL, `transactionTypeKind` INTEGER NOT NULL, `netAmount` INTEGER NOT NULL, `fee` INTEGER, `label` TEXT NOT NULL, `firstSeen` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`txid`))", + "fields": [ + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "transactionData", + "columnName": "transactionData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "context", + "columnName": "context", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockHash", + "columnName": "blockHash", + "affinity": "BLOB" + }, + { + "fieldPath": "blockTimestamp", + "columnName": "blockTimestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockPosition", + "columnName": "blockPosition", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasBlockPosition", + "columnName": "hasBlockPosition", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "transactionType", + "columnName": "transactionType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "transactionTypeKind", + "columnName": "transactionTypeKind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "netAmount", + "columnName": "netAmount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fee", + "columnName": "fee", + "affinity": "INTEGER" + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "firstSeen", + "columnName": "firstSeen", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "txid" + ] + }, + "indices": [ + { + "name": "index_transactions_firstSeen", + "unique": false, + "columnNames": [ + "firstSeen" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_transactions_firstSeen` ON `${TABLE_NAME}` (`firstSeen`)" + } + ] + }, + { + "tableName": "transaction_account_involvements", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`transactionTxid` BLOB NOT NULL, `accountId` INTEGER NOT NULL, PRIMARY KEY(`transactionTxid`, `accountId`), FOREIGN KEY(`transactionTxid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "transactionTxid", + "columnName": "transactionTxid", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "transactionTxid", + "accountId" + ] + }, + "indices": [ + { + "name": "index_transaction_account_involvements_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_transaction_account_involvements_accountId` ON `${TABLE_NAME}` (`accountId`)" + } + ], + "foreignKeys": [ + { + "table": "transactions", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "transactionTxid" + ], + "referencedColumns": [ + "txid" + ] + }, + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "txos", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`outpoint` BLOB NOT NULL, `vout` INTEGER NOT NULL, `amount` INTEGER NOT NULL, `address` TEXT NOT NULL, `scriptPubKey` BLOB NOT NULL, `height` INTEGER NOT NULL, `isCoinbase` INTEGER NOT NULL, `isConfirmed` INTEGER NOT NULL, `isInstantLocked` INTEGER NOT NULL, `isLocked` INTEGER NOT NULL, `isSpent` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `walletId` BLOB NOT NULL, `txid` BLOB, `spendingTxid` BLOB, `spendingInputIndex` INTEGER, `accountId` INTEGER, `coreAddressId` TEXT, `supersededByTxid` BLOB, PRIMARY KEY(`outpoint`), FOREIGN KEY(`txid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`spendingTxid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`coreAddressId`) REFERENCES `core_addresses`(`address`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "outpoint", + "columnName": "outpoint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "vout", + "columnName": "vout", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scriptPubKey", + "columnName": "scriptPubKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "height", + "columnName": "height", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isCoinbase", + "columnName": "isCoinbase", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isConfirmed", + "columnName": "isConfirmed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isInstantLocked", + "columnName": "isInstantLocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isLocked", + "columnName": "isLocked", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSpent", + "columnName": "isSpent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "BLOB" + }, + { + "fieldPath": "spendingTxid", + "columnName": "spendingTxid", + "affinity": "BLOB" + }, + { + "fieldPath": "spendingInputIndex", + "columnName": "spendingInputIndex", + "affinity": "INTEGER" + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER" + }, + { + "fieldPath": "coreAddressId", + "columnName": "coreAddressId", + "affinity": "TEXT" + }, + { + "fieldPath": "supersededByTxid", + "columnName": "supersededByTxid", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "outpoint" + ] + }, + "indices": [ + { + "name": "index_txos_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_walletId` ON `${TABLE_NAME}` (`walletId`)" + }, + { + "name": "index_txos_txid", + "unique": false, + "columnNames": [ + "txid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_txid` ON `${TABLE_NAME}` (`txid`)" + }, + { + "name": "index_txos_spendingTxid", + "unique": false, + "columnNames": [ + "spendingTxid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_spendingTxid` ON `${TABLE_NAME}` (`spendingTxid`)" + }, + { + "name": "index_txos_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_accountId` ON `${TABLE_NAME}` (`accountId`)" + }, + { + "name": "index_txos_coreAddressId", + "unique": false, + "columnNames": [ + "coreAddressId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_txos_coreAddressId` ON `${TABLE_NAME}` (`coreAddressId`)" + } + ], + "foreignKeys": [ + { + "table": "transactions", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "txid" + ], + "referencedColumns": [ + "txid" + ] + }, + { + "table": "transactions", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "spendingTxid" + ], + "referencedColumns": [ + "txid" + ] + }, + { + "table": "accounts", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "core_addresses", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "coreAddressId" + ], + "referencedColumns": [ + "address" + ] + } + ] + }, + { + "tableName": "core_addresses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `publicKey` BLOB NOT NULL, `poolTypeTag` INTEGER NOT NULL, `addressIndex` INTEGER NOT NULL, `derivationPath` TEXT NOT NULL, `isUsed` INTEGER NOT NULL, `firstSeenHeight` INTEGER NOT NULL, `lastSeenHeight` INTEGER NOT NULL, `balance` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `accountId` INTEGER, PRIMARY KEY(`address`), FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "poolTypeTag", + "columnName": "poolTypeTag", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addressIndex", + "columnName": "addressIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUsed", + "columnName": "isUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "firstSeenHeight", + "columnName": "firstSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSeenHeight", + "columnName": "lastSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "address" + ] + }, + "indices": [ + { + "name": "index_core_addresses_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_core_addresses_accountId` ON `${TABLE_NAME}` (`accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "asset_locks", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`outPointHex` TEXT NOT NULL, `walletId` BLOB NOT NULL, `transactionBytes` BLOB NOT NULL, `fundingTypeRaw` INTEGER NOT NULL, `identityIndexRaw` INTEGER NOT NULL, `accountIndexRaw` INTEGER NOT NULL, `amountDuffs` INTEGER NOT NULL, `statusRaw` INTEGER NOT NULL, `proofBytes` BLOB, `recipientPlatformAddressHash` BLOB, `recipientPlatformAddressType` INTEGER, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`outPointHex`))", + "fields": [ + { + "fieldPath": "outPointHex", + "columnName": "outPointHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "transactionBytes", + "columnName": "transactionBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "fundingTypeRaw", + "columnName": "fundingTypeRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityIndexRaw", + "columnName": "identityIndexRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountIndexRaw", + "columnName": "accountIndexRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amountDuffs", + "columnName": "amountDuffs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "statusRaw", + "columnName": "statusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "proofBytes", + "columnName": "proofBytes", + "affinity": "BLOB" + }, + { + "fieldPath": "recipientPlatformAddressHash", + "columnName": "recipientPlatformAddressHash", + "affinity": "BLOB" + }, + { + "fieldPath": "recipientPlatformAddressType", + "columnName": "recipientPlatformAddressType", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "outPointHex" + ] + }, + "indices": [ + { + "name": "index_asset_locks_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_asset_locks_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "invitations", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`outPointHex` TEXT NOT NULL, `rawOutPoint` BLOB NOT NULL, `walletId` BLOB NOT NULL, `fundingIndexRaw` INTEGER NOT NULL, `amountDuffs` INTEGER NOT NULL, `expiryUnix` INTEGER NOT NULL, `createdAtSecs` INTEGER NOT NULL, `hasInviter` INTEGER NOT NULL, `statusRaw` INTEGER NOT NULL, `reclaimInFlight` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`outPointHex`))", + "fields": [ + { + "fieldPath": "outPointHex", + "columnName": "outPointHex", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "rawOutPoint", + "columnName": "rawOutPoint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "fundingIndexRaw", + "columnName": "fundingIndexRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amountDuffs", + "columnName": "amountDuffs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "expiryUnix", + "columnName": "expiryUnix", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtSecs", + "columnName": "createdAtSecs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasInviter", + "columnName": "hasInviter", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "statusRaw", + "columnName": "statusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reclaimInFlight", + "columnName": "reclaimInFlight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "outPointHex" + ] + }, + "indices": [ + { + "name": "index_invitations_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_invitations_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "identities", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`identityId` BLOB NOT NULL, `balance` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `isLocal` INTEGER NOT NULL, `alias` TEXT, `dpnsName` TEXT, `mainDpnsName` TEXT, `identityType` TEXT NOT NULL, `votingPrivateKeyIdentifier` TEXT, `ownerPrivateKeyIdentifier` TEXT, `payoutPrivateKeyIdentifier` TEXT, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `lastSyncedAt` INTEGER, `networkRaw` INTEGER NOT NULL, `walletId` BLOB, `identityIndex` INTEGER NOT NULL, PRIMARY KEY(`identityId`), FOREIGN KEY(`walletId`) REFERENCES `wallets`(`walletId`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "revision", + "columnName": "revision", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isLocal", + "columnName": "isLocal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "alias", + "columnName": "alias", + "affinity": "TEXT" + }, + { + "fieldPath": "dpnsName", + "columnName": "dpnsName", + "affinity": "TEXT" + }, + { + "fieldPath": "mainDpnsName", + "columnName": "mainDpnsName", + "affinity": "TEXT" + }, + { + "fieldPath": "identityType", + "columnName": "identityType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "votingPrivateKeyIdentifier", + "columnName": "votingPrivateKeyIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "ownerPrivateKeyIdentifier", + "columnName": "ownerPrivateKeyIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "payoutPrivateKeyIdentifier", + "columnName": "payoutPrivateKeyIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedAt", + "columnName": "lastSyncedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB" + }, + { + "fieldPath": "identityIndex", + "columnName": "identityIndex", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "identityId" + ] + }, + "indices": [ + { + "name": "index_identities_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_identities_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_identities_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_identities_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ], + "foreignKeys": [ + { + "table": "wallets", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "walletId" + ], + "referencedColumns": [ + "walletId" + ] + } + ] + }, + { + "tableName": "public_keys", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `keyId` INTEGER NOT NULL, `purpose` TEXT NOT NULL, `securityLevel` TEXT NOT NULL, `keyType` TEXT NOT NULL, `readOnly` INTEGER NOT NULL, `disabledAt` INTEGER, `totalBudget` INTEGER, `expiresAt` INTEGER, `publicKeyData` BLOB NOT NULL, `contractBoundsData` BLOB, `contractBoundsDocumentTypeName` TEXT, `contractBoundsKind` INTEGER, `privateKeyKeychainIdentifier` TEXT, `derivationIdentityIndex` INTEGER, `derivationKeyIndex` INTEGER, `identityId` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `lastAccessed` INTEGER, `identityIdData` BLOB, FOREIGN KEY(`identityIdData`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keyId", + "columnName": "keyId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "purpose", + "columnName": "purpose", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "securityLevel", + "columnName": "securityLevel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyType", + "columnName": "keyType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "readOnly", + "columnName": "readOnly", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "disabledAt", + "columnName": "disabledAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "totalBudget", + "columnName": "totalBudget", + "affinity": "INTEGER" + }, + { + "fieldPath": "expiresAt", + "columnName": "expiresAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicKeyData", + "columnName": "publicKeyData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractBoundsData", + "columnName": "contractBoundsData", + "affinity": "BLOB" + }, + { + "fieldPath": "contractBoundsDocumentTypeName", + "columnName": "contractBoundsDocumentTypeName", + "affinity": "TEXT" + }, + { + "fieldPath": "contractBoundsKind", + "columnName": "contractBoundsKind", + "affinity": "INTEGER" + }, + { + "fieldPath": "privateKeyKeychainIdentifier", + "columnName": "privateKeyKeychainIdentifier", + "affinity": "TEXT" + }, + { + "fieldPath": "derivationIdentityIndex", + "columnName": "derivationIdentityIndex", + "affinity": "INTEGER" + }, + { + "fieldPath": "derivationKeyIndex", + "columnName": "derivationKeyIndex", + "affinity": "INTEGER" + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAccessed", + "columnName": "lastAccessed", + "affinity": "INTEGER" + }, + { + "fieldPath": "identityIdData", + "columnName": "identityIdData", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_public_keys_identityId_keyId", + "unique": false, + "columnNames": [ + "identityId", + "keyId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_public_keys_identityId_keyId` ON `${TABLE_NAME}` (`identityId`, `keyId`)" + }, + { + "name": "index_public_keys_identityIdData", + "unique": false, + "columnNames": [ + "identityIdData" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_public_keys_identityIdData` ON `${TABLE_NAME}` (`identityIdData`)" + }, + { + "name": "index_public_keys_publicKeyData", + "unique": false, + "columnNames": [ + "publicKeyData" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_public_keys_publicKeyData` ON `${TABLE_NAME}` (`publicKeyData`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "identityIdData" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dpns_names", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `label` TEXT NOT NULL, `normalizedLabel` TEXT NOT NULL, `parentDomainName` TEXT NOT NULL, `normalizedParentDomainName` TEXT NOT NULL, `acquiredAt` INTEGER NOT NULL, `identityId` BLOB NOT NULL, `documentId` BLOB, `isOwned` INTEGER NOT NULL, `priceCredits` INTEGER, `saleStatusRaw` INTEGER NOT NULL, `counterpartyIdentityId` BLOB, `documentCreatedAtMs` INTEGER NOT NULL, `documentUpdatedAtMs` INTEGER NOT NULL, `documentTransferredAtMs` INTEGER NOT NULL, `marketplaceUpdatedAt` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `normalizedParentDomainName`, `normalizedLabel`), FOREIGN KEY(`identityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "label", + "columnName": "label", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "normalizedLabel", + "columnName": "normalizedLabel", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "parentDomainName", + "columnName": "parentDomainName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "normalizedParentDomainName", + "columnName": "normalizedParentDomainName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "acquiredAt", + "columnName": "acquiredAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentId", + "columnName": "documentId", + "affinity": "BLOB" + }, + { + "fieldPath": "isOwned", + "columnName": "isOwned", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "priceCredits", + "columnName": "priceCredits", + "affinity": "INTEGER" + }, + { + "fieldPath": "saleStatusRaw", + "columnName": "saleStatusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "counterpartyIdentityId", + "columnName": "counterpartyIdentityId", + "affinity": "BLOB" + }, + { + "fieldPath": "documentCreatedAtMs", + "columnName": "documentCreatedAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentUpdatedAtMs", + "columnName": "documentUpdatedAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTransferredAtMs", + "columnName": "documentTransferredAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "marketplaceUpdatedAt", + "columnName": "marketplaceUpdatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "normalizedParentDomainName", + "normalizedLabel" + ] + }, + "indices": [ + { + "name": "index_dpns_names_identityId", + "unique": false, + "columnNames": [ + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dpns_names_identityId` ON `${TABLE_NAME}` (`identityId`)" + }, + { + "name": "index_dpns_names_documentId", + "unique": false, + "columnNames": [ + "documentId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dpns_names_documentId` ON `${TABLE_NAME}` (`documentId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "identityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_profiles", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `identityId` BLOB NOT NULL, `displayName` TEXT, `publicMessage` TEXT, `bio` TEXT, `avatarUrl` TEXT, `avatarHash` BLOB, `avatarFingerprint` BLOB, `corePaymentAddress` BLOB, `platformPaymentAddress` BLOB, `shieldedAddress` BLOB, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `identityId`), FOREIGN KEY(`identityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "publicMessage", + "columnName": "publicMessage", + "affinity": "TEXT" + }, + { + "fieldPath": "bio", + "columnName": "bio", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarHash", + "columnName": "avatarHash", + "affinity": "BLOB" + }, + { + "fieldPath": "avatarFingerprint", + "columnName": "avatarFingerprint", + "affinity": "BLOB" + }, + { + "fieldPath": "corePaymentAddress", + "columnName": "corePaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "platformPaymentAddress", + "columnName": "platformPaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "shieldedAddress", + "columnName": "shieldedAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "identityId" + ] + }, + "indices": [ + { + "name": "index_dashpay_profiles_identityId", + "unique": false, + "columnNames": [ + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_profiles_identityId` ON `${TABLE_NAME}` (`identityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "identityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_contact_requests", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `contactIdentityId` BLOB NOT NULL, `isOutgoing` INTEGER NOT NULL, `senderKeyIndex` INTEGER NOT NULL, `recipientKeyIndex` INTEGER NOT NULL, `accountReference` INTEGER NOT NULL, `encryptedPublicKey` BLOB NOT NULL, `encryptedAccountLabel` BLOB, `autoAcceptProof` BLOB, `coreHeightCreatedAt` INTEGER NOT NULL, `createdAtMillis` INTEGER NOT NULL, `paymentChannelBroken` INTEGER NOT NULL DEFAULT 0, `contactAlias` TEXT, `contactNote` TEXT, `contactHidden` INTEGER NOT NULL DEFAULT 0, `contactAccountLabel` TEXT, `contactAcceptedAccounts` BLOB, `externalAccountReference` INTEGER, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `contactIdentityId`, `isOutgoing`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contactIdentityId", + "columnName": "contactIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "isOutgoing", + "columnName": "isOutgoing", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderKeyIndex", + "columnName": "senderKeyIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recipientKeyIndex", + "columnName": "recipientKeyIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountReference", + "columnName": "accountReference", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "encryptedPublicKey", + "columnName": "encryptedPublicKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "encryptedAccountLabel", + "columnName": "encryptedAccountLabel", + "affinity": "BLOB" + }, + { + "fieldPath": "autoAcceptProof", + "columnName": "autoAcceptProof", + "affinity": "BLOB" + }, + { + "fieldPath": "coreHeightCreatedAt", + "columnName": "coreHeightCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtMillis", + "columnName": "createdAtMillis", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "paymentChannelBroken", + "columnName": "paymentChannelBroken", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "contactAlias", + "columnName": "contactAlias", + "affinity": "TEXT" + }, + { + "fieldPath": "contactNote", + "columnName": "contactNote", + "affinity": "TEXT" + }, + { + "fieldPath": "contactHidden", + "columnName": "contactHidden", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "contactAccountLabel", + "columnName": "contactAccountLabel", + "affinity": "TEXT" + }, + { + "fieldPath": "contactAcceptedAccounts", + "columnName": "contactAcceptedAccounts", + "affinity": "BLOB" + }, + { + "fieldPath": "externalAccountReference", + "columnName": "externalAccountReference", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "contactIdentityId", + "isOutgoing" + ] + }, + "indices": [ + { + "name": "index_dashpay_contact_requests_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_contact_requests_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_ignored_senders", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `ignoredSenderId` BLOB NOT NULL, `ignoredAt` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `ignoredSenderId`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ignoredSenderId", + "columnName": "ignoredSenderId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ignoredAt", + "columnName": "ignoredAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "ignoredSenderId" + ] + }, + "indices": [ + { + "name": "index_dashpay_ignored_senders_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_ignored_senders_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_contact_profiles", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `contactIdentityId` BLOB NOT NULL, `displayName` TEXT, `publicMessage` TEXT, `bio` TEXT, `avatarUrl` TEXT, `avatarHash` BLOB, `avatarFingerprint` BLOB, `corePaymentAddress` BLOB, `platformPaymentAddress` BLOB, `shieldedAddress` BLOB, `checkedAtMs` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `contactIdentityId`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contactIdentityId", + "columnName": "contactIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT" + }, + { + "fieldPath": "publicMessage", + "columnName": "publicMessage", + "affinity": "TEXT" + }, + { + "fieldPath": "bio", + "columnName": "bio", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarUrl", + "columnName": "avatarUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "avatarHash", + "columnName": "avatarHash", + "affinity": "BLOB" + }, + { + "fieldPath": "avatarFingerprint", + "columnName": "avatarFingerprint", + "affinity": "BLOB" + }, + { + "fieldPath": "corePaymentAddress", + "columnName": "corePaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "platformPaymentAddress", + "columnName": "platformPaymentAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "shieldedAddress", + "columnName": "shieldedAddress", + "affinity": "BLOB" + }, + { + "fieldPath": "checkedAtMs", + "columnName": "checkedAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "contactIdentityId" + ] + }, + "indices": [ + { + "name": "index_dashpay_contact_profiles_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_contact_profiles_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "dashpay_payments", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `ownerIdentityId` BLOB NOT NULL, `counterpartyIdentityId` BLOB NOT NULL, `amountDuffs` INTEGER NOT NULL, `directionRaw` INTEGER NOT NULL, `statusRaw` INTEGER NOT NULL, `txid` TEXT NOT NULL, `memo` TEXT, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`, `ownerIdentityId`, `txid`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "counterpartyIdentityId", + "columnName": "counterpartyIdentityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "amountDuffs", + "columnName": "amountDuffs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "directionRaw", + "columnName": "directionRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "statusRaw", + "columnName": "statusRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "txid", + "columnName": "txid", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "memo", + "columnName": "memo", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw", + "ownerIdentityId", + "txid" + ] + }, + "indices": [ + { + "name": "index_dashpay_payments_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_dashpay_payments_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "data_contracts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `name` TEXT NOT NULL, `serializedContract` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastAccessedAt` INTEGER NOT NULL, `binarySerialization` BLOB, `version` INTEGER, `ownerId` BLOB, `contractDescription` TEXT, `schemaData` BLOB NOT NULL, `documentTypesData` BLOB NOT NULL, `groupsData` BLOB, `networkRaw` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `lastSyncedAt` INTEGER, `canBeDeleted` INTEGER NOT NULL, `readonly` INTEGER NOT NULL, `keepsHistory` INTEGER NOT NULL, `schemaDefs` INTEGER, `documentsKeepHistoryContractDefault` INTEGER NOT NULL, `documentsMutableContractDefault` INTEGER NOT NULL, `documentsCanBeDeletedContractDefault` INTEGER NOT NULL, `hasTokens` INTEGER NOT NULL, `tokensData` BLOB, `ownerIdentityId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE SET NULL )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "serializedContract", + "columnName": "serializedContract", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAccessedAt", + "columnName": "lastAccessedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "binarySerialization", + "columnName": "binarySerialization", + "affinity": "BLOB" + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER" + }, + { + "fieldPath": "ownerId", + "columnName": "ownerId", + "affinity": "BLOB" + }, + { + "fieldPath": "contractDescription", + "columnName": "contractDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "schemaData", + "columnName": "schemaData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentTypesData", + "columnName": "documentTypesData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "groupsData", + "columnName": "groupsData", + "affinity": "BLOB" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedAt", + "columnName": "lastSyncedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "canBeDeleted", + "columnName": "canBeDeleted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "readonly", + "columnName": "readonly", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsHistory", + "columnName": "keepsHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "schemaDefs", + "columnName": "schemaDefs", + "affinity": "INTEGER" + }, + { + "fieldPath": "documentsKeepHistoryContractDefault", + "columnName": "documentsKeepHistoryContractDefault", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsMutableContractDefault", + "columnName": "documentsMutableContractDefault", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsCanBeDeletedContractDefault", + "columnName": "documentsCanBeDeletedContractDefault", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasTokens", + "columnName": "hasTokens", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tokensData", + "columnName": "tokensData", + "affinity": "BLOB" + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_data_contracts_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_data_contracts_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_data_contracts_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_data_contracts_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "document_types", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `name` TEXT NOT NULL, `schemaJSON` BLOB NOT NULL, `propertiesJSON` BLOB NOT NULL, `documentsKeepHistory` INTEGER NOT NULL, `documentsMutable` INTEGER NOT NULL, `documentsCanBeDeleted` INTEGER NOT NULL, `documentsTransferable` INTEGER NOT NULL, `requiredFieldsJSON` BLOB, `securityLevel` INTEGER NOT NULL, `tradeMode` INTEGER NOT NULL, `creationRestrictionMode` INTEGER NOT NULL, `requiresIdentityEncryptionBoundedKey` INTEGER NOT NULL, `requiresIdentityDecryptionBoundedKey` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastAccessedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`contractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "schemaJSON", + "columnName": "schemaJSON", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "propertiesJSON", + "columnName": "propertiesJSON", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentsKeepHistory", + "columnName": "documentsKeepHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsMutable", + "columnName": "documentsMutable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsCanBeDeleted", + "columnName": "documentsCanBeDeleted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentsTransferable", + "columnName": "documentsTransferable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiredFieldsJSON", + "columnName": "requiredFieldsJSON", + "affinity": "BLOB" + }, + { + "fieldPath": "securityLevel", + "columnName": "securityLevel", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tradeMode", + "columnName": "tradeMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "creationRestrictionMode", + "columnName": "creationRestrictionMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiresIdentityEncryptionBoundedKey", + "columnName": "requiresIdentityEncryptionBoundedKey", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "requiresIdentityDecryptionBoundedKey", + "columnName": "requiresIdentityDecryptionBoundedKey", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastAccessedAt", + "columnName": "lastAccessedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_document_types_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_document_types_contractId` ON `${TABLE_NAME}` (`contractId`)" + } + ], + "foreignKeys": [ + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "contractId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "documents", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`documentId` TEXT NOT NULL, `documentType` TEXT NOT NULL, `revision` INTEGER NOT NULL, `data` BLOB NOT NULL, `contractId` TEXT NOT NULL, `ownerId` TEXT NOT NULL, `contractIdData` BLOB NOT NULL, `ownerIdData` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `transferredAt` INTEGER, `createdAtBlockHeight` INTEGER, `updatedAtBlockHeight` INTEGER, `transferredAtBlockHeight` INTEGER, `createdAtCoreBlockHeight` INTEGER, `updatedAtCoreBlockHeight` INTEGER, `transferredAtCoreBlockHeight` INTEGER, `networkRaw` INTEGER NOT NULL, `isDeleted` INTEGER NOT NULL, `localCreatedAt` INTEGER NOT NULL, `localUpdatedAt` INTEGER NOT NULL, `documentTypeRelationId` BLOB, `dataContractId` BLOB, `ownerIdentityId` BLOB, PRIMARY KEY(`documentId`), FOREIGN KEY(`documentTypeRelationId`) REFERENCES `document_types`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`dataContractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`ownerIdentityId`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "documentId", + "columnName": "documentId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "documentType", + "columnName": "documentType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "revision", + "columnName": "revision", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "data", + "columnName": "data", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ownerId", + "columnName": "ownerId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "contractIdData", + "columnName": "contractIdData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ownerIdData", + "columnName": "ownerIdData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "transferredAt", + "columnName": "transferredAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAtBlockHeight", + "columnName": "createdAtBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "updatedAtBlockHeight", + "columnName": "updatedAtBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "transferredAtBlockHeight", + "columnName": "transferredAtBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "createdAtCoreBlockHeight", + "columnName": "createdAtCoreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "updatedAtCoreBlockHeight", + "columnName": "updatedAtCoreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "transferredAtCoreBlockHeight", + "columnName": "transferredAtCoreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isDeleted", + "columnName": "isDeleted", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "localCreatedAt", + "columnName": "localCreatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "localUpdatedAt", + "columnName": "localUpdatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTypeRelationId", + "columnName": "documentTypeRelationId", + "affinity": "BLOB" + }, + { + "fieldPath": "dataContractId", + "columnName": "dataContractId", + "affinity": "BLOB" + }, + { + "fieldPath": "ownerIdentityId", + "columnName": "ownerIdentityId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "documentId" + ] + }, + "indices": [ + { + "name": "index_documents_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_documents_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_contractId` ON `${TABLE_NAME}` (`contractId`)" + }, + { + "name": "index_documents_ownerId", + "unique": false, + "columnNames": [ + "ownerId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_ownerId` ON `${TABLE_NAME}` (`ownerId`)" + }, + { + "name": "index_documents_documentTypeRelationId", + "unique": false, + "columnNames": [ + "documentTypeRelationId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_documentTypeRelationId` ON `${TABLE_NAME}` (`documentTypeRelationId`)" + }, + { + "name": "index_documents_dataContractId", + "unique": false, + "columnNames": [ + "dataContractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_dataContractId` ON `${TABLE_NAME}` (`dataContractId`)" + }, + { + "name": "index_documents_ownerIdentityId", + "unique": false, + "columnNames": [ + "ownerIdentityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_documents_ownerIdentityId` ON `${TABLE_NAME}` (`ownerIdentityId`)" + } + ], + "foreignKeys": [ + { + "table": "document_types", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "documentTypeRelationId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dataContractId" + ], + "referencedColumns": [ + "id" + ] + }, + { + "table": "identities", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "ownerIdentityId" + ], + "referencedColumns": [ + "identityId" + ] + } + ] + }, + { + "tableName": "indices", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `documentTypeName` TEXT NOT NULL, `name` TEXT NOT NULL, `unique` INTEGER NOT NULL, `nullSearchable` INTEGER NOT NULL, `contested` INTEGER NOT NULL, `propertiesJSON` BLOB NOT NULL, `contestedDetailsJSON` BLOB, `createdAt` INTEGER NOT NULL, `documentTypeId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`documentTypeId`) REFERENCES `document_types`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentTypeName", + "columnName": "documentTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "unique", + "columnName": "unique", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nullSearchable", + "columnName": "nullSearchable", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contested", + "columnName": "contested", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "propertiesJSON", + "columnName": "propertiesJSON", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contestedDetailsJSON", + "columnName": "contestedDetailsJSON", + "affinity": "BLOB" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTypeId", + "columnName": "documentTypeId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_indices_documentTypeId", + "unique": false, + "columnNames": [ + "documentTypeId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_indices_documentTypeId` ON `${TABLE_NAME}` (`documentTypeId`)" + } + ], + "foreignKeys": [ + { + "table": "document_types", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "documentTypeId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "keywords", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `keyword` TEXT NOT NULL, `contractId` TEXT NOT NULL, `dataContractId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`dataContractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyword", + "columnName": "keyword", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "dataContractId", + "columnName": "dataContractId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_keywords_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_keywords_contractId` ON `${TABLE_NAME}` (`contractId`)" + }, + { + "name": "index_keywords_dataContractId", + "unique": false, + "columnNames": [ + "dataContractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_keywords_dataContractId` ON `${TABLE_NAME}` (`dataContractId`)" + } + ], + "foreignKeys": [ + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "dataContractId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "properties", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `documentTypeName` TEXT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `format` TEXT, `contentMediaType` TEXT, `byteArray` INTEGER NOT NULL, `minItems` INTEGER, `maxItems` INTEGER, `pattern` TEXT, `minLength` INTEGER, `maxLength` INTEGER, `minValue` INTEGER, `maxValue` INTEGER, `fieldDescription` TEXT, `transient` INTEGER NOT NULL, `isRequired` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `documentTypeId` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`documentTypeId`) REFERENCES `document_types`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "documentTypeName", + "columnName": "documentTypeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "format", + "columnName": "format", + "affinity": "TEXT" + }, + { + "fieldPath": "contentMediaType", + "columnName": "contentMediaType", + "affinity": "TEXT" + }, + { + "fieldPath": "byteArray", + "columnName": "byteArray", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "minItems", + "columnName": "minItems", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxItems", + "columnName": "maxItems", + "affinity": "INTEGER" + }, + { + "fieldPath": "pattern", + "columnName": "pattern", + "affinity": "TEXT" + }, + { + "fieldPath": "minLength", + "columnName": "minLength", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxLength", + "columnName": "maxLength", + "affinity": "INTEGER" + }, + { + "fieldPath": "minValue", + "columnName": "minValue", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxValue", + "columnName": "maxValue", + "affinity": "INTEGER" + }, + { + "fieldPath": "fieldDescription", + "columnName": "fieldDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "transient", + "columnName": "transient", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isRequired", + "columnName": "isRequired", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "documentTypeId", + "columnName": "documentTypeId", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_properties_documentTypeId", + "unique": false, + "columnNames": [ + "documentTypeId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_properties_documentTypeId` ON `${TABLE_NAME}` (`documentTypeId`)" + } + ], + "foreignKeys": [ + { + "table": "document_types", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "documentTypeId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "pending_inputs", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `outpoint` BLOB NOT NULL, `inputIndex` INTEGER NOT NULL, `spendingTxid` BLOB NOT NULL, `spendingTransactionTxid` BLOB, `walletId` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `isSweptTombstone` INTEGER NOT NULL DEFAULT 0, `winnerMinedHeight` INTEGER, FOREIGN KEY(`spendingTransactionTxid`) REFERENCES `transactions`(`txid`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "outpoint", + "columnName": "outpoint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "inputIndex", + "columnName": "inputIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "spendingTxid", + "columnName": "spendingTxid", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "spendingTransactionTxid", + "columnName": "spendingTransactionTxid", + "affinity": "BLOB" + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSweptTombstone", + "columnName": "isSweptTombstone", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "winnerMinedHeight", + "columnName": "winnerMinedHeight", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_pending_inputs_outpoint", + "unique": false, + "columnNames": [ + "outpoint" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_outpoint` ON `${TABLE_NAME}` (`outpoint`)" + }, + { + "name": "index_pending_inputs_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_walletId` ON `${TABLE_NAME}` (`walletId`)" + }, + { + "name": "index_pending_inputs_spendingTransactionTxid", + "unique": false, + "columnNames": [ + "spendingTransactionTxid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_spendingTransactionTxid` ON `${TABLE_NAME}` (`spendingTransactionTxid`)" + }, + { + "name": "index_pending_inputs_spendingTxid", + "unique": false, + "columnNames": [ + "spendingTxid" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_spendingTxid` ON `${TABLE_NAME}` (`spendingTxid`)" + }, + { + "name": "index_pending_inputs_walletId_isSweptTombstone_winnerMinedHeight", + "unique": false, + "columnNames": [ + "walletId", + "isSweptTombstone", + "winnerMinedHeight" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_pending_inputs_walletId_isSweptTombstone_winnerMinedHeight` ON `${TABLE_NAME}` (`walletId`, `isSweptTombstone`, `winnerMinedHeight`)" + } + ], + "foreignKeys": [ + { + "table": "transactions", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "spendingTransactionTxid" + ], + "referencedColumns": [ + "txid" + ] + } + ] + }, + { + "tableName": "tokens", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` BLOB NOT NULL, `contractId` BLOB NOT NULL, `position` INTEGER NOT NULL, `name` TEXT NOT NULL, `baseSupply` TEXT NOT NULL, `maxSupply` TEXT, `decimals` INTEGER NOT NULL, `localizations` TEXT, `isPaused` INTEGER NOT NULL, `allowTransferToFrozenBalance` INTEGER NOT NULL, `keepsTransferHistory` INTEGER NOT NULL, `keepsFreezingHistory` INTEGER NOT NULL, `keepsMintingHistory` INTEGER NOT NULL, `keepsBurningHistory` INTEGER NOT NULL, `keepsDirectPricingHistory` INTEGER NOT NULL, `keepsDirectPurchaseHistory` INTEGER NOT NULL, `conventionsChangeRules` TEXT, `maxSupplyChangeRules` TEXT, `manualMintingRules` TEXT, `manualBurningRules` TEXT, `freezeRules` TEXT, `unfreezeRules` TEXT, `destroyFrozenFundsRules` TEXT, `emergencyActionRules` TEXT, `perpetualDistribution` TEXT, `preProgrammedDistribution` TEXT, `oncePerIdentityDistribution` TEXT, `newTokensDestinationIdentity` BLOB, `mintingAllowChoosingDestination` INTEGER NOT NULL, `distributionChangeRules` TEXT, `tradeMode` TEXT NOT NULL, `tradeModeChangeRules` TEXT, `mainControlGroupPosition` INTEGER, `mainControlGroupCanBeModified` TEXT, `tokenDescription` TEXT, `createdAt` INTEGER NOT NULL, `lastUpdatedAt` INTEGER NOT NULL, `canManuallyMint` INTEGER NOT NULL, `canManuallyBurn` INTEGER NOT NULL, `canFreeze` INTEGER NOT NULL, `canUnfreeze` INTEGER NOT NULL, `canDestroyFrozenFunds` INTEGER NOT NULL, `hasEmergencyActions` INTEGER NOT NULL, `canChangeMaxSupply` INTEGER NOT NULL, `canChangeConventions` INTEGER NOT NULL, `canChangeTradeMode` INTEGER NOT NULL, `hasDistribution` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`contractId`) REFERENCES `data_contracts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contractId", + "columnName": "contractId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "baseSupply", + "columnName": "baseSupply", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "maxSupply", + "columnName": "maxSupply", + "affinity": "TEXT" + }, + { + "fieldPath": "decimals", + "columnName": "decimals", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "localizations", + "columnName": "localizations", + "affinity": "TEXT" + }, + { + "fieldPath": "isPaused", + "columnName": "isPaused", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "allowTransferToFrozenBalance", + "columnName": "allowTransferToFrozenBalance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsTransferHistory", + "columnName": "keepsTransferHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsFreezingHistory", + "columnName": "keepsFreezingHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsMintingHistory", + "columnName": "keepsMintingHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsBurningHistory", + "columnName": "keepsBurningHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsDirectPricingHistory", + "columnName": "keepsDirectPricingHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keepsDirectPurchaseHistory", + "columnName": "keepsDirectPurchaseHistory", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "conventionsChangeRules", + "columnName": "conventionsChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "maxSupplyChangeRules", + "columnName": "maxSupplyChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "manualMintingRules", + "columnName": "manualMintingRules", + "affinity": "TEXT" + }, + { + "fieldPath": "manualBurningRules", + "columnName": "manualBurningRules", + "affinity": "TEXT" + }, + { + "fieldPath": "freezeRules", + "columnName": "freezeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "unfreezeRules", + "columnName": "unfreezeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "destroyFrozenFundsRules", + "columnName": "destroyFrozenFundsRules", + "affinity": "TEXT" + }, + { + "fieldPath": "emergencyActionRules", + "columnName": "emergencyActionRules", + "affinity": "TEXT" + }, + { + "fieldPath": "perpetualDistribution", + "columnName": "perpetualDistribution", + "affinity": "TEXT" + }, + { + "fieldPath": "preProgrammedDistribution", + "columnName": "preProgrammedDistribution", + "affinity": "TEXT" + }, + { + "fieldPath": "oncePerIdentityDistribution", + "columnName": "oncePerIdentityDistribution", + "affinity": "TEXT" + }, + { + "fieldPath": "newTokensDestinationIdentity", + "columnName": "newTokensDestinationIdentity", + "affinity": "BLOB" + }, + { + "fieldPath": "mintingAllowChoosingDestination", + "columnName": "mintingAllowChoosingDestination", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "distributionChangeRules", + "columnName": "distributionChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "tradeMode", + "columnName": "tradeMode", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tradeModeChangeRules", + "columnName": "tradeModeChangeRules", + "affinity": "TEXT" + }, + { + "fieldPath": "mainControlGroupPosition", + "columnName": "mainControlGroupPosition", + "affinity": "INTEGER" + }, + { + "fieldPath": "mainControlGroupCanBeModified", + "columnName": "mainControlGroupCanBeModified", + "affinity": "TEXT" + }, + { + "fieldPath": "tokenDescription", + "columnName": "tokenDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdatedAt", + "columnName": "lastUpdatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManuallyMint", + "columnName": "canManuallyMint", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canManuallyBurn", + "columnName": "canManuallyBurn", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canFreeze", + "columnName": "canFreeze", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canUnfreeze", + "columnName": "canUnfreeze", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canDestroyFrozenFunds", + "columnName": "canDestroyFrozenFunds", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasEmergencyActions", + "columnName": "hasEmergencyActions", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canChangeMaxSupply", + "columnName": "canChangeMaxSupply", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canChangeConventions", + "columnName": "canChangeConventions", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "canChangeTradeMode", + "columnName": "canChangeTradeMode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasDistribution", + "columnName": "hasDistribution", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_tokens_contractId", + "unique": false, + "columnNames": [ + "contractId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_tokens_contractId` ON `${TABLE_NAME}` (`contractId`)" + } + ], + "foreignKeys": [ + { + "table": "data_contracts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "contractId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "token_balances", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `tokenId` TEXT NOT NULL, `identityId` BLOB NOT NULL, `balance` BLOB NOT NULL, `frozen` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `lastSyncedAt` INTEGER, `tokenName` TEXT, `tokenSymbol` TEXT, `tokenDecimals` INTEGER, `networkRaw` INTEGER NOT NULL, `identityRef` BLOB, `tokenRef` BLOB, FOREIGN KEY(`identityRef`) REFERENCES `identities`(`identityId`) ON UPDATE NO ACTION ON DELETE SET NULL , FOREIGN KEY(`tokenRef`) REFERENCES `tokens`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tokenId", + "columnName": "tokenId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "frozen", + "columnName": "frozen", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedAt", + "columnName": "lastSyncedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "tokenName", + "columnName": "tokenName", + "affinity": "TEXT" + }, + { + "fieldPath": "tokenSymbol", + "columnName": "tokenSymbol", + "affinity": "TEXT" + }, + { + "fieldPath": "tokenDecimals", + "columnName": "tokenDecimals", + "affinity": "INTEGER" + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityRef", + "columnName": "identityRef", + "affinity": "BLOB" + }, + { + "fieldPath": "tokenRef", + "columnName": "tokenRef", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_token_balances_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + }, + { + "name": "index_token_balances_tokenId_identityId", + "unique": false, + "columnNames": [ + "tokenId", + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_tokenId_identityId` ON `${TABLE_NAME}` (`tokenId`, `identityId`)" + }, + { + "name": "index_token_balances_identityId", + "unique": false, + "columnNames": [ + "identityId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_identityId` ON `${TABLE_NAME}` (`identityId`)" + }, + { + "name": "index_token_balances_identityRef", + "unique": false, + "columnNames": [ + "identityRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_identityRef` ON `${TABLE_NAME}` (`identityRef`)" + }, + { + "name": "index_token_balances_tokenRef", + "unique": false, + "columnNames": [ + "tokenRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_balances_tokenRef` ON `${TABLE_NAME}` (`tokenRef`)" + } + ], + "foreignKeys": [ + { + "table": "identities", + "onDelete": "SET NULL", + "onUpdate": "NO ACTION", + "columns": [ + "identityRef" + ], + "referencedColumns": [ + "identityId" + ] + }, + { + "table": "tokens", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "tokenRef" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "token_history_events", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `eventType` TEXT NOT NULL, `transactionId` BLOB, `blockHeight` INTEGER, `coreBlockHeight` INTEGER, `fromIdentity` BLOB, `toIdentity` BLOB, `performedByIdentity` BLOB NOT NULL, `amount` TEXT, `balanceBefore` TEXT, `balanceAfter` TEXT, `additionalDataJSON` BLOB, `eventDescription` TEXT, `createdAt` INTEGER NOT NULL, `eventTimestamp` INTEGER NOT NULL, `tokenRef` BLOB, PRIMARY KEY(`id`), FOREIGN KEY(`tokenRef`) REFERENCES `tokens`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "eventType", + "columnName": "eventType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "transactionId", + "columnName": "transactionId", + "affinity": "BLOB" + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "coreBlockHeight", + "columnName": "coreBlockHeight", + "affinity": "INTEGER" + }, + { + "fieldPath": "fromIdentity", + "columnName": "fromIdentity", + "affinity": "BLOB" + }, + { + "fieldPath": "toIdentity", + "columnName": "toIdentity", + "affinity": "BLOB" + }, + { + "fieldPath": "performedByIdentity", + "columnName": "performedByIdentity", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "TEXT" + }, + { + "fieldPath": "balanceBefore", + "columnName": "balanceBefore", + "affinity": "TEXT" + }, + { + "fieldPath": "balanceAfter", + "columnName": "balanceAfter", + "affinity": "TEXT" + }, + { + "fieldPath": "additionalDataJSON", + "columnName": "additionalDataJSON", + "affinity": "BLOB" + }, + { + "fieldPath": "eventDescription", + "columnName": "eventDescription", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventTimestamp", + "columnName": "eventTimestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tokenRef", + "columnName": "tokenRef", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_token_history_events_tokenRef", + "unique": false, + "columnNames": [ + "tokenRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_token_history_events_tokenRef` ON `${TABLE_NAME}` (`tokenRef`)" + } + ], + "foreignKeys": [ + { + "table": "tokens", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "tokenRef" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "platform_addresses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `addressType` INTEGER NOT NULL, `addressHash` BLOB NOT NULL, `publicKey` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `addressIndex` INTEGER NOT NULL, `derivationPath` TEXT NOT NULL, `isUsed` INTEGER NOT NULL, `balance` INTEGER NOT NULL, `nonce` INTEGER NOT NULL, `firstSeenHeight` INTEGER NOT NULL, `lastSeenHeight` INTEGER NOT NULL, `walletId` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, `accountId` INTEGER, PRIMARY KEY(`walletId`, `address`), FOREIGN KEY(`accountId`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )", + "fields": [ + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "addressType", + "columnName": "addressType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addressHash", + "columnName": "addressHash", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "addressIndex", + "columnName": "addressIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "derivationPath", + "columnName": "derivationPath", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "isUsed", + "columnName": "isUsed", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "balance", + "columnName": "balance", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nonce", + "columnName": "nonce", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "firstSeenHeight", + "columnName": "firstSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSeenHeight", + "columnName": "lastSeenHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "accountId", + "columnName": "accountId", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "address" + ] + }, + "indices": [ + { + "name": "index_platform_addresses_walletId_addressHash", + "unique": true, + "columnNames": [ + "walletId", + "addressHash" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_platform_addresses_walletId_addressHash` ON `${TABLE_NAME}` (`walletId`, `addressHash`)" + }, + { + "name": "index_platform_addresses_accountId", + "unique": false, + "columnNames": [ + "accountId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_platform_addresses_accountId` ON `${TABLE_NAME}` (`accountId`)" + } + ], + "foreignKeys": [ + { + "table": "accounts", + "onDelete": "CASCADE", + "onUpdate": "NO ACTION", + "columns": [ + "accountId" + ], + "referencedColumns": [ + "id" + ] + } + ] + }, + { + "tableName": "platform_addresses_sync_states", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `networkRaw` INTEGER NOT NULL, `syncHeight` INTEGER NOT NULL, `syncTimestamp` INTEGER NOT NULL, `lastKnownRecentBlock` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncHeight", + "columnName": "syncHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "syncTimestamp", + "columnName": "syncTimestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastKnownRecentBlock", + "columnName": "lastKnownRecentBlock", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId" + ] + }, + "indices": [ + { + "name": "index_platform_addresses_sync_states_networkRaw", + "unique": false, + "columnNames": [ + "networkRaw" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_platform_addresses_sync_states_networkRaw` ON `${TABLE_NAME}` (`networkRaw`)" + } + ] + }, + { + "tableName": "shielded_notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`nullifier` BLOB NOT NULL, `walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `position` INTEGER NOT NULL, `cmx` BLOB NOT NULL, `blockHeight` INTEGER NOT NULL, `isSpent` INTEGER NOT NULL, `value` INTEGER NOT NULL, `noteData` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`nullifier`))", + "fields": [ + { + "fieldPath": "nullifier", + "columnName": "nullifier", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cmx", + "columnName": "cmx", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isSpent", + "columnName": "isSpent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "noteData", + "columnName": "noteData", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "nullifier" + ] + }, + "indices": [ + { + "name": "index_shielded_notes_walletId_accountIndex", + "unique": false, + "columnNames": [ + "walletId", + "accountIndex" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_notes_walletId_accountIndex` ON `${TABLE_NAME}` (`walletId`, `accountIndex`)" + } + ] + }, + { + "tableName": "shielded_outgoing_notes", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `cmx` BLOB NOT NULL, `recipient` BLOB NOT NULL, `value` INTEGER NOT NULL, `memo` BLOB NOT NULL, `blockHeight` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`, `cmx`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cmx", + "columnName": "cmx", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "recipient", + "columnName": "recipient", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "memo", + "columnName": "memo", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex", + "cmx" + ] + }, + "indices": [ + { + "name": "index_shielded_outgoing_notes_walletId_accountIndex", + "unique": false, + "columnNames": [ + "walletId", + "accountIndex" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_outgoing_notes_walletId_accountIndex` ON `${TABLE_NAME}` (`walletId`, `accountIndex`)" + } + ] + }, + { + "tableName": "shielded_activities", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `entryId` BLOB NOT NULL, `kindTag` INTEGER NOT NULL, `direction` INTEGER NOT NULL, `status` INTEGER NOT NULL, `amount` INTEGER NOT NULL, `fee` INTEGER NOT NULL, `hasFee` INTEGER NOT NULL, `blockHeight` INTEGER NOT NULL, `hasBlockHeight` INTEGER NOT NULL, `createdAtMs` INTEGER NOT NULL, `identityId` BLOB NOT NULL, `counterparty` BLOB NOT NULL, `memo` BLOB NOT NULL, `noteCmxs` BLOB NOT NULL, `spentNullifiers` BLOB NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`, `entryId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "entryId", + "columnName": "entryId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "kindTag", + "columnName": "kindTag", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "amount", + "columnName": "amount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fee", + "columnName": "fee", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasFee", + "columnName": "hasFee", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "blockHeight", + "columnName": "blockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasBlockHeight", + "columnName": "hasBlockHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAtMs", + "columnName": "createdAtMs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "counterparty", + "columnName": "counterparty", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "memo", + "columnName": "memo", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "noteCmxs", + "columnName": "noteCmxs", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "spentNullifiers", + "columnName": "spentNullifiers", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex", + "entryId" + ] + }, + "indices": [ + { + "name": "index_shielded_activities_walletId_accountIndex", + "unique": false, + "columnNames": [ + "walletId", + "accountIndex" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_activities_walletId_accountIndex` ON `${TABLE_NAME}` (`walletId`, `accountIndex`)" + } + ] + }, + { + "tableName": "shielded_sync_states", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `lastSyncedIndex` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastSyncedIndex", + "columnName": "lastSyncedIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex" + ] + }, + "indices": [ + { + "name": "index_shielded_sync_states_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_sync_states_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "shielded_viewing_keys", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `accountIndex` INTEGER NOT NULL, `fvkBytes` BLOB NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`walletId`, `accountIndex`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "accountIndex", + "columnName": "accountIndex", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fvkBytes", + "columnName": "fvkBytes", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "accountIndex" + ] + }, + "indices": [ + { + "name": "index_shielded_viewing_keys_walletId", + "unique": false, + "columnNames": [ + "walletId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_shielded_viewing_keys_walletId` ON `${TABLE_NAME}` (`walletId`)" + } + ] + }, + { + "tableName": "wallet_manager_metadata", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`networkRaw` INTEGER NOT NULL, `combinedSyncHeight` INTEGER NOT NULL, `combinedSyncBlockHash` BLOB, `walletCount` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `lastUpdated` INTEGER NOT NULL, PRIMARY KEY(`networkRaw`))", + "fields": [ + { + "fieldPath": "networkRaw", + "columnName": "networkRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "combinedSyncHeight", + "columnName": "combinedSyncHeight", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "combinedSyncBlockHash", + "columnName": "combinedSyncBlockHash", + "affinity": "BLOB" + }, + { + "fieldPath": "walletCount", + "columnName": "walletCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lastUpdated", + "columnName": "lastUpdated", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "networkRaw" + ] + } + }, + { + "tableName": "private_contact_requests_positions", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `identityId` BLOB NOT NULL, `position` INTEGER NOT NULL, `keyFingerprint` BLOB NOT NULL, `privatePaymentsUnresolved` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`walletId`, `identityId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "identityId", + "columnName": "identityId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "keyFingerprint", + "columnName": "keyFingerprint", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "privatePaymentsUnresolved", + "columnName": "privatePaymentsUnresolved", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "identityId" + ] + } + }, + { + "tableName": "private_shielded_addresses", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`walletId` BLOB NOT NULL, `ownerId` BLOB NOT NULL, `contactId` BLOB NOT NULL, `address` BLOB NOT NULL, PRIMARY KEY(`walletId`, `ownerId`, `contactId`))", + "fields": [ + { + "fieldPath": "walletId", + "columnName": "walletId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "ownerId", + "columnName": "ownerId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "BLOB", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "walletId", + "ownerId", + "contactId" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'aa58da0a7ca53a564b0a4a9bf012000b')" + ] + } +} \ No newline at end of file diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt index 9e7ed9141e6..a5fbee6aa97 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/ShieldedDao.kt @@ -53,6 +53,12 @@ interface ShieldedDao { @Query("SELECT * FROM shielded_notes WHERE walletId = :walletId AND isSpent = 0") fun observeUnspentNotesByWallet(walletId: ByteArray): Flow> + @Query("SELECT * FROM shielded_notes WHERE walletId = :walletId AND accountIndex = :accountIndex AND isSpent = 0") + fun observeUnspentNotesByWalletAccount( + walletId: ByteArray, + accountIndex: Int, + ): Flow> + @Upsert suspend fun upsertNote(note: ShieldedNoteEntity) diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt index 406921c256f..90135ce60c1 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/DashDatabaseTest.kt @@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.dashfoundation.dashsdk.persistence.entities.AccountEntity import org.dashfoundation.dashsdk.persistence.entities.IdentityEntity +import org.dashfoundation.dashsdk.persistence.entities.ShieldedNoteEntity import org.dashfoundation.dashsdk.persistence.entities.ShieldedViewingKeyEntity import org.dashfoundation.dashsdk.persistence.entities.TokenBalanceEntity import org.dashfoundation.dashsdk.persistence.entities.TokenEntity @@ -42,6 +43,31 @@ class DashDatabaseTest { db.close() } + @Test + fun ordinarySendBalanceIncludesOnlyUnspentAccountZeroNotes() = runTest { + val dao = db.shieldedDao() + fun note(id: Int, account: Int, value: Long, spent: Boolean = false, wallet: ByteArray = walletId) = + ShieldedNoteEntity( + nullifier = ByteArray(32) { id.toByte() }, + walletId = wallet, + accountIndex = account, + position = id.toLong(), + cmx = ByteArray(32), + blockHeight = 1, + isSpent = spent, + value = value, + noteData = ByteArray(115), + ) + dao.upsertNote(note(1, 0x40000000, 900)) + assertEquals(0L, dao.observeUnspentNotesByWalletAccount(walletId, 0).first().sumOf { it.value }) + dao.upsertNote(note(2, 0, 100)) + dao.upsertNote(note(3, 0, 200)) + dao.upsertNote(note(4, 1, 500)) + dao.upsertNote(note(5, 0, 700, spent = true)) + dao.upsertNote(note(6, 0, 800, wallet = ByteArray(32) { 2 })) + assertEquals(300L, dao.observeUnspentNotesByWalletAccount(walletId, 0).first().sumOf { it.value }) + } + @Test fun walletRoundTripsThroughUpsertAndFlow() = runTest { val wallet = WalletEntity( diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 0d06ef1dc9b..3e954d37a2a 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -9304,7 +9304,7 @@ mod tests { let wallet = create(&manager); assert_eq!(wallet.wallet_id(), wallet_id); - let held = |id: Identifier| { + let held = |id: Identifier, index: u32| { runtime().block_on(async { let mut wm = wallet.wallet_manager().write().await; let identities = &mut wm @@ -9319,7 +9319,7 @@ mod tests { balance: 0, revision: 0, }), - 0, + index, wallet.wallet_id(), wallet.persister(), ) @@ -9331,8 +9331,11 @@ mod tests { .private_payments_unrestored() }) }; - assert!(held(marked), "the identity the kept record names is held"); - assert!(!held(other), "an identity no kept record names is not"); + assert!( + held(marked, 0), + "the identity the kept record names is held" + ); + assert!(!held(other, 1), "an identity no kept record names is not"); } #[test] @@ -9599,22 +9602,17 @@ mod tests { address } - /// Host bytes for a shielded address, and what restore keeps of them: a - /// decodable Orchard address where shielded support is built in, and - /// nothing without it, where no shielded address is payable. + /// Orchard key-components vector 0 (`default_d || default_pk_d`), retained + /// as public profile metadata with or without shielded spending support. + /// https://github.com/zcash-hackworks/zcash-test-vectors/blob/master/orchard_key_components.py fn shielded_fixture() -> ([u8; 43], Option>) { - #[cfg(feature = "shielded")] - { - let address = OrchardKeySet::from_seed(&[42; 64], Network::Testnet, 0) - .expect("orchard keys") - .default_address - .to_raw_address_bytes(); - (address, Some(address.to_vec())) - } - #[cfg(not(feature = "shielded"))] - { - ([0xE1; 43], None) - } + let address = [ + 0x8f, 0xf3, 0x38, 0x69, 0x71, 0xcb, 0x64, 0xb8, 0xe7, 0x78, 0x99, 0x08, 0xdd, 0x8e, + 0xbd, 0x7d, 0xe9, 0x2a, 0x68, 0xe5, 0x86, 0xa3, 0x4d, 0xb8, 0xfe, 0xa9, 0x99, 0xef, + 0xd2, 0x01, 0x6f, 0xae, 0x76, 0x75, 0x0a, 0xfa, 0xe7, 0xee, 0x94, 0x16, 0x46, 0xbc, + 0xb9, + ]; + (address, Some(address.to_vec())) } /// Restore re-validates each payment address as a profile fetch would, @@ -9659,6 +9657,8 @@ mod tests { #[test] fn owned_dashpay_profile_hydrates_through_the_load_callback() { use crate::wallet_restore_types::{ContactProfileRestoreEntryFFI, IdentityRestoreEntryFFI}; + use dpp::identity::accessors::IdentitySettersV0; + use platform_wallet::changeset::IdentityEntry; use std::sync::atomic::{AtomicUsize, Ordering}; struct Host { @@ -9798,6 +9798,17 @@ mod tests { bucket[&1].dashpay().profile.is_none(), "a null profile pointer restores no profile" ); + + let mut managed = bucket[&0].clone(); + managed.identity.set_balance(8); + let entry = IdentityEntry::from_managed(&managed); + assert_eq!(entry.balance, 8); + assert_eq!( + entry.dashpay_profile.as_ref().unwrap().shielded_address, + shielded_fixture().1, + "an unrelated scalar snapshot retains restored public address metadata" + ); + assert_eq!(entry.dashpay_profile, Some(profile)); } unsafe extern "C" fn noop_free_wallets( @@ -12617,8 +12628,6 @@ mod tests { use key_wallet::transaction_checking::{BlockInfo, TransactionContext}; use key_wallet::wallet::managed_wallet_info::wallet_info_interface::WalletInfoInterface; use key_wallet::wallet::Wallet; - #[cfg(feature = "shielded")] - use platform_wallet::wallet::shielded::OrchardKeySet; /// Regression: restored pool addresses must be tagged with the /// WALLET's network, not the network the base58 string parses as. diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs index 453cb04f5a2..a73bf23260e 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_profile_address_encoding.rs @@ -85,7 +85,7 @@ fn stored_profile(conn: &Connection) -> DashPayProfile { /// and the new fields round-trip; an insert that omits the stamp is read as /// the current shape. #[test] -fn pre_v020_rows_stay_readable_and_rewrites_restamp() { +fn pre_v021_rows_stay_readable_and_rewrites_restamp() { let id = Identifier::from([1; 32]); let old = entry(id); @@ -239,7 +239,7 @@ fn unknown_stamp_is_rejected_by_the_check_constraint() { /// regenerate the fixture and its decoder in step. Every field holds a /// distinct value, so a positional shift misreads at least one of them. #[test] -fn literal_pre_v020_profile_bytes_decode_positionally() { +fn literal_pre_v021_profile_bytes_decode_positionally() { let mut bytes = vec![0x01, 0x02, b'A', b'l']; // display_name: Some("Al") bytes.extend([0x01, 0x01, b'b']); // bio: Some("b") bytes.push(0x00); // avatar_url: None diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs index f1c5755c448..8c51cf7a0dc 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_schema_pinning.rs @@ -15,13 +15,13 @@ use platform_wallet_storage::sqlite::{migrations as mig, schema::versions::Domai /// Golden `(version, name)` fingerprint of the frozen migration set. Bump /// deliberately only when adding/removing/renaming a migration file. const EXPECTED_ID_FINGERPRINT: &str = - "b1e10a6494cc31d24fabe4852477b3b93a2a98a7f310681b132ca8d9adef7311"; + "e6f2e947830f270bd68f96172be146ed627a3264981c6bce8a28d3c458668a91"; /// Golden content-level fingerprint over every migration's rendered SQL. /// Bump it only when ADDING a migration file; a body change on an already /// applied migration is a defect, not a golden to refresh. const EXPECTED_SQL_FINGERPRINT: &str = - "4490b15ba9de27bf5b30a47e462dc3b71c061a47f738a5240cdc89b3abc4ff43"; + "974e26e40c8b93c0ac148b2cbf3ef009d78ef3ec94fbf94cef91a2e82a4ec029"; /// The migrations merged `v4.2-dev` already ships. Refinery keys /// `refinery_schema_history` by version and validates an applied migration's diff --git a/packages/rs-platform-wallet/Cargo.toml b/packages/rs-platform-wallet/Cargo.toml index 0c0ee88abb2..d37ed44a144 100644 --- a/packages/rs-platform-wallet/Cargo.toml +++ b/packages/rs-platform-wallet/Cargo.toml @@ -58,6 +58,9 @@ zeroize = "1" # output is discarded there. log = "0.4" +# Profile metadata validation must also work without shielded spending support. +orchard = { git = "https://github.com/dashpay/orchard.git", tag = "dashified-0.14.1", default-features = false } + # Shielded pool (optional, behind `shielded` feature) grovedb-commitment-tree = { workspace = true, optional = true } # Direct `rusqlite` access so `FileBackedShieldedStore::open_path` can set diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 03526c86408..1011fd5d856 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -1029,6 +1029,107 @@ mod address_patch_tests { .contains("does not support corePaymentAddress")); } + #[tokio::test] + async fn should_sync_address_only_profile_and_retain_it_in_snapshots() { + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents}; + use dpp::document::DocumentV0; + use dpp::identity::IdentityV0; + use dpp::version::PlatformVersion; + + let owner = Identifier::from([0x61; 32]); + let key = orchard::keys::SpendingKey::from_bytes([42; 32]).unwrap(); + let raw = orchard::keys::FullViewingKey::from(&key) + .address_at(19u32, orchard::keys::Scope::External) + .to_raw_address_bytes(); + let contract = super::super::dashpay_contract().unwrap(); + let query = DocumentQuery::new(contract, "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![owner.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + let document = Document::V0(DocumentV0 { + id: Identifier::from([0x62; 32]), + owner_id: owner, + revision: Some(1), + properties: [("shieldedAddress".into(), Value::Bytes(raw.to_vec()))].into(), + ..Default::default() + }); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(key_wallet::Network::Testnet) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch_many::( + query, + Some([(document.id(), Some(document))].into()), + ) + .await + .unwrap(); + let (wm, wallet_id, generation, _) = crate::test_support::funded_wallet_manager( + key_wallet::account::StandardAccountType::BIP44Account, + ) + .await; + let persister: Arc = + Arc::new(crate::wallet::persister::NoPlatformPersistence); + wm.write() + .await + .get_wallet_info_mut(&wallet_id) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: owner, + public_keys: Default::default(), + balance: 0, + revision: 0, + }), + 0, + wallet_id, + &crate::wallet::persister::WalletPersister::new(wallet_id, persister.clone()), + ) + .unwrap(); + let spv = Arc::new(crate::spv::SpvRuntime::new( + wm.clone(), + Arc::new(crate::events::PlatformEventManager::new(vec![])), + )); + let wallet = crate::PlatformWallet::new( + Arc::new(sdk), + wallet_id, + wm.clone(), + generation, + Arc::new(tokio::sync::Notify::new()), + persister, + Arc::new(crate::broadcaster::SpvBroadcaster::new(spv)), + Arc::new(std::sync::atomic::AtomicBool::new(false)), + crate::changeset::DurableCursors::default(), + ); + assert_eq!( + wallet.identity().dashpay().sync_profiles().await.unwrap(), + 1 + ); + let manager = wm.read().await; + let managed = manager + .get_wallet_info(&wallet_id) + .unwrap() + .identity_manager + .managed_identity(&owner) + .unwrap(); + let snapshot = crate::changeset::IdentityEntry::from_managed(managed); + assert_eq!( + snapshot.dashpay_profile.unwrap().shielded_address, + Some(raw.to_vec()) + ); + } + #[test] fn should_ignore_invalid_addresses_without_losing_profile() { let profile = profile_from_properties(&std::collections::BTreeMap::from([ diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs index 34ff43c3fe5..209a3a8f0e6 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs @@ -106,22 +106,10 @@ pub struct ShieldedTipRecipient { pub address: [u8; 43], } -/// Decode a raw Orchard recipient using the same decoder as shielded transfers. -/// Without shielded support an address must never be advertised as payable. +/// Validate public Orchard address metadata independently of spending support. pub fn validated_shielded_address(bytes: &[u8]) -> Option<[u8; 43]> { - #[cfg(feature = "shielded")] - { - let raw: [u8; 43] = bytes.try_into().ok()?; - Option::::from( - grovedb_commitment_tree::PaymentAddress::from_raw_address_bytes(&raw), - ) - .map(|_| raw) - } - #[cfg(not(feature = "shielded"))] - { - let _ = bytes; - None - } + let raw: [u8; 43] = bytes.try_into().ok()?; + Option::::from(orchard::Address::from_raw_address_bytes(&raw)).map(|_| raw) } /// Storage-form transparent address validation, matching the DashPay trigger. diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 7e7581a37ff..359bcd73bb5 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -303,8 +303,10 @@ impl PlatformWallet { memo: [u8; 36], prover: P, ) -> Result<(), PlatformWalletError> { - let _placement = self.identity.identity_placement.read().await; - let account = self.tip_source_account(seed, source).await?; + { + let _placement = self.identity.identity_placement.read().await; + self.tip_source_account(seed, source).await?; + } let current = self .identity() .dashpay() @@ -315,6 +317,8 @@ impl PlatformWallet { "The tip recipient changed; review and confirm the payment again".to_string(), )); } + let _placement = self.identity.identity_placement.read().await; + let account = self.tip_source_account(seed, source).await?; self.shielded_transfer_to( coordinator, seed, diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index d00f393c62b..ae23f48ea35 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -1287,7 +1287,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .add_identity( Identity::V0(IdentityV0 { id, - public_keys: seed_master_key(&seed, 5), + public_keys: seed_master_key(&seed[..], 5), balance: 0, revision: 0, }), @@ -1300,7 +1300,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( let coordinator = coordinator_at(&temp_dir("tips_placeholder_index")); let identity_zero_tips = shielded_tip_account_index(0).unwrap(); wallet - .bind_shielded(&seed, &[0, identity_zero_tips], &coordinator) + .bind_shielded(&seed[..], &[0, identity_zero_tips], &coordinator) .await .unwrap(); let identity_zero_address = wallet @@ -1309,7 +1309,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .unwrap(); let refused = wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await; assert!( matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), @@ -1327,11 +1327,12 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( let wallet = wallet.clone(); let coordinator = Arc::clone(&coordinator); let recipient = recipient.clone(); + let seed = seed.clone(); async move { wallet .send_shielded_tip( &coordinator, - &seed, + &seed[..], source, "recipient.dash", &recipient, @@ -1382,7 +1383,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .unwrap(); } let address = wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await .unwrap(); assert_ne!(address, identity_zero_address); @@ -1395,7 +1396,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( ); assert_eq!( wallet - .tip_source_account(&seed, crate::ShieldedTipSource::Identity(id)) + .tip_source_account(&seed[..], crate::ShieldedTipSource::Identity(id)) .await .unwrap(), shielded_tip_account_index(5).unwrap() @@ -1476,7 +1477,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .add_identity( Identity::V0(IdentityV0 { id, - public_keys: seed_master_key(&seed, 3), + public_keys: seed_master_key(&seed[..], 3), balance: 0, revision: 0, }), @@ -1515,7 +1516,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn // identity discovery introduces a tip account without an FVK. Seedless // success here would suppress the host's seed fallback and lose scans // for that identity's tip history. - let ordinary = super::OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + let ordinary = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, 0).unwrap(); persister.serve_viewing_keys(BTreeMap::from([( SubwalletId::new(wallet.wallet_id(), 0), ordinary.full_viewing_key.to_bytes().to_vec(), @@ -1531,7 +1532,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .is_err()); assert!(matches!( wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await, Err(crate::PlatformWalletError::ShieldedNotBound) )); @@ -1539,7 +1540,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn assert!(persister.captured_viewing_keys().is_empty()); assert!(coordinator.registered_subwallets().await.is_empty()); wallet - .bind_shielded(&seed, &[0], &coordinator) + .bind_shielded(&seed[..], &[0], &coordinator) .await .unwrap(); assert!(coordinator @@ -1558,7 +1559,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .store(true, std::sync::atomic::Ordering::SeqCst); assert!(matches!( wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await, Err(crate::PlatformWalletError::Persistence(_)) )); @@ -1572,11 +1573,11 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .store(false, std::sync::atomic::Ordering::SeqCst); persister.durability_events.lock().unwrap().clear(); let address = wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await .unwrap(); assert!(wallet - .prepare_shielded_tip_address(&seed, &Identifier::from([0x44; 32]), &coordinator) + .prepare_shielded_tip_address(&seed[..], &Identifier::from([0x44; 32]), &coordinator) .await .is_err()); assert_eq!( @@ -1586,7 +1587,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn assert_ne!(wallet.shielded_default_address(0).await.unwrap(), address); assert_eq!( wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await .unwrap(), address @@ -1608,8 +1609,8 @@ async fn should_rebind_retired_tip_accounts_without_profile_or_identity() { let account = crate::shielded_tip_account_index(7).unwrap(); let persister = Arc::new(CapturingPersistence::default()); let wallet = platform_wallet_with(Arc::clone(&persister)).await; - let keys = super::OrchardKeySet::from_seed(&seed, Network::Testnet, account).unwrap(); - let ordinary = super::OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); + let keys = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, account).unwrap(); + let ordinary = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, 0).unwrap(); persister.serve_viewing_keys(BTreeMap::from([ ( SubwalletId::new(wallet.wallet_id(), 0), @@ -1653,7 +1654,7 @@ async fn should_bind_more_than_64_persisted_tip_accounts_from_an_ordinary_reques let mut rows = BTreeMap::new(); for &account in std::iter::once(&0).chain(tips.iter()) { let keys = - super::OrchardKeySet::from_seed(&seed, wallet.sdk().network, account).unwrap(); + super::OrchardKeySet::from_seed(&seed[..], wallet.sdk().network, account).unwrap(); rows.insert( SubwalletId::new(wallet.wallet_id(), account), keys.full_viewing_key.to_bytes().to_vec(), @@ -1663,7 +1664,7 @@ async fn should_bind_more_than_64_persisted_tip_accounts_from_an_ordinary_reques let coordinator = coordinator_at(&temp_dir(tag)); if seeded { wallet - .bind_shielded(&seed, &[0], &coordinator) + .bind_shielded(&seed[..], &[0], &coordinator) .await .unwrap(); } else { @@ -1748,7 +1749,7 @@ async fn tip_race_fixture( .add_identity( Identity::V0(IdentityV0 { id, - public_keys: seed_master_key(&seed, 2), + public_keys: seed_master_key(&seed[..], 2), balance: 0, revision: 0, }), @@ -1760,10 +1761,10 @@ async fn tip_race_fixture( } let coordinator = coordinator_at(&temp_dir(tag)); wallet - .bind_shielded(&seed, &[0], &coordinator) + .bind_shielded(&seed[..], &[0], &coordinator) .await .unwrap(); - (wallet, seed, id, coordinator) + (wallet, *seed, id, coordinator) } /// Pause tip preparation right after its account snapshot, run `writer` @@ -1784,7 +1785,7 @@ async fn race_tip_preparation( let coordinator = Arc::clone(coordinator); tokio::spawn(async move { wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await }) }; @@ -1816,7 +1817,7 @@ async fn should_keep_an_ordinary_account_bound_during_tip_preparation() { let bind_coordinator = Arc::clone(&coordinator); race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { wallet - .bind_shielded(&seed, &[0, 1], &bind_coordinator) + .bind_shielded(&seed[..], &[0, 1], &bind_coordinator) .await }) .await; @@ -1846,7 +1847,7 @@ async fn should_keep_an_added_account_during_tip_preparation() { let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_add").await; let tip = shielded_tip_account_index(2).unwrap(); race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { - wallet.shielded_add_account(&seed, 1).await + wallet.shielded_add_account(&seed[..], 1).await }) .await; @@ -1879,7 +1880,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal .identity_manager .managed_identity_mut(&id) .unwrap(); - let mut second = seed_master_key(&seed, 7).remove(&0).unwrap(); + let mut second = seed_master_key(&seed[..], 7).remove(&0).unwrap(); second.set_id(1); managed.identity.add_public_key(second); } @@ -1890,7 +1891,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal let coordinator = Arc::clone(&coordinator); tokio::spawn(async move { wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await }) }; @@ -1929,7 +1930,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal "{refused:?}" ); let fresh = wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_tip_address(&seed[..], &id, &coordinator) .await .unwrap(); assert_ne!(fresh, stale); diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index aafe0adb062..8ecf1bfa7da 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -4185,7 +4185,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { profileIdentityId: contactIdentityId, core: nil, platform: nil, shielded: nil, fetcher: modelFetcher) // Confirmed-absent: delete the stale row if one exists; a // never-persisted contact is a no-op. - if let existing = try? backgroundContext.fetch(descriptor).first { + if let existing = try modelFetcher.fetch(descriptor, in: backgroundContext).first { backgroundContext.delete(existing) } continue diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift index de48fdf33bb..08f8aa7d1b0 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Core/Views/SendTransactionView.swift @@ -52,7 +52,7 @@ struct SendTransactionView: View { /// credits". @Query private var syncStates: [PersistentPlatformAddressesSyncState] - /// This wallet's unspent shielded (Orchard) notes. Summed into + /// This wallet's unspent account-0 shielded (Orchard) notes. Summed into /// `shieldedBalance` below so the shielded source row reflects THIS /// wallet's own pool, not the single-mirror `shieldedService`. @Query private var shieldedNotes: [PersistentShieldedNote] @@ -71,10 +71,16 @@ struct SendTransactionView: View { } ) _shieldedNotes = Query( - filter: PersistentShieldedNote.unspentPredicate(walletId: walletId) + filter: Self.shieldedSourcePredicate(walletId: walletId) ) } + static func shieldedSourcePredicate(walletId: Data) -> Predicate { + #Predicate { + $0.walletId == walletId && $0.accountIndex == 0 && $0.isSpent == false + } + } + var body: some View { // Snapshot Core balance once per render — `coreBalance` goes // through a blocking FFI call (`accountBalances(for:)`); the @@ -486,7 +492,7 @@ struct SendTransactionView: View { .reduce(0) { $0 + $1.confirmed } } - /// Per-wallet shielded balance: sum of THIS wallet's unspent + /// Account-0 shielded balance: sum of THIS wallet's unspent /// `PersistentShieldedNote` values (Rust pushes note rows via the /// shielded persister). Reads SwiftData rather than the /// single-mirror `shieldedService.shieldedBalance`, so the shielded diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift index 188e698c789..d78f73ddd11 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift @@ -63,15 +63,53 @@ final class PersistentShieldedNotePredicateTests: XCTestCase { ) } + func testShieldedSendHasNoSourceBalanceForTipOnlyWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x01, isSpent: false, value: 900)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: SendTransactionView.shieldedSourcePredicate(walletId: wallet) + )) + XCTAssertTrue(notes.isEmpty) + XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 0) + } + + func testShieldedSendSourceBalanceIncludesOnlyUnspentAccountZeroInSelectedWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + context.insert(makeNote(walletId: wallet, nullifier: 0x01, isSpent: false, value: 100)) + context.insert(makeNote(walletId: wallet, nullifier: 0x02, isSpent: false, value: 50)) + context.insert(makeNote(walletId: wallet, nullifier: 0x03, isSpent: true, value: 999)) + context.insert(makeNote(walletId: wallet, accountIndex: 1, + nullifier: 0x04, isSpent: false, value: 200)) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x05, isSpent: false, value: 900)) + context.insert(makeNote(walletId: walletId(0xBB), + nullifier: 0x06, isSpent: false, value: 300)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: SendTransactionView.shieldedSourcePredicate(walletId: wallet) + )) + XCTAssertEqual(notes.count, 2) + XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 150) + } + private func makeNote( walletId: Data, + accountIndex: UInt32 = 0, nullifier: UInt8, isSpent: Bool, value: UInt64 ) -> PersistentShieldedNote { PersistentShieldedNote( walletId: walletId, - accountIndex: 0, + accountIndex: accountIndex, position: 0, cmx: Data(repeating: 0, count: 32), nullifier: Data(repeating: nullifier, count: 32), diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index 5b2e29fd58a..a02c78f2d2f 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -182,6 +182,37 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertTrue(try fetchContactProfileRows().isEmpty) } + func testContactProfileReadFailureRollsBackTombstoneAddressesAndIdentityChanges() throws { + let shielded = Data(repeating: 3, count: 43) + XCTAssertTrue(applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: true, displayName: "Keep profile", + bio: nil, publicMessage: nil, avatarUrl: nil, avatarHash: nil, + avatarFingerprint: nil, shieldedAddress: shielded, checkedAtMs: 1)])) + let context = ModelContext(container) + let owner = try XCTUnwrap(context.fetch(FetchDescriptor()).first) + owner.balance = 321 + owner.revision = 5 + try context.save() + + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: ContactProfileReadFailure()) + XCTAssertFalse(applyContactProfiles([.init( + contactIdentityId: contactId, isPresent: false, displayName: nil, + bio: nil, publicMessage: nil, avatarUrl: nil, avatarHash: nil, + avatarFingerprint: nil, checkedAtMs: 2)])) + + let restored = ModelContext(container) + let profile = try XCTUnwrap(restored.fetch( + FetchDescriptor()).first) + XCTAssertEqual(profile.displayName, "Keep profile") + let addresses = try restored.fetch(FetchDescriptor()) + XCTAssertEqual(addresses.count, 1) + XCTAssertEqual(addresses.first?.shieldedAddress, shielded) + let restoredOwner = try XCTUnwrap(restored.fetch(FetchDescriptor()).first) + XCTAssertEqual(restoredOwner.balance, 321) + XCTAssertEqual(restoredOwner.revision, 5) + } + func testPaymentAddressReadFailureRejectsWalletRestore() throws { let context = ModelContext(container) let wallet = PersistentWallet(walletId: walletId, network: .testnet) @@ -1316,3 +1347,11 @@ private struct PaymentAddressReadFailure: ModelFetching { return try context.fetch(descriptor) } } + +private struct ContactProfileReadFailure: ModelFetching { + struct ReadError: Error {} + func fetch(_ descriptor: FetchDescriptor, in context: ModelContext) throws -> [T] { + if T.self == PersistentDashpayContactProfile.self { throw ReadError() } + return try context.fetch(descriptor) + } +} From b5dbcdc1b089a148f4528c729245a65e3b487ed8 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 19:51:31 +0000 Subject: [PATCH 20/41] fix(platform-wallet): invalidate cleared tip preparation and protect identity funding --- .../src/shielded_send.rs | 70 +++++++++++++- packages/rs-platform-wallet/src/error.rs | 9 ++ .../identity/state/manager/lifecycle.rs | 4 +- .../src/wallet/platform_wallet.rs | 71 +++++++------- .../src/wallet/shielded/tips.rs | 58 +++++++++++- .../wallet/shielded/viewing_key_bind_tests.rs | 94 +++++++++++++++++++ .../Views/CreateIdentityView.swift | 14 ++- ...PersistentShieldedNotePredicateTests.swift | 39 ++++++++ .../DashLegacySchemaMigrationTests.swift | 3 +- 9 files changed, 316 insertions(+), 46 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index daffbbb6635..7a63f54ec6c 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -43,6 +43,7 @@ use std::ffi::CStr; use std::os::raw::{c_char, c_void}; use dpp::address_funds::{OrchardAddress, PlatformAddress}; +use dpp::prelude::Identifier; use dpp::shielded::{ compute_minimum_shielded_fee, compute_shielded_identity_balance_write_fee, compute_shielded_identity_top_up_fee, compute_shielded_unshield_fee, @@ -915,9 +916,9 @@ fn map_asset_lock_funding_result( /// independently if needed. /// /// `out_identity_id` is ALSO written on the [`ErrorShieldedBroadcastUnconfirmed`] result code: the -/// broadcast was accepted but its execution result couldn't be confirmed, so the derived id is -/// handed back (the identity may already exist on chain) and the host must hold the slot rather than -/// treat the registration as failed. On every other error code `out_identity_id` is left untouched. +/// broadcast could not be confirmed, or creation succeeded on chain but local registration failed. +/// The diagnostic distinguishes these outcomes. The host must hold the slot rather than re-submit +/// creation. On every other error code `out_identity_id` is left untouched. /// /// [`ErrorShieldedBroadcastUnconfirmed`]: crate::error::PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed /// @@ -1055,13 +1056,20 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_identity_create_from_p r }); + map_identity_create_result(result, &mut *out_identity_id) +} + +fn map_identity_create_result( + result: Result, + out_identity_id: &mut [u8; 32], +) -> PlatformWalletFFIResult { match result { Ok(identity_id) => { *out_identity_id = identity_id.to_buffer(); PlatformWalletFFIResult::ok() } // Broadcast accepted but its execution result couldn't be confirmed and a direct fetch came - // back empty. The identity MAY exist on chain, so — unlike every other error arm — we still + // back empty. The identity MAY exist on chain, so we still // write the derived id to `out_identity_id` (see the `# Safety` note) so the caller can hold // the slot against re-submission and surface the pending identity. The notes' reservations // were intentionally NOT released wallet-side. @@ -1077,6 +1085,13 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_identity_create_from_p ), ) } + Err(error @ PlatformWalletError::IdentityCreatedButNotRegistered { identity_id, .. }) => { + *out_identity_id = identity_id.to_buffer(); + PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed, + error.to_string(), + ) + } // Retryable: no Platform-recorded anchor covered the selected notes yet // (the commitment tree is mid-block after an index-chunk sync). Nothing // was broadcast and the notes were released, so the host may retry after @@ -3512,6 +3527,53 @@ mod tests { ); } + #[test] + fn should_preserve_created_identity_and_hold_its_slot_after_local_registration_failure() { + let identity_id = Identifier::from([0x42; 32]); + let error = PlatformWalletError::IdentityCreatedButNotRegistered { + identity_id, + reason: "identity slot is occupied".to_string(), + }; + let diagnostic = error.to_string(); + let mut out_identity_id = [0; 32]; + let mut result = map_identity_create_result(Err(error), &mut out_identity_id); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed + ); + assert_eq!(out_identity_id, identity_id.to_buffer()); + assert_eq!(message_of(&result), diagnostic); + assert!(diagnostic.contains("created on chain")); + assert!(diagnostic.contains("could not be registered locally")); + assert!(diagnostic.contains("do not re-submit")); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + } + + #[test] + fn should_preserve_unconfirmed_identity_create_diagnostic_and_id() { + let identity_id = Identifier::from([0x43; 32]); + let mut out_identity_id = [0; 32]; + let mut result = map_identity_create_result( + Err(PlatformWalletError::ShieldedBroadcastUnconfirmed { + identity_id, + reason: "result proof unavailable".to_string(), + }), + &mut out_identity_id, + ); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedBroadcastUnconfirmed + ); + assert_eq!(out_identity_id, identity_id.to_buffer()); + assert_eq!( + message_of(&result), + format!("shielded identity-create-from-pool broadcast unconfirmed (identity {identity_id} may exist on chain): result proof unavailable") + ); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + } + /// `map_spend_result` pins the retry-relevant code split the three spend /// entry points depend on: /// - `ShieldedSpendUnconfirmed` → `ErrorShieldedSpendUnconfirmed` (host diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index eee0fd9aa89..0c05fa3eb8b 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -108,6 +108,15 @@ pub enum PlatformWalletError { occupant: Identifier, }, + #[error( + "Identity {identity_id} was created on chain but could not be registered locally: \ + {reason}; do not re-submit identity creation" + )] + IdentityCreatedButNotRegistered { + identity_id: Identifier, + reason: String, + }, + #[error("Identity not found: {0}")] IdentityNotFound(Identifier), diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs index 07707ea4c11..e6618d9211d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/lifecycle.rs @@ -206,7 +206,9 @@ impl IdentityManager { /// updated `wallet_id` / `identity_index`. Fails with /// [`PlatformWalletError::IdentityIndexOccupied`], changing nothing, when /// the slot already holds a different identity. - pub fn adopt_into_wallet( + /// Live-wallet callers hold `identity_placement` before the manager write + /// lock so a tip operation keeps its verified source slot until it finishes. + pub(crate) fn adopt_into_wallet( &mut self, identity_id: &Identifier, wallet_id: WalletId, diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index c7699a15b54..201799e0a7d 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -44,6 +44,8 @@ use crate::{DashPayProfile, PaymentAddressUpdate, ProfileUpdate}; use dash_sdk::platform::transition::put_settings::PutSettings; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; +#[cfg(feature = "shielded")] +use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey}; use dpp::prelude::Identifier; @@ -58,6 +60,7 @@ use { super::shielded::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, PrivatePaymentRecord, }, + super::shielded::tips::PreparedTipAccount, super::shielded::{ FileBackedShieldedStore, NetworkShieldedCoordinator, OrchardKeySet, ShieldedStore, }, @@ -449,11 +452,11 @@ pub struct PlatformWallet { /// The tip account each identity's address was last prepared for in /// this session, after its slot was proved with the seed. Publication /// of a wallet tip address requires it, so an address is published only - /// for the identity and slot it was prepared for. `Arc` so cloned wallet - /// handles share it. + /// for the identity and slot it was prepared for, and invalidated by a + /// coordinator Clear. `Arc` so cloned wallet handles share it. #[cfg(feature = "shielded")] pub(crate) prepared_tip_accounts: - Arc>>, + Arc>>, /// Set once this wallet has been removed from the manager, to stop /// a handle that outlives the removal from binding shielded state /// back onto the coordinator. Callers resolve an @@ -2284,8 +2287,9 @@ impl PlatformWallet { /// local `IdentityManager`; on a successful broadcast the proof-verified identity is registered /// there (mirroring `register_from_addresses`) so the host persister emits the /// `IdentityChangeSet` / `IdentityKeysChangeSet` that creates the app's identity row. A failed - /// registration after a successful broadcast is logged and swallowed — the identity already - /// exists on chain, so the next sync heals the local row. Returns the new identity's id. + /// registration after a successful broadcast returns + /// [`PlatformWalletError::IdentityCreatedButNotRegistered`], carrying the created identity's + /// id. Creation must not be re-submitted in that case. #[cfg(feature = "shielded")] #[allow(clippy::too_many_arguments)] pub async fn shielded_identity_create_from_pool( @@ -2307,6 +2311,23 @@ impl PlatformWallet { P: dpp::shielded::builder::OrchardProver, IS: dpp::identity::signer::Signer + Send + Sync, { + { + let wm = self.wallet_manager.read().await; + let info = wm + .get_wallet_info(&self.wallet_id) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id)))?; + if let Some(occupant) = info + .identity_manager + .wallet_identities + .get(&self.wallet_id) + .and_then(|identities| identities.get(&identity_index)) + { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "Cannot create an identity at index {identity_index}: the slot holds identity {}", + occupant.identity.id() + ))); + } + } let (identity_id, identity) = { // Scope the transient keyset so its spend authority is dropped before we take the // wallet-manager write lock below — it's only needed for the spend, not for the @@ -2331,36 +2352,22 @@ impl PlatformWallet { // Register the proof-verified identity in the local manager at its HD slot, exactly like // `register_from_addresses`' Step 3 — this drives the host persister's // `IdentityChangeSet` / `IdentityKeysChangeSet` emit so the app's identity row is created. - // The broadcast already succeeded; a registration failure here (e.g. the slot is already - // occupied locally) is logged and swallowed rather than surfaced as an error, since the - // identity exists on chain and the next sync heals the local view. { let mut wm = self.wallet_manager.write().await; - match wm.get_wallet_info_mut(&self.wallet_id) { - Some(info) => { - if let Err(e) = info.identity_manager.add_identity( - identity, - identity_index, - self.wallet_id, - &self.persister, - ) { - tracing::warn!( - identity_index, - error = %e, - "IdentityCreateFromShieldedPool broadcast succeeded but registering the \ - identity in the local manager failed; the on-chain identity exists and \ - the next sync will heal the local row" - ); - } - } - None => { - tracing::warn!( - identity_index, - "IdentityCreateFromShieldedPool broadcast succeeded but the wallet info was \ - not found in the manager; skipping local registration (heals on next sync)" - ); + let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { + PlatformWalletError::IdentityCreatedButNotRegistered { + identity_id, + reason: "wallet was removed from the manager".to_string(), } - } + })?; + info.identity_manager + .add_identity(identity, identity_index, self.wallet_id, &self.persister) + .map_err( + |error| PlatformWalletError::IdentityCreatedButNotRegistered { + identity_id, + reason: error.to_string(), + }, + )?; } Ok(identity_id) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 359bcd73bb5..7f88b7b17d8 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -14,7 +14,13 @@ use crate::{PlatformWalletError, ShieldedTipRecipient}; use dpp::identity::accessors::IdentityGettersV0; use dpp::prelude::Identifier; use grovedb_commitment_tree::PaymentAddress; -use std::sync::{Arc, PoisonError}; +use std::sync::{Arc, PoisonError, Weak}; + +pub(crate) struct PreparedTipAccount { + account: u32, + coordinator: Weak, + clear_generation: u64, +} pub const SHIELDED_TIP_ACCOUNT_BASE: u32 = 0x4000_0000; @@ -136,6 +142,7 @@ impl PlatformWallet { // replaces the registration, so another bind landing in between // would have its ordinary accounts dropped by this stale snapshot. let _config = self.shielded_config_lock.lock().await; + let clear_generation = coordinator.clear_generation(); let mut accounts = self.shielded_account_indices().await; if accounts.is_empty() { return Err(PlatformWalletError::ShieldedNotBound); @@ -152,10 +159,22 @@ impl PlatformWallet { .shielded_default_address(account) .await .ok_or(PlatformWalletError::ShieldedNotBound)?; + #[cfg(test)] + test_hooks::after_bind(self).await; + if coordinator.clear_generation() != clear_generation { + return Err(PlatformWalletError::ShieldedNotBound); + } self.prepared_tip_accounts .lock() .unwrap_or_else(PoisonError::into_inner) - .insert(*identity_id, account); + .insert( + *identity_id, + PreparedTipAccount { + account, + coordinator: Arc::downgrade(coordinator), + clear_generation, + }, + ); Ok(address) } @@ -264,7 +283,12 @@ impl PlatformWallet { .lock() .unwrap_or_else(PoisonError::into_inner) .get(identity_id) - .copied(); + .is_some_and(|prepared| { + prepared.account == owning_account + && prepared.coordinator.upgrade().is_some_and(|coordinator| { + coordinator.clear_generation() == prepared.clear_generation + }) + }); let wm = self.wallet_manager.read().await; let current = wm .get_wallet_info(&self.wallet_id()) @@ -272,7 +296,7 @@ impl PlatformWallet { .filter(|identity| identity.wallet_id == Some(self.wallet_id())) .and_then(|identity| identity.identity_index) .and_then(|index| shielded_tip_account_index(index).ok()); - if prepared == Some(owning_account) && current == Some(owning_account) { + if prepared && current == Some(owning_account) { Ok(()) } else { Err(PlatformWalletError::InvalidIdentityData( @@ -344,6 +368,7 @@ pub(crate) mod test_hooks { type Hook = (oneshot::Sender<()>, oneshot::Receiver<()>); static AFTER_SNAPSHOT: Mutex>> = Mutex::new(None); + static AFTER_BIND: Mutex>> = Mutex::new(None); fn key(wallet: &PlatformWallet) -> usize { Arc::as_ptr(&wallet.shielded_config_lock) as usize @@ -375,6 +400,31 @@ pub(crate) mod test_hooks { let _ = resume.await; } } + + pub(crate) fn pause_after_bind( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = oneshot::channel(); + AFTER_BIND + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(key(wallet), (reached_tx, resume_rx)); + (reached_rx, resume_tx) + } + + pub(crate) async fn after_bind(wallet: &PlatformWallet) { + let hook = AFTER_BIND + .lock() + .unwrap() + .as_mut() + .and_then(|hooks| hooks.remove(&key(wallet))); + if let Some((reached, resume)) = hook { + let _ = reached.send(()); + let _ = resume.await; + } + } } #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index ae23f48ea35..1cf64a838cc 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -1950,3 +1950,97 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal .expect("publishable"); } } + +#[tokio::test] +async fn should_require_fresh_tip_preparation_after_clear_even_after_rebind() { + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_clear").await; + let address = wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + .unwrap(); + wallet + .check_tip_address_publication(&id, &address) + .await + .unwrap(); + + coordinator.clear().await.unwrap(); + assert!(wallet + .check_tip_address_publication(&id, &address) + .await + .is_err()); + wallet + .bind_shielded(&seed, &[0], &coordinator) + .await + .unwrap(); + assert!(wallet + .check_tip_address_publication(&id, &address) + .await + .is_err()); + + assert_eq!( + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + .unwrap(), + address + ); + wallet + .check_tip_address_publication(&id, &address) + .await + .unwrap(); +} + +#[tokio::test] +async fn should_refuse_tip_preparation_cleared_after_its_bind() { + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_clear_during_prepare").await; + let (reached, resume) = super::tips::test_hooks::pause_after_bind(&wallet); + let preparing = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_tip_address(&seed, &id, &coordinator) + .await + }) + }; + reached.await.unwrap(); + let address = wallet + .shielded_default_address(crate::shielded_tip_account_index(2).unwrap()) + .await + .unwrap(); + coordinator.clear().await.unwrap(); + resume.send(()).unwrap(); + assert!(matches!( + preparing.await.unwrap(), + Err(crate::PlatformWalletError::ShieldedNotBound) + )); + assert!(wallet + .check_tip_address_publication(&id, &address) + .await + .is_err()); +} + +#[tokio::test] +async fn should_refuse_shielded_identity_creation_at_an_occupied_slot_before_deriving_or_spending() +{ + let (wallet, _, occupant, coordinator) = tip_race_fixture("tips_occupied_creation").await; + let error = wallet + .shielded_identity_create_from_pool( + &coordinator, + &[], + 0, + 2, + vec![], + 0, + dpp::address_funds::PlatformAddress::P2pkh([0x11; 20]), + &NoSigner, + &super::CachedOrchardProver::new(), + ) + .await + .unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::InvalidIdentityData(ref message) + if message.contains("index 2") && message.contains(&format!("{occupant}"))), + "{error:?}" + ); +} diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift index 5c5d8974477..cf4c3084c19 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/CreateIdentityView.swift @@ -248,7 +248,7 @@ struct CreateIdentityView: View { @Query(sort: [SortDescriptor(\PersistentAssetLock.updatedAt, order: .reverse)]) private var allAssetLocks: [PersistentAssetLock] - /// All wallets' unspent shielded notes. The shielded funding + /// All wallets' unspent account-0 shielded notes. The shielded funding /// picker spans multiple wallets, so this uses the all-wallets /// predicate and `shieldedPoolBalance(for:)` scopes by walletId in /// memory — a single-walletId `@Query` couldn't serve every row @@ -256,9 +256,15 @@ struct CreateIdentityView: View { /// `modelContext.fetch`) makes the funding option and denomination /// list update live: rows arriving while this sheet is open /// re-render the view. - @Query(filter: PersistentShieldedNote.unspentPredicate) + @Query(filter: CreateIdentityView.shieldedFundingPredicate) private var unspentShieldedNotes: [PersistentShieldedNote] + static var shieldedFundingPredicate: Predicate { + #Predicate { + $0.accountIndex == 0 && $0.isSpent == false + } + } + // MARK: - Selection state /// The source wallet selection. `nil` encodes "pick nothing yet"; @@ -1820,8 +1826,8 @@ struct CreateIdentityView: View { && shieldedFallbackAddressBytes(for: walletId) != nil } - /// Per-wallet shielded pool balance: sum of `walletId`'s unspent - /// `PersistentShieldedNote` values, filtered in memory from the + /// Per-wallet shielded funding balance: sum of `walletId`'s unspent + /// account-0 `PersistentShieldedNote` values, filtered in memory from the /// `unspentShieldedNotes` `@Query` (rather than the single-mirror /// `shieldedService.shieldedBalance`). Correct for ANY loaded /// wallet, not just the mirror's `firstWallet`. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift index d78f73ddd11..14038d24625 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleAppTests/PersistentShieldedNotePredicateTests.swift @@ -100,6 +100,45 @@ final class PersistentShieldedNotePredicateTests: XCTestCase { XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 150) } + func testIdentityFundingHasNoSourceBalanceForTipOnlyWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x01, isSpent: false, value: 900)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: CreateIdentityView.shieldedFundingPredicate + )) + XCTAssertTrue(notes.isEmpty) + XCTAssertEqual(notes.reduce(UInt64(0)) { $0 + $1.value }, 0) + } + + func testIdentityFundingBalanceIncludesOnlyUnspentAccountZeroInSelectedWallet() throws { + let container = try DashModelContainer.createInMemory() + let context = ModelContext(container) + let wallet = walletId(0xAA) + let otherWallet = walletId(0xBB) + context.insert(makeNote(walletId: wallet, nullifier: 0x01, isSpent: false, value: 100)) + context.insert(makeNote(walletId: wallet, nullifier: 0x02, isSpent: false, value: 50)) + context.insert(makeNote(walletId: wallet, nullifier: 0x03, isSpent: true, value: 999)) + context.insert(makeNote(walletId: wallet, accountIndex: 1, + nullifier: 0x04, isSpent: false, value: 200)) + context.insert(makeNote(walletId: wallet, accountIndex: 0x4000_0000, + nullifier: 0x05, isSpent: false, value: 900)) + context.insert(makeNote(walletId: otherWallet, + nullifier: 0x06, isSpent: false, value: 300)) + try context.save() + + let notes = try context.fetch(FetchDescriptor( + predicate: CreateIdentityView.shieldedFundingPredicate + )) + XCTAssertEqual(notes.count, 3) + XCTAssertEqual(notes.filter { $0.walletId == wallet }.reduce(UInt64(0)) { $0 + $1.value }, 150) + XCTAssertEqual(notes.filter { $0.walletId == otherWallet }.reduce(UInt64(0)) { $0 + $1.value }, 300) + } + private func makeNote( walletId: Data, accountIndex: UInt32 = 0, diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift index 84f46da808a..a90a4035082 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashLegacySchemaMigrationTests.swift @@ -842,8 +842,9 @@ final class DashLegacySchemaMigrationTests: XCTestCase { ("converted.store", dropIndex + drop + "ALTER TABLE ZPERSISTENTTOKENBALANCE ADD COLUMN Z14TOKENBALANCES VARCHAR;"), ] { + let candidate = try renumbered(name, tail: tail) XCTAssertThrowsError( - try DashLegacyStoreSQLite.validatePreservation(from: before, to: try renumbered(name, tail: tail)), + try DashLegacyStoreSQLite.validatePreservation(from: before, to: candidate), name) } } From 9cb13d33eaa43ab8424c36e1a708d46b8c63036a Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 20:21:19 +0000 Subject: [PATCH 21/41] fix(platform-wallet): fence public identity placement mutations --- .../src/contact_request.rs | 10 +- .../rs-platform-wallet-ffi/src/dashpay.rs | 5 +- .../submission_result_tests.rs | 5 +- .../rs-platform-wallet-ffi/src/persistence.rs | 7 +- .../src/private_contact_request.rs | 12 +- .../src/txo_reconcile.rs | 42 +++- .../src/manager/accessors.rs | 12 +- .../identity/network/identity_handle.rs | 21 -- .../network/private_contact_requests.rs | 6 +- .../fund_from_asset_lock.rs | 4 +- .../src/wallet/platform_wallet.rs | 55 ++++- .../src/wallet/shielded/tips.rs | 65 +++--- .../wallet/shielded/viewing_key_bind_tests.rs | 197 +++++++++++++++++- 13 files changed, 331 insertions(+), 110 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/contact_request.rs b/packages/rs-platform-wallet-ffi/src/contact_request.rs index dbbb65e8938..71c67688c3f 100644 --- a/packages/rs-platform-wallet-ffi/src/contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/contact_request.rs @@ -460,9 +460,8 @@ mod tests { revision: 0, }); crate::runtime::runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + let mut state = wallet.state_mut().await; + state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) .expect("the identity"); @@ -504,10 +503,9 @@ mod tests { PLATFORM_WALLET_STORAGE .with_item(handle, |wallet| { crate::runtime::runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; + let mut state = wallet.state_mut().await; change( - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + state .identity_manager .managed_identity_mut(&identity_id) .expect("the identity"), diff --git a/packages/rs-platform-wallet-ffi/src/dashpay.rs b/packages/rs-platform-wallet-ffi/src/dashpay.rs index 72c795781f2..0eb3b1d808c 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay.rs @@ -2031,9 +2031,8 @@ mod tests { revision: 0, }); runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + let mut state = wallet.state_mut().await; + state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) .expect("the identity"); diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs index f0ebd8ebee1..bc2ebc0bee1 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs @@ -209,11 +209,8 @@ impl Fixture { .await .unwrap(); wallet - .wallet_manager() - .write() + .state_mut() .await - .get_wallet_info_mut(&wallet.wallet_id()) - .unwrap() .identity_manager .add_identity(identity.clone(), 0, wallet.wallet_id(), wallet.persister()) .unwrap(); diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 3e954d37a2a..f8fea1db9f0 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -9306,11 +9306,8 @@ mod tests { let held = |id: Identifier, index: u32| { runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - let identities = &mut wm - .get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") - .identity_manager; + let mut state = wallet.state_mut().await; + let identities = &mut state.identity_manager; identities .add_identity( Identity::V0(IdentityV0 { diff --git a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs index a9940b6ecc6..4df1f3cda35 100644 --- a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs @@ -1697,11 +1697,8 @@ mod tests { PLATFORM_WALLET_STORAGE .with_item(wallet_handle, |wallet| { runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - let manager = &mut wm - .get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") - .identity_manager; + let mut state = wallet.state_mut().await; + let manager = &mut state.identity_manager; manager .add_identity(bob.clone(), 0, wallet.wallet_id(), wallet.persister()) .expect("Bob"); @@ -1828,9 +1825,8 @@ mod tests { revision: 0, }); runtime().block_on(async { - let mut wm = wallet.wallet_manager().write().await; - wm.get_wallet_info_mut(&wallet.wallet_id()) - .expect("the wallet's info") + let mut state = wallet.state_mut().await; + state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) .expect("the identity"); diff --git a/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs b/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs index 1efff04981a..fc6b6ca29e1 100644 --- a/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs +++ b/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs @@ -991,11 +991,21 @@ mod tests { #[test] fn a_heal_page_is_held_only_under_a_run_claim() { use crate::test_fixtures::mock_manager; - - let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(mock_manager()); - let wallet_id = [0x6bu8; 32]; - let (reconciler, engine) = PLATFORM_WALLET_MANAGER_STORAGE - .with_item(handle, |m| (m.txo_reconciler(), m.wallet_manager_arc())) + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + let manager = mock_manager(); + let wallet = crate::runtime::runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[0x6b; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("an empty wallet"); + let wallet_id = wallet.wallet_id(); + let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(manager); + let reconciler = PLATFORM_WALLET_MANAGER_STORAGE + .with_item(handle, |m| m.txo_reconciler()) .expect("manager"); let heal_page = |held: &mut *mut TxoReconcileHeldVerdictsFFI| { let mut rows: *const TxoHealRowFFI = std::ptr::null(); @@ -1034,11 +1044,11 @@ mod tests { assert_eq!(result.code, PlatformWalletFFIResultCode::Success); assert!(!held.is_null()); assert!( - engine.try_write().is_err(), + wallet.try_state_mut().is_none(), "the engine is held until the page is released" ); unsafe { platform_wallet_txo_reconcile_held_verdicts_free(held) }; - assert!(engine.try_write().is_ok()); + assert!(wallet.try_state_mut().is_some()); reconciler.finish(&wallet_id, TxoReconcileFinish::NotRun); drop(PLATFORM_WALLET_MANAGER_STORAGE.remove(handle)); @@ -1118,6 +1128,7 @@ mod tests { use std::sync::Arc; use crate::test_fixtures::mock_manager; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; /// Poll `condition` until it holds, failing after [`WAIT`]. fn wait_for(what: &str, condition: impl Fn() -> bool) { @@ -1128,8 +1139,17 @@ mod tests { } } - let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(mock_manager()); - let wallet_id = [0x5au8; 32]; + let manager = mock_manager(); + let wallet = crate::runtime::runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[0x5a; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("an empty wallet"); + let wallet_id = wallet.wallet_id(); + let handle = PLATFORM_WALLET_MANAGER_STORAGE.insert(manager); let (reconciler, engine) = PLATFORM_WALLET_MANAGER_STORAGE .with_item(handle, |m| (m.txo_reconciler(), m.wallet_manager_arc())) .expect("manager"); @@ -1170,8 +1190,8 @@ mod tests { // An engine writer queued behind the guard. With the guard held, a // fresh engine read is refused exactly while a writer waits. - let writer_engine = Arc::clone(&engine); - let writer = std::thread::spawn(move || drop(writer_engine.blocking_write())); + let writer_wallet = Arc::clone(&wallet); + let writer = std::thread::spawn(move || drop(writer_wallet.state_mut_blocking())); wait_for("the engine writer never queued behind the guard", || { engine.try_read().is_err() }); diff --git a/packages/rs-platform-wallet/src/manager/accessors.rs b/packages/rs-platform-wallet/src/manager/accessors.rs index b1389f98fe2..9cbbe257ad8 100644 --- a/packages/rs-platform-wallet/src/manager/accessors.rs +++ b/packages/rs-platform-wallet/src/manager/accessors.rs @@ -21,7 +21,7 @@ use crate::manager::platform_address_sync::PlatformAddressSyncManager; #[cfg(feature = "shielded")] use crate::manager::shielded_sync::ShieldedSyncManager; use crate::spv::SpvRuntime; -use crate::wallet::platform_wallet::WalletId; +use crate::wallet::platform_wallet::{WalletId, WalletManagerReader}; use crate::wallet::PlatformWallet; /// Result of [`PlatformWalletManager::provider_masternode_txs_blocking`]: @@ -1155,14 +1155,8 @@ impl PlatformWalletManager

{ /// and waiting on this lock inside that closure would stall /// `platform_wallet_manager_destroy` (a registry write) and, through /// parking_lot's writer preference, every other registry reader. - pub fn wallet_manager_arc( - &self, - ) -> Arc< - tokio::sync::RwLock< - key_wallet_manager::WalletManager, - >, - > { - Arc::clone(&self.wallet_manager) + pub fn wallet_manager_arc(&self) -> WalletManagerReader { + WalletManagerReader::new(Arc::clone(&self.wallet_manager)) } /// [`wallet_utxos_page`] under this manager's read lock. Blocking; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs index 1f09ec6a89c..73f319bff59 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs @@ -686,27 +686,6 @@ impl IdentityWallet { self.wallet_manager.read().await } - /// Get a write-lock handle to the shared [`WalletManager`]. - /// - /// Access wallet info via `wm.get_wallet_info_mut(&wallet_id)` on the - /// returned guard. This allows callers to mutate managed identities (e.g. - /// adding or updating identities from an external persistence layer). - pub async fn wallet_manager_write( - &self, - ) -> tokio::sync::RwLockWriteGuard<'_, WalletManager> { - self.wallet_manager.write().await - } - - /// Try to acquire a write-lock on the shared [`WalletManager`] without blocking. - /// - /// Returns `None` if the lock is currently held by another task. - /// Useful for synchronous callers that cannot await. - pub fn try_wallet_manager_write( - &self, - ) -> Option>> { - self.wallet_manager.try_write().ok() - } - /// The wallet ID for this identity wallet's underlying key material. pub fn wallet_id(&self) -> &WalletId { &self.wallet_id diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs index 3425470a24a..38d02cd6441 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs @@ -6795,7 +6795,7 @@ mod tests { &alice_crypto, )); let mut cx = Context::from_waker(Waker::noop()); - let wallet_manager = old.wallet_manager(); + let wallet_manager = &old.wallet_manager; let mut held = wallet_manager.write().await; let mut gated = false; for _ in 0..200 { @@ -9680,7 +9680,7 @@ mod tests { restore.as_mut().poll(&mut cx).is_pending(), "waits for the store" ); - let mut held_wallet = alice_wallet.wallet_manager().write().await; + let mut held_wallet = alice_wallet.wallet_manager.write().await; drop(held_store); // The restoration reads its journal snapshot, then waits for the wallet. assert!( @@ -9768,7 +9768,7 @@ mod tests { restore.as_mut().poll(&mut cx).is_pending(), "waits for the store" ); - let mut held_wallet = wallet.wallet_manager().write().await; + let mut held_wallet = wallet.wallet_manager.write().await; drop(held_store); // The restoration reads the redrive records, then waits for the // wallet before it opens the entry. diff --git a/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs b/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs index c44e8f14a2c..74e12808593 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_addresses/fund_from_asset_lock.rs @@ -1428,7 +1428,7 @@ mod tests { let (manager, wallet_id) = test_platform_wallet_manager().await; let wallet = manager.get_wallet(&wallet_id).await.expect("wallet handle"); let signer = - fund_test_platform_wallet(wallet.wallet_manager(), &wallet_id, 10_000_000).await; + fund_test_platform_wallet(&wallet.wallet_manager, &wallet_id, 10_000_000).await; let address = wallet .platform() .next_unused_receive_address(PlatformPaymentAccountKey { @@ -1477,7 +1477,7 @@ mod tests { let (manager, wallet_id) = test_platform_wallet_manager().await; let wallet = manager.get_wallet(&wallet_id).await.expect("wallet handle"); let signer = - fund_test_platform_wallet(wallet.wallet_manager(), &wallet_id, 10_000_000).await; + fund_test_platform_wallet(&wallet.wallet_manager, &wallet_id, 10_000_000).await; let address = wallet .platform() .next_unused_receive_address(PlatformPaymentAccountKey { diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 201799e0a7d..e4a827e2da8 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -390,6 +390,7 @@ pub struct PlatformWallet { wallet_id: WalletId, pub(crate) sdk: Arc, pub(crate) wallet_manager: Arc>>, + wallet_manager_reader: WalletManagerReader, // Sub-wallets that hold a broadcaster are monomorphized with // `SpvBroadcaster` — the only production broadcaster in use. // Swapping this out to another broadcaster is a three-line flip @@ -528,9 +529,9 @@ impl PlatformWallet { Arc::clone(&self.sdk) } - /// Get a reference to the shared wallet manager lock. - pub fn wallet_manager(&self) -> &Arc>> { - &self.wallet_manager + /// Read the shared wallet manager. Mutations use [`Self::state_mut`]. + pub fn wallet_manager(&self) -> &WalletManagerReader { + &self.wallet_manager_reader } /// Get the lock-free balance for UI reads. @@ -565,10 +566,14 @@ impl PlatformWallet { /// Write-lock the wallet manager and return a guard that derefs to this /// wallet's `PlatformWalletInfo` (with `DerefMut`). + /// Holds the identity-placement write lock first, so replacing the manager + /// or removing/re-adding an identity cannot race a tip operation. pub async fn state_mut(&self) -> WalletStateWriteGuard<'_> { + let placement = self.identity.identity_placement.write().await; WalletStateWriteGuard { guard: self.wallet_manager.write().await, wallet_id: self.wallet_id, + _placement: placement, } } @@ -582,14 +587,17 @@ impl PlatformWallet { /// Blocking write-lock. /// + /// Holds identity placement before wallet state, like [`Self::state_mut`]. /// Uses `tokio::sync::RwLock::blocking_write` — must NOT be /// called from within a tokio async context. Exists so sync /// callers (e.g. SPV-driven transaction processing) can reach /// mutation methods that require the wallet-manager write lock. pub fn state_mut_blocking(&self) -> WalletStateWriteGuard<'_> { + let placement = self.identity.identity_placement.blocking_write(); WalletStateWriteGuard { guard: self.wallet_manager.blocking_write(), wallet_id: self.wallet_id, + _placement: placement, } } @@ -747,15 +755,17 @@ impl PlatformWallet { } /// Non-blocking write-lock. Returns `None` if the lock is currently - /// held by any reader or writer. Same safety properties as + /// held by any reader or writer, or identity placement is in use. Same safety properties as /// [`try_state`]: never panics, never blocks. pub fn try_state_mut(&self) -> Option> { + let placement = self.identity.identity_placement.try_write().ok()?; self.wallet_manager .try_write() .ok() .map(|guard| WalletStateWriteGuard { guard, wallet_id: self.wallet_id, + _placement: placement, }) } @@ -845,6 +855,7 @@ impl PlatformWallet { Self { wallet_id, sdk, + wallet_manager_reader: WalletManagerReader::new(Arc::clone(&wallet_manager)), wallet_manager, core, identity, @@ -2978,6 +2989,7 @@ impl Clone for PlatformWallet { wallet_id: self.wallet_id, sdk: self.sdk.clone(), wallet_manager: self.wallet_manager.clone(), + wallet_manager_reader: self.wallet_manager_reader.clone(), core: self.core.clone(), identity: self.identity.clone(), platform: self.platform.clone(), @@ -3054,6 +3066,40 @@ impl std::fmt::Debug for PlatformWallet { // Wallet state guard types — lock WalletManager, deref to PlatformWalletInfo // --------------------------------------------------------------------------- +/// Shared read access without exposing an unlocked identity-placement mutation path. +/// Use [`PlatformWallet::state_mut`] to change a live wallet's state. +/// +/// ```compile_fail +/// async fn bypass(reader: &platform_wallet::wallet::platform_wallet::WalletManagerReader) { +/// reader.write().await; +/// } +/// ``` +#[derive(Clone)] +pub struct WalletManagerReader { + inner: Arc>>, +} + +impl WalletManagerReader { + pub(crate) fn new(inner: Arc>>) -> Self { + Self { inner } + } + + pub async fn read(&self) -> RwLockReadGuard<'_, WalletManager> { + self.inner.read().await + } + + pub fn blocking_read(&self) -> RwLockReadGuard<'_, WalletManager> { + self.inner.blocking_read() + } + + pub fn try_read( + &self, + ) -> Result>, tokio::sync::TryLockError> + { + self.inner.try_read() + } +} + /// Read guard that locks `WalletManager` and derefs to this wallet's /// `PlatformWalletInfo`. Also provides `.wallet()` for key material access. pub struct WalletStateReadGuard<'a> { @@ -3084,6 +3130,7 @@ impl Deref for WalletStateReadGuard<'_> { pub struct WalletStateWriteGuard<'a> { guard: RwLockWriteGuard<'a, WalletManager>, wallet_id: WalletId, + _placement: RwLockWriteGuard<'a, ()>, } impl<'a> WalletStateWriteGuard<'a> { diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 7f88b7b17d8..05c173bb7cd 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -343,6 +343,8 @@ impl PlatformWallet { } let _placement = self.identity.identity_placement.read().await; let account = self.tip_source_account(seed, source).await?; + #[cfg(test)] + test_hooks::before_spend(self).await; self.shielded_transfer_to( coordinator, seed, @@ -367,63 +369,72 @@ pub(crate) mod test_hooks { use tokio::sync::oneshot; type Hook = (oneshot::Sender<()>, oneshot::Receiver<()>); - static AFTER_SNAPSHOT: Mutex>> = Mutex::new(None); - static AFTER_BIND: Mutex>> = Mutex::new(None); + #[derive(Clone, Copy, PartialEq, Eq, Hash)] + enum Stage { + Snapshot, + Bound, + Spend, + } + static HOOKS: Mutex>> = Mutex::new(None); fn key(wallet: &PlatformWallet) -> usize { Arc::as_ptr(&wallet.shielded_config_lock) as usize } - /// Arm the pause for `wallet`. Returns a receiver that fires when - /// preparation reaches the pause, and the sender that resumes it. - pub(crate) fn pause_after_snapshot( + fn pause( wallet: &PlatformWallet, + stage: Stage, ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { let (reached_tx, reached_rx) = oneshot::channel(); let (resume_tx, resume_rx) = oneshot::channel(); - AFTER_SNAPSHOT + HOOKS .lock() .unwrap() .get_or_insert_with(HashMap::new) - .insert(key(wallet), (reached_tx, resume_rx)); + .insert((key(wallet), stage), (reached_tx, resume_rx)); (reached_rx, resume_tx) } - pub(crate) async fn after_snapshot(wallet: &PlatformWallet) { - let hook = AFTER_SNAPSHOT + async fn reach(wallet: &PlatformWallet, stage: Stage) { + let hook = HOOKS .lock() .unwrap() .as_mut() - .and_then(|hooks| hooks.remove(&key(wallet))); + .and_then(|hooks| hooks.remove(&(key(wallet), stage))); if let Some((reached, resume)) = hook { let _ = reached.send(()); let _ = resume.await; } } + pub(crate) fn pause_after_snapshot( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + pause(wallet, Stage::Snapshot) + } + + pub(crate) async fn after_snapshot(wallet: &PlatformWallet) { + reach(wallet, Stage::Snapshot).await; + } + pub(crate) fn pause_after_bind( wallet: &PlatformWallet, ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { - let (reached_tx, reached_rx) = oneshot::channel(); - let (resume_tx, resume_rx) = oneshot::channel(); - AFTER_BIND - .lock() - .unwrap() - .get_or_insert_with(HashMap::new) - .insert(key(wallet), (reached_tx, resume_rx)); - (reached_rx, resume_tx) + pause(wallet, Stage::Bound) } pub(crate) async fn after_bind(wallet: &PlatformWallet) { - let hook = AFTER_BIND - .lock() - .unwrap() - .as_mut() - .and_then(|hooks| hooks.remove(&key(wallet))); - if let Some((reached, resume)) = hook { - let _ = reached.send(()); - let _ = resume.await; - } + reach(wallet, Stage::Bound).await; + } + + pub(crate) fn pause_before_spend( + wallet: &PlatformWallet, + ) -> (oneshot::Receiver<()>, oneshot::Sender<()>) { + pause(wallet, Stage::Spend) + } + + pub(crate) async fn before_spend(wallet: &PlatformWallet) { + reach(wallet, Stage::Spend).await; } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 1cf64a838cc..b27a769d718 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -1280,7 +1280,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( // Restored at the host's placeholder 0, but its keys are identity 5's. let id = Identifier::from([0x55; 32]); { - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; wm.get_wallet_info_mut(&wallet.wallet_id()) .unwrap() .identity_manager @@ -1375,7 +1375,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( // Rediscovery proves index 5 and re-slots the identity. { - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; wm.get_wallet_info_mut(&wallet.wallet_id()) .unwrap() .identity_manager @@ -1470,7 +1470,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn crate::changeset::DurableCursors::default(), ); { - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; wm.get_wallet_info_mut(&wallet.wallet_id()) .unwrap() .identity_manager @@ -1488,7 +1488,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .unwrap(); } { - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; wm.get_wallet_info_mut(&wallet.wallet_id()) .unwrap() .identity_manager @@ -1724,8 +1724,12 @@ async fn tip_race_fixture( Arc::clone(&wallet_manager), Arc::new(crate::events::PlatformEventManager::new(Vec::new())), )); + let mock_dir = temp_dir(tag); + std::fs::create_dir_all(&mock_dir).unwrap(); let sdk = dash_sdk::SdkBuilder::new_mock() .with_network(Network::Testnet) + .with_dump_dir(&mock_dir) + .with_version(dpp::version::PlatformVersion::latest()) .build() .unwrap(); let persister = Arc::new(CapturingPersistence::default()); @@ -1742,7 +1746,7 @@ async fn tip_race_fixture( ); let id = Identifier::from([0x66; 32]); { - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; wm.get_wallet_info_mut(&wallet.wallet_id()) .unwrap() .identity_manager @@ -1873,7 +1877,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; let (wallet, seed, id, coordinator) = tip_race_fixture("tips_placement_move").await; { - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; let managed = wm .get_wallet_info_mut(&wallet.wallet_id()) .unwrap() @@ -1901,7 +1905,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal let wallet = wallet.clone(); tokio::spawn(async move { let _placement = wallet.identity.identity_placement.write().await; - let mut wm = wallet.wallet_manager().write().await; + let mut wm = wallet.wallet_manager.write().await; wm.get_wallet_info_mut(&wallet.wallet_id()) .unwrap() .identity_manager @@ -2044,3 +2048,182 @@ async fn should_refuse_shielded_identity_creation_at_an_occupied_slot_before_der "{error:?}" ); } + +#[tokio::test] +async fn should_order_public_identity_manager_replacement_after_tip_spending() { + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents}; + use dpp::document::{Document, DocumentV0, DocumentV0Getters}; + use dpp::platform_value::Value; + use dpp::prelude::Identifier; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + use futures::FutureExt; + + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_public_mutation").await; + let recipient = Identifier::from([0x77; 32]); + let address = OrchardKeySet::from_seed(&[9; 64], Network::Testnet, 0) + .unwrap() + .default_address + .to_raw_address_bytes(); + let mut sdk = wallet.sdk().clone(); + let dpns = + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()).unwrap(); + sdk.mock() + .expect_fetch(SystemDataContract::DPNS.id(), Some(dpns.clone())) + .await + .unwrap(); + let domain = Document::V0(DocumentV0 { + id: Identifier::from([3; 32]), + owner_id: recipient, + revision: Some(1), + properties: [( + "records".into(), + Value::Map(vec![( + Value::Text("identity".into()), + Value::Identifier(recipient.to_buffer()), + )]), + )] + .into(), + ..Default::default() + }); + let query = DocumentQuery::new(dpns, "domain") + .unwrap() + .with_where(WhereClause { + field: "normalizedParentDomainName".into(), + operator: WhereOperator::Equal, + value: Value::Text("dash".into()), + }) + .with_where(WhereClause { + field: "normalizedLabel".into(), + operator: WhereOperator::Equal, + value: Value::Text("a11ce".into()), + }) + .with_limit(1); + sdk.mock() + .expect_fetch_many::( + query, + Some([(domain.id(), Some(domain))].into()), + ) + .await + .unwrap(); + let profile = Document::V0(DocumentV0 { + id: Identifier::from([4; 32]), + owner_id: recipient, + revision: Some(1), + properties: [("shieldedAddress".into(), Value::Bytes(address.to_vec()))].into(), + ..Default::default() + }); + let query = DocumentQuery::new( + crate::wallet::identity::network::dashpay_contract().unwrap(), + "profile", + ) + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![recipient.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + sdk.mock() + .expect_fetch_many::( + query, + Some([(profile.id(), Some(profile))].into()), + ) + .await + .unwrap(); + + let (reached, resume) = super::tips::test_hooks::pause_before_spend(&wallet); + let mut sending = { + let wallet = wallet.clone(); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .send_shielded_tip( + &coordinator, + &seed, + crate::ShieldedTipSource::Identity(id), + "Alice.dash", + &crate::ShieldedTipRecipient { + identity_id: recipient, + address, + }, + 0, + [0; 36], + &super::CachedOrchardProver::new(), + ) + .await + }) + }; + tokio::time::timeout(std::time::Duration::from_secs(5), async { + tokio::select! { + result = reached => result.unwrap(), + result = &mut sending => panic!("tip send stopped before source validation: {result:?}"), + } + }) + .await + .expect("tip send reached source validation"); + assert!( + wallet.try_state_mut().is_none(), + "public writes must respect placement" + ); + let mut replacing = Box::pin(wallet.state_mut()); + assert!( + replacing.as_mut().now_or_never().is_none(), + "replacement must wait for the send" + ); + resume.send(()).unwrap(); + let error = sending.await.unwrap().unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::ShieldedBuildError(ref message) if message.starts_with("amount must be > 0")), + "{error:?}" + ); + let mut state = replacing.await; + let mut replacement = state.identity_manager.clone(); + let identity = replacement + .remove_identity(&id, wallet.persister()) + .unwrap(); + replacement + .add_identity(identity, 7, wallet.wallet_id(), wallet.persister()) + .unwrap(); + state.identity_manager = replacement; + assert_eq!(state.identity_manager.identity_index(&id), Some(7)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn should_order_blocking_public_state_mutation_against_identity_placement() { + let (wallet, _, id, _) = tip_race_fixture("tips_blocking_public_mutation").await; + let placement = wallet.identity.identity_placement.read().await; + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let mut writing = { + let wallet = wallet.clone(); + tokio::task::spawn_blocking(move || { + started_tx.send(()).unwrap(); + let mut state = wallet.state_mut_blocking(); + let identity = state + .identity_manager + .remove_identity(&id, wallet.persister()) + .unwrap(); + state + .identity_manager + .add_identity(identity, 7, wallet.wallet_id(), wallet.persister()) + .unwrap(); + }) + }; + started_rx.await.unwrap(); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(500), &mut writing) + .await + .is_err() + ); + drop(placement); + writing.await.unwrap(); + assert_eq!( + wallet.state().await.identity_manager.identity_index(&id), + Some(7) + ); +} From be427e4b854b04240ca6bc6a29e25a0a7faca2b0 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 21:17:34 +0000 Subject: [PATCH 22/41] fix(platform-wallet): protect identity shielded accounts and tip lifecycle --- .../dashsdk/ffi/FundingNative.kt | 4 +- .../dashsdk/wallet/PlatformWalletManager.kt | 6 +- .../src/shielded_send.rs | 26 +- .../rs-platform-wallet/docs/SHIELDED_TIPS.md | 54 +-- packages/rs-platform-wallet/src/lib.rs | 4 +- .../src/wallet/platform_wallet.rs | 4 +- .../src/wallet/shielded/mod.rs | 4 +- .../shielded/sync/memo_roundtrip_tests.rs | 4 +- .../src/wallet/shielded/tips.rs | 62 +-- .../wallet/shielded/viewing_key_bind_tests.rs | 380 +++++++++++++++--- packages/rs-unified-sdk-jni/src/funding.rs | 10 +- .../PlatformWalletManagerShieldedSync.swift | 16 +- .../SwiftDashSDK/PlatformWallet/README.md | 2 +- 13 files changed, 442 insertions(+), 134 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt index 5b3ae7ad0aa..78ea263cd93 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/FundingNative.kt @@ -16,8 +16,8 @@ package org.dashfoundation.dashsdk.ffi * non-shielded build throws [UnsatisfiedLinkError]. */ internal object FundingNative { - external fun tipAccountIndex(identityIndex: Int): Int - external fun prepareShieldedTipAddress( + external fun identityAccountIndex(identityIndex: Int): Int + external fun prepareShieldedIdentityAddress( manager: Long, walletId: ByteArray, resolver: Long, identityId: ByteArray, ): ByteArray external fun resolveShieldedTip(wallet: Long, username: String): ByteArray diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt index d5d4da7170e..4119242ce73 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/PlatformWalletManager.kt @@ -2028,10 +2028,10 @@ class PlatformWalletManager( // until a later shielded sync resolves them). /** Dedicated account index derived by Rust's wallet convention. */ - fun shieldedTipAccountIndex(identityIndex: Int): Int = mapNativeErrors { FundingNative.tipAccountIndex(identityIndex) } + fun shieldedIdentityAccountIndex(identityIndex: Int): Int = mapNativeErrors { FundingNative.identityAccountIndex(identityIndex) } - suspend fun prepareShieldedTipAddress(walletId: ByteArray, identityId: ByteArray): ByteArray = teardownGate.op { - mapNativeErrors { FundingNative.prepareShieldedTipAddress(managerHandle, walletId, mnemonicResolver.nativeHandle, identityId) } + suspend fun prepareShieldedIdentityAddress(walletId: ByteArray, identityId: ByteArray): ByteArray = teardownGate.op { + mapNativeErrors { FundingNative.prepareShieldedIdentityAddress(managerHandle, walletId, mnemonicResolver.nativeHandle, identityId) } } /** Send only if fresh resolution still matches the recipient shown in confirmation. */ diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 7a63f54ec6c..141a6db1783 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -2381,10 +2381,10 @@ pub(crate) fn resolve_shielded_coordinator( } } -/// Derive and register the identity's dedicated tip account, without publishing it. +/// Derive and register the identity's dedicated shielded account, without publishing it. /// All ID pointers must reference 32 bytes; `out_address` must reference 43 writable bytes. #[no_mangle] -pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_tip_address( +pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_identity_address( handle: Handle, wallet_id_bytes: *const u8, mnemonic_resolver_handle: *mut MnemonicResolverHandle, @@ -2409,7 +2409,7 @@ pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_tip_address( // output write happens outside it, only on success, so a panic leaves the // zeroed buffer untouched. let mut address = [0u8; 43]; - let result = catch_query_panic("shielded tip address preparation", || { + let result = catch_query_panic("shielded identity address preparation", || { let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { Ok(value) => value, Err(e) => return e, @@ -2424,7 +2424,7 @@ pub unsafe extern "C" fn platform_wallet_manager_prepare_shielded_tip_address( match block_on_worker(async move { maybe_inject_tip_worker_panic(); wallet - .prepare_shielded_tip_address(seed.as_ref(), &identity_id, &coordinator) + .prepare_shielded_identity_address(seed.as_ref(), &identity_id, &coordinator) .await }) { Ok(bytes) => { @@ -2620,15 +2620,15 @@ pub unsafe extern "C" fn platform_wallet_manager_send_shielded_tip( }) } -/// Return the dedicated ZIP-32 tip account for a wallet identity derivation index. +/// Return the dedicated ZIP-32 shielded account for a wallet identity derivation index. #[no_mangle] -pub unsafe extern "C" fn platform_wallet_shielded_tip_account_index( +pub unsafe extern "C" fn platform_wallet_shielded_identity_account_index( identity_index: u32, out_account: *mut u32, ) -> PlatformWalletFFIResult { check_ptr!(out_account); *out_account = 0; - match platform_wallet::wallet::shielded::tips::shielded_tip_account_index(identity_index) { + match platform_wallet::wallet::shielded::tips::shielded_identity_account_index(identity_index) { Ok(account) => { *out_account = account; PlatformWalletFFIResult::ok() @@ -2637,10 +2637,10 @@ pub unsafe extern "C" fn platform_wallet_shielded_tip_account_index( } } -/// Whether an account is reserved for explicitly selected DashPay tip activity. +/// Whether an account is reserved for a wallet identity's shielded activity. #[no_mangle] -pub extern "C" fn platform_wallet_is_shielded_tip_account(account: u32) -> bool { - platform_wallet::wallet::shielded::is_shielded_tip_account(account) +pub extern "C" fn platform_wallet_is_shielded_identity_account(account: u32) -> bool { + platform_wallet::wallet::shielded::is_shielded_identity_account(account) } #[cfg(test)] @@ -3307,7 +3307,7 @@ mod tests { ) }; let prepare = unsafe { - platform_wallet_manager_prepare_shielded_tip_address( + platform_wallet_manager_prepare_shielded_identity_address( handle, wallet_id.as_ptr(), &mut resolver, @@ -3331,7 +3331,7 @@ mod tests { ); let message = message_of(&prepare); assert!( - message.contains("shielded tip address preparation panicked"), + message.contains("shielded identity address preparation panicked"), "{message}" ); assert_eq!(out_address, [0u8; 43]); @@ -3400,7 +3400,7 @@ mod tests { // Non-spending exports: a retryable failure with the outputs left zeroed. let mut out_address = [0xAAu8; 43]; let mut prepare = unsafe { - platform_wallet_manager_prepare_shielded_tip_address( + platform_wallet_manager_prepare_shielded_identity_address( handle, wallet_id.as_ptr(), &mut resolver, diff --git a/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md index 4ffa17dbd95..1a99880ed9d 100644 --- a/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md +++ b/packages/rs-platform-wallet/docs/SHIELDED_TIPS.md @@ -25,13 +25,13 @@ address field. A bundled schema alone does not demonstrate network activation. ## Dedicated local accounts The wallet reserves ZIP-32 account indices `0x40000000..0x80000000` for DashPay -tips. A wallet-owned identity at derivation index `i` uses account -`0x40000000 + i`; identity indices outside the lower half are rejected by the tip -helper. Ordinary account allocation must stay below `0x40000000`. Use -`shielded_tip_account_index` and `is_shielded_tip_account` instead of duplicating -these constants in applications. +identities. A wallet-owned identity at derivation index `i` uses account +`0x40000000 + i`; identity indices outside the lower half are rejected by the +account helper. Ordinary account allocation must stay below `0x40000000`. Use +`shielded_identity_account_index` and `is_shielded_identity_account` instead of +duplicating these constants in applications. -Call `PlatformWallet::prepare_shielded_tip_address(seed, identity_id, coordinator)` +Call `PlatformWallet::prepare_shielded_identity_address(seed, identity_id, coordinator)` to obtain the default address of this account. The helper binds its viewing keys to the synchronization coordinator and flushes persistence before returning. It does not publish the address; publication remains an explicit profile operation. @@ -39,20 +39,22 @@ Repeated preparation derives the same account and address. An identity without a wallet derivation index can publish an external address instead. Publish through `PlatformWallet::write_dashpay_profile`. A shielded address that is -one of this wallet's bound tip addresses is published only if preparation, in this -session, proved with the seed that the identity holds the slot selecting it, and the -identity still holds that slot. Discovery can move an identity whose keys derive at -several indices, and a restored placeholder index proves nothing, so prepare the +one of this wallet's bound identity shielded addresses is published only if +preparation, in this session, proved with the seed that the identity holds the slot +selecting it, and the identity still holds that slot. Addresses from this wallet's +bound ordinary accounts are refused, including fresh diversified addresses; +addresses of another wallet remain allowed. Discovery can move an identity whose +keys derive at several indices, and a restored placeholder index proves nothing, so prepare the address again after a restart or a move; preparation is idempotent. Preparation, publication and tip sends hold a per-wallet placement lock that discovery, loading and changeset apply take before moving an identity. An address already published before a move keeps receiving into its old account until the profile is updated. -Tip accounts have distinct viewing keys. Hosts must exclude them from ordinary -receive, balance, and automatic spending choices, as the example apps do. -`shielded_balances()` returns all bound accounts separately, including tip -accounts; it does not apply this policy. Spending a tip balance is an explicit -host action. +Identity shielded accounts have distinct viewing keys. Hosts must exclude them from +ordinary receive, balance, and automatic spending choices, as the example apps do. +`shielded_balances()` returns all bound accounts separately, including identity +shielded accounts; it does not apply this policy. Spending a tip balance is an +explicit host action. The generic shielded spend APIs (transfer, unshield, withdraw, top-up) still accept an explicitly selected account and apply none of the tip-slot checks below; use `send_shielded_tip` with a `ShieldedTipSource` for tips. @@ -66,7 +68,7 @@ accounts first; preparation preserves them while adding the dedicated account. ## Restoration and address changes On seed restoration, discover the wallet's identities before binding and scanning -shielded accounts. Seed-backed `bind_shielded` adds each discovered identity's tip +shielded accounts. Seed-backed `bind_shielded` adds each discovered identity's shielded account even if the caller supplies only account zero. This does not depend on the current profile: removal or replacement of a published address does not remove received funds from recovery. After discovering more identities in an existing @@ -74,10 +76,11 @@ session, bind again. Newly bound accounts start with their own scan watermark at zero, so the next synchronization scans their history while retaining the shared commitment tree and previously synchronized accounts. -Seedless binding includes persisted tip viewing keys, including retired accounts. -If a newly discovered identity's key is missing, it returns `false` so the host can -perform seed-backed binding. Address rotation within a tip account uses a new -diversifier; the account viewing key detects both old and new addresses. Removing +Seedless binding includes persisted identity shielded viewing keys, including +retired accounts. If a newly discovered identity's key is missing, it returns +`false` so the host can perform seed-backed binding. Address rotation within an +identity shielded account uses a new diversifier; the account viewing key detects +both old and new addresses. Removing publication neither revokes old address copies nor stops their monitoring. An externally supplied address is not automatically owned by this wallet. Its @@ -89,12 +92,17 @@ Use `wallet.identity().dashpay().resolve_shielded_tip(username)` to obtain a fre `ShieldedTipRecipient`. Display the resolved identity and address for confirmation. `wallet.send_shielded_tip(...)` takes that confirmed recipient, re-resolves the name and profile, and refuses payment if either changed. Its `ShieldedTipSource` -names what pays: `Identity(id)` spends that identity's tip account, after the seed -proves the slot it holds; `Account(n)` spends an ordinary account, or the tip -account of a slot that holds no identity (a retired identity's funds). It never switches to a +names what pays: `Identity(id)` spends that identity's shielded account, after the +seed proves the slot it holds; `Account(n)` spends an ordinary account, or the +identity shielded account of a slot that holds no identity (a retired identity's +funds). It never switches to a transparent destination. This is a snapshot check: the submitted payment always uses the address that was confirmed, even if the profile changes afterward. +A tip send holds the wallet generation's payment gate through proving, persistence, +and broadcast. Removal waits for an admitted send to finish; a retained handle +from a removed or replaced generation cannot start another spend. + Tips to a public profile address are anonymous from the receiver's perspective unless the payer provides additional context. This feature does not implement per-contact addresses or authenticated sender attribution. diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index a36d6ad2db7..a31c264d13a 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -134,6 +134,6 @@ pub use wallet::identity::types::dashpay::profile::{ #[cfg(feature = "shielded")] pub use wallet::shielded::tips::{ - is_shielded_tip_account, shielded_tip_account_index, ShieldedTipSource, - SHIELDED_TIP_ACCOUNT_BASE, + is_shielded_identity_account, shielded_identity_account_index, ShieldedTipSource, + SHIELDED_IDENTITY_ACCOUNT_BASE, }; diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index e4a827e2da8..5f1473c06f5 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -964,7 +964,7 @@ impl PlatformWallet { .keys() .filter(|id| { id.wallet_id == self.wallet_id - && super::shielded::is_shielded_tip_account(id.account_index) + && super::shielded::is_shielded_identity_account(id.account_index) }) .map(|id| id.account_index), ); @@ -1091,7 +1091,7 @@ impl PlatformWallet { .keys() .filter(|id| { id.wallet_id == self.wallet_id - && super::shielded::is_shielded_tip_account(id.account_index) + && super::shielded::is_shielded_identity_account(id.account_index) }) .map(|id| id.account_index), ); diff --git a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs index 3c267336f2a..9f4f49c2de0 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/mod.rs @@ -54,8 +54,8 @@ pub mod store; pub mod sync; pub mod tips; pub use tips::{ - is_shielded_tip_account, shielded_tip_account_index, ShieldedTipSource, - SHIELDED_TIP_ACCOUNT_BASE, + is_shielded_identity_account, shielded_identity_account_index, ShieldedTipSource, + SHIELDED_IDENTITY_ACCOUNT_BASE, }; #[cfg(test)] mod viewing_key_bind_tests; diff --git a/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs index 010015e32e9..e1fdd622497 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/sync/memo_roundtrip_tests.rs @@ -284,9 +284,9 @@ fn shield_memo_round_trips_through_ovk_recovery() { #[test] fn should_restore_tip_notes_without_exposing_personal_notes_to_tip_viewing_key() { - use crate::wallet::shielded::shielded_tip_account_index; + use crate::wallet::shielded::shielded_identity_account_index; let seed = [0x67; 64]; - let tip_index = shielded_tip_account_index(0).unwrap(); + let tip_index = shielded_identity_account_index(0).unwrap(); let tips = OrchardKeySet::from_seed(&seed, Network::Testnet, tip_index).unwrap(); let restored = OrchardKeySet::from_seed(&seed, Network::Testnet, tip_index).unwrap(); let personal = OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 05c173bb7cd..df14f593874 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -1,7 +1,7 @@ -//! Dedicated DashPay tip accounts. Account selection is wallet policy, not +//! Dedicated DashPay identity shielded accounts. Account selection is wallet policy, not //! consensus: external Orchard addresses remain valid profile values. //! -//! Reserve the upper half of the ZIP-32 account space for tips. A wallet-owned +//! Reserve the upper half of the ZIP-32 account space for identities. A wallet-owned //! identity at index i uses account 0x40000000 + i. Ordinary accounts use the //! lower half. This mapping never depends on a username, the current profile, //! or local allocation history: identity discovery followed by shielded bind @@ -22,19 +22,19 @@ pub(crate) struct PreparedTipAccount { clear_generation: u64, } -pub const SHIELDED_TIP_ACCOUNT_BASE: u32 = 0x4000_0000; +pub const SHIELDED_IDENTITY_ACCOUNT_BASE: u32 = 0x4000_0000; -pub fn shielded_tip_account_index(identity_index: u32) -> Result { - if identity_index >= SHIELDED_TIP_ACCOUNT_BASE { +pub fn shielded_identity_account_index(identity_index: u32) -> Result { + if identity_index >= SHIELDED_IDENTITY_ACCOUNT_BASE { return Err(PlatformWalletError::ShieldedKeyDerivation( - "Identity index exceeds the dedicated tip account range".to_string(), + "Identity index exceeds the identity shielded account range".to_string(), )); } - Ok(SHIELDED_TIP_ACCOUNT_BASE + identity_index) + Ok(SHIELDED_IDENTITY_ACCOUNT_BASE + identity_index) } -pub fn is_shielded_tip_account(account: u32) -> bool { - (SHIELDED_TIP_ACCOUNT_BASE..0x8000_0000).contains(&account) +pub fn is_shielded_identity_account(account: u32) -> bool { + (SHIELDED_IDENTITY_ACCOUNT_BASE..0x8000_0000).contains(&account) } /// The account a tip is paid from. @@ -99,7 +99,7 @@ impl PlatformWallet { .managed_identities() .filter(|identity| identity.wallet_id == Some(self.wallet_id())) .filter_map(|identity| identity.identity_index) - .filter_map(|index| shielded_tip_account_index(index).ok()) + .filter_map(|index| shielded_identity_account_index(index).ok()) .collect()) } @@ -108,7 +108,7 @@ impl PlatformWallet { /// callers can publish the returned address. Repeated calls are idempotent. /// Requires an existing shielded bind so preparing a tip account cannot /// silently replace the host's ordinary account configuration. - pub async fn prepare_shielded_tip_address( + pub async fn prepare_shielded_identity_address( &self, seed: &[u8], identity_id: &Identifier, @@ -207,7 +207,7 @@ impl PlatformWallet { ) })?; verify_identity_index(seed, self.sdk.network, index, &identity.identity)?; - shielded_tip_account_index(index) + shielded_identity_account_index(index) } /// The account `source` spends. An identity spends the tip account of @@ -224,7 +224,7 @@ impl PlatformWallet { ShieldedTipSource::Identity(identity_id) => { self.verified_tip_account(seed, &identity_id).await } - ShieldedTipSource::Account(account) if is_shielded_tip_account(account) => { + ShieldedTipSource::Account(account) if is_shielded_identity_account(account) => { let wm = self.wallet_manager.read().await; let info = wm.get_wallet_info(&self.wallet_id()).ok_or_else(|| { PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id())) @@ -233,7 +233,7 @@ impl PlatformWallet { .identity_manager .wallet_identities .get(&self.wallet_id()) - .and_then(|bucket| bucket.get(&(account - SHIELDED_TIP_ACCOUNT_BASE))); + .and_then(|bucket| bucket.get(&(account - SHIELDED_IDENTITY_ACCOUNT_BASE))); match occupant { Some(owner) => Err(PlatformWalletError::InvalidIdentityData(format!( "Account {account} is the tip account of identity {}; \ @@ -247,13 +247,13 @@ impl PlatformWallet { } } - /// Refuse to publish one of this wallet's dedicated tip addresses unless + /// Refuse to publish one of this wallet's shielded addresses unless /// preparation, in this session, proved with the seed that `identity_id` /// holds the slot selecting that account, and the identity still holds /// it. Discovery can move an identity whose keys derive at several /// indices, and a restored placeholder index is not proof of a slot. - /// Addresses of ordinary accounts and of other wallets are the owner's - /// choice. Only bound accounts are recognised; preparation binds the + /// Ordinary accounts cannot be published; addresses of other wallets are + /// the owner's choice. Only bound accounts are recognised; preparation binds the /// account it hands out. Callers hold the placement lock through the /// profile write. pub(crate) async fn check_tip_address_publication( @@ -270,7 +270,6 @@ impl PlatformWallet { let keys = self.shielded_keys.read().await; keys.as_ref().and_then(|keys| { keys.iter() - .filter(|(account, _)| is_shielded_tip_account(**account)) .find(|(_, views)| views.full_viewing_key.scope_for_address(&address).is_some()) .map(|(account, _)| *account) }) @@ -278,6 +277,13 @@ impl PlatformWallet { let Some(owning_account) = owning_account else { return Ok(()); }; + if !is_shielded_identity_account(owning_account) { + return Err(PlatformWalletError::InvalidIdentityData( + "An address from this wallet's ordinary shielded accounts cannot be published \ + in an identity profile" + .to_string(), + )); + } let prepared = self .prepared_tip_accounts .lock() @@ -295,7 +301,7 @@ impl PlatformWallet { .and_then(|info| info.identity_manager.managed_identity(identity_id)) .filter(|identity| identity.wallet_id == Some(self.wallet_id())) .and_then(|identity| identity.identity_index) - .and_then(|index| shielded_tip_account_index(index).ok()); + .and_then(|index| shielded_identity_account_index(index).ok()); if prepared && current == Some(owning_account) { Ok(()) } else { @@ -341,6 +347,12 @@ impl PlatformWallet { "The tip recipient changed; review and confirm the payment again".to_string(), )); } + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id(), + ))); + } let _placement = self.identity.identity_placement.read().await; let account = self.tip_source_account(seed, source).await?; #[cfg(test)] @@ -448,18 +460,18 @@ mod tests { fn should_derive_distinct_recoverable_tip_accounts() { let seed = [42u8; 64]; let ordinary = OrchardKeySet::from_seed(&seed, Network::Testnet, 0).unwrap(); - let index = shielded_tip_account_index(0).unwrap(); + let index = shielded_identity_account_index(0).unwrap(); let tip = OrchardKeySet::from_seed(&seed, Network::Testnet, index).unwrap(); let restored = OrchardKeySet::from_seed( &seed, Network::Testnet, - shielded_tip_account_index(0).unwrap(), + shielded_identity_account_index(0).unwrap(), ) .unwrap(); let other = OrchardKeySet::from_seed( &seed, Network::Testnet, - shielded_tip_account_index(1).unwrap(), + shielded_identity_account_index(1).unwrap(), ) .unwrap(); assert_ne!( @@ -474,8 +486,8 @@ mod tests { tip.full_viewing_key.to_bytes(), restored.full_viewing_key.to_bytes() ); - assert!(!is_shielded_tip_account(0)); - assert!(is_shielded_tip_account(index)); - assert!(shielded_tip_account_index(SHIELDED_TIP_ACCOUNT_BASE).is_err()); + assert!(!is_shielded_identity_account(0)); + assert!(is_shielded_identity_account(index)); + assert!(shielded_identity_account_index(SHIELDED_IDENTITY_ACCOUNT_BASE).is_err()); } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index b27a769d718..a1dadb3bf09 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -15,6 +15,7 @@ use std::sync::{Arc, Mutex}; use dashcore::Network; use key_wallet::account::StandardAccountType; +use orchard::keys::Scope; use crate::changeset::PersistenceError; use crate::changeset::PlatformWalletPersistence; @@ -1241,7 +1242,7 @@ impl dpp::identity::signer::Signer for NoSigne /// and must accept it once rediscovery proves its real index. #[tokio::test] async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified() { - use crate::shielded_tip_account_index; + use crate::shielded_identity_account_index; use dpp::identity::{Identity, IdentityV0}; use dpp::prelude::Identifier; let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; @@ -1298,7 +1299,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .unwrap(); } let coordinator = coordinator_at(&temp_dir("tips_placeholder_index")); - let identity_zero_tips = shielded_tip_account_index(0).unwrap(); + let identity_zero_tips = shielded_identity_account_index(0).unwrap(); wallet .bind_shielded(&seed[..], &[0, identity_zero_tips], &coordinator) .await @@ -1309,7 +1310,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .unwrap(); let refused = wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await; assert!( matches!(refused, Err(crate::PlatformWalletError::InvalidIdentityData(ref msg)) if msg.contains("not verified")), @@ -1383,13 +1384,13 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .unwrap(); } let address = wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await .unwrap(); assert_ne!(address, identity_zero_address); assert_eq!( wallet - .shielded_default_address(shielded_tip_account_index(5).unwrap()) + .shielded_default_address(shielded_identity_account_index(5).unwrap()) .await .unwrap(), address @@ -1399,7 +1400,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( .tip_source_account(&seed[..], crate::ShieldedTipSource::Identity(id)) .await .unwrap(), - shielded_tip_account_index(5).unwrap() + shielded_identity_account_index(5).unwrap() ); // The identity now passes the source check (the mock SDK then fails the // recipient lookup). Slot 0 is empty, so its account is spendable by @@ -1418,7 +1419,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( ); } let own_by_number = spend(crate::ShieldedTipSource::Account( - shielded_tip_account_index(5).unwrap(), + shielded_identity_account_index(5).unwrap(), )) .await; assert!( @@ -1429,7 +1430,7 @@ async fn should_refuse_tip_account_for_a_placeholder_index_until_it_is_verified( #[tokio::test] async fn should_restore_tip_account_from_identity_discovery_and_register_for_sync() { - use crate::shielded_tip_account_index; + use crate::shielded_identity_account_index; use dpp::identity::{Identity, IdentityV0}; use dpp::prelude::Identifier; let phrase = crate::test_support::MESSAGE_SIGNING_TEST_MNEMONIC; @@ -1437,7 +1438,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .unwrap() .to_seed(""); let id = Identifier::from([0x33; 32]); - let account = shielded_tip_account_index(3).unwrap(); + let account = shielded_identity_account_index(3).unwrap(); let mut original = None; for session in 0..2 { let persister = Arc::new(CapturingPersistence::default()); @@ -1499,7 +1500,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn balance: 0, revision: 0, }), - crate::SHIELDED_TIP_ACCOUNT_BASE, + crate::SHIELDED_IDENTITY_ACCOUNT_BASE, wallet.wallet_id(), wallet.persister(), ) @@ -1527,12 +1528,12 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .unwrap()); assert!(!wallet.is_shielded_bound().await); assert!(wallet - .prepare_shielded_tip_address(&[0x11; 64], &id, &coordinator) + .prepare_shielded_identity_address(&[0x11; 64], &id, &coordinator) .await .is_err()); assert!(matches!( wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await, Err(crate::PlatformWalletError::ShieldedNotBound) )); @@ -1548,7 +1549,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .await .contains(&SubwalletId::new(wallet.wallet_id(), account))); assert!(wallet - .prepare_shielded_tip_address(&[0x11; 64], &id, &coordinator) + .prepare_shielded_identity_address(&[0x11; 64], &id, &coordinator) .await .is_err()); // A queued FVK is insufficient: no publishable address may escape a @@ -1559,7 +1560,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .store(true, std::sync::atomic::Ordering::SeqCst); assert!(matches!( wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await, Err(crate::PlatformWalletError::Persistence(_)) )); @@ -1573,11 +1574,15 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn .store(false, std::sync::atomic::Ordering::SeqCst); persister.durability_events.lock().unwrap().clear(); let address = wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await .unwrap(); assert!(wallet - .prepare_shielded_tip_address(&seed[..], &Identifier::from([0x44; 32]), &coordinator) + .prepare_shielded_identity_address( + &seed[..], + &Identifier::from([0x44; 32]), + &coordinator + ) .await .is_err()); assert_eq!( @@ -1587,7 +1592,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn assert_ne!(wallet.shielded_default_address(0).await.unwrap(), address); assert_eq!( wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await .unwrap(), address @@ -1606,7 +1611,7 @@ async fn should_restore_tip_account_from_identity_discovery_and_register_for_syn #[tokio::test] async fn should_rebind_retired_tip_accounts_without_profile_or_identity() { let seed = [0x42; 64]; - let account = crate::shielded_tip_account_index(7).unwrap(); + let account = crate::shielded_identity_account_index(7).unwrap(); let persister = Arc::new(CapturingPersistence::default()); let wallet = platform_wallet_with(Arc::clone(&persister)).await; let keys = super::OrchardKeySet::from_seed(&seed[..], Network::Testnet, account).unwrap(); @@ -1646,7 +1651,7 @@ async fn should_rebind_retired_tip_accounts_without_profile_or_identity() { async fn should_bind_more_than_64_persisted_tip_accounts_from_an_ordinary_request() { let seed = [0x42; 64]; let tips: Vec = (0..70) - .map(|index| crate::shielded_tip_account_index(index).unwrap()) + .map(|index| crate::shielded_identity_account_index(index).unwrap()) .collect(); for (tag, seeded) in [("many_tips_persisted", false), ("many_tips_seeded", true)] { let persister = Arc::new(CapturingPersistence::default()); @@ -1682,7 +1687,7 @@ async fn should_bind_more_than_64_persisted_tip_accounts_from_an_ordinary_reques let ordinary: Vec = bound .iter() .copied() - .filter(|&account| !super::is_shielded_tip_account(account)) + .filter(|&account| !super::is_shielded_identity_account(account)) .collect(); assert_eq!(ordinary, vec![0], "{tag}"); let registered = coordinator.registered_subwallets().await; @@ -1789,7 +1794,7 @@ async fn race_tip_preparation( let coordinator = Arc::clone(coordinator); tokio::spawn(async move { wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await }) }; @@ -1815,9 +1820,9 @@ async fn race_tip_preparation( /// still be bound and registered once both finish. #[tokio::test] async fn should_keep_an_ordinary_account_bound_during_tip_preparation() { - use crate::shielded_tip_account_index; + use crate::shielded_identity_account_index; let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_bind").await; - let tip = shielded_tip_account_index(2).unwrap(); + let tip = shielded_identity_account_index(2).unwrap(); let bind_coordinator = Arc::clone(&coordinator); race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { wallet @@ -1847,9 +1852,9 @@ async fn should_keep_an_ordinary_account_bound_during_tip_preparation() { /// the key map without the added account. #[tokio::test] async fn should_keep_an_added_account_during_tip_preparation() { - use crate::shielded_tip_account_index; + use crate::shielded_identity_account_index; let (wallet, seed, id, coordinator) = tip_race_fixture("tips_concurrent_add").await; - let tip = shielded_tip_account_index(2).unwrap(); + let tip = shielded_identity_account_index(2).unwrap(); race_tip_preparation(&wallet, seed, id, &coordinator, move |wallet| async move { wallet.shielded_add_account(&seed[..], 1).await }) @@ -1868,11 +1873,11 @@ async fn should_keep_an_added_account_during_tip_preparation() { /// their slots. Preparation holds the placement lock from its slot check to /// its return, so a move waits for it; the address it returned then names the /// old slot's account, and publishing that address for the moved identity is -/// refused until its address is prepared again. Ordinary accounts' addresses -/// and other wallets' addresses stay publishable. +/// refused until its address is prepared again. Other wallets' addresses stay +/// publishable. #[tokio::test] async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stale_address() { - use crate::shielded_tip_account_index; + use crate::shielded_identity_account_index; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; let (wallet, seed, id, coordinator) = tip_race_fixture("tips_placement_move").await; @@ -1895,7 +1900,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal let coordinator = Arc::clone(&coordinator); tokio::spawn(async move { wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await }) }; @@ -1923,7 +1928,7 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal assert_eq!( Some(stale), wallet - .shielded_default_address(shielded_tip_account_index(2).unwrap()) + .shielded_default_address(shielded_identity_account_index(2).unwrap()) .await ); moving.await.unwrap().expect("identity moved to slot 7"); @@ -1934,20 +1939,19 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal "{refused:?}" ); let fresh = wallet - .prepare_shielded_tip_address(&seed[..], &id, &coordinator) + .prepare_shielded_identity_address(&seed[..], &id, &coordinator) .await .unwrap(); assert_ne!(fresh, stale); - let ordinary = wallet.shielded_default_address(0).await.unwrap(); let external = super::OrchardKeySet::from_seed( &[9; 64], Network::Testnet, - shielded_tip_account_index(2).unwrap(), + shielded_identity_account_index(2).unwrap(), ) .unwrap() .default_address .to_raw_address_bytes(); - for address in [fresh, ordinary, external] { + for address in [fresh, external] { wallet .check_tip_address_publication(&id, &address) .await @@ -1955,11 +1959,68 @@ async fn should_order_an_identity_move_after_tip_preparation_and_refuse_its_stal } } +#[tokio::test] +async fn should_reject_ordinary_account_profile_addresses_at_every_diversifier() { + let (wallet, seed, id, coordinator) = tip_race_fixture("identity_profile_privacy").await; + let other_account = crate::shielded_identity_account_index(7).unwrap(); + wallet + .bind_shielded(&seed, &[0, 1, other_account], &coordinator) + .await + .unwrap(); + let prepared = wallet + .prepare_shielded_identity_address(&seed, &id, &coordinator) + .await + .unwrap(); + for account in [0, 1] { + let keys = OrchardKeySet::from_seed(&seed, Network::Testnet, account).unwrap(); + for address in [ + keys.default_address, + keys.address_at(17), + keys.full_viewing_key.address_at(3u32, Scope::Internal), + ] { + let error = wallet + .check_tip_address_publication(&id, &address.to_raw_address_bytes()) + .await + .unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::InvalidIdentityData(ref message) if message.contains("ordinary shielded accounts")), + "{error:?}" + ); + } + } + let other = wallet + .shielded_default_address(other_account) + .await + .unwrap(); + assert!(wallet + .check_tip_address_publication(&id, &other) + .await + .is_err()); + let own = OrchardKeySet::from_seed( + &seed, + Network::Testnet, + crate::shielded_identity_account_index(2).unwrap(), + ) + .unwrap(); + let external = OrchardKeySet::from_seed(&[9; 64], Network::Testnet, 0).unwrap(); + for address in [ + prepared, + own.address_at(17).to_raw_address_bytes(), + external.default_address.to_raw_address_bytes(), + external.address_at(17).to_raw_address_bytes(), + ] { + wallet + .check_tip_address_publication(&id, &address) + .await + .unwrap(); + } +} + #[tokio::test] async fn should_require_fresh_tip_preparation_after_clear_even_after_rebind() { let (wallet, seed, id, coordinator) = tip_race_fixture("tips_clear").await; let address = wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_identity_address(&seed, &id, &coordinator) .await .unwrap(); wallet @@ -1983,7 +2044,7 @@ async fn should_require_fresh_tip_preparation_after_clear_even_after_rebind() { assert_eq!( wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_identity_address(&seed, &id, &coordinator) .await .unwrap(), address @@ -2003,13 +2064,13 @@ async fn should_refuse_tip_preparation_cleared_after_its_bind() { let coordinator = Arc::clone(&coordinator); tokio::spawn(async move { wallet - .prepare_shielded_tip_address(&seed, &id, &coordinator) + .prepare_shielded_identity_address(&seed, &id, &coordinator) .await }) }; reached.await.unwrap(); let address = wallet - .shielded_default_address(crate::shielded_tip_account_index(2).unwrap()) + .shielded_default_address(crate::shielded_identity_account_index(2).unwrap()) .await .unwrap(); coordinator.clear().await.unwrap(); @@ -2049,8 +2110,7 @@ async fn should_refuse_shielded_identity_creation_at_an_occupied_slot_before_der ); } -#[tokio::test] -async fn should_order_public_identity_manager_replacement_after_tip_spending() { +async fn mock_tip_recipient(wallet: &PlatformWallet) -> crate::ShieldedTipRecipient { use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; use dash_sdk::{platform::DocumentQuery, query_types::Documents}; use dpp::document::{Document, DocumentV0, DocumentV0Getters}; @@ -2058,9 +2118,7 @@ async fn should_order_public_identity_manager_replacement_after_tip_spending() { use dpp::prelude::Identifier; use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; use dpp::version::PlatformVersion; - use futures::FutureExt; - let (wallet, seed, id, coordinator) = tip_race_fixture("tips_public_mutation").await; let recipient = Identifier::from([0x77; 32]); let address = OrchardKeySet::from_seed(&[9; 64], Network::Testnet, 0) .unwrap() @@ -2137,6 +2195,17 @@ async fn should_order_public_identity_manager_replacement_after_tip_spending() { .await .unwrap(); + crate::ShieldedTipRecipient { + identity_id: recipient, + address, + } +} + +#[tokio::test] +async fn should_order_public_identity_manager_replacement_after_tip_spending() { + use futures::FutureExt; + let (wallet, seed, id, coordinator) = tip_race_fixture("tips_public_mutation").await; + let recipient = mock_tip_recipient(&wallet).await; let (reached, resume) = super::tips::test_hooks::pause_before_spend(&wallet); let mut sending = { let wallet = wallet.clone(); @@ -2148,10 +2217,7 @@ async fn should_order_public_identity_manager_replacement_after_tip_spending() { &seed, crate::ShieldedTipSource::Identity(id), "Alice.dash", - &crate::ShieldedTipRecipient { - identity_id: recipient, - address, - }, + &recipient, 0, [0; 36], &super::CachedOrchardProver::new(), @@ -2227,3 +2293,225 @@ async fn should_order_blocking_public_state_mutation_against_identity_placement( Some(7) ); } + +mod tip_lifecycle_tests { + use super::*; + use crate::events::{EventHandler, PlatformEventHandler}; + use crate::wallet::shielded::CachedOrchardProver; + use crate::{PlatformWalletManager, ShieldedTipSource}; + use dash_sdk::query_types::{NoParamQuery, ShieldedAnchors}; + use dpp::shielded::builder::OrchardProver; + use futures::FutureExt; + use grovedb_commitment_tree::{ + ExtractedNoteCommitment, Note, NoteValue, ProvingKey, RandomSeed, Rho, + }; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + use std::panic::AssertUnwindSafe; + use std::time::Duration; + use tokio::sync::oneshot; + + const SEED: [u8; 64] = [0x42; 64]; + + struct NoopEvents; + impl EventHandler for NoopEvents {} + impl PlatformEventHandler for NoopEvents {} + + async fn fixture() -> ( + tempfile::TempDir, + Arc>, + Arc, + Arc, + ) { + let dir = tempfile::tempdir().unwrap(); + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_version(dpp::version::PlatformVersion::latest()) + .with_dump_dir(dir.path()) + .build() + .unwrap(); + let manager = Arc::new(PlatformWalletManager::new( + Arc::new(sdk), + Arc::new(CapturingPersistence::default()), + Arc::new(NoopEvents), + )); + let wallet = add_wallet(&manager).await; + manager + .configure_shielded(dir.path().join("tree.sqlite")) + .await + .unwrap(); + let coordinator = manager.shielded_coordinator().await.unwrap(); + wallet + .bind_shielded(&SEED, &[0], &coordinator) + .await + .unwrap(); + (dir, manager, wallet, coordinator) + } + + async fn add_wallet( + manager: &PlatformWalletManager, + ) -> Arc { + manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &SEED, + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap() + } + + struct PausedProver { + reached: Mutex>>, + resume: Mutex>, + } + + impl OrchardProver for PausedProver { + fn proving_key(&self) -> &ProvingKey { + self.reached + .lock() + .unwrap() + .take() + .unwrap() + .send(()) + .unwrap(); + self.resume + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + panic!("stop the proof after checking the teardown fence") + } + } + + async fn fund(wallet: &PlatformWallet, coordinator: &NetworkShieldedCoordinator) { + let keys = OrchardKeySet::from_seed(&SEED, Network::Testnet, 0).unwrap(); + let rho = Rho::from_bytes(&[1; 32]).into_option().unwrap(); + let rseed = RandomSeed::from_bytes([2; 32], &rho).into_option().unwrap(); + let note = Note::from_parts( + keys.default_address, + NoteValue::from_raw(1_000_000_000_000), + rho, + rseed, + ) + .into_option() + .unwrap(); + let mut note_data = Vec::new(); + note_data.extend_from_slice(¬e.recipient().to_raw_address_bytes()); + note_data.extend_from_slice(¬e.value().inner().to_le_bytes()); + note_data.extend_from_slice(¬e.rho().to_bytes()); + note_data.extend_from_slice(note.rseed().as_bytes()); + let note = ShieldedNote { + position: 0, + cmx: ExtractedNoteCommitment::from(note.commitment()).to_bytes(), + nullifier: note.nullifier(&keys.full_viewing_key).to_bytes(), + block_height: 1, + is_spent: false, + value: note.value().inner(), + note_data, + }; + let mut store = coordinator.store().write().await; + store.append_commitment(¬e.cmx, true).unwrap(); + store.checkpoint_tree(1).unwrap(); + store + .save_note(SubwalletId::new(wallet.wallet_id(), 0), ¬e) + .unwrap(); + let anchor = store.tree_anchor().unwrap(); + drop(store); + let mut sdk = wallet.sdk().clone(); + sdk.mock() + .expect_fetch(NoParamQuery {}, Some(ShieldedAnchors(vec![anchor]))) + .await + .unwrap(); + sdk.mock().set_response_height_of::(10); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_hold_removal_until_tip_proving_returns() { + let (_dir, manager, wallet, coordinator) = fixture().await; + let recipient = mock_tip_recipient(&wallet).await; + fund(&wallet, &coordinator).await; + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let prover = PausedProver { + reached: Mutex::new(Some(reached_tx)), + resume: Mutex::new(resume_rx), + }; + let sending = { + let wallet = Arc::clone(&wallet); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + AssertUnwindSafe(wallet.send_shielded_tip( + &coordinator, + &SEED, + ShieldedTipSource::Account(0), + "Alice.dash", + &recipient, + 100_000_000_000, + [0; 36], + prover, + )) + .catch_unwind() + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached_rx) + .await + .unwrap() + .unwrap(); + let wallet_id = wallet.wallet_id(); + let mut removing = { + let manager = Arc::clone(&manager); + tokio::spawn(async move { manager.remove_wallet(&wallet_id).await.map(|_| ()) }) + }; + let early = tokio::time::timeout(Duration::from_millis(500), &mut removing).await; + resume_tx.send(()).unwrap(); + assert!( + sending.await.unwrap().is_err(), + "the prover stops at the test boundary" + ); + assert!(early.is_err(), "removal must wait for proving"); + removing.await.unwrap().unwrap(); + assert!(!wallet.core().is_current_generation().await); + let store = coordinator.store().read().await; + let id = SubwalletId::new(wallet_id, 0); + assert!(store.get_all_notes(id).unwrap().is_empty()); + assert!(store.get_activity_ids(id).unwrap().is_empty()); + assert!(store.pending_redrives(id).unwrap().is_empty()); + } + + #[tokio::test] + async fn should_refuse_tip_sends_from_a_removed_generation_after_same_id_recreation() { + let (_dir, manager, old, coordinator) = fixture().await; + let recipient = mock_tip_recipient(&old).await; + let wallet_id = old.wallet_id(); + manager.remove_wallet(&wallet_id).await.unwrap(); + let current = add_wallet(&manager).await; + assert_eq!(current.wallet_id(), wallet_id); + assert!(current.core().is_current_generation().await); + let result = old + .send_shielded_tip( + &coordinator, + &SEED, + ShieldedTipSource::Account(0), + "Alice.dash", + &recipient, + 1, + [0; 36], + &CachedOrchardProver::new(), + ) + .await; + assert!( + matches!( + result, + Err(crate::PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "{result:?}" + ); + let store = coordinator.store().read().await; + let id = SubwalletId::new(wallet_id, 0); + assert!(store.get_all_notes(id).unwrap().is_empty()); + assert!(store.get_activity_ids(id).unwrap().is_empty()); + assert!(store.pending_redrives(id).unwrap().is_empty()); + } +} diff --git a/packages/rs-unified-sdk-jni/src/funding.rs b/packages/rs-unified-sdk-jni/src/funding.rs index 387e0e8af76..e32ce7a43bb 100644 --- a/packages/rs-unified-sdk-jni/src/funding.rs +++ b/packages/rs-unified-sdk-jni/src/funding.rs @@ -1260,9 +1260,9 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_shielde }) } -/// Dedicated tip account preparation; returns the complete raw Orchard address. +/// Dedicated identity shielded account preparation; returns the complete raw Orchard address. #[no_mangle] -pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_prepareShieldedTipAddress( +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_prepareShieldedIdentityAddress( mut env: JNIEnv, _class: JClass, manager: jlong, @@ -1279,7 +1279,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_prepare }; let mut address = [0; 43]; let result = unsafe { - platform_wallet_ffi::platform_wallet_manager_prepare_shielded_tip_address( + platform_wallet_ffi::platform_wallet_manager_prepare_shielded_identity_address( manager as Handle, wid.as_ptr(), resolver as *mut MnemonicResolverHandle, @@ -1407,7 +1407,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_sendShi } #[no_mangle] -pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_tipAccountIndex( +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_identityAccountIndex( mut env: JNIEnv, _class: JClass, identity_index: jint, @@ -1419,7 +1419,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_FundingNative_tipAcco } let mut account = 0; let result = unsafe { - platform_wallet_ffi::platform_wallet_shielded_tip_account_index( + platform_wallet_ffi::platform_wallet_shielded_identity_account_index( identity_index as u32, &mut account, ) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 4e8f878ff94..ed884920dd9 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -1740,13 +1740,13 @@ extension ManagedPlatformWallet { } extension PlatformWalletManager { - /// Prepare the dedicated tip account. Publication is a separate profile update. - public func prepareShieldedTipAddress(walletId: Data, identityId: Data, resolver: MnemonicResolver) async throws -> Data { + /// Prepare the identity's dedicated shielded account. Publication is a separate profile update. + public func prepareShieldedIdentityAddress(walletId: Data, identityId: Data, resolver: MnemonicResolver) async throws -> Data { guard walletId.count == 32, identityId.count == 32, let resolverHandle = resolver.handle else { throw PlatformWalletError.invalidParameter("Expected wallet/identity IDs and mnemonic resolver") } // Admitted, so `shutdown()` waits for this call before destroying the handle. - try admitNativeOp("prepareShieldedTipAddress") + try admitNativeOp("prepareShieldedIdentityAddress") defer { finishNativeOp() } let handle = self.handle return try await Task.detached(priority: .userInitiated) { @@ -1754,7 +1754,7 @@ extension PlatformWalletManager { var address = [UInt8](repeating: 0, count: 43) try walletId.withUnsafeBytes { wallet in try identityId.withUnsafeBytes { identity in - try platform_wallet_manager_prepare_shielded_tip_address( + try platform_wallet_manager_prepare_shielded_identity_address( handle, wallet.baseAddress!.assumingMemoryBound(to: UInt8.self), resolverHandle, identity.baseAddress!.assumingMemoryBound(to: UInt8.self), &address ).check() @@ -1797,15 +1797,15 @@ extension PlatformWalletManager { } extension PlatformWalletManager { - public static func shieldedTipAccountIndex(identityIndex: UInt32) throws -> UInt32 { + public static func shieldedIdentityAccountIndex(identityIndex: UInt32) throws -> UInt32 { var account: UInt32 = 0 - try platform_wallet_shielded_tip_account_index(identityIndex, &account).check() + try platform_wallet_shielded_identity_account_index(identityIndex, &account).check() return account } } extension PlatformWalletManager { - public static func isShieldedTipAccount(_ account: UInt32) -> Bool { - platform_wallet_is_shielded_tip_account(account) + public static func isShieldedIdentityAccount(_ account: UInt32) -> Bool { + platform_wallet_is_shielded_identity_account(account) } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md index 2186860d536..3b017da8f5f 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/README.md @@ -704,7 +704,7 @@ DashPay profiles can publish `shieldedAddress`, a complete 43-byte raw Orchard address. `DashPayProfileUpdate` uses `.keep`, `.set(Data)`, and `.remove` for payment address changes; unrelated profile edits preserve the published address. Wallet-generated tip addresses use a dedicated shielded account for each local -identity. Call `prepareShieldedTipAddress` and then explicitly publish the returned +identity. Call `prepareShieldedIdentityAddress` and then explicitly publish the returned address through a signed profile update. External receiving addresses may also be published; their funds are managed and recovered by the external wallet. From 8073e427673a104d8a83ff9a01bd6c718973446d Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 22:07:50 +0000 Subject: [PATCH 23/41] fix(wallet): fence shielded tip preparation teardown --- .../src/wallet/shielded/coordinator.rs | 11 ++ .../src/wallet/shielded/tips.rs | 11 +- .../wallet/shielded/viewing_key_bind_tests.rs | 131 ++++++++++++++---- 3 files changed, 121 insertions(+), 32 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs index e224586420b..a98272f92e0 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs @@ -251,6 +251,11 @@ pub struct NetworkShieldedCoordinator { /// other way round. lifecycle: tokio::sync::Mutex<()>, + /// Preparation calls bind (which takes `lifecycle`) and then flushes the + /// host's viewing keys. Clear must wait for both without re-entering that + /// mutex. Lock order: `preparation` → `lifecycle` → `store`. + preparation: RwLock<()>, + /// Wallets whose per-subwallet store state has been successfully /// hydrated from the host's persisted snapshot this session /// (`restore_for_wallet` completed without error after the @@ -420,6 +425,7 @@ impl NetworkShieldedCoordinator { progress_handler: std::sync::Mutex::new(None), tree_progress_handler: std::sync::Mutex::new(None), lifecycle: tokio::sync::Mutex::new(()), + preparation: RwLock::new(()), hydrated: RwLock::new(std::collections::BTreeSet::new()), clear_generation: std::sync::atomic::AtomicU64::new(0), } @@ -679,6 +685,10 @@ impl NetworkShieldedCoordinator { } } + pub(crate) async fn preparation_guard(&self) -> tokio::sync::RwLockReadGuard<'_, ()> { + self.preparation.read().await + } + /// [`register_wallet`](Self::register_wallet)'s body, with the /// lifecycle mutex already held by the caller's transaction. async fn register_locked( @@ -1222,6 +1232,7 @@ impl NetworkShieldedCoordinator { /// stays populated, and the next cold resync would gate-skip every /// re-downloaded position against the stale `tree_size`. pub async fn clear(&self) -> Result<(), crate::error::PlatformWalletError> { + let _preparation = self.preparation.write().await; // Held across the whole Clear, store reset included, so no bind // install can be halfway through its transaction here: one that // already registered would otherwise restore its pre-Clear diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index df14f593874..cb1f690dc71 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -131,6 +131,12 @@ impl PlatformWallet { "The supplied seed does not belong to this wallet".to_string(), )); } + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletNotFound(hex::encode( + self.wallet_id(), + ))); + } // Held until the address is returned, so the identity cannot move to // another slot between the check below and the bind of the account // that slot selects. Publication rechecks it (see @@ -142,6 +148,7 @@ impl PlatformWallet { // replaces the registration, so another bind landing in between // would have its ordinary accounts dropped by this stale snapshot. let _config = self.shielded_config_lock.lock().await; + let _preparation = coordinator.preparation_guard().await; let clear_generation = coordinator.clear_generation(); let mut accounts = self.shielded_account_indices().await; if accounts.is_empty() { @@ -152,6 +159,8 @@ impl PlatformWallet { accounts.push(account); self.bind_shielded_locked(seed, &accounts, coordinator) .await?; + #[cfg(test)] + test_hooks::after_bind(self).await; self.persister() .flush() .map_err(|e| PlatformWalletError::Persistence(e.to_string()))?; @@ -159,8 +168,6 @@ impl PlatformWallet { .shielded_default_address(account) .await .ok_or(PlatformWalletError::ShieldedNotBound)?; - #[cfg(test)] - test_hooks::after_bind(self).await; if coordinator.clear_generation() != clear_generation { return Err(PlatformWalletError::ShieldedNotBound); } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index a1dadb3bf09..4bacb1493e7 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -2055,36 +2055,6 @@ async fn should_require_fresh_tip_preparation_after_clear_even_after_rebind() { .unwrap(); } -#[tokio::test] -async fn should_refuse_tip_preparation_cleared_after_its_bind() { - let (wallet, seed, id, coordinator) = tip_race_fixture("tips_clear_during_prepare").await; - let (reached, resume) = super::tips::test_hooks::pause_after_bind(&wallet); - let preparing = { - let wallet = wallet.clone(); - let coordinator = Arc::clone(&coordinator); - tokio::spawn(async move { - wallet - .prepare_shielded_identity_address(&seed, &id, &coordinator) - .await - }) - }; - reached.await.unwrap(); - let address = wallet - .shielded_default_address(crate::shielded_identity_account_index(2).unwrap()) - .await - .unwrap(); - coordinator.clear().await.unwrap(); - resume.send(()).unwrap(); - assert!(matches!( - preparing.await.unwrap(), - Err(crate::PlatformWalletError::ShieldedNotBound) - )); - assert!(wallet - .check_tip_address_publication(&id, &address) - .await - .is_err()); -} - #[tokio::test] async fn should_refuse_shielded_identity_creation_at_an_occupied_slot_before_deriving_or_spending() { @@ -2361,6 +2331,107 @@ mod tip_lifecycle_tests { .unwrap() } + async fn assert_preparation_precedes_host_deletion(clear: bool) { + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + + let (_dir, manager, wallet, coordinator) = fixture().await; + let identity_id = Identifier::from([0x66; 32]); + wallet + .wallet_manager + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: identity_id, + public_keys: seed_master_key(&SEED, 2), + balance: 0, + revision: 0, + }), + 2, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + let (reached, resume) = super::super::tips::test_hooks::pause_after_bind(&wallet); + let preparing = { + let wallet = Arc::clone(&wallet); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + wallet + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached) + .await + .unwrap() + .unwrap(); + assert_eq!( + manager.persister.durability_events.lock().unwrap().last(), + Some(&"store") + ); + let mut deleting = { + let manager = Arc::clone(&manager); + let wallet_id = wallet.wallet_id(); + tokio::spawn(async move { + if clear { + manager.clear_shielded().await.unwrap(); + } else { + manager.remove_wallet(&wallet_id).await.unwrap(); + } + manager.persister.stored.lock().unwrap().clear(); + manager + .persister + .durability_events + .lock() + .unwrap() + .push("host deletion"); + }) + }; + let early = tokio::time::timeout(Duration::from_millis(500), &mut deleting).await; + resume.send(()).unwrap(); + let address = preparing.await.unwrap().unwrap(); + assert!(early.is_err(), "teardown must wait for the post-bind flush"); + deleting.await.unwrap(); + let events = manager.persister.durability_events.lock().unwrap().clone(); + assert_eq!(&events[events.len() - 2..], &["flush", "host deletion"]); + assert!(manager.persister.captured_viewing_keys().is_empty()); + if clear { + assert!(wallet + .check_tip_address_publication(&identity_id, &address) + .await + .is_err()); + } else { + let current = add_wallet(&manager).await; + assert_eq!(current.wallet_id(), wallet.wallet_id()); + let after_create = manager.persister.durability_events.lock().unwrap().len(); + assert!(matches!( + wallet + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert_eq!( + manager.persister.durability_events.lock().unwrap().len(), + after_create + ); + } + } + + #[tokio::test] + async fn should_finish_tip_preparation_persistence_before_clear_and_host_deletion() { + assert_preparation_precedes_host_deletion(true).await; + } + + #[tokio::test] + async fn should_finish_tip_preparation_persistence_before_removal_and_host_deletion() { + assert_preparation_precedes_host_deletion(false).await; + } + struct PausedProver { reached: Mutex>>, resume: Mutex>, From 95f279e4877c7d0b669bf126e969a988bb90c0fc Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 22:51:37 +0000 Subject: [PATCH 24/41] fix(wallet): exclude clear during shielded tip spending --- .../src/wallet/shielded/coordinator.rs | 18 +++++---- .../src/wallet/shielded/tips.rs | 3 +- .../wallet/shielded/viewing_key_bind_tests.rs | 39 ++++++++++++++++--- 3 files changed, 45 insertions(+), 15 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs index a98272f92e0..69386a16905 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs @@ -251,10 +251,10 @@ pub struct NetworkShieldedCoordinator { /// other way round. lifecycle: tokio::sync::Mutex<()>, - /// Preparation calls bind (which takes `lifecycle`) and then flushes the - /// host's viewing keys. Clear must wait for both without re-entering that - /// mutex. Lock order: `preparation` → `lifecycle` → `store`. - preparation: RwLock<()>, + /// Clear waits for operations that bind/flush viewing keys or spend from + /// extracted notes. Separate from `lifecycle`, which bind takes internally. + /// Lock order: `operation_admission` → `lifecycle` → `store`. + operation_admission: RwLock<()>, /// Wallets whose per-subwallet store state has been successfully /// hydrated from the host's persisted snapshot this session @@ -425,7 +425,7 @@ impl NetworkShieldedCoordinator { progress_handler: std::sync::Mutex::new(None), tree_progress_handler: std::sync::Mutex::new(None), lifecycle: tokio::sync::Mutex::new(()), - preparation: RwLock::new(()), + operation_admission: RwLock::new(()), hydrated: RwLock::new(std::collections::BTreeSet::new()), clear_generation: std::sync::atomic::AtomicU64::new(0), } @@ -685,8 +685,10 @@ impl NetworkShieldedCoordinator { } } - pub(crate) async fn preparation_guard(&self) -> tokio::sync::RwLockReadGuard<'_, ()> { - self.preparation.read().await + /// Acquire before wallet placement/configuration locks; retain through persistence + /// and the operation result so Clear cannot delete state while it is still in use. + pub(crate) async fn operation_guard(&self) -> tokio::sync::RwLockReadGuard<'_, ()> { + self.operation_admission.read().await } /// [`register_wallet`](Self::register_wallet)'s body, with the @@ -1232,7 +1234,7 @@ impl NetworkShieldedCoordinator { /// stays populated, and the next cold resync would gate-skip every /// re-downloaded position against the stale `tree_size`. pub async fn clear(&self) -> Result<(), crate::error::PlatformWalletError> { - let _preparation = self.preparation.write().await; + let _operations = self.operation_admission.write().await; // Held across the whole Clear, store reset included, so no bind // install can be halfway through its transaction here: one that // already registered would otherwise restore its pre-Clear diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index cb1f690dc71..09ce546bcef 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -137,6 +137,7 @@ impl PlatformWallet { self.wallet_id(), ))); } + let _operation = coordinator.operation_guard().await; // Held until the address is returned, so the identity cannot move to // another slot between the check below and the bind of the account // that slot selects. Publication rechecks it (see @@ -148,7 +149,6 @@ impl PlatformWallet { // replaces the registration, so another bind landing in between // would have its ordinary accounts dropped by this stale snapshot. let _config = self.shielded_config_lock.lock().await; - let _preparation = coordinator.preparation_guard().await; let clear_generation = coordinator.clear_generation(); let mut accounts = self.shielded_account_indices().await; if accounts.is_empty() { @@ -360,6 +360,7 @@ impl PlatformWallet { self.wallet_id(), ))); } + let _operation = coordinator.operation_guard().await; let _placement = self.identity.identity_placement.read().await; let account = self.tip_source_account(seed, source).await?; #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 4bacb1493e7..204911907a9 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -2497,8 +2497,7 @@ mod tip_lifecycle_tests { sdk.mock().set_response_height_of::(10); } - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn should_hold_removal_until_tip_proving_returns() { + async fn assert_teardown_waits_for_tip_proving(clear: bool) { let (_dir, manager, wallet, coordinator) = fixture().await; let recipient = mock_tip_recipient(&wallet).await; fund(&wallet, &coordinator).await; @@ -2533,7 +2532,20 @@ mod tip_lifecycle_tests { let wallet_id = wallet.wallet_id(); let mut removing = { let manager = Arc::clone(&manager); - tokio::spawn(async move { manager.remove_wallet(&wallet_id).await.map(|_| ()) }) + tokio::spawn(async move { + if clear { + manager.clear_shielded().await.unwrap(); + } else { + manager.remove_wallet(&wallet_id).await.unwrap(); + } + manager.persister.stored.lock().unwrap().clear(); + manager + .persister + .durability_events + .lock() + .unwrap() + .push("host deletion"); + }) }; let early = tokio::time::timeout(Duration::from_millis(500), &mut removing).await; resume_tx.send(()).unwrap(); @@ -2541,9 +2553,14 @@ mod tip_lifecycle_tests { sending.await.unwrap().is_err(), "the prover stops at the test boundary" ); - assert!(early.is_err(), "removal must wait for proving"); - removing.await.unwrap().unwrap(); - assert!(!wallet.core().is_current_generation().await); + assert!(early.is_err(), "teardown must wait for proving"); + removing.await.unwrap(); + assert_eq!(wallet.core().is_current_generation().await, clear); + assert_eq!( + manager.persister.durability_events.lock().unwrap().last(), + Some(&"host deletion") + ); + assert_eq!(manager.persister.stored_count(), 0); let store = coordinator.store().read().await; let id = SubwalletId::new(wallet_id, 0); assert!(store.get_all_notes(id).unwrap().is_empty()); @@ -2551,6 +2568,16 @@ mod tip_lifecycle_tests { assert!(store.pending_redrives(id).unwrap().is_empty()); } + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_hold_removal_until_tip_proving_returns() { + assert_teardown_waits_for_tip_proving(false).await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_hold_clear_until_tip_proving_returns() { + assert_teardown_waits_for_tip_proving(true).await; + } + #[tokio::test] async fn should_refuse_tip_sends_from_a_removed_generation_after_same_id_recreation() { let (_dir, manager, old, coordinator) = fixture().await; From d7ff7ba61e4611b14baced087d11f1d080bd4166 Mon Sep 17 00:00:00 2001 From: pasta Date: Thu, 12 Nov 2026 23:36:56 +0000 Subject: [PATCH 25/41] fix(wallet): reject undiscoverable shielded tip addresses --- .../src/wallet/shielded/tips.rs | 22 ++++++++++++++----- .../wallet/shielded/viewing_key_bind_tests.rs | 15 +++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 09ce546bcef..6d9574ce932 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -14,6 +14,7 @@ use crate::{PlatformWalletError, ShieldedTipRecipient}; use dpp::identity::accessors::IdentityGettersV0; use dpp::prelude::Identifier; use grovedb_commitment_tree::PaymentAddress; +use orchard::keys::Scope; use std::sync::{Arc, PoisonError, Weak}; pub(crate) struct PreparedTipAccount { @@ -259,7 +260,8 @@ impl PlatformWallet { /// holds the slot selecting that account, and the identity still holds /// it. Discovery can move an identity whose keys derive at several /// indices, and a restored placeholder index is not proof of a slot. - /// Ordinary accounts cannot be published; addresses of other wallets are + /// Ordinary accounts and internal-scope identity addresses cannot be published; + /// this wallet scans external receiving addresses. Addresses of other wallets are /// the owner's choice. Only bound accounts are recognised; preparation binds the /// account it hands out. Callers hold the placement lock through the /// profile write. @@ -276,12 +278,15 @@ impl PlatformWallet { let owning_account = { let keys = self.shielded_keys.read().await; keys.as_ref().and_then(|keys| { - keys.iter() - .find(|(_, views)| views.full_viewing_key.scope_for_address(&address).is_some()) - .map(|(account, _)| *account) + keys.iter().find_map(|(account, views)| { + views + .full_viewing_key + .scope_for_address(&address) + .map(|scope| (*account, scope)) + }) }) }; - let Some(owning_account) = owning_account else { + let Some((owning_account, scope)) = owning_account else { return Ok(()); }; if !is_shielded_identity_account(owning_account) { @@ -291,6 +296,13 @@ impl PlatformWallet { .to_string(), )); } + if matches!(scope, Scope::Internal) { + return Err(PlatformWalletError::InvalidIdentityData( + "Only external receiving addresses from this wallet can be published \ + in an identity profile" + .to_string(), + )); + } let prepared = self .prepared_tip_accounts .lock() diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 204911907a9..a8566a05928 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -2002,12 +2002,27 @@ async fn should_reject_ordinary_account_profile_addresses_at_every_diversifier() crate::shielded_identity_account_index(2).unwrap(), ) .unwrap(); + for index in [0u32, 17] { + let address = own.full_viewing_key.address_at(index, Scope::Internal); + let error = wallet + .check_tip_address_publication(&id, &address.to_raw_address_bytes()) + .await + .unwrap_err(); + assert!( + matches!(error, crate::PlatformWalletError::InvalidIdentityData(ref message) if message.contains("external receiving addresses")), + "{error:?}" + ); + } let external = OrchardKeySet::from_seed(&[9; 64], Network::Testnet, 0).unwrap(); for address in [ prepared, own.address_at(17).to_raw_address_bytes(), external.default_address.to_raw_address_bytes(), external.address_at(17).to_raw_address_bytes(), + external + .full_viewing_key + .address_at(17u32, Scope::Internal) + .to_raw_address_bytes(), ] { wallet .check_tip_address_publication(&id, &address) From 162a2420a44a232563a8575d7080e9be81362522 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 00:45:32 +0000 Subject: [PATCH 26/41] fix(wallet): reject stale generation state mutations --- .../src/contact_request.rs | 4 +- .../rs-platform-wallet-ffi/src/dashpay.rs | 2 +- .../submission_result_tests.rs | 1 + .../rs-platform-wallet-ffi/src/persistence.rs | 2 +- .../src/private_contact_request.rs | 4 +- .../src/txo_reconcile.rs | 6 +- .../src/wallet/identity/network/discovery.rs | 24 +-- .../src/wallet/identity/network/loading.rs | 24 +-- .../src/wallet/platform_wallet.rs | 117 +++++++++--- .../wallet/shielded/viewing_key_bind_tests.rs | 167 +++++++++++++++++- 10 files changed, 277 insertions(+), 74 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/contact_request.rs b/packages/rs-platform-wallet-ffi/src/contact_request.rs index 71c67688c3f..593f711f95b 100644 --- a/packages/rs-platform-wallet-ffi/src/contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/contact_request.rs @@ -460,7 +460,7 @@ mod tests { revision: 0, }); crate::runtime::runtime().block_on(async { - let mut state = wallet.state_mut().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) @@ -503,7 +503,7 @@ mod tests { PLATFORM_WALLET_STORAGE .with_item(handle, |wallet| { crate::runtime::runtime().block_on(async { - let mut state = wallet.state_mut().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); change( state .identity_manager diff --git a/packages/rs-platform-wallet-ffi/src/dashpay.rs b/packages/rs-platform-wallet-ffi/src/dashpay.rs index 0eb3b1d808c..12a568ff746 100644 --- a/packages/rs-platform-wallet-ffi/src/dashpay.rs +++ b/packages/rs-platform-wallet-ffi/src/dashpay.rs @@ -2031,7 +2031,7 @@ mod tests { revision: 0, }); runtime().block_on(async { - let mut state = wallet.state_mut().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs index bc2ebc0bee1..67944f59aa7 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs @@ -211,6 +211,7 @@ impl Fixture { wallet .state_mut() .await + .expect("live wallet state") .identity_manager .add_identity(identity.clone(), 0, wallet.wallet_id(), wallet.persister()) .unwrap(); diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index f8fea1db9f0..44758355302 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -9306,7 +9306,7 @@ mod tests { let held = |id: Identifier, index: u32| { runtime().block_on(async { - let mut state = wallet.state_mut().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); let identities = &mut state.identity_manager; identities .add_identity( diff --git a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs index 4df1f3cda35..3f3ce470fcd 100644 --- a/packages/rs-platform-wallet-ffi/src/private_contact_request.rs +++ b/packages/rs-platform-wallet-ffi/src/private_contact_request.rs @@ -1697,7 +1697,7 @@ mod tests { PLATFORM_WALLET_STORAGE .with_item(wallet_handle, |wallet| { runtime().block_on(async { - let mut state = wallet.state_mut().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); let manager = &mut state.identity_manager; manager .add_identity(bob.clone(), 0, wallet.wallet_id(), wallet.persister()) @@ -1825,7 +1825,7 @@ mod tests { revision: 0, }); runtime().block_on(async { - let mut state = wallet.state_mut().await; + let mut state = wallet.state_mut().await.expect("live wallet state"); state .identity_manager .add_identity(identity, 0, wallet.wallet_id(), wallet.persister()) diff --git a/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs b/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs index fc6b6ca29e1..bdea1baceee 100644 --- a/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs +++ b/packages/rs-platform-wallet-ffi/src/txo_reconcile.rs @@ -1191,7 +1191,11 @@ mod tests { // An engine writer queued behind the guard. With the guard held, a // fresh engine read is refused exactly while a writer waits. let writer_wallet = Arc::clone(&wallet); - let writer = std::thread::spawn(move || drop(writer_wallet.state_mut_blocking())); + let writer = std::thread::spawn(move || { + writer_wallet + .state_mut_blocking() + .expect("live wallet state"); + }); wait_for("the engine writer never queued behind the guard", || { engine.try_read().is_err() }); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs index c0173a3f8f9..854d5106a04 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/discovery.rs @@ -444,14 +444,7 @@ impl IdentityWallet { // Placement lock first; see `identity_placement`. let placement_guard = self.identity_placement.write().await; let mut wm_guard = self.wallet_manager.write().await; - let info_guard = - wm_guard - .get_wallet_info_mut(&self.wallet_id) - .ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info_guard = self.current_wallet_info_mut(&mut wm_guard)?; // The key hash at `identity_index` proved the index: add // the identity there, or move an identity known from // elsewhere into that slot (stored below, with its @@ -619,14 +612,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm_guard = self.wallet_manager.write().await; - let info_guard = - wm_guard - .get_wallet_info_mut(&self.wallet_id) - .ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info_guard = self.current_wallet_info_mut(&mut wm_guard)?; if let Some(managed) = info_guard .identity_manager .managed_identity_mut(&identity_id) @@ -672,11 +658,11 @@ impl IdentityWallet { // own verdict instead would drop the gaps the fold carried forward. let recorded = { let mut wm = self.wallet_manager.write().await; - match wm.get_wallet_info_mut(&wallet_id) { - Some(info) => info + match self.current_wallet_info_mut(&mut wm) { + Ok(info) => info .identity_manager .record_identity_scan(wallet_id, verdict), - None => { + Err(_) => { tracing::warn!( wallet_id = %hex::encode(wallet_id), "identity scan finished for a wallet that is no longer managed; \ diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs index 2ba94b92660..2a40cdd069d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/loading.rs @@ -246,11 +246,7 @@ impl IdentityWallet { { let _placement = self.identity_placement.write().await; let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; // The probe at `identity_index` proved the index: add the identity // there, or move an identity known from elsewhere into that slot; // either is stored below, with its verified keys, as one changeset. @@ -300,11 +296,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { managed.apply_fetched_dpns_names(names, fetch, &self.persister); } @@ -416,11 +408,7 @@ impl IdentityWallet { match self.fetch_owned_dpns_names(identity_id, None).await { Ok((names, fetch)) => { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; if let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) { managed.apply_fetched_dpns_names(names, fetch, &self.persister); @@ -481,11 +469,7 @@ impl IdentityWallet { // don't know the wallet index and cannot sign). { let mut wm = self.wallet_manager.write().await; - let info = wm.get_wallet_info_mut(&self.wallet_id).ok_or_else(|| { - crate::error::PlatformWalletError::WalletNotFound( - "Wallet info not found in wallet manager".to_string(), - ) - })?; + let info = self.current_wallet_info_mut(&mut wm)?; info.identity_manager .add_out_of_wallet_identity(identity.clone(), &self.persister)?; } diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 5f1473c06f5..4cb1bc1dfd1 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -568,13 +568,16 @@ impl PlatformWallet { /// wallet's `PlatformWalletInfo` (with `DerefMut`). /// Holds the identity-placement write lock first, so replacing the manager /// or removing/re-adding an identity cannot race a tip operation. - pub async fn state_mut(&self) -> WalletStateWriteGuard<'_> { + /// Returns `WalletNotFound` if this handle's generation is no longer current. + pub async fn state_mut(&self) -> Result, PlatformWalletError> { let placement = self.identity.identity_placement.write().await; - WalletStateWriteGuard { - guard: self.wallet_manager.write().await, + let mut guard = self.wallet_manager.write().await; + self.identity.current_wallet_info_mut(&mut guard)?; + Ok(WalletStateWriteGuard { + guard, wallet_id: self.wallet_id, _placement: placement, - } + }) } /// Blocking read-lock. @@ -592,13 +595,16 @@ impl PlatformWallet { /// called from within a tokio async context. Exists so sync /// callers (e.g. SPV-driven transaction processing) can reach /// mutation methods that require the wallet-manager write lock. - pub fn state_mut_blocking(&self) -> WalletStateWriteGuard<'_> { + /// Returns `WalletNotFound` if this handle's generation is no longer current. + pub fn state_mut_blocking(&self) -> Result, PlatformWalletError> { let placement = self.identity.identity_placement.blocking_write(); - WalletStateWriteGuard { - guard: self.wallet_manager.blocking_write(), + let mut guard = self.wallet_manager.blocking_write(); + self.identity.current_wallet_info_mut(&mut guard)?; + Ok(WalletStateWriteGuard { + guard, wallet_id: self.wallet_id, _placement: placement, - } + }) } // ----------------------------------------------------------------- @@ -755,18 +761,18 @@ impl PlatformWallet { } /// Non-blocking write-lock. Returns `None` if the lock is currently - /// held by any reader or writer, or identity placement is in use. Same safety properties as + /// held by any reader or writer, identity placement is in use, or this handle's + /// generation is no longer current. Same safety properties as /// [`try_state`]: never panics, never blocks. pub fn try_state_mut(&self) -> Option> { let placement = self.identity.identity_placement.try_write().ok()?; - self.wallet_manager - .try_write() - .ok() - .map(|guard| WalletStateWriteGuard { - guard, - wallet_id: self.wallet_id, - _placement: placement, - }) + let mut guard = self.wallet_manager.try_write().ok()?; + self.identity.current_wallet_info_mut(&mut guard).ok()?; + Some(WalletStateWriteGuard { + guard, + wallet_id: self.wallet_id, + _placement: placement, + }) } /// Construct a PlatformWallet from a WalletManager that already contains @@ -2897,8 +2903,8 @@ impl PlatformWallet { /// `Wallet::add_account`. /// /// Returns [`ApplyError::WalletNotFound`](crate::wallet::ApplyError::WalletNotFound) - /// if the wallet has been removed from the manager between handle - /// acquisition and this call. + /// if this handle's wallet has been removed or replaced in the manager + /// between handle acquisition and this call. /// /// Consumes the changeset by value — `apply_changeset` drains /// every map straight into the wallet maps with no clones. @@ -2927,9 +2933,10 @@ impl PlatformWallet { None }; let mut wm = self.wallet_manager.write().await; - let (wallet, info) = wm - .get_wallet_mut_and_info_mut(&self.wallet_id) - .ok_or(crate::wallet::ApplyError::WalletNotFound(self.wallet_id))?; + let (wallet, info) = self + .identity + .current_wallet_and_info_mut(&mut wm) + .map_err(|_| crate::wallet::ApplyError::WalletNotFound(self.wallet_id))?; info.apply_changeset(wallet, changeset)?; } @@ -3683,6 +3690,72 @@ fn check_recipient_hrp( Ok(()) } +#[cfg(test)] +mod state_generation_tests { + use super::*; + use crate::events::{EventHandler, PlatformEventHandler}; + use crate::wallet::persister::NoPlatformPersistence; + use crate::PlatformWalletManager; + use dashcore::Network; + use key_wallet::wallet::initialization::WalletAccountCreationOptions; + + struct NoopEvents; + impl EventHandler for NoopEvents {} + impl PlatformEventHandler for NoopEvents {} + + #[tokio::test] + async fn should_reject_mutations_from_a_removed_wallet_generation() { + let manager = PlatformWalletManager::new( + Arc::new(dash_sdk::Sdk::new_mock()), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + ); + let old = manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + let id = old.wallet_id(); + manager.remove_wallet(&id).await.unwrap(); + assert!(matches!( + old.state_mut().await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + let current = manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + assert_eq!(current.wallet_id(), id); + assert!(matches!( + old.state_mut().await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + assert!(old.try_state_mut().is_none()); + let blocking_old = Arc::clone(&old); + assert!(tokio::task::spawn_blocking(move || matches!( + blocking_old.state_mut_blocking(), + Err(PlatformWalletError::WalletNotFound(_)) + )) + .await + .unwrap()); + assert!( + matches!(old.apply(PlatformWalletChangeSet::default()).await, + Err(crate::wallet::ApplyError::WalletNotFound(wallet_id)) if wallet_id == id) + ); + assert!(current.state_mut().await.is_ok()); + assert!(current.try_state_mut().is_some()); + } +} + #[cfg(all(test, feature = "shielded"))] mod private_contact_request_redrive_tests { use super::*; diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index a8566a05928..749aa3670c5 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -2233,7 +2233,7 @@ async fn should_order_public_identity_manager_replacement_after_tip_spending() { matches!(error, crate::PlatformWalletError::ShieldedBuildError(ref message) if message.starts_with("amount must be > 0")), "{error:?}" ); - let mut state = replacing.await; + let mut state = replacing.await.unwrap(); let mut replacement = state.identity_manager.clone(); let identity = replacement .remove_identity(&id, wallet.persister()) @@ -2254,7 +2254,7 @@ async fn should_order_blocking_public_state_mutation_against_identity_placement( let wallet = wallet.clone(); tokio::task::spawn_blocking(move || { started_tx.send(()).unwrap(); - let mut state = wallet.state_mut_blocking(); + let mut state = wallet.state_mut_blocking().unwrap(); let identity = state .identity_manager .remove_identity(&id, wallet.persister()) @@ -2470,8 +2470,8 @@ mod tip_lifecycle_tests { } } - async fn fund(wallet: &PlatformWallet, coordinator: &NetworkShieldedCoordinator) { - let keys = OrchardKeySet::from_seed(&SEED, Network::Testnet, 0).unwrap(); + async fn fund(wallet: &PlatformWallet, coordinator: &NetworkShieldedCoordinator, account: u32) { + let keys = OrchardKeySet::from_seed(&SEED, Network::Testnet, account).unwrap(); let rho = Rho::from_bytes(&[1; 32]).into_option().unwrap(); let rseed = RandomSeed::from_bytes([2; 32], &rho).into_option().unwrap(); let note = Note::from_parts( @@ -2500,7 +2500,7 @@ mod tip_lifecycle_tests { store.append_commitment(¬e.cmx, true).unwrap(); store.checkpoint_tree(1).unwrap(); store - .save_note(SubwalletId::new(wallet.wallet_id(), 0), ¬e) + .save_note(SubwalletId::new(wallet.wallet_id(), account), ¬e) .unwrap(); let anchor = store.tree_anchor().unwrap(); drop(store); @@ -2515,7 +2515,7 @@ mod tip_lifecycle_tests { async fn assert_teardown_waits_for_tip_proving(clear: bool) { let (_dir, manager, wallet, coordinator) = fixture().await; let recipient = mock_tip_recipient(&wallet).await; - fund(&wallet, &coordinator).await; + fund(&wallet, &coordinator, 0).await; let (reached_tx, reached_rx) = oneshot::channel(); let (resume_tx, resume_rx) = std::sync::mpsc::channel(); let prover = PausedProver { @@ -2593,6 +2593,161 @@ mod tip_lifecycle_tests { assert_teardown_waits_for_tip_proving(true).await; } + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_refuse_stale_mutations_while_replacement_tip_source_is_locked() { + use crate::changeset::IdentityChangeSet; + use crate::wallet::identity::network::{ + derive_identity_auth_key_hash_from_master, IdentityDiscoveryOptions, MASTER_KEY_INDEX, + }; + use dash_sdk::platform::types::identity::PublicKeyHash; + use dpp::identity::{Identity, IdentityV0}; + use dpp::prelude::Identifier; + + let (_dir, manager, old, coordinator) = fixture().await; + manager.remove_wallet(&old.wallet_id()).await.unwrap(); + let current = add_wallet(&manager).await; + let identity_id = Identifier::from([0x66; 32]); + let identity = Identity::V0(IdentityV0 { + id: identity_id, + public_keys: seed_master_key(&SEED, 2), + balance: 0, + revision: 0, + }); + current + .state_mut() + .await + .unwrap() + .identity_manager + .add_identity( + identity.clone(), + 2, + current.wallet_id(), + current.persister(), + ) + .unwrap(); + current + .bind_shielded(&SEED, &[0], &coordinator) + .await + .unwrap(); + current + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await + .unwrap(); + fund( + ¤t, + &coordinator, + crate::shielded_identity_account_index(2).unwrap(), + ) + .await; + let recipient = mock_tip_recipient(¤t).await; + let master = + key_wallet::bip32::ExtendedPrivKey::new_master(Network::Testnet, &SEED).unwrap(); + let probe = derive_identity_auth_key_hash_from_master( + &master, + Network::Testnet, + 2, + MASTER_KEY_INDEX, + ) + .unwrap(); + let mut sdk = old.sdk().clone(); + sdk.mock() + .expect_fetch(PublicKeyHash(probe), Some(identity)) + .await + .unwrap(); + + let (reached, resume) = super::super::tips::test_hooks::pause_before_spend(¤t); + let (proof_reached_tx, proof_reached) = oneshot::channel(); + let (proof_resume_tx, proof_resume_rx) = std::sync::mpsc::channel(); + proof_resume_tx.send(()).unwrap(); + let prover = PausedProver { + reached: Mutex::new(Some(proof_reached_tx)), + resume: Mutex::new(proof_resume_rx), + }; + let sending = { + let current = Arc::clone(¤t); + let coordinator = Arc::clone(&coordinator); + tokio::spawn(async move { + AssertUnwindSafe(current.send_shielded_tip( + &coordinator, + &SEED, + ShieldedTipSource::Identity(identity_id), + "Alice.dash", + &recipient, + 100_000_000_000, + [0; 36], + prover, + )) + .catch_unwind() + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached) + .await + .unwrap() + .unwrap(); + assert!( + current.try_state_mut().is_none(), + "the live placement gate is held" + ); + let before = manager.persister.stored_count(); + assert!(matches!( + old.state_mut().await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert!(old.try_state_mut().is_none()); + let blocking_old = Arc::clone(&old); + assert!(tokio::task::spawn_blocking(move || matches!( + blocking_old.state_mut_blocking(), + Err(crate::PlatformWalletError::WalletNotFound(_)) + )) + .await + .unwrap()); + let changeset = PlatformWalletChangeSet { + identities: Some(IdentityChangeSet { + removed: [identity_id].into(), + ..Default::default() + }), + ..Default::default() + }; + assert!(matches!( + old.apply(changeset).await, + Err(crate::wallet::ApplyError::WalletNotFound(_)) + )); + assert!(matches!( + old.identity() + .load_identity_by_index_from_master(2, &master) + .await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert!(matches!( + old.identity() + .discover_from_master( + IdentityDiscoveryOptions { + start_index: Some(2), + gap_limit: 1 + }, + &master, + ) + .await, + Err(crate::PlatformWalletError::WalletNotFound(_)) + )); + assert_eq!(manager.persister.stored_count(), before); + assert_eq!( + current + .state() + .await + .identity_manager + .identity_index(&identity_id), + Some(2) + ); + resume.send(()).unwrap(); + proof_reached.await.unwrap(); + assert!( + sending.await.unwrap().is_err(), + "the funded transfer reached the test prover" + ); + } + #[tokio::test] async fn should_refuse_tip_sends_from_a_removed_generation_after_same_id_recreation() { let (_dir, manager, old, coordinator) = fixture().await; From ccc4d085e3c3094a094b8abce4ff9ff3b47a94c5 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 01:31:01 +0000 Subject: [PATCH 27/41] fix(wallet): fence profile writes against wallet removal --- .../src/wallet/platform_wallet.rs | 28 +++- .../wallet/shielded/viewing_key_bind_tests.rs | 152 ++++++++++++++++++ 2 files changed, 179 insertions(+), 1 deletion(-) diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 4cb1bc1dfd1..9c2956ba55d 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -3024,7 +3024,8 @@ impl PlatformWallet { /// shielded address that is one of this wallet's dedicated tip addresses /// must have been prepared for this identity at the slot it holds, and /// the placement lock is held through a write that sets one, so the slot - /// cannot change before it lands. + /// cannot change before it lands. Wallet removal waits for the complete + /// write; removed or replaced wallet handles cannot publish. pub async fn write_dashpay_profile( &self, identity_id: &Identifier, @@ -3035,6 +3036,12 @@ impl PlatformWallet { where S: Signer + Send + Sync, { + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletNotFound(hex::encode( + self.wallet_id(), + ))); + } let sets_shielded = matches!(input.shielded_address, PaymentAddressUpdate::Set(_)); let _placement = if sets_shielded { Some(self.identity.identity_placement.read().await) @@ -3705,6 +3712,23 @@ mod state_generation_tests { #[tokio::test] async fn should_reject_mutations_from_a_removed_wallet_generation() { + async fn assert_profile_write_refused(wallet: &PlatformWallet) { + let signer = simple_signer::signer::SimpleSigner::default(); + for create in [true, false] { + assert!(matches!( + wallet + .write_dashpay_profile( + &Identifier::default(), + ProfileUpdate::default(), + &signer, + create, + ) + .await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + } + } + let manager = PlatformWalletManager::new( Arc::new(dash_sdk::Sdk::new_mock()), Arc::new(NoPlatformPersistence), @@ -3721,6 +3745,7 @@ mod state_generation_tests { .unwrap(); let id = old.wallet_id(); manager.remove_wallet(&id).await.unwrap(); + assert_profile_write_refused(&old).await; assert!(matches!( old.state_mut().await, Err(PlatformWalletError::WalletNotFound(_)) @@ -3735,6 +3760,7 @@ mod state_generation_tests { .await .unwrap(); assert_eq!(current.wallet_id(), id); + assert_profile_write_refused(&old).await; assert!(matches!( old.state_mut().await, Err(PlatformWalletError::WalletNotFound(_)) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index 749aa3670c5..f83802708d6 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -2447,6 +2447,158 @@ mod tip_lifecycle_tests { assert_preparation_precedes_host_deletion(false).await; } + #[derive(Debug)] + struct PausedProfileSigner { + reached: Mutex>>, + resume: Mutex>, + } + + #[async_trait::async_trait] + impl dpp::identity::signer::Signer for PausedProfileSigner { + async fn sign( + &self, + _: &dpp::identity::IdentityPublicKey, + _: &[u8], + ) -> Result { + panic!("the unavailable signer must prevent publication") + } + + async fn sign_create_witness( + &self, + _: &dpp::identity::IdentityPublicKey, + _: &[u8], + ) -> Result { + panic!("profile publication must not create a witness") + } + + fn can_sign_with(&self, _: &dpp::identity::IdentityPublicKey) -> bool { + self.reached + .lock() + .unwrap() + .take() + .unwrap() + .send(()) + .unwrap(); + self.resume + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + false + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn should_fence_profile_publication_against_wallet_replacement() { + use crate::wallet::identity::network::dashpay_contract; + use crate::{PaymentAddressUpdate, PlatformWalletError, ProfileUpdate}; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::{Identity, IdentityV0, SecurityLevel}; + use dpp::prelude::Identifier; + use dpp::system_data_contracts::SystemDataContract; + + for create in [true, false] { + let (_dir, manager, wallet, coordinator) = fixture().await; + let identity_id = Identifier::from([0x66; 32]); + let mut public_keys = seed_master_key(&SEED, 2); + let mut signing_key = public_keys[&0].clone(); + signing_key.set_id(1); + signing_key.set_security_level(SecurityLevel::CRITICAL); + public_keys.insert(1, signing_key); + wallet + .state_mut() + .await + .unwrap() + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: identity_id, + public_keys, + balance: 0, + revision: 0, + }), + 2, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + let address = wallet + .prepare_shielded_identity_address(&SEED, &identity_id, &coordinator) + .await + .unwrap(); + let input = ProfileUpdate { + shielded_address: PaymentAddressUpdate::Set(address.to_vec()), + ..Default::default() + }; + let mut sdk = wallet.sdk().clone(); + sdk.mock() + .expect_fetch( + SystemDataContract::Dashpay.id(), + Some(dashpay_contract().unwrap().as_ref().clone()), + ) + .await + .unwrap(); + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let signer = PausedProfileSigner { + reached: Mutex::new(Some(reached_tx)), + resume: Mutex::new(resume_rx), + }; + let before = manager.persister.stored_count(); + let publishing = { + let wallet = Arc::clone(&wallet); + let input = input.clone(); + tokio::spawn(async move { + wallet + .write_dashpay_profile(&identity_id, input, &signer, create) + .await + }) + }; + tokio::time::timeout(Duration::from_secs(10), reached_rx) + .await + .unwrap() + .unwrap(); + let mut replacing = { + let manager = Arc::clone(&manager); + let wallet_id = wallet.wallet_id(); + tokio::spawn(async move { + manager.remove_wallet(&wallet_id).await.unwrap(); + add_wallet(&manager).await + }) + }; + let early = tokio::time::timeout(Duration::from_millis(500), &mut replacing).await; + resume_tx.send(()).unwrap(); + let error = publishing.await.unwrap().unwrap_err(); + assert!( + error.to_string().contains("unavailable to signer"), + "{error}" + ); + assert!(early.is_err(), "removal must wait for profile publication"); + let current = replacing.await.unwrap(); + assert_eq!(wallet.wallet_id(), current.wallet_id()); + assert!(current.core().is_current_generation().await); + assert!(manager.persister.stored.lock().unwrap()[before..] + .iter() + .all(|changes| changes.dashpay_profiles.is_none())); + let after_replacement = manager.persister.stored_count(); + for stale_input in [input, ProfileUpdate::default()] { + assert!(matches!( + wallet + .write_dashpay_profile(&identity_id, stale_input, &NoSigner, create) + .await, + Err(PlatformWalletError::WalletNotFound(_)) + )); + } + assert_eq!(manager.persister.stored_count(), after_replacement); + assert!(current + .state() + .await + .identity_manager + .managed_identity(&identity_id) + .is_none()); + } + } + struct PausedProver { reached: Mutex>>, resume: Mutex>, From 919a3e0f489aa9290e3710b9482d03a9099abbc2 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 02:17:53 +0000 Subject: [PATCH 28/41] fix(wallet): discard stale profile synchronization results --- .../src/wallet/identity/network/profile.rs | 293 +++++++++++++++++- 1 file changed, 290 insertions(+), 3 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 1011fd5d856..2046bccf199 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -59,7 +59,8 @@ impl DashPayView<'_, B> { /// fetched profile differs from the cached one — a `None` result clears the /// cache only when a profile is currently stored (both arms guarded so a /// no-change sweep writes nothing). Returns the number of identities whose - /// cached profile changed. + /// cached profile changed. Results for a removed or replaced wallet + /// generation are discarded without changing state or persistence. pub async fn sync_profiles(&self) -> Result { // 1. Collect all managed identity IDs under a short read lock. let identity_ids: Vec = { @@ -103,7 +104,7 @@ impl DashPayView<'_, B> { // None-arm's is_some guard for both directions). let mut changed = 0u32; let mut wm = self.wallet_manager.write().await; - let Some(info) = wm.get_wallet_info_mut(&self.wallet_id) else { + let Ok(info) = self.current_wallet_info_mut(&mut wm) else { return Ok(0); }; for (identity_id, profile) in fetched { @@ -435,6 +436,8 @@ impl DashPayView<'_, B> { /// are themselves managed identities are skipped (their own /// `dashpay_profile` is authoritative). Display-only: a failure never /// aborts the sweep. Returns the number of cache entries changed. + /// Results for a removed or replaced wallet generation are discarded + /// without changing state or persistence. /// /// Fetching pending senders' profiles is an accepted privacy cost: an /// observer could link the `$ownerId In [...]` query to our inbound set, @@ -528,7 +531,7 @@ impl DashPayView<'_, B> { let mut written = 0u32; { let mut wm = self.wallet_manager.write().await; - let Some(info) = wm.get_wallet_info_mut(&self.wallet_id) else { + let Ok(info) = self.current_wallet_info_mut(&mut wm) else { return Ok(0); }; for (owner_id, owner_results) in results { @@ -584,6 +587,9 @@ impl DashPayView<'_, B> { .await .map_err(PlatformWalletError::Sdk)?; + #[cfg(test)] + sync_generation_tests::after_fetch(&self.generation).await; + Ok(docs .into_iter() .map(|(owner, doc)| (owner, cacheable_profile(doc.properties()))) @@ -1355,3 +1361,284 @@ mod tip_resolution_tests { } } } + +#[cfg(test)] +mod sync_generation_tests { + use super::*; + use crate::changeset::{ + ClientStartState, IdentityChangeSet, IdentityEntry, PersistenceError, + PlatformWalletChangeSet, PlatformWalletPersistence, + }; + use crate::test_support::NoopTestEventHandler; + use crate::wallet::core::WalletGeneration; + use crate::wallet::identity::ContactRequest; + use crate::wallet::platform_wallet::WalletId; + use crate::{PlatformWallet, PlatformWalletManager}; + use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; + use dash_sdk::{platform::DocumentQuery, query_types::Documents, SdkBuilder}; + use dpp::document::DocumentV0; + use dpp::identity::IdentityV0; + use dpp::version::PlatformVersion; + use key_wallet::{wallet::initialization::WalletAccountCreationOptions, Network}; + use std::collections::BTreeMap; + use std::sync::Mutex; + use std::time::Duration; + use tokio::sync::oneshot; + + type FetchPause = (oneshot::Sender<()>, oneshot::Receiver<()>); + static FETCH_PAUSES: Mutex> = Mutex::new(BTreeMap::new()); + + pub(super) async fn after_fetch(generation: &Arc) { + let pause = FETCH_PAUSES + .lock() + .unwrap() + .remove(&(Arc::as_ptr(generation) as usize)); + if let Some((reached, resume)) = pause { + reached.send(()).unwrap(); + resume.await.unwrap(); + } + } + + #[derive(Default)] + struct CapturingPersistence(Mutex>); + + impl PlatformWalletPersistence for CapturingPersistence { + fn store( + &self, + _: WalletId, + changeset: PlatformWalletChangeSet, + ) -> Result<(), PersistenceError> { + self.0.lock().unwrap().push(changeset); + Ok(()) + } + + fn flush(&self, _: WalletId) -> Result<(), PersistenceError> { + Ok(()) + } + + fn load(&self) -> Result { + Ok(ClientStartState::default()) + } + } + + async fn add_wallet( + manager: &PlatformWalletManager, + ) -> Arc { + manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap() + } + + async fn sync(wallet: &PlatformWallet, contacts: bool) -> u32 { + if contacts { + wallet + .identity() + .dashpay() + .sync_contact_profiles() + .await + .unwrap() + } else { + wallet.identity().dashpay().sync_profiles().await.unwrap() + } + } + + async fn assert_delayed_sync_preserves_replacement(contacts: bool) { + for present in [true, false] { + let owner = Identifier::from([0x61; 32]); + let contact = Identifier::from([0x62; 32]); + let target = if contacts { contact } else { owner }; + let key = orchard::keys::SpendingKey::from_bytes([42; 32]).unwrap(); + let fvk = orchard::keys::FullViewingKey::from(&key); + let fetched_address = fvk + .address_at(19u32, orchard::keys::Scope::External) + .to_raw_address_bytes() + .to_vec(); + let restored_profile = DashPayProfile { + display_name: Some("Restored profile".into()), + shielded_address: Some( + fvk.address_at(20u32, orchard::keys::Scope::External) + .to_raw_address_bytes() + .to_vec(), + ), + ..Default::default() + }; + let contract = dashpay_contract().unwrap(); + let query = DocumentQuery::new(contract, "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![target.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + let document = Document::V0(DocumentV0 { + id: Identifier::from([0x63; 32]), + owner_id: target, + revision: Some(1), + properties: [( + "shieldedAddress".into(), + Value::Bytes(fetched_address.clone()), + )] + .into(), + ..Default::default() + }); + let docs: Documents = if present { + [(document.id(), Some(document))].into() + } else { + Default::default() + }; + let mut sdk = SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch_many::(query, Some(docs)) + .await + .unwrap(); + let persistence = Arc::new(CapturingPersistence::default()); + let manager = PlatformWalletManager::new( + Arc::new(sdk), + Arc::clone(&persistence), + Arc::new(NoopTestEventHandler), + ); + let old = add_wallet(&manager).await; + let mut restored = { + let mut state = old.state_mut().await.unwrap(); + state + .identity_manager + .add_identity( + Identity::V0(IdentityV0 { + id: owner, + public_keys: Default::default(), + balance: 123, + revision: 7, + }), + 0, + old.wallet_id(), + old.persister(), + ) + .unwrap(); + let managed = state.identity_manager.managed_identity_mut(&owner).unwrap(); + if contacts { + managed + .add_incoming_contact_request( + ContactRequest::new(contact, owner, 0, 0, 0, vec![], 0, 0), + old.persister(), + ) + .unwrap(); + } + IdentityEntry::from_managed(managed) + }; + restored.dashpay_profile = Some(restored_profile.clone()); + restored.contact_profiles.insert( + contact, + ContactProfileEntry { + profile: Some(restored_profile.clone()), + checked_at_ms: 42, + }, + ); + let (reached_tx, reached_rx) = oneshot::channel(); + let (resume_tx, resume_rx) = oneshot::channel(); + FETCH_PAUSES.lock().unwrap().insert( + Arc::as_ptr(&old.identity().generation) as usize, + (reached_tx, resume_rx), + ); + let syncing = { + let old = Arc::clone(&old); + tokio::spawn(async move { sync(&old, contacts).await }) + }; + tokio::time::timeout(Duration::from_secs(10), reached_rx) + .await + .unwrap() + .unwrap(); + tokio::time::timeout( + Duration::from_secs(10), + manager.remove_wallet(&old.wallet_id()), + ) + .await + .unwrap() + .unwrap(); + let current = add_wallet(&manager).await; + assert_eq!(old.wallet_id(), current.wallet_id()); + current + .apply( + IdentityChangeSet { + identities: [(owner, restored.clone())].into(), + ..Default::default() + } + .into(), + ) + .await + .unwrap(); + if contacts { + current + .state_mut() + .await + .unwrap() + .identity_manager + .managed_identity_mut(&owner) + .unwrap() + .add_incoming_contact_request( + ContactRequest::new(contact, owner, 0, 0, 0, vec![], 0, 0), + current.persister(), + ) + .unwrap(); + } + let before = persistence.0.lock().unwrap().len(); + resume_tx.send(()).unwrap(); + assert_eq!( + syncing.await.unwrap(), + 0, + "stale synchronization must be discarded" + ); + assert_eq!( + persistence.0.lock().unwrap().len(), + before, + "stale synchronization must not persist through its retained handle" + ); + { + let state = current.state().await; + let managed = state.identity_manager.managed_identity(&owner).unwrap(); + assert_eq!(IdentityEntry::from_managed(managed), restored); + } + assert_eq!( + sync(¤t, contacts).await, + 1, + "current generation can synchronize" + ); + assert!(persistence.0.lock().unwrap().len() > before); + let state = current.state().await; + let managed = state.identity_manager.managed_identity(&owner).unwrap(); + let profile = if contacts { + &managed.dashpay().contact_profiles[&contact].profile + } else { + &managed.dashpay().profile + }; + assert_eq!( + profile.as_ref().and_then(|p| p.shielded_address.as_ref()), + present.then_some(&fetched_address) + ); + } + } + + #[tokio::test] + async fn should_discard_delayed_own_profile_sync_after_wallet_replacement() { + assert_delayed_sync_preserves_replacement(false).await; + } + + #[tokio::test] + async fn should_discard_delayed_contact_profile_sync_after_wallet_replacement() { + assert_delayed_sync_preserves_replacement(true).await; + } +} From 633fe72420c54b33cb9c073ed1fdf36a829c1a59 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 03:55:54 +0000 Subject: [PATCH 29/41] fix(wallet): carry explicit profile authority to persistence --- .../dashsdk/ffi/NativePersistenceBridge.kt | 19 +++ .../PlatformWalletPersistenceHandler.kt | 52 +++++- .../PlatformWalletPersistenceHandlerTest.kt | 45 ++++- .../src/identity_persistence.rs | 39 +++-- .../rs-platform-wallet-ffi/src/manager.rs | 36 +++- .../rs-platform-wallet-ffi/src/persistence.rs | 160 +++++++++++++++++- packages/rs-platform-wallet-storage/SCHEMA.md | 6 +- .../src/sqlite/schema/dashpay.rs | 48 +++++- .../src/sqlite/schema/identities.rs | 17 +- .../sqlite_dashpay_overlay_contract.rs | 104 +++++++++++- .../src/changeset/changeset.rs | 18 +- .../rs-platform-wallet/src/wallet/apply.rs | 57 ++++++- .../src/wallet/identity/network/profile.rs | 110 +++++++++++- .../state/managed_identity/dashpay.rs | 3 + .../state/managed_identity/identity_ops.rs | 15 +- .../identity/state/managed_identity/mod.rs | 7 + .../wallet/identity/state/manager/apply.rs | 4 +- .../rs-unified-sdk-jni/src/persistence.rs | 134 ++++++++++++++- .../PlatformWalletPersistenceHandler.swift | 83 +++++++-- .../DashPayPersistenceTests.swift | 80 ++++++++- 20 files changed, 947 insertions(+), 90 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt index c9c18a68858..49e05a3be0d 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt @@ -556,6 +556,25 @@ abstract class NativePersistenceBridge { dashpayShieldedAddress: ByteArray? = null, ): Int = 0 + /** Authoritative profile update, independent of identity ownership or placement. */ + @Suppress("LongParameterList") + open fun onPersistDashpayProfile( + walletId: ByteArray, + identityId: ByteArray, + isPresent: Boolean, + displayName: String?, + bio: String?, + avatarUrl: String?, + avatarHash: ByteArray, + avatarHashPresent: Boolean, + avatarFingerprint: ByteArray, + avatarFingerprintPresent: Boolean, + publicMessage: String?, + corePaymentAddress: ByteArray?, + platformPaymentAddress: ByteArray?, + shieldedAddress: ByteArray?, + ): Int = 0 + /** One identity-id removal. Descriptor `([B[B)I`. */ open fun onPersistIdentityRemoval(walletId: ByteArray, identityId: ByteArray): Int = 0 diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index 9640be2c81e..661a2cde408 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -1830,14 +1830,7 @@ class PlatformWalletPersistenceHandler( ) } - // DashPay profile: present == "update the whole document". - // Absent deletes the row for a wallet-owned identity (the load - // path hydrated it, so absent means Platform has none); for an - // out-of-wallet identity, which is never hydrated, it is "no - // update". Mirrors Swift `persistIdentities`. - if (!dashpayProfilePresent) { - if (identityIndexIsSome) db.dashpayDao().deleteProfile(networkRaw, identityId) - } else { + if (dashpayProfilePresent) { db.dashpayDao().upsertProfile( DashpayProfileEntity( networkRaw = networkRaw, @@ -1860,6 +1853,49 @@ class PlatformWalletPersistenceHandler( 0 } + @Suppress("LongParameterList") + override fun onPersistDashpayProfile( + walletId: ByteArray, + identityId: ByteArray, + isPresent: Boolean, + displayName: String?, + bio: String?, + avatarUrl: String?, + avatarHash: ByteArray, + avatarHashPresent: Boolean, + avatarFingerprint: ByteArray, + avatarFingerprintPresent: Boolean, + publicMessage: String?, + corePaymentAddress: ByteArray?, + platformPaymentAddress: ByteArray?, + shieldedAddress: ByteArray?, + ): Int = guarded { + stage(walletId) { db -> + val identity = requireNotNull(db.identityDao().getByIdentityId(identityId)) + if (isPresent) { + db.dashpayDao().upsertProfile( + DashpayProfileEntity( + networkRaw = identity.networkRaw, + identityId = identityId, + displayName = displayName, + publicMessage = publicMessage, + bio = bio, + avatarUrl = avatarUrl, + avatarHash = avatarHash.takeIf { avatarHashPresent }, + avatarFingerprint = avatarFingerprint.takeIf { avatarFingerprintPresent }, + corePaymentAddress = corePaymentAddress, + platformPaymentAddress = platformPaymentAddress, + shieldedAddress = shieldedAddress, + lastUpdated = now(), + ), + ) + } else { + db.dashpayDao().deleteProfile(identity.networkRaw, identityId) + } + } + 0 + } + override fun onPersistIdentityRemoval(walletId: ByteArray, identityId: ByteArray): Int = guarded { val identityBase58 = identityId.toBase58String() stage(walletId) { db -> db.identityDao().deleteByIdentityId(identityId) } diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index 71508fd8d23..cb0398ee8ee 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -941,7 +941,7 @@ class PlatformWalletPersistenceHandlerTest { } @Test - fun shouldDeleteOwnedProfileWhenWalletIdentitySnapshotHasNone() = runTest { + fun shouldPreserveUnknownProfileUntilExplicitAbsence() = runTest { // `sync_profiles` clears a profile deleted on Platform; the cached // row must not be hydrated back on the next cold start. handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) @@ -972,11 +972,54 @@ class PlatformWalletPersistenceHandlerTest { ) persistSnapshot(profilePresent = false) + assertTrue(ByteArray(43) { 3 }.contentEquals(db.dashpayDao().getProfile(testnet, identityId)!!.shieldedAddress)) + handler.onChangesetBegin(walletId) + assertEquals(0, handler.onPersistDashpayProfile( + walletId, identityId, false, null, null, null, ByteArray(32), false, + ByteArray(8), false, null, null, null, null, + )) + handler.onChangesetEnd(walletId, success = true) assertNull(db.dashpayDao().getProfile(testnet, identityId)) assertNotNull(db.dashpayDao().getProfile(otherNetwork, identityId)) assertNull(handler.onLoadWalletList().single().identities.single().dashpayProfile) } + @Test + fun observedProfileUpdateSurvivesAdoptionAndExplicitAbsenceRemovesIt() = runTest { + handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) + val identityId = ByteArray(32) { 14 } + fun snapshot(owned: Boolean) { + handler.onChangesetBegin(walletId) + handler.onPersistIdentityUpsert( + walletId, identityId, 42, 1, owned, 0, 0, owned, walletId, + emptyArray(), LongArray(0), false, null, null, null, + ByteArray(32), false, ByteArray(8), false, null, + ) + handler.onChangesetEnd(walletId, success = true) + } + snapshot(false) + handler.onChangesetBegin(walletId) + handler.onPersistDashpayProfile( + walletId, identityId, true, "Observed", null, null, ByteArray(32), false, + ByteArray(8), false, null, ByteArray(21) { 1 }, ByteArray(21) { 2 }, ByteArray(43) { 3 }, + ) + handler.onChangesetEnd(walletId, success = true) + snapshot(true) + val profile = db.dashpayDao().getProfile(testnet, identityId)!! + assertEquals("Observed", profile.displayName) + assertTrue(ByteArray(21) { 1 }.contentEquals(profile.corePaymentAddress)) + assertTrue(ByteArray(21) { 2 }.contentEquals(profile.platformPaymentAddress)) + assertTrue(ByteArray(43) { 3 }.contentEquals(profile.shieldedAddress)) + snapshot(false) + handler.onChangesetBegin(walletId) + handler.onPersistDashpayProfile( + walletId, identityId, false, null, null, null, ByteArray(32), false, + ByteArray(8), false, null, null, null, null, + ) + handler.onChangesetEnd(walletId, success = true) + assertNull(db.dashpayDao().getProfile(testnet, identityId)) + } + @Test fun identityDpnsSnapshotRemovesStaleOwnedLabels() = runTest { handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) diff --git a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs index 68bc3ca5e93..de1b9bf9271 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_persistence.rs @@ -57,6 +57,9 @@ use platform_wallet::{DashPayProfile, IdentityStatus}; /// distinguish "no profile yet" (skip the row) from "profile present /// with this field unset" (clear the column). All heap-allocated /// strings are freed in [`free_identity_entry_ffi`]. +/// Confirmed absence travels separately on the size-negotiated +/// `on_persist_dashpay_profiles_fn` extension; identity placement does not +/// establish whether the profile was checked. #[repr(C)] pub struct IdentityEntryFFI { pub identity_id: [u8; 32], @@ -643,7 +646,7 @@ fn allocate_dpns_arrays( /// pointers — every one must be released with `CString::from_raw` /// before the outer slice drops. [`free_identity_entry_ffi`] does this /// row-by-row, mirroring the DPNS label-array free path exactly. -fn allocate_contact_profile_rows( +pub(crate) fn allocate_contact_profile_rows( contact_profiles: &std::collections::BTreeMap< dpp::prelude::Identifier, platform_wallet::ContactProfileEntry, @@ -924,23 +927,29 @@ pub unsafe fn free_identity_entry_ffi(entry: &mut IdentityEntryFFI) { // produced by `optional_c_string` (`CString::into_raw`) so it MUST be // reclaimed with `CString::from_raw` — the byte arrays are inline and // need no free. - if !entry.contact_profiles.is_null() && entry.contact_profiles_count > 0 { - let rows = unsafe { - std::slice::from_raw_parts_mut( - entry.contact_profiles as *mut ContactProfileRowFFI, - entry.contact_profiles_count, - ) - }; + unsafe { free_contact_profile_rows(entry.contact_profiles, entry.contact_profiles_count) }; + entry.contact_profiles = ptr::null(); + entry.contact_profiles_count = 0; +} + +/// Release rows allocated by `allocate_contact_profile_rows` after the host copied them. +/// +/// # Safety +/// The pointer and count must describe the original allocation, freed exactly once. +pub(crate) unsafe fn free_contact_profile_rows(ptr: *const ContactProfileRowFFI, count: usize) { + if !ptr.is_null() && count > 0 { + let rows = + unsafe { std::slice::from_raw_parts_mut(ptr as *mut ContactProfileRowFFI, count) }; for row in rows.iter_mut() { - free_optional_c_string(&mut row.display_name); - free_optional_c_string(&mut row.bio); - free_optional_c_string(&mut row.avatar_url); - free_optional_c_string(&mut row.public_message); + unsafe { + free_optional_c_string(&mut row.display_name); + free_optional_c_string(&mut row.bio); + free_optional_c_string(&mut row.avatar_url); + free_optional_c_string(&mut row.public_message); + } } - let _ = unsafe { Box::from_raw(rows as *mut [ContactProfileRowFFI]) }; - entry.contact_profiles = ptr::null(); + drop(unsafe { Box::from_raw(rows as *mut [ContactProfileRowFFI]) }); } - entry.contact_profiles_count = 0; } /// Release a heap-allocated C string produced by diff --git a/packages/rs-platform-wallet-ffi/src/manager.rs b/packages/rs-platform-wallet-ffi/src/manager.rs index 51e38104709..fbc4e6b5d6a 100644 --- a/packages/rs-platform-wallet-ffi/src/manager.rs +++ b/packages/rs-platform-wallet-ffi/src/manager.rs @@ -12,7 +12,7 @@ use crate::persistence::{ FreeTrackedMasternodesFn, LoadAssetLockOperationIdFn, LoadAssetLockShieldedRecipientFn, LoadIdentityBalanceBlockTimeFn, LoadPrivateContactScanStateFn, LoadPrivateContactScanStateWalletsFn, LoadTrackedMasternodesFn, PersistAssetLockOperationIdFn, - PersistAssetLockShieldedRecipientFn, PersistDpnsNameStatesFn, + PersistAssetLockShieldedRecipientFn, PersistDashpayProfilesFn, PersistDpnsNameStatesFn, PersistIdentityBalanceBlockTimeFn, PersistPrivateContactScanStateFn, PersistTrackedMasternodesFn, PersistWalletChangesetChainLockHeightFn, PersistWalletChangesetSweepsFn, PersistWalletChangesetUtxoVerdictsFn, @@ -408,6 +408,7 @@ unsafe fn persistence_extension_callbacks( on_load_private_contact_scan_state_wallets_free_fn, FreePrivateContactScanStateWalletsFn ), + persist_dashpay_profiles: slot!(on_persist_dashpay_profiles_fn, PersistDashpayProfilesFn), } } @@ -1693,6 +1694,39 @@ mod tests { assert!(read.wallet_dashpay_backfill.is_some()); } + #[test] + fn should_size_gate_authoritative_dashpay_profile_slot() { + unsafe extern "C" fn persist( + _: *mut c_void, + _: *const u8, + _: *const crate::identity_persistence::ContactProfileRowFFI, + _: usize, + ) -> i32 { + 0 + } + let offset = std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_dashpay_profiles_fn + ); + let mut extension = PersistenceCallbacksExtension { + on_persist_dashpay_profiles_fn: Some(persist), + ..Default::default() + }; + for size in [ + offset, + offset + std::mem::size_of::>() - 1, + ] { + extension.struct_size = size; + assert!(unsafe { persistence_extension_callbacks(&extension) } + .persist_dashpay_profiles + .is_none()); + } + extension.struct_size = std::mem::size_of::(); + assert!(unsafe { persistence_extension_callbacks(&extension) } + .persist_dashpay_profiles + .is_some()); + } + #[test] fn should_size_gate_identity_balance_watermark_slots_independently() { unsafe extern "C" fn persist( diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index 44758355302..bc0635eb119 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -68,7 +68,8 @@ use crate::dpns_name_state_persistence::{ build_dpns_name_state_entries, free_dpns_name_state_entries, DpnsNameStateFFI, }; use crate::identity_persistence::{ - free_identity_entry_ffi, free_identity_key_entry_ffi, IdentityEntryFFI, IdentityKeyEntryFFI, + allocate_contact_profile_rows, free_contact_profile_rows, free_identity_entry_ffi, + free_identity_key_entry_ffi, ContactProfileRowFFI, IdentityEntryFFI, IdentityKeyEntryFFI, IdentityKeyRemovalFFI, }; use crate::invitation_persistence::{build_invitation_entries, InvitationEntryFFI}; @@ -709,6 +710,10 @@ pub struct PersistenceCallbacksExtension { wallet_ids_count: usize, ), >, + /// Authoritative profile overlays. `contact_id` is the profile identity ID; + /// `is_present == false` deletes it, independent of identity placement. + /// The host must copy all row data before returning. + pub on_persist_dashpay_profiles_fn: Option, } impl Default for PersistenceCallbacksExtension { @@ -736,10 +741,18 @@ impl Default for PersistenceCallbacksExtension { on_load_private_contact_scan_state_free_fn: None, on_load_private_contact_scan_state_wallets_fn: None, on_load_private_contact_scan_state_wallets_free_fn: None, + on_persist_dashpay_profiles_fn: None, } } } +pub type PersistDashpayProfilesFn = unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + profiles: *const ContactProfileRowFFI, + profiles_count: usize, +) -> i32; + /// The additive (extension-negotiated) callbacks in Rust-side form, read /// out of a size-gated [`PersistenceCallbacksExtension`] by the manager /// create path. @@ -764,6 +777,7 @@ pub struct PersistenceExtensionCallbacks { pub load_private_contact_scan_state_free: Option, pub load_private_contact_scan_state_wallets: Option, pub load_private_contact_scan_state_wallets_free: Option, + pub persist_dashpay_profiles: Option, } /// Return value by which a persistence callback reports a **retryable** @@ -2776,6 +2790,30 @@ impl PlatformWalletPersistence for FFIPersister { } } + if let (Some(profiles), Some(cb)) = ( + changeset.dashpay_profiles.as_ref(), + self.tracked_masternodes_callbacks.persist_dashpay_profiles, + ) { + let rows = profiles + .iter() + .map(|(id, profile)| { + ( + *id, + platform_wallet::ContactProfileEntry { + profile: profile.clone(), + checked_at_ms: 0, + }, + ) + }) + .collect(); + let (rows, count) = allocate_contact_profile_rows(&rows); + let rc = unsafe { cb(self.callbacks.context, wallet_id.as_ptr(), rows, count) }; + unsafe { free_contact_profile_rows(rows, count) }; + if rc != 0 { + outcome.record(rc); + } + } + // Stamp sidecars share the begin/end transaction with identity scalars. // Run after the legacy callback has staged any new identity rows. if let (Some(id_cs), Some(cb)) = ( @@ -9461,6 +9499,116 @@ mod tests { } } + #[test] + fn should_forward_authoritative_profile_overlays_after_scalar_snapshots() { + use dpp::identity::{Identity, IdentityV0}; + use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry}; + use platform_wallet::ManagedIdentity; + use std::sync::Mutex; + #[derive(Default)] + struct Host { + profiles: Mutex, bool)>>, + order: Mutex>, + } + unsafe extern "C" fn scalar( + context: *mut c_void, + _: *const u8, + entries: *const IdentityEntryFFI, + count: usize, + _: *const [u8; 32], + _: usize, + ) -> i32 { + let host = &*(context as *const Host); + assert_eq!(count, 1); + assert!(!(*entries).dashpay_profile_present); + host.order.lock().unwrap().push("scalar"); + 0 + } + unsafe extern "C" fn persist( + context: *mut c_void, + wallet: *const u8, + rows: *const ContactProfileRowFFI, + count: usize, + ) -> i32 { + assert_eq!(slice::from_raw_parts(wallet, 32), &[42; 32]); + let host = &*(context as *const Host); + host.order.lock().unwrap().push("profile"); + for row in slice::from_raw_parts(rows, count) { + assert_eq!(row.contact_id, [9; 32]); + let display = (!row.display_name.is_null()).then(|| { + CStr::from_ptr(row.display_name) + .to_str() + .unwrap() + .to_owned() + }); + host.profiles.lock().unwrap().push(( + row.is_present, + display, + row.shielded_address_present, + )); + } + 0 + } + let host = Host::default(); + let persister = FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (&host as *const Host).cast_mut().cast(), + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(noop_end), + on_persist_identities_fn: Some(scalar), + ..Default::default() + }, + PersistenceCapabilities::NONE, + PersistenceExtensionCallbacks { + persist_dashpay_profiles: Some(persist), + ..Default::default() + }, + ); + let id = Identifier::from([9; 32]); + let managed = ManagedIdentity::new_out_of_wallet(Identity::V0(IdentityV0 { + id, + public_keys: Default::default(), + balance: 0, + revision: 0, + })); + for profile in [ + Some(platform_wallet::DashPayProfile { + display_name: Some("Owned copy".into()), + shielded_address: Some(vec![3; 43]), + ..Default::default() + }), + None, + ] { + persister + .store( + [42; 32], + PlatformWalletChangeSet { + identities: Some(IdentityChangeSet { + identities: BTreeMap::from([( + id, + IdentityEntry::from_managed(&managed), + )]), + ..Default::default() + }), + dashpay_profiles: Some(BTreeMap::from([(id, profile)])), + ..Default::default() + }, + ) + .unwrap(); + } + assert_eq!( + *host.profiles.lock().unwrap(), + vec![ + (true, Some("Owned copy".into()), true), + (false, None, false) + ] + ); + assert_eq!( + *host.order.lock().unwrap(), + vec!["scalar", "profile", "scalar", "profile"] + ); + } + // --- persists_durably: the fail-closed durability attestation --- unsafe extern "C" fn noop_begin(_ctx: *mut c_void, _wallet_id: *const u8) -> i32 { @@ -12335,6 +12483,16 @@ mod tests { PersistenceCallbacksExtension, on_load_private_contact_scan_state_wallets_free_fn ) + std::mem::size_of::>(), + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_dashpay_profiles_fn + ) + ); + assert_eq!( + std::mem::offset_of!( + PersistenceCallbacksExtension, + on_persist_dashpay_profiles_fn + ) + std::mem::size_of::>(), std::mem::size_of::() ); assert_eq!( diff --git a/packages/rs-platform-wallet-storage/SCHEMA.md b/packages/rs-platform-wallet-storage/SCHEMA.md index 49f0c4045cd..f6eefa8a1c9 100644 --- a/packages/rs-platform-wallet-storage/SCHEMA.md +++ b/packages/rs-platform-wallet-storage/SCHEMA.md @@ -626,8 +626,10 @@ nullable `identities.wallet_id` link; no direct `wallet_id` column exists. At most one DashPay profile blob per identity. `None` profile maps to a DELETE rather than a NULL blob — the row is absent, not nulled. -`apply` writes these rows, but `load()` does not return them today; -`DashPaySyncManager` rebuilds the canonical profile from Platform. +`apply` also folds each explicit profile update or deletion into the identity's +canonical `entry_blob`, which `load()` reads. An identity scalar snapshot with +no profile preserves the stored profile; only an explicit profile overlay +establishes absence. `profile_format` (V021) stamps the bincode shape of `profile_blob` the same way `identities.entry_format` does (0 = pre-payment-address record, 1 = diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs index af1e3134791..2c1baae8ed5 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/dashpay.rs @@ -8,18 +8,18 @@ //! indexed queries. Round-trip pinned by //! `tests/integration/sqlite_dashpay_overlay_contract.rs`. //! -//! # …which is why the payment overlay is also PATCHED into `entry_blob` +//! # Profile and payment overlays are also folded into `entry_blob` //! -//! Because `load()` reads only the identity blob, a payment row that reached +//! Because `load()` reads only the identity blob, a profile or payment that reached //! the overlay table alone is a write that does not survive a restart. The //! wallet-event adapter is the single writer of swept sent-payment verdicts //! and has no other durable channel for them, so [`apply`] finishes by -//! folding each overlay row into the owning identity's `entry_blob`. +//! folding each overlay row into the owning identity's `entry_blob`, including +//! confirmed-absent profile tombstones. //! -//! The fold is a read-modify-write of ONLY the `(txid -> PaymentEntry)` keys -//! the overlay names, run inside the persister's own write transaction: -//! payments the overlay does not mention, and every other field of the -//! entry, are read back and written out unchanged. That is what distinguishes +//! The folds modify only the named profile or `(txid -> PaymentEntry)` keys +//! inside the persister's own write transaction. Payments the overlay does +//! not mention and every other field of the entry survive unchanged. That is what distinguishes //! it from shipping a whole `IdentityEntry` from the caller — a snapshot //! captured before the lock was released would wholesale replace the blob and //! silently drop any payment another writer committed in between @@ -93,6 +93,7 @@ pub fn apply( } } } + patch_profiles_into_entry_blobs(tx, profiles)?; } } if let Some(payments) = payments { @@ -176,3 +177,36 @@ fn patch_payments_into_entry_blobs( } Ok(()) } + +fn patch_profiles_into_entry_blobs( + tx: &Transaction<'_>, + profiles: &BTreeMap>, +) -> Result<(), WalletStorageError> { + let mut read = tx.prepare_cached( + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ + WHERE identity_id = ?1", + )?; + let mut write = tx.prepare_cached( + "UPDATE identities SET entry_blob = ?2, entry_format = 1 WHERE identity_id = ?1", + )?; + for (identity_id, profile) in profiles { + let stored: Option<(i64, Vec, i64)> = read + .query_row(params![identity_id.as_slice()], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .map(Some) + .or_else(|e| match e { + rusqlite::Error::QueryReturnedNoRows => Ok(None), + other => Err(other), + })?; + let Some((len, payload, format)) = stored else { + continue; + }; + blob::check_size(len)?; + let mut entry: IdentityEntry = decode_identity(&payload, format)?; + entry.dashpay_profile = profile.clone(); + let patched = blob::encode(&entry)?; + write.execute(params![identity_id.as_slice(), patched])?; + } + Ok(()) +} diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs index a3d23dd3458..406ef862c7d 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/identities.rs @@ -87,7 +87,22 @@ pub fn apply_upserts( }); } } - let payload = blob::encode(entry)?; + let mut entry = entry.clone(); + if entry.dashpay_profile.is_none() { + let stored: Option<(i64, Vec, i64)> = tx + .query_row( + "SELECT length(entry_blob), entry_blob, entry_format FROM identities \ + WHERE identity_id = ?1 AND (wallet_id IS NULL OR wallet_id IS ?2)", + params![id.as_slice(), wallet_id_param], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional()?; + if let Some((len, payload, format)) = stored { + blob::check_size(len)?; + entry.dashpay_profile = decode_identity(&payload, format)?.dashpay_profile; + } + } + let payload = blob::encode(&entry)?; stmt.execute(params![ id.as_slice(), wallet_id_param, diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs index 6b716cc9f35..fce9fb14dc5 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_dashpay_overlay_contract.rs @@ -9,9 +9,9 @@ //! tests pin both halves of that contract: //! //! 1. A `dashpay_*` write lands in the overlay tables (queryable directly). -//! 2. Writing ONLY the overlay (no identity blob carrying the same data) -//! does not corrupt `load()` — load succeeds and surfaces the wallet's -//! other state intact. +//! 2. Overlay-only writes fold into the canonical identity blob and survive load. +//! 3. Unknown scalar profile snapshots retain the canonical profile, while +//! explicit profile tombstones clear it. use crate::common; @@ -90,10 +90,7 @@ fn overlay_only_write_does_not_corrupt_load() { persister.store(w, overlay_cs).expect("store overlay"); persister.flush(w).expect("flush overlay"); - // The documented contract: load() reads DashPay from the identities - // blob (not the overlay table), so the overlay-only write neither - // appears in nor corrupts the loaded state. load() must still - // succeed and surface the wallet's core state. + // Loading the canonical blob must include the overlay and unrelated core state. let state = persister .load() .expect("load must succeed despite overlay-only write"); @@ -101,8 +98,101 @@ fn overlay_only_write_does_not_corrupt_load() { .wallets .get(&w) .expect("wallet present in loaded state"); + assert_eq!( + wallet.identity_manager.out_of_wallet_identities[&Identifier::from(identity)] + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("bob") + ); assert_eq!( wallet.wallet_info.metadata.synced_height, 99, "core state must rehydrate intact alongside an unread overlay" ); } + +#[test] +fn should_preserve_profile_on_unknown_scalar_snapshot_and_apply_explicit_absence() { + use platform_wallet::changeset::{IdentityChangeSet, IdentityEntry, Merge}; + let (persister, _tmp, _path) = fresh_persister(); + let w = wid(0xC1); + let raw = [0xC2; 32]; + let id = Identifier::from(raw); + ensure_wallet_meta(&persister, &w); + ensure_identity(&persister, &raw, Some(&w)); + let apply_profile = |profile| { + persister + .store( + w, + PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, profile)])), + ..Default::default() + }, + ) + .unwrap(); + persister.flush(w).unwrap(); + }; + apply_profile(Some(profile("Retained"))); + let state = persister.load().unwrap(); + let managed = &state.wallets[&w].identity_manager.out_of_wallet_identities[&id]; + assert_eq!( + managed + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Retained") + ); + let mut scalar = IdentityEntry::from_managed(managed); + scalar.dashpay_profile = None; + scalar.balance = 321; + let scalar_cs = IdentityChangeSet { + identities: BTreeMap::from([(id, scalar)]), + ..Default::default() + }; + persister.store(w, scalar_cs.clone().into()).unwrap(); + persister.flush(w).unwrap(); + let state = persister.load().unwrap(); + let managed = &state.wallets[&w].identity_manager.out_of_wallet_identities[&id]; + assert_eq!( + managed + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Retained") + ); + let mut cleared = PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, None)])), + ..Default::default() + }; + cleared.merge(scalar_cs.into()); + persister.store(w, cleared).unwrap(); + persister.flush(w).unwrap(); + let state = persister.load().unwrap(); + let managed = &state.wallets[&w].identity_manager.out_of_wallet_identities[&id]; + assert!(managed.dashpay().profile.is_none()); + assert_eq!( + dpp::identity::accessors::IdentityGettersV0::balance(&managed.identity), + 321 + ); + apply_profile(Some(profile("Restored"))); + let state = persister.load().unwrap(); + assert_eq!( + state.wallets[&w].identity_manager.out_of_wallet_identities[&id] + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Restored") + ); +} diff --git a/packages/rs-platform-wallet/src/changeset/changeset.rs b/packages/rs-platform-wallet/src/changeset/changeset.rs index acbd65ec69b..ecfdac65e70 100644 --- a/packages/rs-platform-wallet/src/changeset/changeset.rs +++ b/packages/rs-platform-wallet/src/changeset/changeset.rs @@ -940,7 +940,8 @@ pub struct IdentityEntry { /// the wallet that owns this identity, if known. pub wallet_id: Option<[u8; 32]>, /// DashPay profile snapshot (display name, bio, avatar, public - /// message). `None` until the profile has been fetched or set. + /// message). `None` is unknown/no update; confirmed absence is carried + /// by `PlatformWalletChangeSet::dashpay_profiles`. pub dashpay_profile: Option, /// DashPay payment history keyed by transaction id (hex string). /// Mutations that don't touch payments still carry the current @@ -1180,12 +1181,9 @@ impl Merge for IdentityChangeSet { // the first value would flush the stale slot and leave it // occupied for the identity that legitimately owns it. existing.identity_index = entry.identity_index; - // DashPay profile: last-write-wins. Same policy as - // every other Option scalar in this block — - // every mutation snapshot copies the current - // profile via `from_managed`, so LWW converges - // correctly within a single wallet. - existing.dashpay_profile = entry.dashpay_profile.clone(); + if entry.dashpay_profile.is_some() { + existing.dashpay_profile = entry.dashpay_profile.clone(); + } // DPNS names: last-write-wins wholesale, same policy // as `contested_dpns_names` below. Every emitter // snapshots the complete current list via @@ -2357,9 +2355,9 @@ pub struct PlatformWalletChangeSet { pub token_balances: Option, /// DashPay profile overlays keyed by identity ID. Applied AFTER /// `identities` — updates the `dashpay_profile` field on existing - /// `ManagedIdentity` entries without touching other fields. Used - /// by the persister load path where only DashPay data is available - /// (the identity blob lives in the external `identity` table). + /// `ManagedIdentity` entries without touching other fields. A missing key + /// is no update; `Some(profile)` is present and `None` is confirmed absent. + /// Scalar identity snapshots with no profile do not carry this authority. /// Identities not in the wallet are silently skipped. pub dashpay_profiles: Option>>, /// DashPay payment history overlays keyed by identity ID. Same diff --git a/packages/rs-platform-wallet/src/wallet/apply.rs b/packages/rs-platform-wallet/src/wallet/apply.rs index 6dcda5ac4cb..ae23ea87e54 100644 --- a/packages/rs-platform-wallet/src/wallet/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/apply.rs @@ -337,7 +337,7 @@ impl PlatformWalletInfo { if let Some(profiles) = dashpay_profiles { for (id, profile) in profiles { if let Some(managed) = self.identity_manager.managed_identity_mut(&id) { - *managed.dashpay_profile_mut() = profile; + managed.apply_dashpay_profile(profile); } } } @@ -2213,6 +2213,30 @@ mod tests { .apply_changeset(&mut wallet_b, wrap_id(id_cs)) .expect("apply"); + assert_eq!( + info_b + .identity_manager + .managed_identity(&id) + .unwrap() + .dashpay() + .profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("seed"), + "a scalar snapshot with no profile must preserve the retained profile" + ); + info_b + .apply_changeset( + &mut wallet_b, + PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, None)])), + ..Default::default() + }, + ) + .expect("apply explicit profile absence"); + // Both wallets should have profile == None. assert_eq!( info_a @@ -2234,6 +2258,37 @@ mod tests { ); } + #[test] + fn apply_first_absent_profile_establishes_session_authority_for_observed_identity() { + let mut wallet = build_test_wallet(); + let mut info = empty_info(&wallet); + let p = noop_persister(); + let id = Identifier::from([9; 32]); + info.identity_manager + .add_out_of_wallet_identity(make_test_identity(9, 1), &p) + .unwrap(); + assert!( + !info + .identity_manager + .managed_identity(&id) + .unwrap() + .dashpay() + .profile_checked + ); + info.apply_changeset( + &mut wallet, + PlatformWalletChangeSet { + dashpay_profiles: Some(BTreeMap::from([(id, None)])), + ..Default::default() + }, + ) + .unwrap(); + let managed = info.identity_manager.managed_identity(&id).unwrap(); + assert!(managed.dashpay().profile_checked); + assert!(managed.dashpay().profile.is_none()); + assert!(managed.identity_index.is_none()); + } + #[test] fn round_trip_double_apply_is_idempotent() { let wallet_a = build_test_wallet(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 2046bccf199..30551062f8f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -55,11 +55,10 @@ impl DashPayView<'_, B> { /// /// Fetches through [`Sdk::get_profiles`](dash_sdk::Sdk::get_profiles) (`In` /// queries, not N+1; a failed fetch leaves the cache as is for the next - /// sweep), and persists only when the - /// fetched profile differs from the cached one — a `None` result clears the - /// cache only when a profile is currently stored (both arms guarded so a - /// no-change sweep writes nothing). Returns the number of identities whose - /// cached profile changed. Results for a removed or replaced wallet + /// sweep), and persists when the fetched profile differs from the cached + /// one or establishes the first confirmed absence this session. Subsequent + /// unchanged results emit nothing. Returns the number of identities whose + /// profile state was updated. Results for a removed or replaced wallet /// generation are discarded without changing state or persistence. pub async fn sync_profiles(&self) -> Result { // 1. Collect all managed identity IDs under a short read lock. @@ -100,8 +99,7 @@ impl DashPayView<'_, B> { .map(|id| (*id, found.get(id).cloned().flatten())) .collect(); - // 4. Under the write guard: persist-on-change only (mirror the - // None-arm's is_some guard for both directions). + // A first confirmed absence must emit a tombstone even on a cold cache. let mut changed = 0u32; let mut wm = self.wallet_manager.write().await; let Ok(info) = self.current_wallet_info_mut(&mut wm) else { @@ -111,7 +109,9 @@ impl DashPayView<'_, B> { let Some(managed) = info.identity_manager.managed_identity_mut(&identity_id) else { continue; }; - if managed.dashpay().profile == profile { + if (managed.dashpay().profile_checked || managed.dashpay().profile.is_some()) + && managed.dashpay().profile == profile + { continue; } managed.set_dashpay_profile(profile, &self.persister); @@ -1448,6 +1448,100 @@ mod sync_generation_tests { } } + #[tokio::test] + async fn should_persist_first_observed_profile_absence_once_and_keep_overlay_across_scalars() { + use crate::changeset::Merge; + let owner = Identifier::from([0x61; 32]); + let query = DocumentQuery::new(dashpay_contract().unwrap(), "profile") + .unwrap() + .with_where(WhereClause { + field: "$ownerId".into(), + operator: WhereOperator::In, + value: Value::Array(vec![owner.into()]), + }) + .with_order_by(OrderClause { + field: "$ownerId".into(), + ascending: true, + }) + .with_limit(100); + let mut sdk = SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch_many::( + query, + Some(Default::default()), + ) + .await + .unwrap(); + let persistence = Arc::new(CapturingPersistence::default()); + let manager = PlatformWalletManager::new( + Arc::new(sdk), + Arc::clone(&persistence), + Arc::new(NoopTestEventHandler), + ); + let wallet = add_wallet(&manager).await; + { + let mut state = wallet.state_mut().await.unwrap(); + state + .identity_manager + .add_out_of_wallet_identity( + Identity::V0(IdentityV0 { + id: owner, + public_keys: Default::default(), + balance: 123, + revision: 7, + }), + wallet.persister(), + ) + .unwrap(); + } + persistence.0.lock().unwrap().clear(); + assert_eq!(sync(&wallet, false).await, 1); + assert_eq!(sync(&wallet, false).await, 0); + let mut merged = { + let mut writes = persistence.0.lock().unwrap(); + assert_eq!(writes.len(), 1); + writes.pop().unwrap() + }; + assert_eq!( + merged.dashpay_profiles.as_ref().unwrap().get(&owner), + Some(&None) + ); + let scalar = merged.identities.clone().unwrap(); + let mut known = scalar.clone(); + known.identities.get_mut(&owner).unwrap().dashpay_profile = Some(DashPayProfile { + display_name: Some("Retained".into()), + ..Default::default() + }); + known.merge(scalar.clone()); + assert_eq!( + known.identities[&owner] + .dashpay_profile + .as_ref() + .unwrap() + .display_name + .as_deref(), + Some("Retained") + ); + merged.merge(scalar.into()); + assert_eq!( + merged.dashpay_profiles.as_ref().unwrap().get(&owner), + Some(&None) + ); + let state = wallet.state().await; + assert!( + state + .identity_manager + .managed_identity(&owner) + .unwrap() + .dashpay() + .profile_checked + ); + } + async fn assert_delayed_sync_preserves_replacement(contacts: bool) { for present in [true, false] { let owner = Identifier::from([0x61; 32]); diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs index a9b1fdeca06..498b50bd9d5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/dashpay.rs @@ -249,6 +249,9 @@ pub struct DashPayState { /// profile has been fetched or set. pub profile: Option, + /// Session-only authority: a successful fetch or explicit update checked this profile. + pub(crate) profile_checked: bool, + /// DashPay payment history keyed by transaction id (hex string). /// Each entry records a single Dash payment to or from a contact /// identity, with direction, amount, memo, and status. diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs index bc960262ea9..c091e156289 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/identity_ops.rs @@ -4,7 +4,7 @@ use super::key_storage::{DpnsFetch, DpnsNameInfo, IdentityStatus}; use super::ManagedIdentity; use crate::changeset::{ IdentityChangeSet, IdentityEntry, IdentityKeyEntry, IdentityKeysChangeSet, KeyWithBreadcrumb, - PersistenceError, + PersistenceError, PlatformWalletChangeSet, }; use crate::wallet::persister::WalletPersister; use crate::BlockTime; @@ -133,10 +133,15 @@ impl ManagedIdentity { profile: Option, persister: &WalletPersister, ) { - self.dashpay.profile = profile; - let cs = self.snapshot_changeset(); - if let Err(e) = persister.store(cs.into()) { - tracing::error!("Failed to persist changeset: {}", e); + let previous = std::mem::replace(&mut self.dashpay.profile, profile.clone()); + let mut cs: PlatformWalletChangeSet = self.snapshot_changeset().into(); + cs.dashpay_profiles = Some(BTreeMap::from([(self.id(), profile)])); + match persister.store(cs) { + Ok(()) => self.dashpay.profile_checked = true, + Err(e) => { + self.dashpay.profile = previous; + tracing::error!("Failed to persist changeset: {}", e); + } } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs index c11f1e91f8a..cc4fd32590a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/managed_identity/mod.rs @@ -20,6 +20,7 @@ pub use crate::wallet::identity::types::key_storage::{ self, DpnsFetch, DpnsNameInfo, IdentityStatus, KeyStorage, PrivateKeyData, }; +use crate::wallet::identity::DashPayProfile; use dpp::identity::Identity; /// A managed identity that combines an Identity with wallet-specific metadata. @@ -117,6 +118,12 @@ impl ManagedIdentity { &mut self.dashpay.profile } + /// Apply an authoritative profile overlay without emitting another write. + pub(crate) fn apply_dashpay_profile(&mut self, profile: Option) { + self.dashpay.profile = profile; + self.dashpay.profile_checked = true; + } + /// Mutable access to the DashPay payment-history cache. /// /// Replay/restore surface: bypasses persistence and the diff --git a/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs b/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs index 38b221d4ab4..16be8b01bae 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/state/manager/apply.rs @@ -74,7 +74,9 @@ impl IdentityManager { } existing.last_synced_keys_block_time = entry.last_synced_keys_block_time; existing.status = entry.status; - *existing.dashpay_profile_mut() = entry.dashpay_profile; + if let Some(profile) = entry.dashpay_profile { + existing.apply_dashpay_profile(Some(profile)); + } // DPNS names: wholesale assign, matching the changeset's // last-write-wins merge — entries carry the complete list // (snapshotted via `from_managed`), and a sold/transferred diff --git a/packages/rs-unified-sdk-jni/src/persistence.rs b/packages/rs-unified-sdk-jni/src/persistence.rs index 84b4ebac257..5803d268265 100644 --- a/packages/rs-unified-sdk-jni/src/persistence.rs +++ b/packages/rs-unified-sdk-jni/src/persistence.rs @@ -53,11 +53,11 @@ use jni::sys::jstring; use jni::JNIEnv; use platform_wallet_ffi::{ AccountAddressPoolFFI, AccountChangeSetFFI, AccountSpecFFI, AddressBalanceEntryFFI, - AssetLockEntryFFI, ContactIgnoredSenderFFI, ContactProfileRestoreEntryFFI, ContactRequestFFI, - ContactRequestRemovalFFI, CoreAddressEntryFFI, DashPayBackfillCoveredContactFFI, - DpnsNameStateFFI, IdentityEntryFFI, IdentityKeyEntryFFI, IdentityKeyRemovalFFI, - IdentityKeyRestoreFFI, IdentityRestoreEntryFFI, InvitationEntryFFI, OutPointFFI, - PaymentRestoreEntryFFI, PersistenceCallbacks, PersistenceCallbacksExtension, + AssetLockEntryFFI, ContactIgnoredSenderFFI, ContactProfileRestoreEntryFFI, + ContactProfileRowFFI, ContactRequestFFI, ContactRequestRemovalFFI, CoreAddressEntryFFI, + DashPayBackfillCoveredContactFFI, DpnsNameStateFFI, IdentityEntryFFI, IdentityKeyEntryFFI, + IdentityKeyRemovalFFI, IdentityKeyRestoreFFI, IdentityRestoreEntryFFI, InvitationEntryFFI, + OutPointFFI, PaymentRestoreEntryFFI, PersistenceCallbacks, PersistenceCallbacksExtension, PlatformAddressFFI, PrivateContactRequestsPositionFFI, PrivateShieldedAddressFFI, ProviderSpecialTxRestoreEntryFFI, SpentOutPointFFI, SweepBatchFFI, TokenBalanceRemovalFFI, TokenBalanceUpsertFFI, TransactionRecordFFI, UnresolvedAssetLockTxRecordFFI, UtxoEntryFFI, @@ -226,6 +226,12 @@ pub(crate) fn build_vtable(context: *mut c_void) -> PersistenceCallbacks { /// publication fails closed. pub(crate) fn build_extension(env: &mut JNIEnv, bridge: &JObject) -> PersistenceCallbacksExtension { extension_for(BridgeOverrides { + dashpay_profiles: bridge_overrides( + env, + bridge, + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR, + ), sweeps: bridge_overrides( env, bridge, @@ -328,6 +334,7 @@ struct BridgeOverrides { /// vouches for the contact requests read before it, which an inherited /// no-op contact upsert never keeps. private_contact_scan_state: bool, + dashpay_profiles: bool, } /// The extension slots wired for a bridge with `overrides` (see @@ -335,6 +342,9 @@ struct BridgeOverrides { fn extension_for(overrides: BridgeOverrides) -> PersistenceCallbacksExtension { PersistenceCallbacksExtension { on_persist_dpns_name_states_fn: Some(tramp_persist_dpns_name_states), + on_persist_dashpay_profiles_fn: overrides + .dashpay_profiles + .then_some(tramp_persist_dashpay_profiles), on_persist_wallet_changeset_sweeps_fn: if overrides.sweeps { Some(tramp_persist_wallet_changeset_sweeps) } else { @@ -1856,6 +1866,72 @@ unsafe fn persist_identity_upsert( Ok(0) } +const PERSIST_DASHPAY_PROFILE_DESCRIPTOR: &str = + "([B[BZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[BZ[BZLjava/lang/String;[B[B[B)I"; + +unsafe extern "C" fn tramp_persist_dashpay_profiles( + context: *mut c_void, + wallet_id: *const u8, + rows_ptr: *const ContactProfileRowFFI, + rows_count: usize, +) -> i32 { + with_bridge(context, |env, bridge| { + let wid = id32(env, wallet_id)?; + for row in slice_or_empty(rows_ptr, rows_count) { + let code = env.with_local_frame(16, |env| { + let contact_id = env.byte_array_from_slice(&row.contact_id)?; + let display = cstr_opt(env, row.display_name)?; + let bio = cstr_opt(env, row.bio)?; + let avatar_url = cstr_opt(env, row.avatar_url)?; + let public_message = cstr_opt(env, row.public_message)?; + let avatar_hash = env.byte_array_from_slice(&row.avatar_hash)?; + let avatar_fp = env.byte_array_from_slice(&row.avatar_fingerprint)?; + let core_payment_address = if row.core_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.core_payment_address)?) + } else { + JObject::null() + }; + let platform_payment_address = if row.platform_payment_address_present { + JObject::from(env.byte_array_from_slice(&row.platform_payment_address)?) + } else { + JObject::null() + }; + let shielded_address = if row.shielded_address_present { + JObject::from(env.byte_array_from_slice(&row.shielded_address)?) + } else { + JObject::null() + }; + env.call_method( + bridge, + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR, + &[ + (&wid).into(), + (&contact_id).into(), + JValue::Bool(row.is_present as u8), + (&display).into(), + (&bio).into(), + (&avatar_url).into(), + (&avatar_hash).into(), + JValue::Bool(row.avatar_hash_present as u8), + (&avatar_fp).into(), + JValue::Bool(row.avatar_fingerprint_present as u8), + (&public_message).into(), + (&core_payment_address).into(), + (&platform_payment_address).into(), + (&shielded_address).into(), + ], + )? + .i() + })?; + if code != 0 { + return Ok(code); + } + } + Ok(0) + }) +} + // ── Identity keys ───────────────────────────────────────────────────── unsafe extern "C" fn tramp_persist_identity_keys( @@ -5272,6 +5348,10 @@ fn read_bytes_field_vec( /// [`nativeVerifyPersistenceBridgeDescriptors`] resolves the whole table up /// front instead; keep this table in sync with the `call_method` sites. const BRIDGE_METHOD_TABLE: &[(&str, &str)] = &[ + ( + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR, + ), ("persistenceCapabilitiesVersion", "()I"), ("persistenceCapabilitiesBits", "()J"), ("onChangesetBegin", "([B)I"), @@ -5560,6 +5640,7 @@ mod tests { header, backfill, private_contact_scan_state: false, + dashpay_profiles: false, }); assert_eq!( extension.on_persist_wallet_dashpay_backfill_fn.is_some(), @@ -5572,6 +5653,7 @@ mod tests { header: false, backfill: false, private_contact_scan_state: false, + dashpay_profiles: false, }); assert!(sweeps_only.on_persist_wallet_changeset_sweeps_fn.is_some()); assert!(sweeps_only.on_persist_wallet_dashpay_backfill_fn.is_none()); @@ -5589,6 +5671,7 @@ mod tests { header: false, backfill: false, private_contact_scan_state: wired, + dashpay_profiles: false, }); assert_eq!( extension.on_persist_private_contact_scan_state_fn.is_some(), @@ -5735,6 +5818,47 @@ mod tests { assert!(jint_height(u32::MAX).is_err()); } + #[test] + fn should_negotiate_only_overridden_dashpay_profile_callback_and_match_descriptor() { + let names = [ + "[B", + "[B", + "boolean", + "java.lang.String", + "java.lang.String", + "java.lang.String", + "[B", + "boolean", + "[B", + "boolean", + "java.lang.String", + "[B", + "[B", + "[B", + ] + .into_iter() + .map(str::to_owned) + .collect::>(); + assert_eq!( + method_descriptor(&names, "int"), + PERSIST_DASHPAY_PROFILE_DESCRIPTOR + ); + assert!(BRIDGE_METHOD_TABLE.contains(&( + "onPersistDashpayProfile", + PERSIST_DASHPAY_PROFILE_DESCRIPTOR + ))); + for wired in [false, true] { + let extension = extension_for(BridgeOverrides { + sweeps: false, + header: false, + backfill: false, + private_contact_scan_state: false, + dashpay_profiles: wired, + }); + assert_eq!(extension.on_persist_dashpay_profiles_fn.is_some(), wired); + } + } + #[test] fn sweeps_callback_descriptor_ships_flat_arrays_and_an_explicit_height_pair() { // walletId, packed txids + count, winner, packed released outpoints diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 8ecf1bfa7da..191087a963b 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3395,6 +3395,7 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { extensionCallbacks.struct_size = UInt(MemoryLayout.size) extensionCallbacks.version = UInt32(PLATFORM_WALLET_PERSISTENCE_CALLBACKS_EXTENSION_VERSION) extensionCallbacks.reserved = 0 + extensionCallbacks.on_persist_dashpay_profiles_fn = persistDashpayProfilesCallback extensionCallbacks.on_persist_dpns_name_states_fn = persistDpnsNameStatesCallback extensionCallbacks.on_persist_tracked_masternodes_fn = persistTrackedMasternodesCallback extensionCallbacks.on_load_tracked_masternodes_fn = loadTrackedMasternodesCallback @@ -3816,24 +3817,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { names: entry.dpnsNames ) - // Sync the DashPay profile cache for this identity. - // - // The snapshot carries Rust's current profile. For a - // wallet-owned identity (`identityIndex != nil`) the load - // path hydrated this row into Rust, so a `nil` profile is - // authoritative (e.g. `sync_profiles` found it deleted on - // Platform) and the row plus its address sidecar go. - // Out-of-wallet identities are never hydrated, so for them - // `nil` only means "not fetched" and leaves the row intact. if let profile = entry.dashpayProfile { try upsertDashpayProfile(identityRow: row, profile: profile) - } else if entry.identityIndex != nil { - if let existing = row.dashpayProfile { - backgroundContext.delete(existing) - } - try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, - networkRaw: row.networkRaw, ownerIdentityId: row.identityId, - profileIdentityId: row.identityId, core: nil, platform: nil, shielded: nil, fetcher: modelFetcher) } // Upsert the cached contact-profile rows for this identity. @@ -3920,6 +3905,37 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } // onQueue } + @discardableResult + func persistDashpayProfiles(walletId: Data, profiles: [DashpayProfileOverlaySnapshot]) -> Bool { + onQueue { + do { + for overlay in profiles { + let identityId = overlay.identityId + let descriptor = FetchDescriptor( + predicate: #Predicate { $0.identityId == identityId } + ) + guard let row = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { + return false + } + if let profile = overlay.profile { + try upsertDashpayProfile(identityRow: row, profile: profile) + } else { + if let existing = row.dashpayProfile { backgroundContext.delete(existing) } + try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, + networkRaw: row.networkRaw, ownerIdentityId: row.identityId, + profileIdentityId: row.identityId, core: nil, platform: nil, shielded: nil, + fetcher: modelFetcher) + } + } + return true + } catch { + SDKLogger.event("persistence_profile_overlay_failed", category: .persistence, + severity: .error, error: error) + return false + } + } + } + /// Upsert a `PersistentDPNSName` row for every label the FFI /// identity entry carried. Rows are keyed on /// `(networkRaw, normalizedParentDomainName, normalizedLabel)`, @@ -5486,6 +5502,11 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { let contactProfiles: [ContactProfileSnapshot] } + struct DashpayProfileOverlaySnapshot { + let identityId: Data + let profile: DashpayProfileSnapshot? + } + /// Owned snapshot of one `ContactProfileRowFFI` — the contact's /// identity id, the five public profile fields, and the /// `checked_at_ms` self-heal timestamp. Decouples every contained @@ -10526,6 +10547,36 @@ private func persistAccountAddressPoolsCallback( return allOk ? 0 : 1 } +private func persistDashpayProfilesCallback( + context: UnsafeMutableRawPointer?, + walletIdPtr: UnsafePointer?, + rowsPtr: UnsafePointer?, + rowsCount: UInt +) -> Int32 { + guard let context, let walletIdPtr else { return 1 } + guard rowsCount == 0 || rowsPtr != nil else { return 1 } + let handler = Unmanaged.fromOpaque(context).takeUnretainedValue() + var profiles: [PlatformWalletPersistenceHandler.DashpayProfileOverlaySnapshot] = [] + if let rowsPtr { + for index in 0..()), 1) persist(nil) + XCTAssertEqual(try ModelContext(container).fetchCount(FetchDescriptor()), 1) + XCTAssertEqual(try ModelContext(container).fetchCount(FetchDescriptor()), 1) + handler.beginChangeset(walletId: walletId) + let cleared = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: nil)]) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: cleared)) let reader = ModelContext(container) XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) @@ -292,6 +298,78 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertNil(try XCTUnwrap(buffer[0].identities)[0].dashpay_profile) } + func testObservedProfileSurvivesAdoptionAndExplicitCallbackCanRemoveIt() throws { + let callbacks = handler.makePersistenceCallbacksExtension() + let persist = try XCTUnwrap(callbacks.on_persist_dashpay_profiles_fn) + let context = Unmanaged.passUnretained(handler!).toOpaque() + var row = ContactProfileRowFFI() + row.contact_id = Self.tuple32(ownerId) + row.is_present = true + row.shielded_address_present = true + withUnsafeMutableBytes(of: &row.shielded_address) { $0.copyBytes(from: Data(repeating: 3, count: 43)) } + handler.beginChangeset(walletId: walletId) + let stored = "Observed profile".withCString { name in + row.display_name = name + return walletId.withUnsafeBytes { wallet in + withUnsafePointer(to: &row) { persist(context, wallet.bindMemory(to: UInt8.self).baseAddress, $0, 1) } + } + } + row.display_name = nil + XCTAssertEqual(stored, 0) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: stored == 0)) + for index in [nil, UInt32(0)] { + handler.beginChangeset(walletId: walletId) + let kept = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 42, revision: 1, identityIndex: index, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: kept)) + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.displayName, "Observed profile") + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 1) + } + // A tombstone is authoritative even after placement changes back to observed. + handler.beginChangeset(walletId: walletId) + let observed = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 42, revision: 1, identityIndex: nil, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + row.is_present = false + let cleared = walletId.withUnsafeBytes { wallet in + withUnsafePointer(to: &row) { persist(context, wallet.bindMemory(to: UInt8.self).baseAddress, $0, 1) } + } + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: observed && cleared == 0)) + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 0) + } + + func testExplicitProfileAbsenceAddressFailureRollsBackProfileAndScalarUpdate() throws { + handler.beginChangeset(walletId: walletId) + let profile = PlatformWalletPersistenceHandler.DashpayProfileSnapshot( + displayName: "Keep me", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43)) + let stored = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: profile)]) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: stored)) + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet, + modelFetcher: PaymentAddressReadFailure()) + handler.beginChangeset(walletId: walletId) + let updated = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 999, revision: 4, identityIndex: nil, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + let cleared = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: nil)]) + XCTAssertTrue(updated) + XCTAssertFalse(cleared) + XCTAssertFalse(handler.endChangeset(walletId: walletId, success: updated && cleared)) + let reader = ModelContext(container) + XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.displayName, "Keep me") + XCTAssertEqual(try reader.fetchCount(FetchDescriptor()), 1) + XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.balance, 0) + } + // MARK: Contact-profile tombstone delete /// A present profile upserts a row; a later `isPresent == false` tombstone From 5560369cb586f083eb98627c9a4387f3d70ad56e Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 04:29:47 +0000 Subject: [PATCH 30/41] fix(ffi): emit profile persistence callback as C function pointer --- packages/rs-platform-wallet-ffi/src/persistence.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index bc0635eb119..fb9b69c230f 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -713,7 +713,14 @@ pub struct PersistenceCallbacksExtension { /// Authoritative profile overlays. `contact_id` is the profile identity ID; /// `is_present == false` deletes it, independent of identity placement. /// The host must copy all row data before returning. - pub on_persist_dashpay_profiles_fn: Option, + pub on_persist_dashpay_profiles_fn: Option< + unsafe extern "C" fn( + context: *mut c_void, + wallet_id: *const u8, + profiles: *const ContactProfileRowFFI, + profiles_count: usize, + ) -> i32, + >, } impl Default for PersistenceCallbacksExtension { From bddc6b4e03b079721dea3732a499a6d946199045 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 05:08:40 +0000 Subject: [PATCH 31/41] fix(swift): fetch profile models before staging tombstones --- .../PlatformWalletPersistenceHandler.swift | 7 +++- .../DashPayPersistenceTests.swift | 34 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 191087a963b..3ade3835a4c 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3920,11 +3920,16 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { if let profile = overlay.profile { try upsertDashpayProfile(identityRow: row, profile: profile) } else { - if let existing = row.dashpayProfile { backgroundContext.delete(existing) } + // Resolve the profile so SwiftData can snapshot it during rollback. + let profileDescriptor = FetchDescriptor( + predicate: PersistentDashpayProfile.predicate(identityId: identityId) + ) + let existing = try modelFetcher.fetch(profileDescriptor, in: backgroundContext).first try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, networkRaw: row.networkRaw, ownerIdentityId: row.identityId, profileIdentityId: row.identityId, core: nil, platform: nil, shielded: nil, fetcher: modelFetcher) + if let existing { backgroundContext.delete(existing) } } } return true diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index beddf7238bf..f0fe7653e29 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -370,6 +370,40 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertEqual(try reader.fetch(FetchDescriptor()).first?.balance, 0) } + func testExplicitProfileAbsenceLaterCallbackFailureRollsBackDeletionAndScalarUpdate() throws { + handler.beginChangeset(walletId: walletId) + let profile = PlatformWalletPersistenceHandler.DashpayProfileSnapshot( + displayName: "Keep me", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: Data(repeating: 3, count: 43)) + let stored = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: profile)]) + XCTAssertTrue(handler.endChangeset(walletId: walletId, success: stored)) + handler = PlatformWalletPersistenceHandler(modelContainer: container, network: .testnet) + + handler.beginChangeset(walletId: walletId) + let updated = handler.persistIdentities(walletId: walletId, upserts: [.init( + identityId: ownerId, balance: 999, revision: 4, identityIndex: nil, + label: nil, status: 0, walletId: walletId, dpnsNames: [], dashpayProfile: nil, + contactProfiles: [])], removed: []) + let cleared = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: ownerId, profile: nil)]) + let laterCallback = handler.persistDashpayProfiles(walletId: walletId, + profiles: [.init(identityId: contactId, profile: nil)]) + XCTAssertTrue(updated) + XCTAssertTrue(cleared) + XCTAssertFalse(laterCallback) + XCTAssertFalse(handler.endChangeset(walletId: walletId, success: updated && cleared && laterCallback)) + + let reader = ModelContext(container) + let restoredProfile = try XCTUnwrap(reader.fetch(FetchDescriptor()).first) + XCTAssertEqual(restoredProfile.displayName, "Keep me") + let addresses = try XCTUnwrap(reader.fetch(FetchDescriptor()).first) + XCTAssertEqual(addresses.shieldedAddress, Data(repeating: 3, count: 43)) + let restoredIdentity = try XCTUnwrap(reader.fetch(FetchDescriptor()).first) + XCTAssertEqual(restoredIdentity.balance, 0) + XCTAssertEqual(restoredIdentity.revision, 0) + } + // MARK: Contact-profile tombstone delete /// A present profile upserts a row; a later `isPresent == false` tombstone From 56bb77d5cbab89d75366f939568e74be7666d6a3 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 06:53:12 +0000 Subject: [PATCH 32/41] fix(wallet): fence profile and shielded persistence races --- .../PlatformWalletPersistenceHandler.kt | 6 +- .../dashsdk/persistence/dao/IdentityDao.kt | 3 + .../PlatformWalletPersistenceHandlerTest.kt | 24 +++++++ .../rs-platform-wallet-ffi/src/persistence.rs | 63 +++++++++++++++++++ .../src/wallet/platform_wallet.rs | 18 ++++-- .../src/wallet/shielded/tips.rs | 2 +- .../PlatformWalletPersistenceHandler.swift | 9 ++- .../DashPayPersistenceTests.swift | 20 ++++++ 8 files changed, 138 insertions(+), 7 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index 661a2cde408..023a2ce2656 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -1871,7 +1871,11 @@ class PlatformWalletPersistenceHandler( shieldedAddress: ByteArray?, ): Int = guarded { stage(walletId) { db -> - val identity = requireNotNull(db.identityDao().getByIdentityId(identityId)) + val networkRaw = db.walletDao().getByWalletId(walletId)?.networkRaw + ?: return@stage + val identity = requireNotNull( + db.identityDao().getByIdentityAndNetwork(identityId, networkRaw) + ) if (isPresent) { db.dashpayDao().upsertProfile( DashpayProfileEntity( diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt index 4b89b39119b..1da3f19bdce 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/IdentityDao.kt @@ -27,6 +27,9 @@ interface IdentityDao { @Query("SELECT * FROM identities WHERE identityId = :identityId") suspend fun getByIdentityId(identityId: ByteArray): IdentityEntity? + @Query("SELECT * FROM identities WHERE identityId = :identityId AND networkRaw = :networkRaw") + suspend fun getByIdentityAndNetwork(identityId: ByteArray, networkRaw: Int): IdentityEntity? + /** Mirror of `predicate(network:)`. */ @Query("SELECT * FROM identities WHERE networkRaw = :networkRaw") fun observeByNetwork(networkRaw: Int): Flow> diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index cb0398ee8ee..694e76cf15a 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -1020,6 +1020,30 @@ class PlatformWalletPersistenceHandlerTest { assertNull(db.dashpayDao().getProfile(testnet, identityId)) } + @Test + fun profileOverlayRejectsIdentityFromAnotherNetwork() = runTest { + handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) + val identityId = ByteArray(32) { 15 } + handler.onChangesetBegin(walletId) + handler.onPersistIdentityUpsert( + walletId, identityId, 1, 0, true, 0, 0, true, walletId, + emptyArray(), LongArray(0), false, null, null, null, + ByteArray(32), false, ByteArray(8), false, null, + ) + handler.onChangesetEnd(walletId, success = true) + + val otherWalletId = ByteArray(32) { 16 } + handler.onPersistWalletMetadata(otherWalletId, testnet + 1, groupId, 0) + handler.onChangesetBegin(otherWalletId) + val result = handler.onPersistDashpayProfile( + otherWalletId, identityId, true, "Wrong network", null, null, + ByteArray(32), false, ByteArray(8), false, null, null, null, null, + ) + assertEquals(0, result) + assertTrue(handler.onChangesetEnd(otherWalletId, success = true) != 0) + assertNull(db.dashpayDao().getProfile(testnet + 1, identityId)) + } + @Test fun identityDpnsSnapshotRemovesStaleOwnedLabels() = runTest { handler.onPersistWalletMetadata(walletId, testnet, groupId, 0) diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index fb9b69c230f..d0bc637d3f6 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -2801,8 +2801,13 @@ impl PlatformWalletPersistence for FFIPersister { changeset.dashpay_profiles.as_ref(), self.tracked_masternodes_callbacks.persist_dashpay_profiles, ) { + let removed = changeset + .identities + .as_ref() + .map(|identity_changes| &identity_changes.removed); let rows = profiles .iter() + .filter(|(id, _)| !removed.is_some_and(|ids| ids.contains(id))) .map(|(id, profile)| { ( *id, @@ -9616,6 +9621,64 @@ mod tests { ); } + #[test] + fn should_not_forward_profile_overlay_for_identity_removed_in_same_changeset() { + use platform_wallet::changeset::IdentityChangeSet; + use std::sync::Mutex; + + #[derive(Default)] + struct Host { + ids: Mutex>, + } + + unsafe extern "C" fn persist( + context: *mut c_void, + _: *const u8, + rows: *const ContactProfileRowFFI, + count: usize, + ) -> i32 { + let host = &*(context as *const Host); + host.ids.lock().unwrap().extend( + slice::from_raw_parts(rows, count) + .iter() + .map(|row| row.contact_id), + ); + 0 + } + + let host = Host::default(); + let persister = FFIPersister::new_with_persistence_capabilities_and_extensions( + PersistenceCallbacks { + context: (&host as *const Host).cast_mut().cast(), + on_changeset_begin_fn: Some(noop_begin), + on_changeset_end_fn: Some(noop_end), + ..Default::default() + }, + PersistenceCapabilities::NONE, + PersistenceExtensionCallbacks { + persist_dashpay_profiles: Some(persist), + ..Default::default() + }, + ); + let removed = Identifier::from([9; 32]); + let kept = Identifier::from([10; 32]); + let mut identities = IdentityChangeSet::default(); + identities.removed.insert(removed); + + persister + .store( + [42; 32], + PlatformWalletChangeSet { + identities: Some(identities), + dashpay_profiles: Some(BTreeMap::from([(removed, None), (kept, None)])), + ..Default::default() + }, + ) + .unwrap(); + + assert_eq!(*host.ids.lock().unwrap(), vec![[10; 32]]); + } + // --- persists_durably: the fail-closed durability attestation --- unsafe extern "C" fn noop_begin(_ctx: *mut c_void, _wallet_id: *const u8) -> i32 { diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 9c2956ba55d..d35ab7de353 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -917,14 +917,18 @@ impl PlatformWallet { accounts: &[u32], coordinator: &Arc, ) -> Result<(), PlatformWalletError> { + // Fence generation teardown across attachment validation, host + // viewing-key persistence, and coordinator/handle installation. + let _lifecycle = self.core().generation_payment_guard().await; let _config = self.shielded_config_lock.lock().await; - self.bind_shielded_locked(seed, accounts, coordinator).await + self.bind_shielded_locked_unfenced(seed, accounts, coordinator) + .await } /// [`Self::bind_shielded`] for a caller already holding - /// `shielded_config_lock`. + /// `shielded_config_lock` and the generation lifecycle guard. #[cfg(feature = "shielded")] - pub(crate) async fn bind_shielded_locked( + pub(crate) async fn bind_shielded_locked_unfenced( &self, seed: &[u8], accounts: &[u32], @@ -1059,6 +1063,9 @@ impl PlatformWallet { coordinator: &Arc, ) -> Result { use super::shielded::{AccountViewingKeys, SubwalletId}; + // Keep the generation alive from attachment validation through the + // persisted snapshot read and coordinator/handle installation. + let _lifecycle = self.core().generation_payment_guard().await; let _config = self.shielded_config_lock.lock().await; let required = crate::changeset::PersistenceCapabilities::SHIELDED_FVK_RESTART; let capabilities = self.persister.persistence_capabilities(); @@ -1374,10 +1381,13 @@ impl PlatformWallet { missing.bits(), ))); } - self.ensure_shielded_attached()?; // Serialized with the binds: tip preparation rebinds a snapshot of // the account set, which would drop an account inserted mid-way. + // The lifecycle gate spans attachment validation through host + // persistence and the final handle mutation. + let _lifecycle = self.core().generation_payment_guard().await; let _config = self.shielded_config_lock.lock().await; + self.ensure_shielded_attached()?; // Everything that calls into the host — the snapshot read below // and the viewing-key write further down — stays OUTSIDE the key // slot's lock. A host callback invoked while this write guard is diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 6d9574ce932..4a8a42224a0 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -158,7 +158,7 @@ impl PlatformWallet { #[cfg(test)] test_hooks::after_snapshot(self).await; accounts.push(account); - self.bind_shielded_locked(seed, &accounts, coordinator) + self.bind_shielded_locked_unfenced(seed, &accounts, coordinator) .await?; #[cfg(test)] test_hooks::after_bind(self).await; diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 3ade3835a4c..deea2f0c297 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3909,10 +3909,17 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { func persistDashpayProfiles(walletId: Data, profiles: [DashpayProfileOverlaySnapshot]) -> Bool { onQueue { do { + let walletDescriptor = FetchDescriptor( + predicate: PersistentWallet.predicate(walletId: walletId) + ) + guard let wallet = try modelFetcher.fetch(walletDescriptor, in: backgroundContext).first, + let networkRaw = wallet.networkRaw else { + return false + } for overlay in profiles { let identityId = overlay.identityId let descriptor = FetchDescriptor( - predicate: #Predicate { $0.identityId == identityId } + predicate: #Predicate { $0.identityId == identityId && $0.networkRaw == networkRaw } ) guard let row = try modelFetcher.fetch(descriptor, in: backgroundContext).first else { return false diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift index f0fe7653e29..c6116430525 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DashPayPersistenceTests.swift @@ -298,6 +298,26 @@ final class DashPayContactPersistenceTests: XCTestCase { XCTAssertNil(try XCTUnwrap(buffer[0].identities)[0].dashpay_profile) } + func testProfileOverlayRequiresIdentityNetworkToMatchCallbackWallet() throws { + let otherWalletId = Data(repeating: 0xBB, count: 32) + let context = ModelContext(container) + context.insert(PersistentWallet(walletId: otherWalletId, network: .devnet)) + try context.save() + + handler.beginChangeset(walletId: otherWalletId) + let stored = handler.persistDashpayProfiles(walletId: otherWalletId, profiles: [ + .init(identityId: ownerId, profile: .init( + displayName: "Wrong network", bio: nil, publicMessage: nil, avatarUrl: nil, + avatarHash: nil, avatarFingerprint: nil, shieldedAddress: nil + )) + ]) + XCTAssertFalse(stored) + XCTAssertFalse(handler.endChangeset(walletId: otherWalletId, success: stored)) + + let reader = ModelContext(container) + XCTAssertTrue(try reader.fetch(FetchDescriptor()).isEmpty) + } + func testObservedProfileSurvivesAdoptionAndExplicitCallbackCanRemoveIt() throws { let callbacks = handler.makePersistenceCallbacksExtension() let persist = try XCTUnwrap(callbacks.on_persist_dashpay_profiles_fn) From e7ea28a9d615cf7d1c9d8adaba453215e4193c2e Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 08:05:57 +0000 Subject: [PATCH 33/41] fix(swift): preserve profile callback network fallback --- .../PlatformWallet/PlatformWalletPersistenceHandler.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index deea2f0c297..4d71913608a 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -3912,8 +3912,8 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { let walletDescriptor = FetchDescriptor( predicate: PersistentWallet.predicate(walletId: walletId) ) - guard let wallet = try modelFetcher.fetch(walletDescriptor, in: backgroundContext).first, - let networkRaw = wallet.networkRaw else { + let wallet = try modelFetcher.fetch(walletDescriptor, in: backgroundContext).first + guard let networkRaw = wallet?.networkRaw ?? network?.rawValue else { return false } for overlay in profiles { @@ -3929,7 +3929,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { } else { // Resolve the profile so SwiftData can snapshot it during rollback. let profileDescriptor = FetchDescriptor( - predicate: PersistentDashpayProfile.predicate(identityId: identityId) + predicate: #Predicate { + $0.identity.identityId == identityId && $0.networkRaw == networkRaw + } ) let existing = try modelFetcher.fetch(profileDescriptor, in: backgroundContext).first try PersistentDashpayPaymentAddresses.replace(in: backgroundContext, From 9c11563911f898b85ad5d971e39fb722d7005a87 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 14:03:34 +0000 Subject: [PATCH 34/41] fix(platform-wallet): close shielded profile restore gaps --- .../rs-platform-wallet-ffi/src/persistence.rs | 35 +++------------ packages/rs-platform-wallet/src/lib.rs | 12 ++--- .../src/wallet/identity/mod.rs | 8 ++-- .../src/wallet/identity/network/profile.rs | 8 ++-- .../src/wallet/identity/types/dashpay/mod.rs | 4 +- .../wallet/identity/types/dashpay/profile.rs | 44 +++++++++++++++++++ .../src/wallet/identity/types/mod.rs | 6 +-- .../src/wallet/platform_wallet.rs | 42 ++++++++++++++++++ 8 files changed, 112 insertions(+), 47 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index d0bc637d3f6..e4678aacd98 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -7377,24 +7377,8 @@ unsafe fn restore_contact_profiles(spec: &IdentityRestoreEntryFFI, managed: &mut apply_contact_profile_rows(rows, managed); } -/// Maximum cached `avatarUrl` length — mirrors the -/// `MAX_AVATAR_URL_LEN` gate `platform-wallet`'s profile fetch applies -/// before caching (DIP-15's 2048-char cap). -const MAX_AVATAR_URL_LEN: usize = 2048; - -/// Defensive re-validation of a cached `avatarUrl` at restore. The -/// fetch path already dropped non-`https://` / over-length URLs before -/// caching ([`platform_wallet`]'s `is_valid_avatar_url`), but the URL is -/// attacker-controlled public data and the UI will load it, so we -/// re-apply the same `https://`-only, length-capped rule on the way back -/// in. A URL that fails is dropped to `None` (the rest of the profile is -/// still restored) rather than discarding the whole row. -fn is_valid_avatar_url(url: &str) -> bool { - !url.is_empty() && url.len() <= MAX_AVATAR_URL_LEN && url.starts_with("https://") -} - -/// Copy a host-owned profile row, retaining the avatar URL validation used for -/// cached contact profiles. The host frees the buffers after restoration returns. +/// Copy a host-owned profile row. The host frees the buffers after restoration +/// returns; platform-wallet owns normalization and payment-address policy. /// /// # Safety /// The row's string pointers must be null or readable NUL-terminated strings. @@ -7408,39 +7392,34 @@ unsafe fn profile_from_restore_row( CStr::from_ptr(ptr).to_str().ok().map(str::to_string) } }; - platform_wallet::DashPayProfile { + platform_wallet::normalize_persisted_profile(platform_wallet::DashPayProfile { display_name: opt_string(row.display_name), bio: opt_string(row.bio), - avatar_url: opt_string(row.avatar_url).filter(|u| is_valid_avatar_url(u)), + avatar_url: opt_string(row.avatar_url), avatar_hash: row.avatar_hash_present.then_some(row.avatar_hash), avatar_fingerprint: row .avatar_fingerprint_present .then_some(row.avatar_fingerprint), public_message: opt_string(row.public_message), - // Re-validated like the avatar URL: a stale or corrupt host row must - // not restore an address that a profile fetch would have rejected. core_payment_address: row .core_payment_address_present .then_some(row.core_payment_address) - .filter(|address| platform_wallet::valid_transparent_payment_address(address)) .map(|address| address.to_vec()), platform_payment_address: row .platform_payment_address_present .then_some(row.platform_payment_address) - .filter(|address| platform_wallet::valid_transparent_payment_address(address)) .map(|address| address.to_vec()), shielded_address: row .shielded_address_present .then_some(row.shielded_address) - .and_then(|address| platform_wallet::validated_shielded_address(&address)) .map(|address| address.to_vec()), - } + }) } /// Fold a slice of [`ContactProfileRestoreEntryFFI`] rows into /// the managed identity's contact-profile cache. Split out from -/// [`restore_contact_profiles`] so the c-string decode + avatar-url -/// re-validation is unit-testable without a full +/// [`restore_contact_profiles`] so the c-string decode + profile +/// normalization is unit-testable without a full /// [`IdentityRestoreEntryFFI`]. /// /// # Safety diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index a31c264d13a..cfc89b4eee3 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -88,12 +88,12 @@ pub use wallet::identity::network::{ }; pub use wallet::identity::{ calculate_account_reference, derive_auto_accept_private_key, derive_contact_payment_address, - derive_contact_payment_addresses, derive_contact_xpub, pubkey_binds_expected_key_data, - unmask_account_reference, BlockTime, ContactProfileEntry, ContactRequest, ContactXpubData, - DashPayProfile, DashPayState, DpnsFetch, DpnsNameInfo, EstablishedContact, IdentityLocation, - IdentityManager, IdentityStatus, KeyStorage, ManagedIdentity, PaymentAddressUpdate, - PrivateContact, PrivateKeyData, ProfileUpdate, RegistrationIndex, ShieldedTipRecipient, - DEFAULT_CONTACT_GAP_LIMIT, + derive_contact_payment_addresses, derive_contact_xpub, normalize_persisted_profile, + pubkey_binds_expected_key_data, unmask_account_reference, BlockTime, ContactProfileEntry, + ContactRequest, ContactXpubData, DashPayProfile, DashPayState, DpnsFetch, DpnsNameInfo, + EstablishedContact, IdentityLocation, IdentityManager, IdentityStatus, KeyStorage, + ManagedIdentity, PaymentAddressUpdate, PrivateContact, PrivateKeyData, ProfileUpdate, + RegistrationIndex, ShieldedTipRecipient, DEFAULT_CONTACT_GAP_LIMIT, }; pub use wallet::masternode_withdrawal::{ MasternodeWithdrawalKey, MasternodeWithdrawalKeys, MasternodeWithdrawalRequest, diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index e64b77354ff..c36c20e8336 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -36,8 +36,8 @@ pub use state::{ }; pub use types::dashpay::profile::{calculate_avatar_hash, calculate_dhash_fingerprint}; pub use types::{ - ContactProfileEntry, ContactRequest, DashPayProfile, DashpayAddressMatch, DpnsFetch, - DpnsNameInfo, EstablishedContact, IdentityStatus, KeyStorage, PaymentAddressUpdate, - PaymentDirection, PaymentEntry, PaymentStatus, PrivateKeyData, ProfileUpdate, - ShieldedTipRecipient, + normalize_persisted_profile, ContactProfileEntry, ContactRequest, DashPayProfile, + DashpayAddressMatch, DpnsFetch, DpnsNameInfo, EstablishedContact, IdentityStatus, KeyStorage, + PaymentAddressUpdate, PaymentDirection, PaymentEntry, PaymentStatus, PrivateKeyData, + ProfileUpdate, ShieldedTipRecipient, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 30551062f8f..e4a1de4490f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -22,8 +22,8 @@ use super::*; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::{ - calculate_avatar_hash, calculate_dhash_fingerprint, ContactProfileEntry, DashPayProfile, - ProfileUpdate, + calculate_avatar_hash, calculate_dhash_fingerprint, normalize_persisted_profile, + ContactProfileEntry, DashPayProfile, ProfileUpdate, }; // Profile documents require HIGH or CRITICAL authentication; MASTER is reserved @@ -345,7 +345,7 @@ fn profile_from_properties(props: &std::collections::BTreeMap) -> .and_then(|v: &Value| v.as_bytes_slice().ok()) .and_then(|bytes| <[u8; 8]>::try_from(bytes).ok()); - DashPayProfile { + normalize_persisted_profile(DashPayProfile { display_name: text("displayName"), bio: public_message.clone(), avatar_url: text("avatarUrl"), @@ -367,7 +367,7 @@ fn profile_from_properties(props: &std::collections::BTreeMap) -> .and_then(|v| v.as_bytes_slice().ok()) .and_then(crate::validated_shielded_address) .map(|bytes| bytes.to_vec()), - } + }) } // --------------------------------------------------------------------------- diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs index a0bd1440c38..5443b88508a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/mod.rs @@ -9,6 +9,6 @@ pub use contact_request::ContactRequest; pub use established_contact::EstablishedContact; pub use payment::{DashpayAddressMatch, PaymentDirection, PaymentEntry, PaymentStatus}; pub use profile::{ - calculate_avatar_hash, calculate_dhash_fingerprint, ContactProfileEntry, DashPayProfile, - PaymentAddressUpdate, ProfileUpdate, ShieldedTipRecipient, + calculate_avatar_hash, calculate_dhash_fingerprint, normalize_persisted_profile, + ContactProfileEntry, DashPayProfile, PaymentAddressUpdate, ProfileUpdate, ShieldedTipRecipient, }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs index 209a3a8f0e6..03cfdec8a1f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/dashpay/profile.rs @@ -50,6 +50,50 @@ pub struct DashPayProfile { pub shielded_address: Option>, } +/// Normalize profile data loaded from a host-owned persistence row. +/// +/// Persistence adapters only marshal the row into this model; acceptance of +/// payment-address bytes belongs to platform-wallet so restore policy cannot +/// drift between FFI, JNI, Swift, and native callers. +pub fn normalize_persisted_profile(mut profile: DashPayProfile) -> DashPayProfile { + profile.avatar_url = profile + .avatar_url + .filter(|url| !url.is_empty() && url.len() <= 2048 && url.starts_with("https://")); + profile.core_payment_address = profile + .core_payment_address + .filter(|address| valid_transparent_payment_address(address)); + profile.platform_payment_address = profile + .platform_payment_address + .filter(|address| valid_transparent_payment_address(address)); + profile.shielded_address = profile + .shielded_address + .and_then(|address| validated_shielded_address(&address).map(|address| address.to_vec())); + profile +} + +#[cfg(test)] +mod normalize_tests { + use super::*; + + #[test] + fn normalize_persisted_profile_drops_invalid_addresses() { + let profile = normalize_persisted_profile(DashPayProfile { + avatar_url: Some("http://example.com/avatar.png".to_string()), + core_payment_address: Some(vec![5; 21]), + platform_payment_address: Some(vec![1; 20]), + shielded_address: Some(vec![0xff; 43]), + display_name: Some("Alice".to_string()), + ..Default::default() + }); + + assert_eq!(profile.display_name.as_deref(), Some("Alice")); + assert_eq!(profile.avatar_url, None); + assert_eq!(profile.core_payment_address, None); + assert_eq!(profile.platform_payment_address, None); + assert_eq!(profile.shielded_address, None); + } +} + /// A cached **contact** profile, keyed by the contact's identity id on the /// owning [`ManagedIdentity`](crate::wallet::identity::ManagedIdentity). /// diff --git a/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs index 2d7e674e051..a098e5f85fd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/types/mod.rs @@ -11,8 +11,8 @@ pub mod key_storage; pub use block_time::BlockTime; pub use dashpay::{ - ContactProfileEntry, ContactRequest, DashPayProfile, DashpayAddressMatch, EstablishedContact, - PaymentAddressUpdate, PaymentDirection, PaymentEntry, PaymentStatus, ProfileUpdate, - ShieldedTipRecipient, + normalize_persisted_profile, ContactProfileEntry, ContactRequest, DashPayProfile, + DashpayAddressMatch, EstablishedContact, PaymentAddressUpdate, PaymentDirection, PaymentEntry, + PaymentStatus, ProfileUpdate, ShieldedTipRecipient, }; pub use key_storage::{DpnsFetch, DpnsNameInfo, IdentityStatus, KeyStorage, PrivateKeyData}; diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index d35ab7de353..8120a0bee65 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -3053,6 +3053,12 @@ impl PlatformWallet { ))); } let sets_shielded = matches!(input.shielded_address, PaymentAddressUpdate::Set(_)); + #[cfg(not(feature = "shielded"))] + if sets_shielded { + return Err(PlatformWalletError::InvalidIdentityData( + "Shielded address publication requires shielded support".to_string(), + )); + } let _placement = if sets_shielded { Some(self.identity.identity_placement.read().await) } else { @@ -3720,6 +3726,42 @@ mod state_generation_tests { impl EventHandler for NoopEvents {} impl PlatformEventHandler for NoopEvents {} + #[cfg(not(feature = "shielded"))] + #[tokio::test] + async fn should_reject_shielded_profile_addresses_without_shielded_support() { + let manager = PlatformWalletManager::new( + Arc::new(dash_sdk::Sdk::new_mock()), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + ); + let wallet = manager + .create_wallet_from_seed_bytes( + Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + let signer = simple_signer::signer::SimpleSigner::default(); + let result = wallet + .write_dashpay_profile( + &Identifier::from([7; 32]), + ProfileUpdate { + shielded_address: PaymentAddressUpdate::Set(vec![0; 43]), + ..Default::default() + }, + &signer, + false, + ) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::InvalidIdentityData(message)) + if message.contains("requires shielded support") + )); + } + #[tokio::test] async fn should_reject_mutations_from_a_removed_wallet_generation() { async fn assert_profile_write_refused(wallet: &PlatformWallet) { From 0ca5170b07f5f11ee4a9d69717c2695c7835013e Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 14:44:23 +0000 Subject: [PATCH 35/41] test(platform-wallet-ffi): use fenced wallet mutation in erase test --- .../src/document/erase_tests.rs | 38 +++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs b/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs index 02e250e9b2e..3c841810daf 100644 --- a/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs @@ -187,26 +187,24 @@ async fn should_preserve_signer_unavailable_and_unknown_submission_through_the_e ) .await .unwrap(); - wallet - .wallet_manager() - .write() - .await - .get_wallet_info_mut(&wallet.wallet_id()) - .unwrap() - .identity_manager - .add_identity( - IdentityV0 { - id: owner, - public_keys: [(1, key.clone())].into(), - balance: 100_000_000, - revision: 0, - } - .into(), - 0, - wallet.wallet_id(), - wallet.persister(), - ) - .unwrap(); + { + let mut state = wallet.state_mut().await.unwrap(); + state + .identity_manager + .add_identity( + IdentityV0 { + id: owner, + public_keys: [(1, key.clone())].into(), + balance: 100_000_000, + revision: 0, + } + .into(), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + } let handle = PLATFORM_WALLET_STORAGE.insert(wallet); let signer = Box::new(VTableSigner::from_native(Arc::new(Signing(available)))); let name = CString::new("note").unwrap(); From 86aa2ab02171a387f5a468b120f096121136f162 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 20:01:47 +0000 Subject: [PATCH 36/41] fix(wallet): serialize shielded profile publication --- .../src/wallet/platform_wallet.rs | 29 +++++++++++++++++++ .../src/wallet/shielded/tips.rs | 6 ++++ 2 files changed, 35 insertions(+) diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index cd2a7e4b76e..b6f73922121 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -918,6 +918,13 @@ impl PlatformWallet { accounts: &[u32], coordinator: &Arc, ) -> Result<(), PlatformWalletError> { + if coordinator.network() != self.network() { + return Err(PlatformWalletError::InvalidParameter(format!( + "the shielded coordinator is for {:?}, this wallet for {:?}", + coordinator.network(), + self.network(), + ))); + } // Fence generation teardown across attachment validation, host // viewing-key persistence, and coordinator/handle installation. let _lifecycle = self.core().generation_payment_guard().await; @@ -1064,6 +1071,13 @@ impl PlatformWallet { coordinator: &Arc, ) -> Result { use super::shielded::{AccountViewingKeys, SubwalletId}; + if coordinator.network() != self.network() { + return Err(PlatformWalletError::InvalidParameter(format!( + "the shielded coordinator is for {:?}, this wallet for {:?}", + coordinator.network(), + self.network(), + ))); + } // Keep the generation alive from attachment validation through the // persisted snapshot read and coordinator/handle installation. let _lifecycle = self.core().generation_payment_guard().await; @@ -3060,6 +3074,21 @@ impl PlatformWallet { "Shielded address publication requires shielded support".to_string(), )); } + #[cfg(feature = "shielded")] + let prepared_coordinator = if sets_shielded { + self.prepared_tip_accounts + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get(identity_id) + .and_then(PreparedTipAccount::coordinator) + } else { + None + }; + #[cfg(feature = "shielded")] + let _coordinator_operation = match prepared_coordinator.as_ref() { + Some(coordinator) => Some(coordinator.operation_guard().await), + None => None, + }; let _placement = if sets_shielded { Some(self.identity.identity_placement.read().await) } else { diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 4a8a42224a0..c9a6cd8d760 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -23,6 +23,12 @@ pub(crate) struct PreparedTipAccount { clear_generation: u64, } +impl PreparedTipAccount { + pub(crate) fn coordinator(&self) -> Option> { + self.coordinator.upgrade() + } +} + pub const SHIELDED_IDENTITY_ACCOUNT_BASE: u32 = 0x4000_0000; pub fn shielded_identity_account_index(identity_index: u32) -> Result { From 74e0829ea333f33da196dd793fd1b6bf301d2613 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 22:05:44 +0000 Subject: [PATCH 37/41] fix(wallet): own shielded coordinator lifecycle --- .../rs-platform-wallet/src/manager/load.rs | 6 ++ .../src/manager/wallet_lifecycle.rs | 6 ++ .../src/wallet/platform_wallet.rs | 85 ++++++++++++++++--- .../src/wallet/shielded/tips.rs | 7 +- 4 files changed, 89 insertions(+), 15 deletions(-) diff --git a/packages/rs-platform-wallet/src/manager/load.rs b/packages/rs-platform-wallet/src/manager/load.rs index db5da2bd8ec..7a59138a48f 100644 --- a/packages/rs-platform-wallet/src/manager/load.rs +++ b/packages/rs-platform-wallet/src/manager/load.rs @@ -559,6 +559,12 @@ impl PlatformWalletManager

{ Arc::clone(&self.sync_fault), Arc::clone(&self.durable_cursors), ); + #[cfg(feature = "shielded")] + let platform_wallet = { + let mut wallet = platform_wallet; + wallet.shielded_coordinator = Some(Arc::clone(&self.shielded_coordinator)); + wallet + }; // Initialize the platform-address provider. If the snapshot // carried a slice for this wallet, restore it directly; diff --git a/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs b/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs index 466c6f5af35..ffec090956b 100644 --- a/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs +++ b/packages/rs-platform-wallet/src/manager/wallet_lifecycle.rs @@ -705,6 +705,12 @@ impl PlatformWalletManager

{ Arc::clone(&self.sync_fault), Arc::clone(&self.durable_cursors), ); + #[cfg(feature = "shielded")] + let platform_wallet = { + let mut wallet = platform_wallet; + wallet.shielded_coordinator = Some(Arc::clone(&self.shielded_coordinator)); + wallet + }; // Restore the platform-address provider from the slice read above — // the only area wired up today. `from_persisted` skips the live diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index b6f73922121..9b1928db08c 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -477,6 +477,12 @@ pub struct PlatformWallet { /// handles share them. #[cfg(feature = "shielded")] private_payment_restores: Arc>, + /// The manager-owned network coordinator slot. Wallet operations resolve + /// the configured coordinator through this slot so callers cannot pair a + /// wallet with a different same-network coordinator. + #[cfg(feature = "shielded")] + pub(crate) shielded_coordinator: + Option>>>>, } impl PlatformWallet { @@ -791,6 +797,36 @@ impl PlatformWallet { broadcaster: Arc, sync_fault: Arc, durable_cursors: crate::changeset::DurableCursors, + ) -> Self { + Self::new_with_coordinator_slot( + sdk, + wallet_id, + wallet_manager, + generation, + lock_notify, + persister, + broadcaster, + sync_fault, + durable_cursors, + #[cfg(feature = "shielded")] + None, + ) + } + + #[allow(clippy::too_many_arguments)] + pub(crate) fn new_with_coordinator_slot( + sdk: Arc, + wallet_id: WalletId, + wallet_manager: Arc>>, + generation: Arc, + lock_notify: Arc, + persister: Arc, + broadcaster: Arc, + sync_fault: Arc, + durable_cursors: crate::changeset::DurableCursors, + #[cfg(feature = "shielded")] shielded_coordinator: Option< + Arc>>>, + >, ) -> Self { // Build the per-wallet persister handle once and share it with // the sub-wallets that need to queue their own changesets @@ -882,9 +918,40 @@ impl PlatformWallet { shielded_detached: Arc::new(std::sync::atomic::AtomicBool::new(false)), #[cfg(feature = "shielded")] private_payment_restores: Arc::default(), + #[cfg(feature = "shielded")] + shielded_coordinator, } } + #[cfg(feature = "shielded")] + pub(crate) async fn resolve_shielded_coordinator( + &self, + supplied: &Arc, + ) -> Result, PlatformWalletError> { + if supplied.network() != self.network() { + return Err(PlatformWalletError::InvalidParameter(format!( + "the shielded coordinator is for {:?}, this wallet for {:?}", + supplied.network(), + self.network(), + ))); + } + if let Some(slot) = &self.shielded_coordinator { + let configured = slot.read().await.clone().ok_or_else(|| { + PlatformWalletError::ShieldedStoreError( + "shielded support is not configured on this wallet manager".to_string(), + ) + })?; + if !Arc::ptr_eq(&configured, supplied) { + return Err(PlatformWalletError::InvalidParameter( + "the supplied shielded coordinator is not owned by this wallet manager" + .to_string(), + )); + } + return Ok(configured); + } + Ok(Arc::clone(supplied)) + } + /// Bind a shielded (Orchard) sub-wallet to this `PlatformWallet`. /// /// Derives ZIP-32 Orchard keys for every entry of `accounts` @@ -918,13 +985,7 @@ impl PlatformWallet { accounts: &[u32], coordinator: &Arc, ) -> Result<(), PlatformWalletError> { - if coordinator.network() != self.network() { - return Err(PlatformWalletError::InvalidParameter(format!( - "the shielded coordinator is for {:?}, this wallet for {:?}", - coordinator.network(), - self.network(), - ))); - } + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; // Fence generation teardown across attachment validation, host // viewing-key persistence, and coordinator/handle installation. let _lifecycle = self.core().generation_payment_guard().await; @@ -1071,13 +1132,7 @@ impl PlatformWallet { coordinator: &Arc, ) -> Result { use super::shielded::{AccountViewingKeys, SubwalletId}; - if coordinator.network() != self.network() { - return Err(PlatformWalletError::InvalidParameter(format!( - "the shielded coordinator is for {:?}, this wallet for {:?}", - coordinator.network(), - self.network(), - ))); - } + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; // Keep the generation alive from attachment validation through the // persisted snapshot read and coordinator/handle installation. let _lifecycle = self.core().generation_payment_guard().await; @@ -3040,6 +3095,8 @@ impl Clone for PlatformWallet { shielded_detached: self.shielded_detached.clone(), #[cfg(feature = "shielded")] private_payment_restores: self.private_payment_restores.clone(), + #[cfg(feature = "shielded")] + shielded_coordinator: self.shielded_coordinator.clone(), } } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index c9a6cd8d760..886fc9a0772 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -121,6 +121,7 @@ impl PlatformWallet { identity_id: &Identifier, coordinator: &Arc, ) -> Result<[u8; 43], PlatformWalletError> { + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; // Do not publish a key from a mis-associated mnemonic. A first bind // has no persisted FVK against which to detect a wrong seed. let root = key_wallet::wallet::root_extended_keys::RootExtendedPrivKey::new_master(seed) @@ -144,7 +145,11 @@ impl PlatformWallet { self.wallet_id(), ))); } + let clear_generation = coordinator.clear_generation(); let _operation = coordinator.operation_guard().await; + if coordinator.clear_generation() != clear_generation { + return Err(PlatformWalletError::ShieldedNotBound); + } // Held until the address is returned, so the identity cannot move to // another slot between the check below and the bind of the account // that slot selects. Publication rechecks it (see @@ -156,7 +161,6 @@ impl PlatformWallet { // replaces the registration, so another bind landing in between // would have its ordinary accounts dropped by this stale snapshot. let _config = self.shielded_config_lock.lock().await; - let clear_generation = coordinator.clear_generation(); let mut accounts = self.shielded_account_indices().await; if accounts.is_empty() { return Err(PlatformWalletError::ShieldedNotBound); @@ -358,6 +362,7 @@ impl PlatformWallet { memo: [u8; 36], prover: P, ) -> Result<(), PlatformWalletError> { + let coordinator = self.resolve_shielded_coordinator(coordinator).await?; { let _placement = self.identity.identity_placement.read().await; self.tip_source_account(seed, source).await?; From 0f73c1bee580b1217526912d6a661f6fc2613a2b Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 22:06:21 +0000 Subject: [PATCH 38/41] fix(wallet): borrow resolved shielded coordinator --- packages/rs-platform-wallet/src/wallet/platform_wallet.rs | 4 ++-- packages/rs-platform-wallet/src/wallet/shielded/tips.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 9b1928db08c..807fa056eec 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -990,7 +990,7 @@ impl PlatformWallet { // viewing-key persistence, and coordinator/handle installation. let _lifecycle = self.core().generation_payment_guard().await; let _config = self.shielded_config_lock.lock().await; - self.bind_shielded_locked_unfenced(seed, accounts, coordinator) + self.bind_shielded_locked_unfenced(seed, accounts, &coordinator) .await } @@ -1108,7 +1108,7 @@ impl PlatformWallet { // because the loop above proved the derived keys equal the // persisted ones: the rows the restore filters on are unchanged // by that write. - self.install_shielded_views(account_views, coordinator, start, snapshot_generation) + self.install_shielded_views(account_views, &coordinator, start, snapshot_generation) .await } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs index 886fc9a0772..2a4a1a54f18 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/tips.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/tips.rs @@ -168,7 +168,7 @@ impl PlatformWallet { #[cfg(test)] test_hooks::after_snapshot(self).await; accounts.push(account); - self.bind_shielded_locked_unfenced(seed, &accounts, coordinator) + self.bind_shielded_locked_unfenced(seed, &accounts, &coordinator) .await?; #[cfg(test)] test_hooks::after_bind(self).await; @@ -189,7 +189,7 @@ impl PlatformWallet { *identity_id, PreparedTipAccount { account, - coordinator: Arc::downgrade(coordinator), + coordinator: Arc::downgrade(&coordinator), clear_generation, }, ); @@ -389,7 +389,7 @@ impl PlatformWallet { #[cfg(test)] test_hooks::before_spend(self).await; self.shielded_transfer_to( - coordinator, + &coordinator, seed, account, ¤t.address, From ff362496235e62726a1222ba1770b7683f435456 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 22:06:58 +0000 Subject: [PATCH 39/41] fix(wallet): pass resolved coordinator to restore --- packages/rs-platform-wallet/src/wallet/platform_wallet.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 807fa056eec..f953ab715f9 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -1195,7 +1195,7 @@ impl PlatformWallet { } // Hand the already-loaded snapshot to the install step so the // restore doesn't pay a second full persister load. - self.install_shielded_views(account_views, coordinator, start, snapshot_generation) + self.install_shielded_views(account_views, &coordinator, start, snapshot_generation) .await?; Ok(true) } From 38f76dd4d82540a0626afe92a62fd397cbbbf002 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 23:05:57 +0000 Subject: [PATCH 40/41] fix(wallet): satisfy clippy coordinator borrow --- packages/rs-platform-wallet/src/wallet/platform_wallet.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index f953ab715f9..9f3263167b7 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -1108,7 +1108,7 @@ impl PlatformWallet { // because the loop above proved the derived keys equal the // persisted ones: the rows the restore filters on are unchanged // by that write. - self.install_shielded_views(account_views, &coordinator, start, snapshot_generation) + self.install_shielded_views(account_views, coordinator, start, snapshot_generation) .await } From 59759624734854ba478902514a04004f36b7d16f Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 14 Nov 2026 08:23:41 -0600 Subject: [PATCH 41/41] test(platform-wallet): bind test wallets to the manager-owned coordinator Manager-created wallets now accept only their manager's configured shielded coordinator, and a coordinator must match the wallet's network. The expiry fixture and the restart test configured no manager coordinator, and the viewing-key bind fixture built Mainnet wallets for a Testnet coordinator, so 20 tests failed at bind. Co-Authored-By: Claude Opus 5.5 --- .../network/private_contact_requests.rs | 23 +++++++++++++------ .../wallet/shielded/viewing_key_bind_tests.rs | 7 +++++- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs index 38d02cd6441..1780ea30e91 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/private_contact_requests.rs @@ -9966,12 +9966,14 @@ mod tests { .await; let dir = tempfile::tempdir().expect("temporary shielded store"); let db_path = dir.path().join("tree.sqlite"); - let coordinator = Arc::new(NetworkShieldedCoordinator::new( - Arc::clone(&wallet.identity().sdk), - Network::Testnet, - db_path.clone(), - FileBackedShieldedStore::open_path(&db_path, 100).expect("the store"), - )); + manager + .configure_shielded(&db_path) + .await + .expect("configured"); + let coordinator = manager + .shielded_coordinator() + .await + .expect("the manager's coordinator"); // Bound, the coordinator holds the wallet's persister, on which it // notes the discharge. wallet @@ -12835,7 +12837,6 @@ mod tests { // The restart: the reply is not in the store and the host restores // nothing; only the bind can. - let after = coordinator_at(db_path); let restarted_manager = PlatformWalletManager::new( Arc::new(dashpay_sdk(&[&alice, &bob], vec![], PlatformVersion::latest(), None).await), kept, @@ -12890,6 +12891,14 @@ mod tests { "{public:?}" ); + restarted_manager + .configure_shielded(&db_path) + .await + .expect("configured"); + let after = restarted_manager + .shielded_coordinator() + .await + .expect("the manager's coordinator"); restarted .bind_shielded(&seed(BOB_PHRASE), &[0], &after) .await diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index f83802708d6..770f20ec431 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -185,7 +185,12 @@ where { let (wallet_manager, wallet_id, balance, _signer) = funded_wallet_manager(StandardAccountType::BIP44Account).await; - let sdk = Arc::new(dash_sdk::Sdk::new_mock()); + let sdk = Arc::new( + dash_sdk::SdkBuilder::new_mock() + .with_network(Network::Testnet) + .build() + .unwrap(), + ); let spv = Arc::new(crate::spv::SpvRuntime::new( Arc::clone(&wallet_manager), Arc::new(crate::events::PlatformEventManager::new(Vec::new())),