From 2a25d6621cfe4f758036bbd951316e21a949d80f Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sat, 14 Nov 2026 16:32:23 -0800 Subject: [PATCH 1/3] feat(kotlin-sdk): top up someone else's identity from the Core balance Kotlin side of dashpay/platform#5924, on top of the Rust/FFI change. Persistence: Room v17 adds the asset-lock sidecars SQLite (V019-V021) and Swift already keep - operationId (16 bytes), shieldedRecipientRaw43 (43) and identityRecipientId (32) - with a unique (walletId, operationId) index and immutability triggers. The handler stores each sidecar in the round of its row's upsert, refuses a different value (constraint) and accepts the same one, carries the values through later upserts, and fails a load whose row is missing or malformed. DrainCompleted (6) is now terminal like Consumed, as in Swift and SQLite. The handler declares bits 13, 14 and 17. JNI: trampolines for the three persist/load pairs, each wired only when the bridge overrides both methods; bindings for the external top-up, the recorded-recipient resume and the recipient assignment; TrackedAssetLock carries the identity recipient and the unassigned flag. Code 81 maps to AssetLockRecipientUnknown. Example app: Top Up from Core resumes through the recorded recipient and lists unassigned unbound locks with an assign action. Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 101 + .../assetlock/IdentityAssetLockRecovery.kt | 21 +- .../ui/credits/TopUpIdentityFromCoreScreen.kt | 134 +- .../IdentityAssetLockRecoveryTest.kt | 24 + packages/kotlin-sdk/PARITY_SUMMARY.md | 15 +- .../17.json | 4309 +++++++++++++++++ .../dashfoundation/dashsdk/FfiSmokeTest.kt | 115 + .../persistence/DashDatabaseMigrationTest.kt | 58 +- .../wallet/WalletManagerRoundTripTest.kt | 66 + .../dashsdk/credits/IdentityCredits.kt | 193 + .../dashsdk/errors/DashSdkError.kt | 20 + .../ffi/AssetLockRecoveryNativeData.kt | 23 +- .../dashsdk/ffi/CreditsNative.kt | 44 + .../dashsdk/ffi/NativePersistenceBridge.kt | 106 + .../dashsdk/persistence/DashDatabase.kt | 67 +- .../PlatformWalletPersistenceHandler.kt | 214 +- .../dashsdk/persistence/dao/AssetLockDao.kt | 28 +- .../persistence/entities/AssetLockEntity.kt | 46 +- .../dashsdk/wallet/PlatformWalletManager.kt | 18 + .../dashsdk/wallet/TrackedAssetLock.kt | 33 +- .../dashsdk/credits/RecipientTopUpTest.kt | 184 + .../dashsdk/errors/DashSdkErrorTest.kt | 12 + .../AssetLockSidecarPersistenceTest.kt | 292 ++ .../dashsdk/persistence/DashDatabaseTest.kt | 9 +- .../PlatformWalletPersistenceHandlerTest.kt | 12 +- .../dashsdk/wallet/TrackedAssetLockTest.kt | 39 + packages/rs-unified-sdk-jni/src/credits.rs | 169 +- .../rs-unified-sdk-jni/src/persistence.rs | 494 +- .../rs-unified-sdk-jni/src/wallet_manager.rs | 17 +- 29 files changed, 6811 insertions(+), 52 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/AssetLockSidecarPersistenceTest.kt diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index ff3277332c9..b5b559cd0da 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -4,6 +4,7 @@ "description": "Executable current Kotlin/Swift parity truth for the correctness, persistence, recovery, shared-policy, and immediate example-app capabilities audited from the PR #3999 baseline.", "declared_persistence_capabilities": [ "asset_lock_funding_indices", + "asset_lock_identity_recipients", "asset_lock_operation_ids", "atomic_changesets", "invitations", @@ -46,6 +47,7 @@ "on_persist_private_contact_scan_state_fn": "packages/rs-platform-wallet-ffi/src/persistence.rs", "on_persist_shielded_viewing_keys_fn": "packages/rs-platform-wallet-ffi/src/persistence.rs", "platform_address_wallet_addresses_with_balances": "packages/rs-platform-wallet-ffi/src/platform_addresses/wallet.rs", + "platform_wallet_assign_identity_top_up_recipient": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_claim_invitation": "packages/rs-platform-wallet-ffi/src/invitation.rs", "platform_wallet_create_document_with_signer": "packages/rs-platform-wallet-ffi/src/document.rs", "platform_wallet_create_invitation": "packages/rs-platform-wallet-ffi/src/invitation.rs", @@ -65,12 +67,14 @@ "platform_wallet_manager_shielded_wallet_drain_status": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", "platform_wallet_manager_spv_rescan_filters": "packages/rs-platform-wallet-ffi/src/spv.rs", "platform_wallet_manager_sync_fault_detected": "packages/rs-platform-wallet-ffi/src/manager.rs", + "platform_wallet_resume_identity_top_up_to_recorded_recipient_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_resume_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_sync_contested_dpns_names": "packages/rs-platform-wallet-ffi/src/dpns.rs", "platform_wallet_sync_private_contact_requests": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_token_purchase": "packages/rs-platform-wallet-ffi/src/tokens/purchase.rs", "platform_wallet_token_transfer": "packages/rs-platform-wallet-ffi/src/tokens/transfer.rs", "platform_wallet_token_update_config": "packages/rs-platform-wallet-ffi/src/tokens/update_config.rs", + "platform_wallet_top_up_external_identity_with_funding_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", "platform_wallet_top_up_from_addresses_with_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", "platform_wallet_topup_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_tracked_asset_locks_free": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", @@ -1160,6 +1164,103 @@ } ] }, + { + "id": "identity.top_up_any_identity_from_core", + "title": "Top up any identity from the Core balance, its recorded recipient kept across restart, assign and resume", + "area": "recovery", + "shared_apis": [ + "platform_wallet_top_up_external_identity_with_funding_signer", + "platform_wallet_resume_identity_top_up_to_recorded_recipient_signer", + "platform_wallet_assign_identity_top_up_recipient", + "platform_wallet_tracked_asset_locks_list" + ], + "required_persistence_capabilities": [ + "asset_lock_identity_recipients", + "atomic_changesets", + "tracked_asset_locks", + "wallet_restore" + ], + "hosts": { + "swift": { + "sdk": "unsupported", + "example_app": "unsupported", + "restart": "required", + "reason": "The Swift bindings, the SwiftData identity-recipient sidecar and the recovery UI are a separate change landing in parallel (dashpay/platform#5924 PR C)." + }, + "kotlin": { + "sdk": "partial", + "example_app": "partial", + "restart": "required", + "reason": "Room v17 keeps the operation-UUID, shielded-recipient and identity-recipient sidecars (immutable, carried through upserts, fail-closed loads) and the handler attests bits 13, 14 and 17; JNI binds the external top-up, the recorded-recipient resume and the assignment, and TrackedAssetLock carries the recipient and the unassigned flag. The Top Up from Core screen resumes through the recorded recipient and assigns unassigned locks, but has no screen for the external top-up itself. Remaining gates: a funded testnet run of external top-up, interrupted resume across process death, and assignment." + } + }, + "verification": [ + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/AssetLockSidecarPersistenceTest.kt", + "id": "shouldStoreEachSidecarAfterItsUpsertInTheSameRoundAndLoadItBack", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:testDebugUnitTest --tests '*AssetLockSidecarPersistenceTest*'", + "covers_restart": false + }, + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/AssetLockSidecarPersistenceTest.kt", + "id": "shouldAcceptTheSameValueAgainAndRefuseADifferentOne", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:testDebugUnitTest --tests '*AssetLockSidecarPersistenceTest*'", + "covers_restart": false + }, + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt", + "id": "shouldResumeEveryIdentityTopUpLockByOutpointWithoutNamingAnIdentity", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:testDebugUnitTest --tests '*RecipientTopUpTest*'", + "covers_restart": false + }, + { + "host": "kotlin", + "kind": "device", + "file": "packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/WalletManagerRoundTripTest.kt", + "id": "assetLockSidecarsRoundTripThroughAReload", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:connectedDebugAndroidTest", + "covers_restart": true + }, + { + "host": "kotlin", + "kind": "device", + "file": "packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt", + "id": "assetLockSidecarCapabilitiesNeedBothOverridesOfTheirPair", + "command": "cd packages/kotlin-sdk && ./gradlew :sdk:connectedDebugAndroidTest", + "covers_restart": false + }, + { + "host": "kotlin", + "kind": "unit", + "file": "packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecoveryTest.kt", + "id": "should list an unassigned unbound topup apart and never as resumable", + "command": "cd packages/kotlin-sdk && ./gradlew :app:testDebugUnitTest", + "covers_restart": false + }, + { + "host": "shared", + "kind": "unit", + "file": "packages/rs-platform-wallet/src/wallet/asset_lock/build.rs", + "id": "should_assign_an_unassigned_unbound_top_up_lock_once", + "command": "cargo test -p platform-wallet should_assign_an_unassigned_unbound_top_up_lock_once", + "covers_restart": false + }, + { + "host": "shared", + "kind": "integration", + "file": "packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs", + "id": "should_preserve_identity_recipient_when_later_snapshot_lacks_it_and_reject_a_change", + "command": "cargo test -p platform-wallet-storage --test integration should_preserve_identity_recipient_when_later_snapshot_lacks_it_and_reject_a_change", + "covers_restart": true + } + ] + }, { "id": "core.compact_filter_rescan", "title": "User-triggered compact-filter rescan", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt index 7c19cb3af97..e5ad810d156 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt @@ -7,6 +7,13 @@ object IdentityAssetLockRecovery { fun registrations(rows: List): List = rows.filter { it.fundingType == TrackedAssetLock.FundingType.IDENTITY_REGISTRATION } + /** + * Top-up locks a resume pays: bound ones for the selected identity, and + * unbound ones Rust has not flagged unassigned. A resume + * (`IdentityCredits.resumeTopUpToRecordedRecipient`) pays the identity + * the lock is for — an unbound lock's recorded recipient, which may be + * someone else's identity — so the screen's identity is never passed. + */ fun topUps( rows: List, selectedIdentityIndex: Int, @@ -14,9 +21,18 @@ object IdentityAssetLockRecovery { rows.filter { (it.fundingType == TrackedAssetLock.FundingType.IDENTITY_TOP_UP && it.registrationIndex == selectedIdentityIndex) || - it.fundingType == TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND + (it.fundingType == TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND && + !it.identityRecipientUnassigned) } + /** + * Unbound top-up locks recording no identity (Rust's + * `identity_recipient_unassigned`): no resume pays them, so they are + * listed apart, for the user to assign an identity first. + */ + fun unassignedTopUps(rows: List): List = + rows.filter { it.identityRecipientUnassigned } + /** Resume-only dispatch: callers cannot accidentally select a fresh-funding operation. */ suspend fun submitRegistrationResume( lock: TrackedAssetLock, @@ -32,5 +48,6 @@ object IdentityAssetLockRecovery { /** Display-only; submission passes the snapshot's original bytes/vout. */ fun label(lock: TrackedAssetLock): String = lock.outpointTxid.reversedArray().joinToString("") { "%02x".format(it) }.take(8) + - ":${lock.outpointVout} · ${lock.status.name.lowercase().replace('_', ' ')}" + ":${lock.outpointVout} · ${lock.status.name.lowercase().replace('_', ' ')}" + + (lock.identityRecipient?.let { " → " + it.joinToString("") { b -> "%02x".format(b) }.take(8) } ?: "") } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt index 219c9286191..63b3dd955aa 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt @@ -41,6 +41,7 @@ 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.hexToBytes +import org.dashfoundation.example.util.toHex import org.dashfoundation.dashsdk.wallet.TrackedAssetLock import org.dashfoundation.example.services.assetlock.IdentityAssetLockRecovery @@ -61,6 +62,17 @@ import org.dashfoundation.example.services.assetlock.IdentityAssetLockRecovery * * Amount is entered in **duffs** (Dash * 1e8), matching the create-identity * screen's `amountText`. + * + * A resume goes through + * [org.dashfoundation.dashsdk.credits.IdentityCredits.resumeTopUpToRecordedRecipient] + * (`platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`): + * the lock pays the identity it is for — a bound lock this identity, an + * unbound lock the identity its row recorded, possibly someone else's — and + * never the identity this screen shows by default. Unbound locks Rust reports + * as unassigned (`TrackedAssetLock.identityRecipientUnassigned`) are listed + * apart with an "assign identity" action + * ([org.dashfoundation.dashsdk.credits.IdentityCredits.assignTopUpRecipient]); + * once assigned they resume like any other (dashpay/platform#5924). */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -83,24 +95,33 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon var recoveryLocks by remember { mutableStateOf(emptyList()) } var selectedRecoveryLock by remember { mutableStateOf(null) } var recoveryLoadError by remember { mutableStateOf(null) } + var unassignedLocks by remember { mutableStateOf(emptyList()) } + var selectedUnassignedLock by remember { mutableStateOf(null) } + var assignIdentityHex by rememberSaveable(identityIdHex) { mutableStateOf(identityIdHex) } + var isAssigning by remember { mutableStateOf(false) } + var paidIdentityHex by remember { mutableStateOf(null) } + // Bumped after an assignment so the tracked-lock snapshot is re-read. + var reloadKey by remember { mutableStateOf(0) } - LaunchedEffect(manager, wallet, identity?.identityIndex, mode) { + LaunchedEffect(manager, wallet, identity?.identityIndex, mode, reloadKey) { recoveryLoadError = null - recoveryLocks = try { + val rows = try { val mgr = manager val currentWallet = wallet - val currentIdentityIndex = identity?.identityIndex - if (mgr == null || currentWallet == null || currentIdentityIndex == null) emptyList() else { - IdentityAssetLockRecovery.topUps( - mgr.trackedIdentityRecoveryAssetLocks(currentWallet.walletId), - currentIdentityIndex, - ) + if (mgr == null || currentWallet == null) emptyList() else { + mgr.trackedIdentityRecoveryAssetLocks(currentWallet.walletId) } } catch (e: Exception) { recoveryLoadError = e.message ?: "Failed to load tracked identity top-up locks" emptyList() } + val currentIdentityIndex = identity?.identityIndex + recoveryLocks = if (currentIdentityIndex == null) emptyList() else { + IdentityAssetLockRecovery.topUps(rows, currentIdentityIndex) + } + unassignedLocks = IdentityAssetLockRecovery.unassignedTopUps(rows) selectedRecoveryLock = recoveryLocks.firstOrNull() + selectedUnassignedLock = unassignedLocks.firstOrNull() } val amount = amountText.toLongOrNull() @@ -134,6 +155,9 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon LabeledContent("Identity", identity?.mainDpnsName ?: identityIdHex.take(16) + "…") LabeledContent("Current balance", "${identity?.balance ?: 0} credits") newBalance?.let { LabeledContent("New balance", "$it credits") } + paidIdentityHex?.takeIf { it != identityIdHex }?.let { + LabeledContent("Paid identity", it.take(16) + "…") + } } FormSection(title = "Funding") { @@ -170,11 +194,42 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon onSelected = { selectedRecoveryLock = it }, ) Text( - "Resumes this exact outpoint. No replacement funding transaction is built.", + "Resumes this exact outpoint to the identity the lock pays. " + + "No replacement funding transaction is built.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } + if (unassignedLocks.isNotEmpty()) { + UnassignedTopUpLocks( + locks = unassignedLocks, + selected = selectedUnassignedLock ?: unassignedLocks.first(), + onSelected = { selectedUnassignedLock = it }, + identityHex = assignIdentityHex, + onIdentityHexChange = { assignIdentityHex = it }, + isAssigning = isAssigning, + onAssign = assign@{ + val mgr = manager ?: return@assign + val w = wallet ?: return@assign + val lock = selectedUnassignedLock ?: unassignedLocks.first() + isAssigning = true + scope.launch { + try { + mgr.identityCredits.assignTopUpRecipient( + walletHandle = w.handle, + lock = lock, + identityId = assignIdentityHex.hexToBytes(), + ) + reloadKey++ + } catch (e: Exception) { + error = e.message ?: "Assigning the identity failed" + } finally { + isAssigning = false + } + } + }, + ) + } } else { Text( "Funded by building and broadcasting a new Core asset lock " + @@ -210,14 +265,15 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon val balance = if (mode == TopUpCoreMode.EXISTING_LOCK) { val lock = selectedRecoveryLock ?: error("No resumable identity top-up lock is selected") - IdentityAssetLockRecovery.submitTopUpResume(lock) { - mgr.identityCredits.resumeTopUpWithExistingAssetLock( + val paid = IdentityAssetLockRecovery.submitTopUpResume(lock) { + mgr.identityCredits.resumeTopUpToRecordedRecipient( walletHandle = w.handle, - identityId = idBytes, lock = it, coreSignerHandle = mgr.mnemonicResolverHandle, ) } + paidIdentityHex = paid.identityId.toHex() + paid.newBalance } else { mgr.identityCredits.topUpFromCore( walletHandle = w.handle, @@ -242,6 +298,60 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon ErrorAlertDialog(message = error, onDismiss = { error = null }) } +/** + * Unbound top-up locks that record no identity: Rust refuses to resume them + * until the user assigns the identity they pay, which is permanent. The id is + * entered as hex and defaults to the screen's identity. + */ +@Composable +private fun UnassignedTopUpLocks( + locks: List, + selected: TrackedAssetLock, + onSelected: (TrackedAssetLock) -> Unit, + identityHex: String, + onIdentityHexChange: (String) -> Unit, + isAssigning: Boolean, + onAssign: () -> Unit, +) { + Text( + "Unassigned top-up locks", + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.testTag("topUpIdentityFromCore.unassigned.header"), + ) + Text( + "These locks were rebuilt from the chain and do not record which identity they top up. " + + "Assign one (permanently) before resuming it.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + AccessiblePicker( + label = "Unassigned asset lock", + options = locks, + selected = selected, + optionLabel = IdentityAssetLockRecovery::label, + testTag = "topUpIdentityFromCore.unassigned.outpoint", + onSelected = onSelected, + ) + OutlinedTextField( + value = identityHex, + onValueChange = { onIdentityHexChange(it.trim().lowercase()) }, + label = { Text("Identity id (hex)") }, + singleLine = true, + modifier = Modifier.fillMaxWidth().testTag("topUpIdentityFromCore.unassigned.identity"), + ) + SubmitButton( + text = "Assign identity", + isLoading = isAssigning, + enabled = !isAssigning && isIdentityIdHex(identityHex), + modifier = Modifier.fillMaxWidth().testTag("topUpIdentityFromCore.unassigned.assign"), + onClick = onAssign, + ) +} + +/** A 32-byte identity id as 64 hex characters. */ +internal fun isIdentityIdHex(value: String): Boolean = + value.length == 64 && value.all { it in '0'..'9' || it in 'a'..'f' } + private enum class TopUpCoreMode(val label: String) { NEW_LOCK("Build new asset lock"), EXISTING_LOCK("Resume existing asset lock"), diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecoveryTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecoveryTest.kt index ad3c95ada0c..14a0a44efb3 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecoveryTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecoveryTest.kt @@ -37,6 +37,26 @@ class IdentityAssetLockRecoveryTest { ) } + @Test + fun `should list an unassigned unbound topup apart and never as resumable`() { + val recorded = lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, 2, recipient = ByteArray(32) { 9 }) + val unassigned = lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, 3, unassigned = true) + val bound = lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP, 4) + val rows = listOf(recorded, unassigned, bound) + + assertEquals(listOf(recorded, bound), IdentityAssetLockRecovery.topUps(rows, selectedIdentityIndex = 4)) + assertEquals(listOf(unassigned), IdentityAssetLockRecovery.unassignedTopUps(rows)) + } + + @Test + fun `should label an unbound topup with the identity it pays`() { + val label = IdentityAssetLockRecovery.label( + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, 2, recipient = ByteArray(32) { 0x0a }), + ) + + assertTrue(label.endsWith(" → 0a0a0a0a")) + } + @Test fun `display formatting does not mutate submission outpoint`() { val lock = lock(TrackedAssetLock.FundingType.IDENTITY_REGISTRATION, 7) @@ -83,6 +103,8 @@ class IdentityAssetLockRecoveryTest { type: TrackedAssetLock.FundingType, vout: Int, registrationIndex: Int = 4, + recipient: ByteArray? = null, + unassigned: Boolean = false, ) = TrackedAssetLock( outpointTxid = ByteArray(32) { it.toByte() }, outpointVout = vout, @@ -91,5 +113,7 @@ class IdentityAssetLockRecoveryTest { registrationIndex = registrationIndex, instantLockPresent = false, chainLockHeight = 0, + identityRecipient = recipient, + identityRecipientUnassigned = unassigned, ) } diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index 4f8eef43841..332c0ee8571 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -2,23 +2,23 @@ # Kotlin/Swift executable parity summary Audit baseline: `PR #3999 @ 6dbc72a54df72d26eb9c4a014b425d2b95134e4e` -Capabilities tracked: **30** +Capabilities tracked: **31** ## Status counts | Host | Surface | Supported | Partial | Unsupported | Not applicable | | --- | --- | ---: | ---: | ---: | ---: | -| Swift | SDK | 17 | 11 | 1 | 1 | -| Swift | Example app | 5 | 14 | 2 | 9 | -| Kotlin | SDK | 14 | 14 | 1 | 1 | -| Kotlin | Example app | 6 | 13 | 1 | 10 | +| Swift | SDK | 17 | 11 | 2 | 1 | +| Swift | Example app | 5 | 14 | 3 | 9 | +| Kotlin | SDK | 14 | 15 | 1 | 1 | +| Kotlin | Example app | 6 | 14 | 1 | 10 | ## Restart coverage | Host | Tested | Required | Not applicable | | --- | ---: | ---: | ---: | -| Swift | 2 | 10 | 18 | -| Kotlin | 5 | 8 | 17 | +| Swift | 2 | 11 | 18 | +| Kotlin | 5 | 9 | 17 | ## Capability status @@ -36,6 +36,7 @@ Capabilities tracked: **30** | `dashpay.private_contact_requests` | partial / partial / required | partial / partial / required | | `dashpay.private_contact_request_scan_state` | partial / partial / required | partial / not-applicable / required | | `identity.asset_lock_resume` | supported / partial / required | partial / partial / required | +| `identity.top_up_any_identity_from_core` | unsupported / unsupported / required | partial / partial / required | | `core.compact_filter_rescan` | supported / partial / not_applicable | partial / partial / not_applicable | | `dpns.contested_names_by_identity` | supported / partial / not_applicable | partial / partial / required | | `persistence.sync_fault_latch` | supported / not-applicable / not_applicable | supported / not-applicable / not_applicable | 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..459c972d0de --- /dev/null +++ b/packages/kotlin-sdk/sdk/schemas/org.dashfoundation.dashsdk.persistence.DashDatabase/17.json @@ -0,0 +1,4309 @@ +{ + "formatVersion": 1, + "database": { + "version": 17, + "identityHash": "120850a8bfaeaa6bf4bb04b91c941ff7", + "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, `operationId` BLOB, `shieldedRecipientRaw43` BLOB, `identityRecipientId` BLOB, 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 + }, + { + "fieldPath": "operationId", + "columnName": "operationId", + "affinity": "BLOB" + }, + { + "fieldPath": "shieldedRecipientRaw43", + "columnName": "shieldedRecipientRaw43", + "affinity": "BLOB" + }, + { + "fieldPath": "identityRecipientId", + "columnName": "identityRecipientId", + "affinity": "BLOB" + } + ], + "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`)" + }, + { + "name": "index_asset_locks_walletId_operationId", + "unique": true, + "columnNames": [ + "walletId", + "operationId" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_asset_locks_walletId_operationId` ON `${TABLE_NAME}` (`walletId`, `operationId`)" + } + ] + }, + { + "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, `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": "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, `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": "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, '120850a8bfaeaa6bf4bb04b91c941ff7')" + ] + } +} \ No newline at end of file diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt index 419de77c636..e41c263f46e 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt @@ -218,6 +218,48 @@ class FfiSmokeTest { } } + /** + * Each asset-lock sidecar capability (bits 13, 14 and 17) is attested + * only for a bridge that declares it AND overrides both the persist and + * the load of its pair (`overrides_sidecar` in rs-unified-sdk-jni): an + * inherited no-op persist would acknowledge a value it never kept, an + * inherited load would restore every lock without it. The Room handler + * attests all three. + */ + @Test + fun assetLockSidecarCapabilitiesNeedBothOverridesOfTheirPair() { + NativeLoader.ensureLoaded() + val operation = NativePersistenceBridge.CAPABILITY_ASSET_LOCK_OPERATION_IDS + val shielded = NativePersistenceBridge.CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS + val identity = NativePersistenceBridge.CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS + fun effective(bridge: NativePersistenceBridge): Long = + WalletManagerNative.nativeEffectivePersistenceCapabilityBits(bridge) and + (operation or shielded or identity) + + assertEquals("every pair", operation or shielded or identity, effective(SidecarBridge.Full())) + assertEquals("identity persist only", 0L, effective(SidecarBridge.IdentityPersistOnly())) + assertEquals("identity load only", 0L, effective(SidecarBridge.IdentityLoadOnly())) + assertEquals("operation pair only", operation, effective(SidecarBridge.OperationPairOnly())) + assertEquals( + "every pair, not declared", + 0L, + effective(object : SidecarBridge.Full() { + override fun persistenceCapabilitiesBits(): Long = ATOMIC_CHANGESETS + }), + ) + + val db = DashDatabase.createInMemory(ApplicationProvider.getApplicationContext()) + try { + assertEquals( + "the Room handler", + operation or shielded or identity, + effective(PlatformWalletPersistenceHandler(db, Dispatchers.Unconfined)), + ) + } finally { + db.close() + } + } + /** * Rust↔Kotlin persistence-descriptor lockstep. The trampolines resolve * each bridge method by (name, descriptor) only when its slot first @@ -415,5 +457,78 @@ private abstract class ScanStateBridge : NativePersistenceBridge() { } } +/** + * Bridges declaring the three asset-lock sidecar capabilities with some of + * the overrides each depends on, for + * [FfiSmokeTest.assetLockSidecarCapabilitiesNeedBothOverridesOfTheirPair]. + * Each concrete class declares exactly the overrides its name says. + */ +private abstract class SidecarBridge : NativePersistenceBridge() { + override fun persistenceCapabilitiesVersion(): Int = 1 + + override fun persistenceCapabilitiesBits(): Long = + ATOMIC_CHANGESETS or WALLET_RESTORE or TRACKED_ASSET_LOCKS or + CAPABILITY_ASSET_LOCK_OPERATION_IDS or + CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS or + CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS + + open class Full : SidecarBridge() { + override fun onPersistAssetLockOperationId( + walletId: ByteArray, + outPoint: ByteArray, + operationId: ByteArray, + ): Int = 0 + + override fun onLoadAssetLockOperationId(walletId: ByteArray, outPoint: ByteArray): ByteArray? = null + + override fun onPersistAssetLockShieldedRecipient( + walletId: ByteArray, + outPoint: ByteArray, + recipientRaw43: ByteArray, + ): Int = 0 + + override fun onLoadAssetLockShieldedRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + null + + override fun onPersistAssetLockIdentityRecipient( + walletId: ByteArray, + outPoint: ByteArray, + identityId: ByteArray, + ): Int = 0 + + override fun onLoadAssetLockIdentityRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + null + } + + class IdentityPersistOnly : SidecarBridge() { + override fun onPersistAssetLockIdentityRecipient( + walletId: ByteArray, + outPoint: ByteArray, + identityId: ByteArray, + ): Int = 0 + } + + class IdentityLoadOnly : SidecarBridge() { + override fun onLoadAssetLockIdentityRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + null + } + + class OperationPairOnly : SidecarBridge() { + override fun onPersistAssetLockOperationId( + walletId: ByteArray, + outPoint: ByteArray, + operationId: ByteArray, + ): Int = 0 + + override fun onLoadAssetLockOperationId(walletId: ByteArray, outPoint: ByteArray): ByteArray? = null + } +} + +/** `PersistenceCapabilities::WALLET_RESTORE` (bit 7). */ +private const val WALLET_RESTORE: Long = 1L shl 7 + +/** `PersistenceCapabilities::TRACKED_ASSET_LOCKS` (bit 9). */ +private const val TRACKED_ASSET_LOCKS: Long = 1L shl 9 + /** `PersistenceCapabilities::ATOMIC_CHANGESETS` (bit 0). */ private const val ATOMIC_CHANGESETS: Long = 1L 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..cfd5923657a 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 @@ -1,9 +1,11 @@ package org.dashfoundation.dashsdk.persistence +import android.database.sqlite.SQLiteException import androidx.room.testing.MigrationTestHelper import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -740,13 +742,61 @@ class DashDatabaseMigrationTest { db.close() } + /** + * v16 → v17 adds the three nullable asset-lock sidecar columns, the + * unique `(walletId, operationId)` index and the immutability triggers. + * A pre-existing row reads back with no sidecar; a sidecar can then be + * set once, and changing it aborts, as the SQLite store's V019–V021 + * triggers make it. + */ + @Test + fun shouldAddTheAssetLockSidecarColumnsIndexAndTriggersFrom16To17() { + helper.createDatabase(dbName, 16).apply { + execSQL( + "INSERT INTO asset_locks (outPointHex, walletId, transactionBytes, fundingTypeRaw, " + + "identityIndexRaw, accountIndexRaw, amountDuffs, statusRaw, createdAt, updatedAt) " + + "VALUES ('aa:0', x'01', x'02', 2, 0, 0, 100000, 1, 0, 0)", + ) + execSQL( + "INSERT INTO asset_locks (outPointHex, walletId, transactionBytes, fundingTypeRaw, " + + "identityIndexRaw, accountIndexRaw, amountDuffs, statusRaw, createdAt, updatedAt) " + + "VALUES ('bb:0', x'01', x'02', 2, 0, 0, 100000, 1, 0, 0)", + ) + close() + } + + val db = helper.runMigrationsAndValidate(dbName, 17, true, DashDatabase.MIGRATION_16_17) + + db.query( + "SELECT operationId, shieldedRecipientRaw43, identityRecipientId FROM asset_locks " + + "WHERE outPointHex = 'aa:0'", + ).use { c -> + assertTrue(c.moveToFirst()) + assertTrue(c.isNull(0) && c.isNull(1) && c.isNull(2)) + } + db.execSQL("UPDATE asset_locks SET identityRecipientId = x'0C', operationId = x'0A' WHERE outPointHex = 'aa:0'") + // The same value again is not a change. + db.execSQL("UPDATE asset_locks SET identityRecipientId = x'0C' WHERE outPointHex = 'aa:0'") + assertThrows(SQLiteException::class.java) { + db.execSQL("UPDATE asset_locks SET identityRecipientId = x'0D' WHERE outPointHex = 'aa:0'") + } + assertThrows(SQLiteException::class.java) { + db.execSQL("UPDATE asset_locks SET operationId = NULL WHERE outPointHex = 'aa:0'") + } + // One wallet never records an operation UUID twice. + assertThrows(SQLiteException::class.java) { + db.execSQL("UPDATE asset_locks SET operationId = x'0A' WHERE outPointHex = 'bb:0'") + } + db.close() + } + /** The requested contiguous path from the pre-u64 v4 schema to latest. */ @Test fun migrate4ToLatest() { helper.createDatabase(dbName, 4).close() helper.runMigrationsAndValidate( dbName, - 16, + 17, true, DashDatabase.MIGRATION_4_5, DashDatabase.MIGRATION_5_6, @@ -760,16 +810,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 +837,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/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/WalletManagerRoundTripTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/WalletManagerRoundTripTest.kt index 77154af19e8..165110bbb73 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/WalletManagerRoundTripTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/wallet/WalletManagerRoundTripTest.kt @@ -8,6 +8,9 @@ import org.dashfoundation.dashsdk.Network import org.dashfoundation.dashsdk.Sdk import org.dashfoundation.dashsdk.config.SdkConfig import org.dashfoundation.dashsdk.persistence.DashDatabase +import org.dashfoundation.dashsdk.persistence.encodeOutPointHex +import org.dashfoundation.dashsdk.persistence.entities.AssetLockEntity +import org.dashfoundation.dashsdk.persistence.makeOutpoint import org.dashfoundation.dashsdk.security.WalletStorage import org.junit.After import org.junit.Assert.assertEquals @@ -102,6 +105,59 @@ class WalletManagerRoundTripTest { } } + /** + * The asset-lock sidecars through the REAL native load path: a manager + * over the Room handler attests bits 13, 14 and 17, and a reload hands + * each stored row's operation UUID and identity recipient to Rust through + * the `onLoadAssetLock*` trampolines, so the tracked-lock list reports + * the recorded recipient — and an unbound top-up recording none as + * unassigned. A malformed trampoline (wrong width, wrong descriptor, a + * missing row read as "none") fails the load or loses the recipient here. + */ + @Test + fun assetLockSidecarsRoundTripThroughAReload() = runBlocking { + val walletId: ByteArray + PlatformWalletManager(sdk, Network.TESTNET, db, walletStorage).use { manager -> + walletId = manager.createWallet( + mnemonic = testMnemonic, + name = "sidecar-round-trip", + createDefaultAccounts = true, + ).walletId + val capabilities = manager.persistenceCapabilities + assertTrue(capabilities.contains(PlatformWalletPersistenceCapabilities.ASSET_LOCK_OPERATION_IDS)) + assertTrue(capabilities.contains(PlatformWalletPersistenceCapabilities.ASSET_LOCK_SHIELDED_RECIPIENTS)) + assertTrue(capabilities.contains(PlatformWalletPersistenceCapabilities.ASSET_LOCK_IDENTITY_RECIPIENTS)) + } + + val lockTxid = ByteArray(32) { 0x22 } + val recipient = ByteArray(32) { 0x33 } + fun row(vout: Int, identityRecipient: ByteArray?, operationId: ByteArray?) = AssetLockEntity( + outPointHex = encodeOutPointHex(makeOutpoint(lockTxid, vout)), + walletId = walletId, + transactionBytes = MINIMAL_TRANSACTION, + fundingTypeRaw = TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND.raw, + identityIndexRaw = 0, + amountDuffs = 100_000, + statusRaw = TrackedAssetLock.Status.BROADCAST.raw, + operationId = operationId, + identityRecipientId = identityRecipient, + ) + db.assetLockDao().upsert(row(0, recipient, ByteArray(16) { 0x44 })) + db.assetLockDao().upsert(row(1, null, null)) + + PlatformWalletManager(sdk, Network.TESTNET, db, walletStorage).use { reloaded -> + reloaded.loadPersistedWallets() + val locks = reloaded.trackedIdentityRecoveryAssetLocks(walletId) + .filter { it.outpointTxid.contentEquals(lockTxid) } + .sortedBy { it.outpointVout } + assertEquals(listOf(0, 1), locks.map { it.outpointVout }) + assertTrue(recipient.contentEquals(locks[0].identityRecipient)) + assertEquals(false, locks[0].identityRecipientUnassigned) + assertNull(locks[1].identityRecipient) + assertTrue(locks[1].identityRecipientUnassigned) + } + } + /** * DashPay persist→wipe→restore→re-read round-trip through the REAL * native marshaling (the staging/seal/free pipeline in @@ -260,3 +316,13 @@ class WalletManagerRoundTripTest { } } } + +/** + * A consensus-decodable classic transaction (version 1, one input, one + * OP_RETURN output, lock time 0): the load path decodes a tracked lock's + * transaction and fails on bytes it cannot parse. + */ +private val MINIMAL_TRANSACTION: ByteArray = byteArrayOf(1, 0, 0, 0, 1) + + ByteArray(32) { 0x11 } + byteArrayOf(0, 0, 0, 0, 0, -1, -1, -1, -1) + + byteArrayOf(1) + byteArrayOf(-96, -122, 1, 0, 0, 0, 0, 0) + byteArrayOf(1, 0x6a) + + byteArrayOf(0, 0, 0, 0) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index d03f3de82c8..9ecfa0c3eae 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -6,6 +6,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.dashfoundation.dashsdk.errors.mapNativeErrors import org.dashfoundation.dashsdk.ffi.CreditsNative +import org.dashfoundation.dashsdk.ffi.IdentityTopUpNativeResult import org.dashfoundation.dashsdk.wallet.TrackedAssetLock internal fun interface ResumeTopUpNativeCall { @@ -19,6 +20,89 @@ internal fun interface ResumeTopUpNativeCall { ): Long } +/** + * The JNI calls behind the top-ups to any identity, as one seam so unit tests + * can stand in for the native library, which Robolectric cannot load. + * Production uses [CreditsNative]. + */ +internal interface RecipientTopUpNative { + fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long + + fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + coreSignerHandle: Long, + ): IdentityTopUpNativeResult + + fun assignTopUpRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + ) + + /** [CreditsNative]'s exports. */ + object Jni : RecipientTopUpNative { + override fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long = CreditsNative.topUpExternalIdentityFromCore( + walletHandle, + identityId, + amountDuffs, + accountIndex, + coreSignerHandle, + ) + + override fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + coreSignerHandle: Long, + ): IdentityTopUpNativeResult = CreditsNative.resumeTopUpToRecordedRecipient( + walletHandle, + outpointTxid, + outpointVout, + coreSignerHandle, + ) + + override fun assignTopUpRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + ) = CreditsNative.assignTopUpRecipient(walletHandle, outpointTxid, outpointVout, identityId) + } +} + +/** + * Outcome of [IdentityCredits.resumeTopUpToRecordedRecipient]: the identity the + * lock paid (32 bytes; in this wallet or not) and its proved new balance. + */ +class IdentityTopUpResult( + val identityId: ByteArray, + val newBalance: Long, +) { + override fun equals(other: Any?): Boolean = + other is IdentityTopUpResult && + identityId.contentEquals(other.identityId) && + newBalance == other.newBalance + + override fun hashCode(): Int = identityId.contentHashCode() * 31 + newBalance.hashCode() + + override fun toString(): String = "IdentityTopUpResult(newBalance=$newBalance)" +} + /** * One Platform-address funding input for an identity top-up — port of the * `IdentityAddressInput` tuple the Swift `TopUpIdentityView` packs. Encodes @@ -81,6 +165,7 @@ class IdentityCredits internal constructor( private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, private val resumeTopUpNative: ResumeTopUpNativeCall = ResumeTopUpNativeCall(CreditsNative::topUpIdentityWithExistingAssetLock), + private val recipientTopUpNative: RecipientTopUpNative = RecipientTopUpNative.Jni, ) { /** @@ -286,4 +371,112 @@ class IdentityCredits internal constructor( ) } } + + /** + * Top up someone else's identity — [identityId] (32 bytes), one this + * wallet does not manage — from a new Core asset lock funded by the + * wallet's balance. Port of + * `platform_wallet_top_up_external_identity_with_funding_signer` + * (packages/rs-platform-wallet-ffi/src/identity_top_up.rs): Rust fetches + * the identity from Platform, records it on the lock's row before the + * broadcast and adds nothing to the wallet. Returns the identity's proved + * post-transition balance. + * + * Refused before anything is built: an amount below Platform's top-up + * minimum (native `ErrorInvalidParameter`), an identity Platform does not + * know + * ([DashSdkError.NotFound][org.dashfoundation.dashsdk.errors.DashSdkError.NotFound]), + * and a store that does not keep identity recipients. Once the lock is + * built a failure may leave it tracked, recording [identityId]: never + * retry with a new lock; resume that one with + * [resumeTopUpToRecordedRecipient], or the identity may be paid twice. + */ + suspend fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long = gate.op { + require(identityId.size == 32) { + "identityId must be exactly 32 bytes, got ${identityId.size}" + } + mapNativeErrors { + recipientTopUpNative.topUpExternalIdentityFromCore( + walletHandle, + identityId, + amountDuffs, + accountIndex, + coreSignerHandle, + ) + } + } + + /** + * Resume the interrupted identity top-up [lock] to the identity it pays — + * the caller names none, so a recovery cannot pay someone else's top-up + * into one of this wallet's identities. Port of + * `platform_wallet_resume_identity_top_up_to_recorded_recipient_signer` + * (packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs): + * a bound top-up lock pays the wallet's identity at its registration + * index, an unbound one the identity its row recorded + * ([TrackedAssetLock.identityRecipient]). Returns the identity paid and + * its proved new balance. + * + * A lock recording no identity ([TrackedAssetLock.identityRecipientUnassigned]) + * is refused with + * [AssetLockRecipientUnknown][org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.AssetLockRecipientUnknown]: + * assign it one with [assignTopUpRecipient] first. Rust decides which + * locks it resumes; nothing is filtered here. + */ + suspend fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + lock: TrackedAssetLock, + coreSignerHandle: Long, + ): IdentityTopUpResult = gate.op { + val native = mapNativeErrors { + recipientTopUpNative.resumeTopUpToRecordedRecipient( + walletHandle, + lock.outpointTxid, + lock.outpointVout, + coreSignerHandle, + ) + } + check(native.identityId.size == 32) { + "native returned a ${native.identityId.size}-byte identity id" + } + IdentityTopUpResult(native.identityId.copyOf(), native.newBalance) + } + + /** + * Assign [identityId] (32 bytes) as the identity the unassigned unbound + * top-up [lock] pays, as the user chose it — then resume it with + * [resumeTopUpToRecordedRecipient]. Port of + * `platform_wallet_assign_identity_top_up_recipient` + * (packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs). + * + * The assignment is permanent. Rust looks the identity up on Platform + * first: one Platform does not know is + * [DashSdkError.NotFound][org.dashfoundation.dashsdk.errors.DashSdkError.NotFound] + * and nothing is assigned. A lock already recording another identity is + * [AssetLockRecipientMismatch][org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.AssetLockRecipientMismatch]; + * the same identity again is a no-op, which also retries a failed store. + */ + suspend fun assignTopUpRecipient( + walletHandle: Long, + lock: TrackedAssetLock, + identityId: ByteArray, + ): Unit = gate.op { + require(identityId.size == 32) { + "identityId must be exactly 32 bytes, got ${identityId.size}" + } + mapNativeErrors { + recipientTopUpNative.assignTopUpRecipient( + walletHandle, + lock.outpointTxid, + lock.outpointVout, + identityId, + ) + } + } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 91547fb3e1d..ec7bbe4ad38 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -255,10 +255,29 @@ sealed class DashSdkError( * recipient than the one the tracked lock recorded when it was built. Nothing * was submitted or paid; resume with the recorded recipient. Locks tracked * before the recipient was recorded carry none and accept the caller's. + * + * Also an unbound identity top-up lock resumed or assigned to a different + * identity than the one its row recorded + * (`PlatformWalletError::AssetLockIdentityRecipientMismatch`, + * dashpay/platform#5924): nothing was submitted; resume to the recorded + * identity ([org.dashfoundation.dashsdk.wallet.TrackedAssetLock.identityRecipient]). */ class AssetLockRecipientMismatch(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * Code 81 (`ErrorAssetLockRecipientUnknown`, dashpay/platform#5924): an + * unbound identity top-up lock records no identity to pay — it was + * rebuilt from the chain, for example after a restore from the seed — + * so no resume pays it; it may have been meant for someone else's + * identity. Nothing was submitted or paid. Not retryable as is: assign + * the lock a recipient the user chooses + * ([org.dashfoundation.dashsdk.credits.IdentityCredits.assignTopUpRecipient]), + * then resume it. + */ + class AssetLockRecipientUnknown(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) + /** * `ErrorShieldedNoRecordedAnchor` (native code 19). A shielded spend * could not be built against a Platform-recorded anchor because the @@ -922,6 +941,7 @@ sealed class DashSdkError( 29 -> PlatformWallet.AssetLockInsufficientFunds(message, cause) // ErrorAssetLockInsufficientFunds 60 -> PlatformWallet.AssetLockTooManyInputs(message, cause) // ErrorAssetLockTooManyInputs 61 -> PlatformWallet.AssetLockRecipientMismatch(message, cause) // ErrorAssetLockRecipientMismatch + 81 -> PlatformWallet.AssetLockRecipientUnknown(message, cause) // ErrorAssetLockRecipientUnknown // The deferred-token trio sits at the contiguous block 34-36 because // 27-33 are claimed elsewhere: 27 ErrorShutdownIncomplete // (dashpay/platform#4268, merged), 29 ErrorAssetLockInsufficientFunds diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/AssetLockRecoveryNativeData.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/AssetLockRecoveryNativeData.kt index 45eccff1c52..6798d9f01fb 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/AssetLockRecoveryNativeData.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/AssetLockRecoveryNativeData.kt @@ -13,7 +13,16 @@ class IdentityRegistrationNativeResult( @JvmField val managedIdentityHandle: Long, ) -/** One copied `TrackedAssetLockEntryFFI`; constructor descriptor `([BIIBIZI)V`. */ +/** + * One copied `TrackedAssetLockEntryFFI`; constructor descriptor + * `([BIIBIZI[BZ)V`. + * + * [identityRecipient] is the 32-byte identity an unbound identity top-up pays + * (`has_identity_recipient` / `identity_recipient`), null when the row records + * none. [identityRecipientUnassigned] is `identity_recipient_unassigned`: an + * unbound top-up, not consumed, recording no identity, which no resume pays + * until one is assigned. + */ class TrackedAssetLockNativeData( @JvmField val outpointTxid: ByteArray, @JvmField val outpointVout: Int, @@ -22,6 +31,18 @@ class TrackedAssetLockNativeData( @JvmField val registrationIndex: Int, @JvmField val instantLockPresent: Boolean, @JvmField val chainLockHeight: Int, + @JvmField val identityRecipient: ByteArray?, + @JvmField val identityRecipientUnassigned: Boolean, +) + +/** + * JNI result of `CreditsNative.resumeTopUpToRecordedRecipient`; constructor + * descriptor `([BJ)V`: the 32-byte identity the resume paid and its proved + * new credit balance. + */ +class IdentityTopUpNativeResult( + @JvmField val identityId: ByteArray, + @JvmField val newBalance: Long, ) /** diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt index 395cf3ddd21..e21ed9b1053 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/CreditsNative.kt @@ -118,4 +118,48 @@ internal object CreditsNative { accountIndex: Int, coreSignerHandle: Long, ): Long + + /** + * Top up [identityId] (32 bytes), an identity this wallet does not + * manage, from a new Core asset lock whose row records the identity. + * Returns its proved post-transition balance. Descriptor `(J[BJIJ)J`. + * + * Thinly marshals + * `platform_wallet_top_up_external_identity_with_funding_signer`. + */ + external fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long + + /** + * Resume the tracked identity top-up at the outpoint to the identity the + * lock pays; the caller names none. Descriptor + * `(J[BIJ)Lorg/dashfoundation/dashsdk/ffi/IdentityTopUpNativeResult;`. + * + * Thinly marshals + * `platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`. + */ + external fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + coreSignerHandle: Long, + ): IdentityTopUpNativeResult + + /** + * Assign [identityId] (32 bytes) as the identity the unassigned unbound + * top-up lock at the outpoint pays. Descriptor `(J[BI[B)V`. + * + * Thinly marshals `platform_wallet_assign_identity_top_up_recipient`. + */ + external fun assignTopUpRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + ) } 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..67f0ae1ae56 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 @@ -113,6 +113,46 @@ abstract class NativePersistenceBridge { */ const val CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE: Long = 1L shl 15 + /** + * `PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS` (bit 13): an + * asset lock's 16-byte operation UUID survives store and load, consumed + * rows included, and a load of a missing or malformed row fails rather + * than reading as "no UUID". Wired only for a bridge that overrides + * both [onPersistAssetLockOperationId] and [onLoadAssetLockOperationId]. + * Together with the asset-lock reconciliation bits it makes up + * `WALLET_DRAIN`. The one Kotlin home of this bit. + */ + const val CAPABILITY_ASSET_LOCK_OPERATION_IDS: Long = 1L shl 13 + + /** + * `PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS` (bit 14): + * the Orchard recipient a shielded funding was built to pay survives + * store and load with its row. Wired only for a bridge that overrides + * both [onPersistAssetLockShieldedRecipient] and + * [onLoadAssetLockShieldedRecipient]. + */ + const val CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS: Long = 1L shl 14 + + /** + * `PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS` (bit 17; + * bit 16 is held by another branch): the identity an unbound identity + * top-up was built or assigned to pay survives store and load with its + * row. Required, not reported: native builds no unbound top-up lock, + * and assigns no recipient, for a host without it. Wired only for a + * bridge that overrides both [onPersistAssetLockIdentityRecipient] and + * [onLoadAssetLockIdentityRecipient]. + */ + const val CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS: Long = 1L shl 17 + + /** Width of an asset-lock operation UUID. */ + const val ASSET_LOCK_OPERATION_ID_SIZE: Int = 16 + + /** Width of a raw Orchard payment address. */ + const val ASSET_LOCK_SHIELDED_RECIPIENT_SIZE: Int = 43 + + /** Width of an identity id. */ + const val ASSET_LOCK_IDENTITY_RECIPIENT_SIZE: Int = 32 + /** * Packed row widths of [onPersistPrivateContactScanState] and * [onLoadPrivateContactScanState]: a read position is the identity @@ -806,6 +846,72 @@ abstract class NativePersistenceBridge { /** One 36-byte outpoint removal. Descriptor `([B[B)I`. */ open fun onPersistAssetLockRemoval(walletId: ByteArray, outPoint: ByteArray): Int = 0 + // The three asset-lock sidecars (`PersistAssetLock*Fn` / `LoadAssetLock*Fn` + // in `packages/rs-platform-wallet-ffi/src/persistence.rs`). Each persist + // fires after the row's [onPersistAssetLockUpsert], in the same round, and + // must refuse (non-zero) a value different from one already stored; the + // same value again succeeds. A later upsert of the row must keep the + // value. Each load returns the stored value, null when the row records + // none, and throws when the row is missing or unreadable: that fails the + // native load instead of reading as a lock without one. Each pair is wired + // only for a bridge that overrides both of its methods, so an inherited + // no-op can never attest the capability. + + /** + * `on_persist_asset_lock_operation_id_fn`: associate the 16-byte + * [operationId] with the lock at the 36-byte [outPoint]. Descriptor + * `([B[B[B)I`. See [CAPABILITY_ASSET_LOCK_OPERATION_IDS]. + */ + open fun onPersistAssetLockOperationId( + walletId: ByteArray, + outPoint: ByteArray, + operationId: ByteArray, + ): Int = 0 + + /** + * `on_load_asset_lock_operation_id_fn`: the 16-byte UUID stored for the + * lock at [outPoint] (consumed rows included), or null. Descriptor + * `([B[B)[B`. + */ + open fun onLoadAssetLockOperationId(walletId: ByteArray, outPoint: ByteArray): ByteArray? = null + + /** + * `on_persist_asset_lock_shielded_recipient_fn`: associate the raw 43-byte + * Orchard [recipientRaw43] with the lock at [outPoint]. Descriptor + * `([B[B[B)I`. See [CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS]. + */ + open fun onPersistAssetLockShieldedRecipient( + walletId: ByteArray, + outPoint: ByteArray, + recipientRaw43: ByteArray, + ): Int = 0 + + /** + * `on_load_asset_lock_shielded_recipient_fn`: the 43-byte recipient stored + * for the lock at [outPoint], or null. Descriptor `([B[B)[B`. + */ + open fun onLoadAssetLockShieldedRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + null + + /** + * `on_persist_asset_lock_identity_recipient_fn`: associate the 32-byte + * [identityId] an unbound identity top-up pays with the lock at + * [outPoint]. Descriptor `([B[B[B)I`. See + * [CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS]. + */ + open fun onPersistAssetLockIdentityRecipient( + walletId: ByteArray, + outPoint: ByteArray, + identityId: ByteArray, + ): Int = 0 + + /** + * `on_load_asset_lock_identity_recipient_fn`: the 32-byte identity stored + * for the lock at [outPoint], or null. Descriptor `([B[B)[B`. + */ + open fun onLoadAssetLockIdentityRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + null + // ── Invitations (DIP-13) ────────────────────────────────────────── /** 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..bbb130a121c 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,18 @@ 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 (asset-lock sidecars, dashpay/platform#5924): adds the nullable + * `asset_locks.operationId` (16 bytes), `asset_locks.shieldedRecipientRaw43` + * (43 bytes) and `asset_locks.identityRecipientId` (32 bytes) columns that the + * SQLite store keeps since its V019–V021 migrations and Swift keeps on + * `PersistentAssetLock`, the unique `(walletId, operationId)` index, and the + * three `asset_locks_*_immutable` triggers ([createAssetLockSidecarTriggers]). + * NULL for every pre-existing row, which reads back as a lock built without a + * UUID or a recorded recipient, as it was. */ @Database( - version = 16, + version = 17, exportSchema = true, entities = [ WalletEntity::class, @@ -752,6 +761,59 @@ abstract class DashDatabase : RoomDatabase() { } } + /** + * v16 -> v17: the three asset-lock sidecar columns, their unique + * operation-id index and immutability triggers, see the version-17 + * class doc above. NULL for every pre-existing row. + */ + val MIGRATION_16_17: Migration = object : Migration(16, 17) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE `asset_locks` ADD COLUMN `operationId` BLOB") + db.execSQL("ALTER TABLE `asset_locks` ADD COLUMN `shieldedRecipientRaw43` BLOB") + db.execSQL("ALTER TABLE `asset_locks` ADD COLUMN `identityRecipientId` BLOB") + db.execSQL( + "CREATE UNIQUE INDEX IF NOT EXISTS `index_asset_locks_walletId_operationId` " + + "ON `asset_locks` (`walletId`, `operationId`)", + ) + createAssetLockSidecarTriggers(db) + } + } + + /** + * The asset-lock sidecars are immutable once stored: an UPDATE that + * changes a non-NULL `operationId`, `shieldedRecipientRaw43` or + * `identityRecipientId` aborts. The same triggers the SQLite store + * creates in `V019__asset_lock_operation_id`, + * `V020__asset_lock_shielded_recipient` and + * `V021__asset_lock_identity_recipient` + * (packages/rs-platform-wallet-storage/migrations). The handler + * refuses a different value before it gets here; these stop any + * other writer. Room does not describe triggers in its schema, so + * they are created by [MIGRATION_16_17] for an upgraded database and + * by [sidecarTriggerCallback] for a new one. + */ + internal fun createAssetLockSidecarTriggers(db: SupportSQLiteDatabase) { + for ((column, label) in listOf( + "operationId" to "operation ID", + "shieldedRecipientRaw43" to "shielded recipient", + "identityRecipientId" to "identity recipient", + )) { + db.execSQL( + "CREATE TRIGGER IF NOT EXISTS `asset_locks_${column}_immutable` " + + "BEFORE UPDATE OF `$column` ON `asset_locks` " + + "WHEN OLD.`$column` IS NOT NULL AND NEW.`$column` IS NOT OLD.`$column` " + + "BEGIN SELECT RAISE(ABORT, 'asset lock $label cannot change'); END", + ) + } + } + + /** Installs [createAssetLockSidecarTriggers] on a newly created database. */ + private val sidecarTriggerCallback = object : RoomDatabase.Callback() { + override fun onCreate(db: SupportSQLiteDatabase) { + createAssetLockSidecarTriggers(db) + } + } + /** * Build the on-disk database. WAL is Room's default journal mode on * API 16+; writes go through the persistence handler inside @@ -783,13 +845,16 @@ abstract class DashDatabase : RoomDatabase() { MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, + MIGRATION_16_17, ) + .addCallback(sidecarTriggerCallback) .build() /** In-memory variant for tests. */ fun createInMemory(context: Context): DashDatabase = Room.inMemoryDatabaseBuilder(context, DashDatabase::class.java) .allowMainThreadQueries() + .addCallback(sidecarTriggerCallback) .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..6f7c8ca55e8 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 @@ -157,7 +157,10 @@ class PlatformWalletPersistenceHandler( CAPABILITY_DPNS_NAME_STATES or CAPABILITY_TRACKED_ASSET_LOCKS or CAPABILITY_CORE_SWEEP_REMOVAL or - CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE + CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE or + CAPABILITY_ASSET_LOCK_OPERATION_IDS or + CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS or + CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS /** * The single-thread executor created when no [dispatcher] is injected. @@ -2417,13 +2420,20 @@ class PlatformWalletPersistenceHandler( // (PlatformWalletPersistenceHandler.swift:270). All other // transitions stay last-write-wins because non-terminal // statuses legitimately move both ways. + // + // DrainCompleted (6) is the stronger terminal state — a proven + // drain consumption — and only another DrainCompleted write may + // touch it; a Consumed row may still advance to it. Same rule as + // the SQLite store's lifecycle-blob guard and Swift's. val incomingStatus = status.toInt() and 0xFF - if (existing != null && - existing.statusRaw == ASSET_LOCK_STATUS_CONSUMED && - incomingStatus != ASSET_LOCK_STATUS_CONSUMED - ) { + if (existing != null && supersedesTerminal(existing.statusRaw, incomingStatus)) { return@stage } + // The sidecars (operation UUID, recorded recipients) arrive through + // their own callbacks after this upsert; a later upsert of the same + // row must carry them forward, never clear them (the immutability + // triggers would refuse it). Keyed by outpoint, as Swift's is. + val carried = existing db.assetLockDao().upsert( AssetLockEntity( outPointHex = outPointHex, @@ -2437,6 +2447,9 @@ class PlatformWalletPersistenceHandler( proofBytes = proofBytes, createdAt = existing?.createdAt ?: java.util.Date(), updatedAt = now(), + operationId = carried?.operationId, + shieldedRecipientRaw43 = carried?.shieldedRecipientRaw43, + identityRecipientId = carried?.identityRecipientId, ), ) // Spend-visibility reconcile: an asset-lock tx burns its value @@ -2471,6 +2484,168 @@ class PlatformWalletPersistenceHandler( 0 } + // ── Asset-lock sidecars ─────────────────────────────────────────── + // + // Ports of `PlatformWalletPersistenceHandler.swift`'s + // `persistAssetLockOperationId` / `persistAssetLockShieldedRecipient` / + // `loadAssetLockShieldedRecipient` / `loadAssetLockOperationId`, plus the + // identity-recipient pair native added for dashpay/platform#5924 (see the + // `PersistAssetLock*Fn` / `LoadAssetLock*Fn` typedefs in + // `packages/rs-platform-wallet-ffi/src/persistence.rs`). + + override fun onPersistAssetLockOperationId( + walletId: ByteArray, + outPoint: ByteArray, + operationId: ByteArray, + ): Int = persistAssetLockSidecar(walletId, outPoint, operationId, AssetLockSidecar.OPERATION_ID) + + override fun onLoadAssetLockOperationId(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + loadAssetLockSidecar(walletId, outPoint, AssetLockSidecar.OPERATION_ID) + + override fun onPersistAssetLockShieldedRecipient( + walletId: ByteArray, + outPoint: ByteArray, + recipientRaw43: ByteArray, + ): Int = persistAssetLockSidecar( + walletId, + outPoint, + recipientRaw43, + AssetLockSidecar.SHIELDED_RECIPIENT, + ) + + override fun onLoadAssetLockShieldedRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + loadAssetLockSidecar(walletId, outPoint, AssetLockSidecar.SHIELDED_RECIPIENT) + + override fun onPersistAssetLockIdentityRecipient( + walletId: ByteArray, + outPoint: ByteArray, + identityId: ByteArray, + ): Int = persistAssetLockSidecar( + walletId, + outPoint, + identityId, + AssetLockSidecar.IDENTITY_RECIPIENT, + ) + + override fun onLoadAssetLockIdentityRecipient(walletId: ByteArray, outPoint: ByteArray): ByteArray? = + loadAssetLockSidecar(walletId, outPoint, AssetLockSidecar.IDENTITY_RECIPIENT) + + /** + * Record [value] as [sidecar] of the asset lock at [outPoint], in the open + * round, after that round's upsert of the row (native fires the sidecars + * after the legacy upsert in the same changeset). Outside a round it is + * refused, as Swift refuses it (`requiresChangeset`): the association must + * commit with the row it belongs to. + * + * The value is immutable once stored, as the SQLite triggers make it: the + * same value again is accepted, a different one is refused. It is checked + * here against the committed row, so the callback's own return reports + * the refusal ([NativePersistenceBridge.PERSIST_RC_CONSTRAINT]), and again + * in the staged write against the row as the round left it, which throws + * and fails the commit. An operation UUID another row of the wallet holds + * is refused the same way. A row that does not exist when the round + * commits fails it too: an association with nothing would be lost. + */ + private fun persistAssetLockSidecar( + walletId: ByteArray, + outPoint: ByteArray, + value: ByteArray, + sidecar: AssetLockSidecar, + ): Int = guarded { + if (walletId.size != 32 || outPoint.size != 36 || value.size != sidecar.size) { + Log.e(TAG, "asset-lock ${sidecar.label}: malformed callback arguments") + return@guarded NativePersistenceBridge.PERSIST_RC_CONSTRAINT + } + val round = openRound(walletId) + if (round == null) { + Log.e(TAG, "asset-lock ${sidecar.label} delivered outside a changeset round") + return@guarded 1 + } + val outPointHex = encodeOutPointHex(outPoint) + val stored = value.copyOf() + val committed = runBlockingResult { + val dao = database.assetLockDao() + val row = dao.getByWalletAndOutPointHex(walletId, outPointHex) + val conflicting = row != null && sidecar.conflicts(row, stored) + val duplicate = sidecar == AssetLockSidecar.OPERATION_ID && + dao.countOtherRowsWithOperationId(walletId, stored, outPointHex) > 0 + !conflicting && !duplicate + } + if (!committed) { + Log.e(TAG, "asset-lock ${sidecar.label} for $outPointHex conflicts with the stored value") + return@guarded NativePersistenceBridge.PERSIST_RC_CONSTRAINT + } + round.ops.add { db -> + val dao = db.assetLockDao() + val row = checkNotNull(dao.getByWalletAndOutPointHex(walletId, outPointHex)) { + "asset-lock ${sidecar.label}: no row for $outPointHex" + } + check(!sidecar.conflicts(row, stored)) { + "asset lock ${sidecar.label} cannot change ($outPointHex)" + } + if (sidecar.read(row) == null) { + dao.upsert(sidecar.write(row, stored)) + } + } + 0 + } + + /** + * The [sidecar] stored for the asset lock at [outPoint], or null when the + * row records none. A missing row or a stored value of the wrong size + * throws, which fails the native load: it must not read as a lock built + * without one (Swift `missingRecord` / `malformedRecord`). + */ + private fun loadAssetLockSidecar( + walletId: ByteArray, + outPoint: ByteArray, + sidecar: AssetLockSidecar, + ): ByteArray? = loadOrThrow { + require(outPoint.size == 36) { "outpoint must be 36 bytes, got ${outPoint.size}" } + val outPointHex = encodeOutPointHex(outPoint) + val row = runBlockingResult { + database.assetLockDao().getByWalletAndOutPointHex(walletId, outPointHex) + } + checkNotNull(row) { "asset-lock ${sidecar.label}: no row for $outPointHex" } + sidecar.read(row)?.also { value -> + check(value.size == sidecar.size) { + "asset-lock ${sidecar.label} for $outPointHex is ${value.size} bytes, not ${sidecar.size}" + } + }?.copyOf() + } + + /** One immutable `asset_locks` sidecar column and its fixed width. */ + private enum class AssetLockSidecar( + val label: String, + val size: Int, + val read: (AssetLockEntity) -> ByteArray?, + val write: (AssetLockEntity, ByteArray) -> AssetLockEntity, + ) { + OPERATION_ID( + "operation ID", + NativePersistenceBridge.ASSET_LOCK_OPERATION_ID_SIZE, + { it.operationId }, + { row, value -> row.copy(operationId = value) }, + ), + SHIELDED_RECIPIENT( + "shielded recipient", + NativePersistenceBridge.ASSET_LOCK_SHIELDED_RECIPIENT_SIZE, + { it.shieldedRecipientRaw43 }, + { row, value -> row.copy(shieldedRecipientRaw43 = value) }, + ), + IDENTITY_RECIPIENT( + "identity recipient", + NativePersistenceBridge.ASSET_LOCK_IDENTITY_RECIPIENT_SIZE, + { it.identityRecipientId }, + { row, value -> row.copy(identityRecipientId = value) }, + ), + ; + + /** Whether [row] already records a value other than [value]. */ + fun conflicts(row: AssetLockEntity, value: ByteArray): Boolean = + read(row)?.contentEquals(value) == false + } + // ── Invitations (DIP-13) ────────────────────────────────────────── override fun onPersistInvitationUpsert( @@ -4211,6 +4386,15 @@ class PlatformWalletPersistenceHandler( internal const val CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE: Long = NativePersistenceBridge.CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE + internal const val CAPABILITY_ASSET_LOCK_OPERATION_IDS: Long = + NativePersistenceBridge.CAPABILITY_ASSET_LOCK_OPERATION_IDS + + internal const val CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS: Long = + NativePersistenceBridge.CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS + + internal const val CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS: Long = + NativePersistenceBridge.CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS + private const val TAG = "DashPersistence" /** @@ -4251,6 +4435,26 @@ class PlatformWalletPersistenceHandler( /** `AssetLockStatus::Consumed` — the terminal lifecycle state. */ private const val ASSET_LOCK_STATUS_CONSUMED = 4 + /** + * `AssetLockStatus::DrainCompleted` — a proven drain consumption, the + * stronger terminal state: both project to SQLite's `consumed`. + */ + private const val ASSET_LOCK_STATUS_DRAIN_COMPLETED = 6 + + /** + * Whether an upsert carrying [incoming] must leave a row at [stored] + * untouched: a DrainCompleted row takes only another DrainCompleted + * write, and a Consumed row only a terminal one. Mirrors Swift + * `persistAssetLocks` and the SQLite store's upsert guard. + */ + internal fun supersedesTerminal(stored: Int, incoming: Int): Boolean = + (stored == ASSET_LOCK_STATUS_DRAIN_COMPLETED && incoming != ASSET_LOCK_STATUS_DRAIN_COMPLETED) || + ( + stored == ASSET_LOCK_STATUS_CONSUMED && + incoming != ASSET_LOCK_STATUS_CONSUMED && + incoming != ASSET_LOCK_STATUS_DRAIN_COMPLETED + ) + private val HEX = "0123456789abcdef".toCharArray() } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt index 6e3fcea24f2..b71909a1363 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt @@ -166,6 +166,25 @@ interface AssetLockDao { ) suspend fun fundingTypeForTxid(txidHex: String): Int? + /** The row of [walletId] at [outPointHex], for the sidecar persist and load callbacks. */ + @Query("SELECT * FROM asset_locks WHERE walletId = :walletId AND outPointHex = :outPointHex") + suspend fun getByWalletAndOutPointHex(walletId: ByteArray, outPointHex: String): AssetLockEntity? + + /** + * Whether another row of [walletId] already records [operationId]: the + * `(walletId, operationId)` uniqueness the index enforces, checked first so + * the persist callback can refuse it as a constraint violation. + */ + @Query( + "SELECT COUNT(*) FROM asset_locks WHERE walletId = :walletId " + + "AND operationId = :operationId AND outPointHex != :outPointHex" + ) + suspend fun countOtherRowsWithOperationId( + walletId: ByteArray, + operationId: ByteArray, + outPointHex: String, + ): Int + @Upsert suspend fun upsert(assetLock: AssetLockEntity) @@ -174,16 +193,17 @@ interface AssetLockDao { /** * Asset-lock removal path (`onPersistAssetLockRemoval`). The - * `statusRaw != 4` guard is the same terminal rule SQLite's DELETE - * (`status != 'consumed'`) and Swift's `statusRaw == 4` skip apply: a - * Consumed row is deliberately retained for historical lookup, and + * `statusRaw NOT IN (4, 6)` guard is the same terminal rule SQLite's DELETE + * (`status != 'consumed'`, which both terminal statuses project to) and + * Swift's `statusRaw == 4 || statusRaw == 6` skip apply: a Consumed or + * DrainCompleted row is deliberately retained for historical lookup, and * neither removal producer can legitimately name one — a Built row * rejected at broadcast never got that far, and a sweep of the funding * transaction only tombstones entries still tracked, which a consumed * lock no longer is — so a removal reaching a consumed row is by * construction a stale write. */ - @Query("DELETE FROM asset_locks WHERE outPointHex = :outPointHex AND statusRaw != 4") + @Query("DELETE FROM asset_locks WHERE outPointHex = :outPointHex AND statusRaw NOT IN (4, 6)") suspend fun deleteByOutPointHex(outPointHex: String) /** Wallet teardown mirror of `deleteWalletData`'s asset-lock pass. */ diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/AssetLockEntity.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/AssetLockEntity.kt index c5505e3746b..359e4b7676d 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/AssetLockEntity.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/entities/AssetLockEntity.kt @@ -15,10 +15,25 @@ import java.util.Date * No FK to `wallets`: the Swift model declares no relationship — rows are * deleted manually by wallet teardown (`deleteWalletData`), which the * `AssetLockDao.deleteByWallet` mirror covers. + * + * The three sidecar columns ([operationId], [shieldedRecipientRaw43], + * [identityRecipientId]) are written by their own persistence callbacks, + * which native fires after the row's upsert in the same changeset (see the + * `PersistAssetLock*Fn` typedefs in + * `packages/rs-platform-wallet-ffi/src/persistence.rs`). Each is immutable + * once stored: the handler refuses a different value, and the + * `asset_locks_*_immutable` triggers [DashDatabase] installs refuse one at + * the SQL layer too, as the SQLite store's V019–V021 triggers do. A later + * upsert of the row carries them forward rather than clearing them. + * `(walletId, operationId)` is unique, as SQLite's + * `asset_locks_wallet_operation_id` index is (NULLs never collide). */ @Entity( tableName = "asset_locks", - indices = [Index(value = ["walletId"])], + indices = [ + Index(value = ["walletId"]), + Index(value = ["walletId", "operationId"], unique = true), + ], ) data class AssetLockEntity( @PrimaryKey val outPointHex: String, @@ -41,9 +56,10 @@ data class AssetLockEntity( /** * `AssetLockStatus` discriminant: 0 Built, 1 Broadcast, * 2 InstantSendLocked, 3 ChainLocked, 4 Consumed, - * 5 RecoveredFromChain. + * 5 RecoveredFromChain, 6 DrainCompleted. * - * `4` is terminal; `5` is NOT, its higher discriminant + * `4` and `6` are terminal (`6`, a proven wallet-drain consumption, is + * the stronger: only another `6` overwrites it); `5` is NOT, its higher discriminant * notwithstanding. `5` means Core finality is proven while * Platform-side consumption is unknown — what the restore scan and the * chainlock-promotion path write — so it belongs in every "still @@ -63,4 +79,28 @@ data class AssetLockEntity( val createdAt: Date = Date(), /** Swift names this `updatedAt` (not `lastUpdated`). */ val updatedAt: Date = Date(), + /** + * 16-byte operation UUID native correlates a wallet drain with + * (`PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS`, bit 13; SQLite + * `V019__asset_lock_operation_id`, Swift + * `PersistentAssetLock.operationId`). Null for a lock built without one. + */ + val operationId: ByteArray? = null, + /** + * Raw 43-byte Orchard address a shielded funding (`fundingTypeRaw == 5`) + * was built to pay, so a resume after restart pays the recipient the user + * confirmed (`ASSET_LOCK_SHIELDED_RECIPIENTS`, bit 14; SQLite + * `V020__asset_lock_shielded_recipient`, Swift + * `PersistentAssetLock.shieldedRecipientRaw43`). + */ + val shieldedRecipientRaw43: ByteArray? = null, + /** + * 32-byte id of the identity an unbound identity top-up + * (`fundingTypeRaw == 2`) was built or assigned to pay, so a resume after + * restart pays that identity and refuses another + * (`ASSET_LOCK_IDENTITY_RECIPIENTS`, bit 17; SQLite + * `V021__asset_lock_identity_recipient`). Null for every other lock, and + * for an unbound lock rebuilt from the chain until the user assigns one. + */ + val identityRecipientId: ByteArray? = null, ) 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 c1ec7960603..92046e3c4fd 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 @@ -88,6 +88,24 @@ data class PlatformWalletPersistenceCapabilities( */ const val PRIVATE_CONTACT_REQUEST_SCAN_STATE: Long = NativePersistenceBridge.CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE + + /** Mirrors `PersistenceCapabilities::ASSET_LOCK_OPERATION_IDS` (bit 13). */ + const val ASSET_LOCK_OPERATION_IDS: Long = + NativePersistenceBridge.CAPABILITY_ASSET_LOCK_OPERATION_IDS + + /** Mirrors `PersistenceCapabilities::ASSET_LOCK_SHIELDED_RECIPIENTS` (bit 14). */ + const val ASSET_LOCK_SHIELDED_RECIPIENTS: Long = + NativePersistenceBridge.CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS + + /** + * Mirrors `PersistenceCapabilities::ASSET_LOCK_IDENTITY_RECIPIENTS` + * (bit 17): required before native builds a top-up lock for an + * identity this wallet does not manage + * ([org.dashfoundation.dashsdk.credits.IdentityCredits.topUpExternalIdentityFromCore]) + * or assigns one a recipient. + */ + const val ASSET_LOCK_IDENTITY_RECIPIENTS: Long = + NativePersistenceBridge.CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS } } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLock.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLock.kt index 57133a21812..86c6b6811a0 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLock.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLock.kt @@ -16,6 +16,25 @@ import org.dashfoundation.dashsdk.ffi.TrackedAssetLocksNativeResult * with a typed error. Do NOT feed this status into any automatic * stuck-lock retry sweep; blind retries of historical locks are the * failure mode the dedicated status exists to prevent. + * + * Recipient fields, from `TrackedAssetLockEntryFFI` + * (`packages/rs-platform-wallet-ffi/src/core_wallet_types.rs`): + * + * - [identityRecipient]: the 32-byte identity an unbound identity top-up + * ([FundingType.IDENTITY_TOP_UP_NOT_BOUND]) was built or assigned to pay, + * null when the row records none. A resume + * ([org.dashfoundation.dashsdk.credits.IdentityCredits.resumeTopUpToRecordedRecipient]) + * pays that identity, in this wallet or not, and refuses any other. + * - [identityRecipientUnassigned]: an unbound top-up recording no identity + * (rebuilt from the chain, for example after a restore from the seed). No + * resume pays it; list it for the user, who assigns a recipient + * ([org.dashfoundation.dashsdk.credits.IdentityCredits.assignTopUpRecipient]), + * rather than resuming it into one of the wallet's identities. Rust decides + * it; this model only carries it. + * + * The shielded recipient a type-5 lock records is not carried: this model + * admits identity locks only, and the entry it is copied from has no such + * field. */ data class TrackedAssetLock( val outpointTxid: ByteArray, @@ -25,6 +44,8 @@ data class TrackedAssetLock( val registrationIndex: Int, val instantLockPresent: Boolean, val chainLockHeight: Int, + val identityRecipient: ByteArray? = null, + val identityRecipientUnassigned: Boolean = false, ) { enum class FundingType(val raw: Int) { IDENTITY_REGISTRATION(0), @@ -53,6 +74,9 @@ data class TrackedAssetLock( require(outpointVout >= 0) { "outpointVout must be non-negative" } require(registrationIndex >= 0) { "registrationIndex must be non-negative" } require(chainLockHeight >= 0) { "chainLockHeight must be non-negative" } + require(identityRecipient == null || identityRecipient.size == 32) { + "identityRecipient must be exactly 32 bytes, got ${identityRecipient?.size}" + } } override fun equals(other: Any?): Boolean = @@ -63,7 +87,9 @@ data class TrackedAssetLock( status == other.status && registrationIndex == other.registrationIndex && instantLockPresent == other.instantLockPresent && - chainLockHeight == other.chainLockHeight + chainLockHeight == other.chainLockHeight && + identityRecipient.contentEquals(other.identityRecipient) && + identityRecipientUnassigned == other.identityRecipientUnassigned override fun hashCode(): Int = outpointTxid.contentHashCode() * 31 + outpointVout @@ -73,7 +99,8 @@ data class TrackedAssetLock( private fun eligibleFromNative(row: TrackedAssetLockNativeData): TrackedAssetLock? { if (row.outpointTxid.size != 32 || row.outpointVout < 0 || - row.registrationIndex < 0 || row.chainLockHeight < 0 + row.registrationIndex < 0 || row.chainLockHeight < 0 || + (row.identityRecipient != null && row.identityRecipient.size != 32) ) return null val fundingType = FundingType.entries.firstOrNull { it.raw == row.fundingType } ?: return null @@ -87,6 +114,8 @@ data class TrackedAssetLock( registrationIndex = row.registrationIndex, instantLockPresent = row.instantLockPresent, chainLockHeight = row.chainLockHeight, + identityRecipient = row.identityRecipient?.copyOf(), + identityRecipientUnassigned = row.identityRecipientUnassigned, ) } } diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt new file mode 100644 index 00000000000..7c65714b821 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt @@ -0,0 +1,184 @@ +package org.dashfoundation.dashsdk.credits + +import kotlinx.coroutines.test.runTest +import org.dashfoundation.dashsdk.errors.DashSdkError +import org.dashfoundation.dashsdk.ffi.DashSDKException +import org.dashfoundation.dashsdk.ffi.IdentityTopUpNativeResult +import org.dashfoundation.dashsdk.wallet.TrackedAssetLock +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * [IdentityCredits]' bindings of the top-up to any identity + * (dashpay/platform#5924): each forwards its arguments unchanged to one JNI + * call and decides nothing — which locks resume, and to whom, is Rust's. + */ +class RecipientTopUpTest { + + private val lockTxid = ByteArray(32) { 5 } + + private fun lock( + type: TrackedAssetLock.FundingType, + recipient: ByteArray? = null, + unassigned: Boolean = false, + ) = TrackedAssetLock( + outpointTxid = lockTxid, + outpointVout = 9, + fundingType = type, + status = TrackedAssetLock.Status.CHAIN_LOCKED, + registrationIndex = 3, + instantLockPresent = true, + chainLockHeight = 100, + identityRecipient = recipient, + identityRecipientUnassigned = unassigned, + ) + + /** Records every call; answers with [resumeResult] or throws [failure]. */ + private class FakeNative( + val resumeResult: IdentityTopUpNativeResult = + IdentityTopUpNativeResult(ByteArray(32) { 7 }, 4_000L), + val failure: DashSDKException? = null, + ) : RecipientTopUpNative { + val calls = mutableListOf>() + + override fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long { + calls += listOf("external", walletHandle, identityId, amountDuffs, accountIndex, coreSignerHandle) + failure?.let { throw it } + return 9_000L + } + + override fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + coreSignerHandle: Long, + ): IdentityTopUpNativeResult { + calls += listOf("resume", walletHandle, outpointTxid, outpointVout, coreSignerHandle) + failure?.let { throw it } + return resumeResult + } + + override fun assignTopUpRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + ) { + calls += listOf("assign", walletHandle, outpointTxid, outpointVout, identityId) + failure?.let { throw it } + } + } + + @Test + fun shouldForwardAnExternalTopUpUnchangedAndReturnTheProvedBalance() = runTest { + val native = FakeNative() + val identity = ByteArray(32) { 3 } + + val balance = IdentityCredits(recipientTopUpNative = native) + .topUpExternalIdentityFromCore(1L, identity, 60_000L, 0, 2L) + + assertEquals(9_000L, balance) + val call = native.calls.single() + assertEquals(listOf("external", 1L), call.take(2)) + assertArrayEquals(identity, call[2] as ByteArray) + assertEquals(60_000L, call[3]) + assertEquals(0, call[4]) + assertEquals(2L, call[5]) + } + + @Test + fun shouldResumeEveryIdentityTopUpLockByOutpointWithoutNamingAnIdentity() = runTest { + val paid = ByteArray(32) { 7 } + val native = FakeNative(resumeResult = IdentityTopUpNativeResult(paid, 4_000L)) + val credits = IdentityCredits(recipientTopUpNative = native) + + // Bound, unbound with a recipient, and unassigned alike: Rust decides. + for (lock in listOf( + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP), + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, recipient = paid), + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, unassigned = true), + )) { + assertEquals( + IdentityTopUpResult(paid, 4_000L), + credits.resumeTopUpToRecordedRecipient(1L, lock, 2L), + ) + } + + assertEquals(3, native.calls.size) + for (call in native.calls) { + assertEquals("resume", call[0]) + assertArrayEquals(lockTxid, call[2] as ByteArray) + assertEquals(9, call[3]) + assertEquals(2L, call[4]) + } + } + + @Test + fun shouldSurfaceAnUnassignedLockRefusalAsAssetLockRecipientUnknown() = runTest { + val native = FakeNative( + failure = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 81, "assign a recipient"), + ) + val failure = runCatching { + IdentityCredits(recipientTopUpNative = native).resumeTopUpToRecordedRecipient( + 1L, + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, unassigned = true), + 2L, + ) + }.exceptionOrNull() + + assertTrue(failure is DashSdkError.PlatformWallet.AssetLockRecipientUnknown) + } + + @Test + fun shouldForwardAnAssignmentUnchangedAndMapAMismatch() = runTest { + val identity = ByteArray(32) { 4 } + val native = FakeNative() + val unassigned = lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, unassigned = true) + + IdentityCredits(recipientTopUpNative = native).assignTopUpRecipient(1L, unassigned, identity) + + val call = native.calls.single() + assertEquals(listOf("assign", 1L), call.take(2)) + assertArrayEquals(lockTxid, call[2] as ByteArray) + assertEquals(9, call[3]) + assertArrayEquals(identity, call[4] as ByteArray) + + val mismatch = FakeNative( + failure = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 61, "cannot be resumed to"), + ) + val failure = runCatching { + IdentityCredits(recipientTopUpNative = mismatch).assignTopUpRecipient(1L, unassigned, identity) + }.exceptionOrNull() + assertTrue(failure is DashSdkError.PlatformWallet.AssetLockRecipientMismatch) + } + + @Test + fun shouldRefuseAnIdentityIdThatIsNot32BytesBeforeJni() = runTest { + val native = FakeNative() + val credits = IdentityCredits(recipientTopUpNative = native) + + assertTrue( + runCatching { + credits.topUpExternalIdentityFromCore(1L, ByteArray(31), 60_000L, 0, 2L) + }.exceptionOrNull() is IllegalArgumentException, + ) + assertTrue( + runCatching { + credits.assignTopUpRecipient( + 1L, + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND), + ByteArray(33), + ) + }.exceptionOrNull() is IllegalArgumentException, + ) + assertTrue(native.calls.isEmpty()) + } +} diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index f56f0736e5e..fd86c438cd1 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -28,6 +28,18 @@ class DashSdkErrorTest { assertFalse(mapped.isRetryable) } + @Test + fun shouldTypeAnUnassignedUnboundTopUpAsAssetLockRecipientUnknown() { + val native = DashSDKException( + DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 81, + "records no identity to top up; assign a recipient before resuming it", + ) + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.AssetLockRecipientUnknown) + assertEquals(native.message, mapped.message) + assertFalse(mapped.isRetryable) + } + @Test fun mapsNativeCodesToHierarchy() { // Codes mirror DashSDKErrorCode in rs-sdk-ffi/src/error.rs. diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/AssetLockSidecarPersistenceTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/AssetLockSidecarPersistenceTest.kt new file mode 100644 index 00000000000..845054f3ec1 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/AssetLockSidecarPersistenceTest.kt @@ -0,0 +1,292 @@ +package org.dashfoundation.dashsdk.persistence + +import android.database.sqlite.SQLiteException +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest +import org.dashfoundation.dashsdk.ffi.NativePersistenceBridge +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +/** + * The three asset-lock sidecars [PlatformWalletPersistenceHandler] keeps on + * `asset_locks` — operation UUID (16 bytes), shielded recipient (43) and + * identity recipient (32) — against the contract of the `PersistAssetLock*Fn` + * / `LoadAssetLock*Fn` typedefs in + * `packages/rs-platform-wallet-ffi/src/persistence.rs`: written after the + * row's upsert in the same round, immutable once stored, kept through later + * upserts, and a load of a missing or malformed row fails instead of reading + * as "none". Parity with Swift `PlatformWalletPersistenceHandler`'s + * `persistAssetLockOperationId` / `persistAssetLockShieldedRecipient` and the + * SQLite store's V019–V021 triggers. + */ +@RunWith(RobolectricTestRunner::class) +class AssetLockSidecarPersistenceTest { + + private lateinit var db: DashDatabase + private lateinit var handler: PlatformWalletPersistenceHandler + + private val walletId = ByteArray(32) { 1 } + private val operationId = ByteArray(16) { 0x0A } + private val shieldedRecipient = ByteArray(43) { 0x0B } + private val identityRecipient = ByteArray(32) { 0x0C } + + @Before + fun setUp() { + db = DashDatabase.createInMemory(ApplicationProvider.getApplicationContext()) + handler = PlatformWalletPersistenceHandler(db, Dispatchers.Unconfined) + } + + @After + fun tearDown() { + db.close() + } + + private fun outpoint(seed: Int, vout: Int = 0) = makeOutpoint(ByteArray(32) { seed.toByte() }, vout) + + private fun upsert(outPoint: ByteArray, status: Byte = 1, fundingType: Byte = 2): Int = + handler.onPersistAssetLockUpsert( + walletId = walletId, + outPoint = outPoint, + transactionBytes = ByteArray(20) { 41 }, + accountIndex = 0, + fundingType = fundingType, + identityIndex = 0, + amountDuffs = 100_000, + status = status, + proofBytes = null, + ) + + /** One committed round: [body] runs between the begin and end callbacks. */ + private fun round(body: () -> Unit): Int { + handler.onChangesetBegin(walletId) + body() + return handler.onChangesetEnd(walletId, success = true) + } + + private suspend fun row(outPoint: ByteArray) = + db.assetLockDao().getByWalletAndOutPointHex(walletId, encodeOutPointHex(outPoint)) + + @Test + fun shouldStoreEachSidecarAfterItsUpsertInTheSameRoundAndLoadItBack() = runTest { + val op = outpoint(1) + assertEquals( + 0, + round { + assertEquals(0, upsert(op)) + assertEquals(0, handler.onPersistAssetLockOperationId(walletId, op, operationId)) + assertEquals(0, handler.onPersistAssetLockShieldedRecipient(walletId, op, shieldedRecipient)) + assertEquals(0, handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient)) + }, + ) + + assertArrayEquals(operationId, handler.onLoadAssetLockOperationId(walletId, op)) + assertArrayEquals(shieldedRecipient, handler.onLoadAssetLockShieldedRecipient(walletId, op)) + assertArrayEquals(identityRecipient, handler.onLoadAssetLockIdentityRecipient(walletId, op)) + } + + @Test + fun shouldLoadNullForARowRecordingNone() { + val op = outpoint(2) + round { upsert(op) } + + assertNull(handler.onLoadAssetLockOperationId(walletId, op)) + assertNull(handler.onLoadAssetLockShieldedRecipient(walletId, op)) + assertNull(handler.onLoadAssetLockIdentityRecipient(walletId, op)) + } + + @Test + fun shouldFailTheLoadOfAMissingRowRatherThanReadNone() { + val missing = outpoint(3) + assertThrows(IllegalStateException::class.java) { + handler.onLoadAssetLockOperationId(walletId, missing) + } + assertThrows(IllegalStateException::class.java) { + handler.onLoadAssetLockShieldedRecipient(walletId, missing) + } + assertThrows(IllegalStateException::class.java) { + handler.onLoadAssetLockIdentityRecipient(walletId, missing) + } + // Another wallet's row is not this wallet's. + round { upsert(missing) } + assertThrows(IllegalStateException::class.java) { + handler.onLoadAssetLockIdentityRecipient(ByteArray(32) { 9 }, missing) + } + } + + @Test + fun shouldFailTheLoadOfAStoredValueOfTheWrongWidth() = runTest { + val op = outpoint(4) + round { upsert(op) } + val stored = requireNotNull(row(op)) + db.assetLockDao().upsert(stored.copy(identityRecipientId = ByteArray(31))) + + assertThrows(IllegalStateException::class.java) { + handler.onLoadAssetLockIdentityRecipient(walletId, op) + } + } + + @Test + fun shouldKeepTheSidecarsThroughALaterUpsertOfTheRow() = runTest { + val op = outpoint(5) + round { + upsert(op, status = 1) + handler.onPersistAssetLockOperationId(walletId, op, operationId) + handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient) + } + // The status advance native sends next carries no sidecar. + assertEquals(0, round { upsert(op, status = 3) }) + + val stored = requireNotNull(row(op)) + assertEquals(3, stored.statusRaw) + assertArrayEquals(operationId, stored.operationId) + assertArrayEquals(identityRecipient, stored.identityRecipientId) + } + + @Test + fun shouldAcceptTheSameValueAgainAndRefuseADifferentOne() = runTest { + val op = outpoint(6) + round { + upsert(op) + handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient) + } + + assertEquals( + 0, + round { + assertEquals(0, handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient)) + }, + ) + handler.onChangesetBegin(walletId) + val refused = handler.onPersistAssetLockIdentityRecipient(walletId, op, ByteArray(32) { 0x0D }) + handler.onChangesetEnd(walletId, success = false) + + assertEquals(NativePersistenceBridge.PERSIST_RC_CONSTRAINT, refused) + assertArrayEquals(identityRecipient, requireNotNull(row(op)).identityRecipientId) + } + + @Test + fun shouldFailTheRoundWhenItRecordsTwoDifferentValuesForOneRow() = runTest { + val op = outpoint(7) + val end = round { + upsert(op) + handler.onPersistAssetLockShieldedRecipient(walletId, op, shieldedRecipient) + handler.onPersistAssetLockShieldedRecipient(walletId, op, ByteArray(43) { 0x0E }) + } + + assertNotEquals(0, end) + assertNull("the whole round rolls back", row(op)) + } + + @Test + fun shouldRefuseAnOperationIdAnotherRowOfTheWalletHolds() = runTest { + val first = outpoint(8) + val second = outpoint(9) + round { + upsert(first) + handler.onPersistAssetLockOperationId(walletId, first, operationId) + upsert(second) + } + + handler.onChangesetBegin(walletId) + val refused = handler.onPersistAssetLockOperationId(walletId, second, operationId) + handler.onChangesetEnd(walletId, success = false) + + assertEquals(NativePersistenceBridge.PERSIST_RC_CONSTRAINT, refused) + assertNull(requireNotNull(row(second)).operationId) + } + + @Test + fun shouldRefuseASidecarOutsideAChangesetRound() = runTest { + val op = outpoint(10) + round { upsert(op) } + + assertNotEquals(0, handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient)) + assertNull(requireNotNull(row(op)).identityRecipientId) + } + + @Test + fun shouldFailTheRoundWhenTheRowDoesNotExist() = runTest { + val op = outpoint(11) + val end = round { + assertEquals(0, handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient)) + } + + assertNotEquals(0, end) + assertNull(row(op)) + } + + @Test + fun shouldRefuseAValueOfTheWrongWidth() { + val op = outpoint(12) + round { upsert(op) } + handler.onChangesetBegin(walletId) + assertEquals( + NativePersistenceBridge.PERSIST_RC_CONSTRAINT, + handler.onPersistAssetLockOperationId(walletId, op, ByteArray(15)), + ) + assertEquals( + NativePersistenceBridge.PERSIST_RC_CONSTRAINT, + handler.onPersistAssetLockShieldedRecipient(walletId, op, ByteArray(32)), + ) + assertEquals( + NativePersistenceBridge.PERSIST_RC_CONSTRAINT, + handler.onPersistAssetLockIdentityRecipient(walletId, op, ByteArray(43)), + ) + handler.onChangesetEnd(walletId, success = false) + } + + @Test + fun shouldRefuseAChangedSidecarAtTheSqlLayerToo() = runTest { + val op = outpoint(13) + round { + upsert(op) + handler.onPersistAssetLockOperationId(walletId, op, operationId) + handler.onPersistAssetLockShieldedRecipient(walletId, op, shieldedRecipient) + handler.onPersistAssetLockIdentityRecipient(walletId, op, identityRecipient) + } + val stored = requireNotNull(row(op)) + + for (changed in listOf( + stored.copy(operationId = ByteArray(16) { 0x7F }), + stored.copy(shieldedRecipientRaw43 = ByteArray(43) { 0x7F }), + stored.copy(identityRecipientId = ByteArray(32) { 0x7F }), + stored.copy(identityRecipientId = null), + )) { + assertThrows(SQLiteException::class.java) { + runBlocking { db.assetLockDao().upsert(changed) } + } + } + // The same values again are not a change. + db.assetLockDao().upsert(stored.copy(statusRaw = 3)) + assertEquals(3, requireNotNull(row(op)).statusRaw) + } + + @Test + fun shouldKeepADrainCompletedRowThroughAConsumedUpsertAndARemoval() = runTest { + val op = outpoint(14) + round { upsert(op, status = 6) } + + round { upsert(op, status = 4) } + assertEquals(6, requireNotNull(row(op)).statusRaw) + + round { handler.onPersistAssetLockRemoval(walletId, op) } + assertNotNull(row(op)) + + // A Consumed row may still advance to DrainCompleted. + val consumed = outpoint(15) + round { upsert(consumed, status = 4) } + round { upsert(consumed, status = 6) } + assertEquals(6, requireNotNull(row(consumed)).statusRaw) + } +} 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..41a0067686d 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 @@ -233,7 +233,7 @@ class DashDatabaseTest { } @Test - fun schemaIsAtVersion16WithTheSweepHoldIndexes() = runTest { + fun schemaIsAtVersion17WithTheSweepHoldIndexes() = runTest { // The sweep-hold columns land in ONE migration (10 → 11), with the // two `pending_inputs` indexes the sweep's claimed-row lookup // (`spendingTxid`) and the end-of-round collector @@ -241,9 +241,10 @@ class DashDatabaseTest { // 11 → 12 adds the identity key usage limits columns on top, // 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) + // backfill record columns on `wallets`, 15 → 16 the private + // contact request scan state tables, and 16 → 17 the asset-lock + // sidecar columns. + 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..42101e0b9cf 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 @@ -220,13 +220,14 @@ class PlatformWalletPersistenceHandlerTest { assertEquals(0L, noOpBridge.persistenceCapabilitiesBits()) assertEquals(1, handler.persistenceCapabilitiesVersion()) - // The private contact request scan state is bit 15 (0x8000). - assertEquals(0x8bbfL, handler.persistenceCapabilitiesBits()) + // The private contact request scan state is bit 15 (0x8000); the + // asset-lock sidecars are bits 13, 14 and 17 (0x2000, 0x4000, 0x20000). + assertEquals(0x2ebbfL, handler.persistenceCapabilitiesBits()) // Android has no pending-contact-crypto callback, so it must not // attest that semantic contract. assertEquals(0L, handler.persistenceCapabilitiesBits() and 0x40L) - // Nor does it keep the shielded recipient of an asset lock (bit 14). - assertEquals(0L, handler.persistenceCapabilitiesBits() and 0x4000L) + // Bit 16 is held by another branch and is not attested. + assertEquals(0L, handler.persistenceCapabilitiesBits() and 0x10000L) val diagnostic = PlatformWalletPersistenceCapabilities( handler.persistenceCapabilitiesVersion(), @@ -240,6 +241,9 @@ class PlatformWalletPersistenceHandlerTest { assertTrue( diagnostic.contains(PlatformWalletPersistenceCapabilities.PRIVATE_CONTACT_REQUEST_SCAN_STATE), ) + assertTrue(diagnostic.contains(PlatformWalletPersistenceCapabilities.ASSET_LOCK_OPERATION_IDS)) + assertTrue(diagnostic.contains(PlatformWalletPersistenceCapabilities.ASSET_LOCK_SHIELDED_RECIPIENTS)) + assertTrue(diagnostic.contains(PlatformWalletPersistenceCapabilities.ASSET_LOCK_IDENTITY_RECIPIENTS)) } @Test diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLockTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLockTest.kt index 6f8e2e68c71..f4c0e02c76d 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLockTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/wallet/TrackedAssetLockTest.kt @@ -2,7 +2,10 @@ package org.dashfoundation.dashsdk.wallet import org.dashfoundation.dashsdk.ffi.TrackedAssetLockNativeData import org.dashfoundation.dashsdk.ffi.TrackedAssetLocksNativeResult +import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -18,6 +21,8 @@ class TrackedAssetLockTest { registrationIndex = 7, instantLockPresent = status >= 2, chainLockHeight = if (status == 3) 500 else 0, + identityRecipient = null, + identityRecipientUnassigned = false, ) val native = TrackedAssetLocksNativeResult( arrayOf( @@ -43,4 +48,38 @@ class TrackedAssetLockTest { native.entries[0].outpointTxid[0] = 99 assertEquals(0, eligible[0].outpointTxid[0].toInt()) } + + @Test + fun shouldCarryTheRecordedIdentityRecipientAndTheUnassignedFlag() { + fun row(vout: Int, recipient: ByteArray?, unassigned: Boolean) = TrackedAssetLockNativeData( + outpointTxid = ByteArray(32) { 1 }, + outpointVout = vout, + fundingType = TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND.raw, + status = 3, + registrationIndex = 0, + instantLockPresent = true, + chainLockHeight = 500, + identityRecipient = recipient, + identityRecipientUnassigned = unassigned, + ) + val recipient = ByteArray(32) { 0x2A } + val native = TrackedAssetLocksNativeResult( + arrayOf( + row(0, recipient, unassigned = false), + row(1, null, unassigned = true), + row(2, ByteArray(31), unassigned = false), // malformed: dropped + ), + ) + + val eligible = TrackedAssetLock.eligibleFromNative(native) + + assertEquals(listOf(0, 1), eligible.map { it.outpointVout }) + assertArrayEquals(recipient, eligible[0].identityRecipient) + assertFalse(eligible[0].identityRecipientUnassigned) + assertNull(eligible[1].identityRecipient) + assertTrue(eligible[1].identityRecipientUnassigned) + // The model owns its copy of the recipient too. + recipient[0] = 0 + assertEquals(0x2A, eligible[0].identityRecipient?.get(0)?.toInt()) + } } diff --git a/packages/rs-unified-sdk-jni/src/credits.rs b/packages/rs-unified-sdk-jni/src/credits.rs index 5d7831254d9..91cc1575e41 100644 --- a/packages/rs-unified-sdk-jni/src/credits.rs +++ b/packages/rs-unified-sdk-jni/src/credits.rs @@ -16,6 +16,14 @@ //! existing identity from a **new Core asset lock** (ID-05); this one //! takes a `MnemonicResolverHandle` (the Core asset-lock signer) rather //! than a plain `SignerHandle`. +//! - [`platform_wallet_top_up_external_identity_with_funding_signer`] — top +//! up an identity this wallet does not manage from a new Core asset lock; +//! the lock records the identity it pays. +//! - [`platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`] +//! — resume a tracked identity top-up lock to the identity it pays (no +//! identity argument). +//! - [`platform_wallet_assign_identity_top_up_recipient`] — assign the +//! identity an unassigned unbound top-up lock pays. //! //! ## Result convention //! @@ -26,8 +34,8 @@ #![allow(clippy::missing_safety_doc)] use crate::support::{guard, take_pwffi_error, throw_sdk_exception}; -use jni::objects::{JByteArray, JClass, JString}; -use jni::sys::{jboolean, jint, jlong}; +use jni::objects::{JByteArray, JClass, JString, JValue}; +use jni::sys::{jboolean, jint, jlong, jobject}; use jni::JNIEnv; use platform_wallet_ffi::core_wallet_types::OutPointFFI; use platform_wallet_ffi::handle::Handle; @@ -389,6 +397,163 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpId }) } +/// Top up an identity this wallet does NOT manage by building and +/// broadcasting a new Core asset lock from the wallet's balance. The lock's +/// row records `identityId` before the broadcast, so an interrupted top-up +/// resumes to that identity only (see `resumeTopUpToRecordedRecipient`). +/// Returns the identity's proved post-transition balance. +/// +/// Wraps `platform_wallet_top_up_external_identity_with_funding_signer`. Its +/// errors cross unchanged: `ErrorInvalidParameter` below the top-up minimum, +/// `ErrorIdentityNotFound` (7) for an identity Platform does not know, and a +/// persistence error when the host does not keep identity recipients. +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpExternalIdentityFromCore( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + identity_id: JByteArray, + amount_duffs: jlong, + account_index: jint, + core_signer_handle: jlong, +) -> jlong { + guard(&mut env, 0i64, |env| { + // Sign errors only: a negative value would bit-cast to a huge + // unsigned one. The amount's minimum is the wallet's to enforce. + if amount_duffs < 0 { + throw_sdk_exception(env, 1, "amountDuffs must be non-negative"); + return 0; + } + if account_index < 0 { + throw_sdk_exception(env, 1, "accountIndex must be non-negative"); + return 0; + } + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return 0; + }; + let mut out_balance: u64 = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_top_up_external_identity_with_funding_signer( + wallet_handle as Handle, + &id, + amount_duffs as u64, + account_index as u32, + core_signer_handle as *mut MnemonicResolverHandle, + &mut out_balance, + ) + }; + if take_pwffi_error(env, result) { + return 0; + } + out_balance as i64 + }) +} + +/// Resume an interrupted identity top-up from a tracked Core outpoint to the +/// identity the lock pays: a bound lock pays the wallet's identity at its +/// registration index, an unbound one the identity its row recorded. The +/// caller names no identity. Returns an `IdentityTopUpNativeResult` +/// (`([BJ)V`) carrying the identity paid and its proved new balance. +/// +/// Wraps `platform_wallet_resume_identity_top_up_to_recorded_recipient_signer`; +/// `ErrorAssetLockRecipientUnknown` (81) means the lock records no identity +/// (assign one with `assignTopUpRecipient` first). +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_resumeTopUpToRecordedRecipient( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + outpoint_txid: JByteArray, + outpoint_vout: jint, + core_signer_handle: jlong, +) -> jobject { + guard(&mut env, std::ptr::null_mut(), |env| { + let Some(outpoint) = read_outpoint(env, &outpoint_txid, outpoint_vout) else { + return std::ptr::null_mut(); + }; + let mut out_identity_id = [0u8; 32]; + let mut out_balance: u64 = 0; + let result = unsafe { + platform_wallet_ffi::platform_wallet_resume_identity_top_up_to_recorded_recipient_signer( + wallet_handle as Handle, + &outpoint, + core_signer_handle as *mut MnemonicResolverHandle, + &mut out_identity_id, + &mut out_balance, + ) + }; + if take_pwffi_error(env, result) { + return std::ptr::null_mut(); + } + let built = env.byte_array_from_slice(&out_identity_id).and_then(|id| { + env.new_object( + "org/dashfoundation/dashsdk/ffi/IdentityTopUpNativeResult", + "([BJ)V", + &[ + JValue::Object(id.as_ref()), + JValue::Long(out_balance as i64), + ], + ) + }); + match built { + Ok(object) => object.into_raw(), + Err(_) => { + // The top-up already happened; only the result could not be + // handed back. The balance refreshes through persistence. + let _ = env.exception_clear(); + throw_sdk_exception(env, 99, "identity top-up result allocation failed"); + std::ptr::null_mut() + } + } + }) +} + +/// Assign the identity an unassigned unbound identity top-up lock pays, as +/// the user chose it. Wraps `platform_wallet_assign_identity_top_up_recipient`: +/// `ErrorIdentityNotFound` (7) for an identity Platform does not know (nothing +/// assigned), `ErrorAssetLockRecipientMismatch` (61) when the lock already +/// records another identity (the same one again is a no-op). +#[no_mangle] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_assignTopUpRecipient( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + outpoint_txid: JByteArray, + outpoint_vout: jint, + identity_id: JByteArray, +) { + guard(&mut env, (), |env| { + let Some(outpoint) = read_outpoint(env, &outpoint_txid, outpoint_vout) else { + return; + }; + let Some(id) = read_id32(env, &identity_id, "identityId") else { + return; + }; + let result = unsafe { + platform_wallet_ffi::platform_wallet_assign_identity_top_up_recipient( + wallet_handle as Handle, + &outpoint, + &id, + ) + }; + take_pwffi_error(env, result); + }) +} + +/// Read a tracked-lock outpoint (32-byte wire-order txid + non-negative vout); +/// throws and returns `None` on a malformed one. +fn read_outpoint(env: &mut JNIEnv, txid: &JByteArray, vout: jint) -> Option { + let txid = read_id32(env, txid, "outpointTxid")?; + if vout < 0 { + throw_sdk_exception(env, 1, "outpointVout must be non-negative"); + return None; + } + Some(OutPointFFI { + txid, + vout: vout as u32, + }) +} + /// Size of one credit row: `u8 addressType, u8[20] hash, u64 credits`. const CREDIT_ROW_LEN: usize = 1 + 20 + 8; diff --git a/packages/rs-unified-sdk-jni/src/persistence.rs b/packages/rs-unified-sdk-jni/src/persistence.rs index 86a38c3329e..c0abd8c7513 100644 --- a/packages/rs-unified-sdk-jni/src/persistence.rs +++ b/packages/rs-unified-sdk-jni/src/persistence.rs @@ -265,9 +265,29 @@ pub(crate) fn build_extension(env: &mut JNIEnv, bridge: &JObject) -> Persistence "onPersistContactUpsert", CONTACT_UPSERT_DESCRIPTOR, ), + asset_lock_operation_ids: overrides_sidecar(env, bridge, &OPERATION_ID_SIDECAR), + asset_lock_shielded_recipients: overrides_sidecar(env, bridge, &SHIELDED_RECIPIENT_SIDECAR), + asset_lock_identity_recipients: overrides_sidecar(env, bridge, &IDENTITY_RECIPIENT_SIDECAR), }) } +/// Whether `bridge` overrides both the persist and the load method of +/// `sidecar`: an inherited no-op persist would acknowledge a value it never +/// stored, and an inherited load would report every row as recording none. +fn overrides_sidecar(env: &mut JNIEnv, bridge: &JObject, sidecar: &AssetLockSidecar) -> bool { + bridge_overrides( + env, + bridge, + sidecar.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ) && bridge_overrides( + env, + bridge, + sidecar.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ) +} + /// Leave the account-registration and address-pool slots of `vtable` unwired /// when the concrete `bridge` inherits `NativePersistenceBridge`'s /// success-returning no-op for them (see [`bridge_overrides`]). @@ -313,7 +333,7 @@ fn gate_account_writers(vtable: &mut PersistenceCallbacks, registrations: bool, /// Which optional `NativePersistenceBridge` callbacks the concrete bridge /// supplies its own body for (see [`bridge_overrides`]). -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, Default)] struct BridgeOverrides { /// `onWalletChangesetTransactionsSwept`. sweeps: bool, @@ -328,6 +348,14 @@ struct BridgeOverrides { /// vouches for the contact requests read before it, which an inherited /// no-op contact upsert never keeps. private_contact_scan_state: bool, + /// `onPersistAssetLockOperationId` and `onLoadAssetLockOperationId`. + asset_lock_operation_ids: bool, + /// `onPersistAssetLockShieldedRecipient` and + /// `onLoadAssetLockShieldedRecipient`. + asset_lock_shielded_recipients: bool, + /// `onPersistAssetLockIdentityRecipient` and + /// `onLoadAssetLockIdentityRecipient`. + asset_lock_identity_recipients: bool, } /// The extension slots wired for a bridge with `overrides` (see @@ -363,6 +391,27 @@ fn extension_for(overrides: BridgeOverrides) -> PersistenceCallbacksExtension { on_load_private_contact_scan_state_wallets_free_fn: overrides .private_contact_scan_state .then_some(tramp_load_private_contact_scan_state_wallets_free), + // Each sidecar pair is wired whole or not at all: `FFIPersister` + // attests a sidecar capability only when both of its slots are + // present, and the host declares the bit. + on_persist_asset_lock_operation_id_fn: overrides + .asset_lock_operation_ids + .then_some(tramp_persist_asset_lock_operation_id), + on_load_asset_lock_operation_id_fn: overrides + .asset_lock_operation_ids + .then_some(tramp_load_asset_lock_operation_id), + on_persist_asset_lock_shielded_recipient_fn: overrides + .asset_lock_shielded_recipients + .then_some(tramp_persist_asset_lock_shielded_recipient), + on_load_asset_lock_shielded_recipient_fn: overrides + .asset_lock_shielded_recipients + .then_some(tramp_load_asset_lock_shielded_recipient), + on_persist_asset_lock_identity_recipient_fn: overrides + .asset_lock_identity_recipients + .then_some(tramp_persist_asset_lock_identity_recipient), + on_load_asset_lock_identity_recipient_fn: overrides + .asset_lock_identity_recipients + .then_some(tramp_load_asset_lock_identity_recipient), ..Default::default() } } @@ -2192,6 +2241,237 @@ unsafe extern "C" fn tramp_persist_asset_locks( }) } +// ── Asset-lock sidecars ─────────────────────────────────────────────── + +/// Descriptor of the three `NativePersistenceBridge.onPersistAssetLock*` +/// sidecar methods: `(walletId, outPoint, value) -> rc`. +const ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR: &str = "([B[B[B)I"; + +/// Descriptor of the three `NativePersistenceBridge.onLoadAssetLock*` sidecar +/// methods: `(walletId, outPoint) -> value`, null when the row records none. +const ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR: &str = "([B[B)[B"; + +/// Width of the raw Orchard recipient `LoadAssetLockShieldedRecipientFn` +/// writes (`out_recipient_raw_43`). +const SHIELDED_RECIPIENT_LEN: usize = 43; + +/// One additive asset-lock sidecar (`PersistAssetLock*Fn` / +/// `LoadAssetLock*Fn` in `platform_wallet_ffi::persistence`): the bridge +/// methods that persist and load it and its fixed width. +struct AssetLockSidecar { + persist_method: &'static str, + load_method: &'static str, + len: usize, +} + +/// The 16-byte operation UUID (`ASSET_LOCK_OPERATION_IDS`). +const OPERATION_ID_SIDECAR: AssetLockSidecar = AssetLockSidecar { + persist_method: "onPersistAssetLockOperationId", + load_method: "onLoadAssetLockOperationId", + len: 16, +}; + +/// The raw 43-byte Orchard recipient (`ASSET_LOCK_SHIELDED_RECIPIENTS`). +const SHIELDED_RECIPIENT_SIDECAR: AssetLockSidecar = AssetLockSidecar { + persist_method: "onPersistAssetLockShieldedRecipient", + load_method: "onLoadAssetLockShieldedRecipient", + len: SHIELDED_RECIPIENT_LEN, +}; + +/// The 32-byte identity an unbound top-up pays +/// (`ASSET_LOCK_IDENTITY_RECIPIENTS`). +const IDENTITY_RECIPIENT_SIDECAR: AssetLockSidecar = AssetLockSidecar { + persist_method: "onPersistAssetLockIdentityRecipient", + load_method: "onLoadAssetLockIdentityRecipient", + len: 32, +}; + +/// Hand one sidecar value to the bridge. The bridge's return is the +/// callback's: non-zero (a different value already stored, no row, no open +/// round) fails the round. +/// +/// # Safety +/// `wallet_id` points to 32 readable bytes, `out_point` to 36 and `value` to +/// `sidecar.len`, for the duration of the call. +unsafe fn persist_asset_lock_sidecar( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + value: *const u8, + sidecar: &AssetLockSidecar, +) -> i32 { + if wallet_id.is_null() || out_point.is_null() || value.is_null() { + return ERR_JNI; + } + with_bridge(context, |env, bridge| { + let wid = id32(env, wallet_id)?; + let outpoint = bytes(env, out_point, 36)?; + let value = bytes(env, value, sidecar.len)?; + env.call_method( + bridge, + sidecar.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + &[(&wid).into(), (&outpoint).into(), (&value).into()], + )? + .i() + }) +} + +/// Ask the bridge for one sidecar value and write it out. A JVM `null` is a +/// row recording none (`*out_found = false`, success). An exception (a +/// missing or unreadable row) or a value of the wrong width returns +/// `ERR_JNI`, which fails the whole native load rather than reading as a lock +/// without the value. +/// +/// # Safety +/// `wallet_id` points to 32 readable bytes and `out_point` to 36; +/// `out_found` is writable and `out_value` points to `N` writable bytes. +unsafe fn load_asset_lock_sidecar( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_value: *mut u8, + sidecar: &AssetLockSidecar, +) -> i32 { + if wallet_id.is_null() || out_point.is_null() || out_found.is_null() || out_value.is_null() { + return ERR_JNI; + } + *out_found = false; + let loaded = with_bridge_load(context, |env, bridge| { + let wid = id32(env, wallet_id)?; + let outpoint = bytes(env, out_point, 36)?; + let value = env + .call_method( + bridge, + sidecar.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + &[(&wid).into(), (&outpoint).into()], + )? + .l()?; + if value.is_null() { + return Ok(None); + } + env.convert_byte_array(JByteArray::from(value)).map(Some) + }); + let Some(loaded) = loaded else { + return ERR_JNI; + }; + match sidecar_value::(loaded) { + Ok(None) => 0, + Ok(Some(value)) => { + ptr::copy_nonoverlapping(value.as_ptr(), out_value, N); + *out_found = true; + 0 + } + Err(()) => ERR_JNI, + } +} + +/// The `N`-byte value a sidecar load returned: `None` for a row recording +/// none, an error for a value of any other width. +fn sidecar_value(loaded: Option>) -> Result, ()> { + loaded + .map(|value| <[u8; N]>::try_from(value.as_slice()).map_err(|_| ())) + .transpose() +} + +unsafe extern "C" fn tramp_persist_asset_lock_operation_id( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + operation_id: *const u8, +) -> i32 { + persist_asset_lock_sidecar( + context, + wallet_id, + out_point, + operation_id, + &OPERATION_ID_SIDECAR, + ) +} + +unsafe extern "C" fn tramp_load_asset_lock_operation_id( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_operation_id: *mut u8, +) -> i32 { + load_asset_lock_sidecar::<16>( + context, + wallet_id, + out_point, + out_found, + out_operation_id, + &OPERATION_ID_SIDECAR, + ) +} + +unsafe extern "C" fn tramp_persist_asset_lock_shielded_recipient( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + recipient_raw_43: *const u8, +) -> i32 { + persist_asset_lock_sidecar( + context, + wallet_id, + out_point, + recipient_raw_43, + &SHIELDED_RECIPIENT_SIDECAR, + ) +} + +unsafe extern "C" fn tramp_load_asset_lock_shielded_recipient( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_recipient_raw_43: *mut u8, +) -> i32 { + load_asset_lock_sidecar::( + context, + wallet_id, + out_point, + out_found, + out_recipient_raw_43, + &SHIELDED_RECIPIENT_SIDECAR, + ) +} + +unsafe extern "C" fn tramp_persist_asset_lock_identity_recipient( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + identity_id_32: *const u8, +) -> i32 { + persist_asset_lock_sidecar( + context, + wallet_id, + out_point, + identity_id_32, + &IDENTITY_RECIPIENT_SIDECAR, + ) +} + +unsafe extern "C" fn tramp_load_asset_lock_identity_recipient( + context: *mut c_void, + wallet_id: *const u8, + out_point: *const u8, + out_found: *mut bool, + out_identity_id_32: *mut u8, +) -> i32 { + load_asset_lock_sidecar::<32>( + context, + wallet_id, + out_point, + out_found, + out_identity_id_32, + &IDENTITY_RECIPIENT_SIDECAR, + ) +} + // ── Invitations (DIP-13) ────────────────────────────────────────────── /// One bridge call per `InvitationEntryFFI` upsert / per removed outpoint, @@ -5271,6 +5551,33 @@ const BRIDGE_METHOD_TABLE: &[(&str, &str)] = &[ ("onPersistContactRemovalIncoming", "([B[B[B)I"), ("onPersistAssetLockUpsert", "([B[B[BIBIJB[B)I"), ("onPersistAssetLockRemoval", "([B[B)I"), + // Wired only for a bridge that overrides both of a pair + // (`overrides_sidecar`), so a drifted descriptor would silently drop the + // slots and the capability. + ( + OPERATION_ID_SIDECAR.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + ( + OPERATION_ID_SIDECAR.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ), + ( + SHIELDED_RECIPIENT_SIDECAR.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + ( + SHIELDED_RECIPIENT_SIDECAR.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ), + ( + IDENTITY_RECIPIENT_SIDECAR.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + ( + IDENTITY_RECIPIENT_SIDECAR.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ), ("onPersistInvitationUpsert", "([B[BIJIIZI)I"), ("onPersistInvitationRemoval", "([B[B)I"), #[cfg(feature = "shielded")] @@ -5473,6 +5780,7 @@ mod tests { header, backfill, private_contact_scan_state: false, + ..BridgeOverrides::default() }); assert_eq!( extension.on_persist_wallet_dashpay_backfill_fn.is_some(), @@ -5485,6 +5793,7 @@ mod tests { header: false, backfill: false, private_contact_scan_state: false, + ..BridgeOverrides::default() }); assert!(sweeps_only.on_persist_wallet_changeset_sweeps_fn.is_some()); assert!(sweeps_only.on_persist_wallet_dashpay_backfill_fn.is_none()); @@ -5502,6 +5811,7 @@ mod tests { header: false, backfill: false, private_contact_scan_state: wired, + ..BridgeOverrides::default() }); assert_eq!( extension.on_persist_private_contact_scan_state_fn.is_some(), @@ -5555,6 +5865,188 @@ mod tests { ); } + /// Each asset-lock sidecar pair is wired only for a bridge that overrides + /// both of its methods, independently of the others, and `FFIPersister` + /// attests the matching capability (declared by the host) only with the + /// pair wired: an inherited no-op persist would acknowledge a value it + /// never stored, an inherited load would report every row as recording + /// none. + #[test] + fn should_wire_each_asset_lock_sidecar_pair_only_for_a_bridge_that_overrides_both() { + use platform_wallet_ffi::manager::effective_persistence_capabilities; + use platform_wallet_ffi::{ + PersistenceCapabilitiesFFI, PLATFORM_WALLET_PERSISTENCE_CAPABILITIES_VERSION, + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_IDENTITY_RECIPIENTS as IDENTITY, + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_OPERATION_IDS as OPERATION, + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ASSET_LOCK_SHIELDED_RECIPIENTS as SHIELDED, + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ATOMIC_CHANGESETS, + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_TRACKED_ASSET_LOCKS, + PLATFORM_WALLET_PERSISTENCE_CAPABILITY_WALLET_RESTORE, + }; + let declared = PersistenceCapabilitiesFFI { + version: PLATFORM_WALLET_PERSISTENCE_CAPABILITIES_VERSION, + reserved: 0, + bits: PLATFORM_WALLET_PERSISTENCE_CAPABILITY_ATOMIC_CHANGESETS + | PLATFORM_WALLET_PERSISTENCE_CAPABILITY_WALLET_RESTORE + | PLATFORM_WALLET_PERSISTENCE_CAPABILITY_TRACKED_ASSET_LOCKS + | OPERATION + | SHIELDED + | IDENTITY, + }; + for (operation, shielded, identity) in [ + (false, false, false), + (true, false, false), + (false, true, false), + (false, false, true), + (true, true, true), + ] { + let extension = extension_for(BridgeOverrides { + asset_lock_operation_ids: operation, + asset_lock_shielded_recipients: shielded, + asset_lock_identity_recipients: identity, + ..BridgeOverrides::default() + }); + assert_eq!( + extension.on_persist_asset_lock_operation_id_fn.is_some(), + operation + ); + assert_eq!( + extension.on_load_asset_lock_operation_id_fn.is_some(), + operation + ); + assert_eq!( + extension + .on_persist_asset_lock_shielded_recipient_fn + .is_some(), + shielded + ); + assert_eq!( + extension.on_load_asset_lock_shielded_recipient_fn.is_some(), + shielded + ); + assert_eq!( + extension + .on_persist_asset_lock_identity_recipient_fn + .is_some(), + identity + ); + assert_eq!( + extension.on_load_asset_lock_identity_recipient_fn.is_some(), + identity + ); + + let mut vtable = build_vtable(ptr::null_mut()); + // `release_fn` must not run on the null context. + vtable.release_fn = None; + let bits = + unsafe { effective_persistence_capabilities(vtable, &declared, &extension) }.bits(); + assert_eq!(bits & OPERATION != 0, operation, "operation ids"); + assert_eq!(bits & SHIELDED != 0, shielded, "shielded recipients"); + assert_eq!(bits & IDENTITY != 0, identity, "identity recipients"); + } + } + + /// The override probe and the trampolines use one descriptor per shape, + /// matching `NativePersistenceBridge`'s `(ByteArray, ByteArray, ByteArray) + /// -> Int` persists and `(ByteArray, ByteArray) -> ByteArray?` loads. + #[test] + fn should_describe_the_asset_lock_sidecar_methods_as_the_bridge_declares_them() { + let names = |names: &[&str]| names.iter().map(|n| n.to_string()).collect::>(); + assert_eq!( + method_descriptor(&names(&["[B", "[B", "[B"]), "int"), + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR + ); + assert_eq!( + method_descriptor(&names(&["[B", "[B"]), "[B"), + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR + ); + assert_eq!(OPERATION_ID_SIDECAR.len, 16); + assert_eq!(SHIELDED_RECIPIENT_SIDECAR.len, 43); + assert_eq!(IDENTITY_RECIPIENT_SIDECAR.len, 32); + for (name, descriptor) in [ + ( + OPERATION_ID_SIDECAR.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + ( + OPERATION_ID_SIDECAR.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ), + ( + SHIELDED_RECIPIENT_SIDECAR.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + ( + SHIELDED_RECIPIENT_SIDECAR.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ), + ( + IDENTITY_RECIPIENT_SIDECAR.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + ( + IDENTITY_RECIPIENT_SIDECAR.load_method, + ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, + ), + ] { + assert!( + BRIDGE_METHOD_TABLE.contains(&(name, descriptor)), + "{name} {descriptor} is checked by the descriptor smoke test" + ); + } + } + + /// A sidecar load reads a JVM `null` as "the row records none" and + /// refuses a value of any other width, which fails the native load. + #[test] + fn should_accept_only_a_null_or_an_exact_width_sidecar_value() { + assert_eq!(sidecar_value::<32>(None), Ok(None)); + assert_eq!(sidecar_value::<32>(Some(vec![7; 32])), Ok(Some([7; 32]))); + assert_eq!(sidecar_value::<32>(Some(vec![7; 31])), Err(())); + assert_eq!(sidecar_value::<32>(Some(vec![7; 33])), Err(())); + assert_eq!(sidecar_value::<16>(Some(Vec::new())), Err(())); + } + + /// Null pointers from native are refused before the JVM is reached. + #[test] + fn should_refuse_a_sidecar_callback_with_a_null_pointer() { + let id = [0u8; 32]; + let out_point = [0u8; 36]; + let mut found = true; + let mut value = [0u8; 32]; + unsafe { + assert_eq!( + tramp_persist_asset_lock_identity_recipient( + ptr::null_mut(), + id.as_ptr(), + out_point.as_ptr(), + ptr::null(), + ), + ERR_JNI + ); + assert_eq!( + tramp_load_asset_lock_identity_recipient( + ptr::null_mut(), + id.as_ptr(), + out_point.as_ptr(), + &mut found, + ptr::null_mut(), + ), + ERR_JNI + ); + assert_eq!( + tramp_load_asset_lock_identity_recipient( + ptr::null_mut(), + ptr::null(), + out_point.as_ptr(), + &mut found, + value.as_mut_ptr(), + ), + ERR_JNI + ); + } + } + /// A read position and a shielded address survive the packed arrays the /// bridge stores and hands back, a full-width position included; an /// array that is not a whole number of rows is refused. diff --git a/packages/rs-unified-sdk-jni/src/wallet_manager.rs b/packages/rs-unified-sdk-jni/src/wallet_manager.rs index bd7aa453525..7c07e4af7da 100644 --- a/packages/rs-unified-sdk-jni/src/wallet_manager.rs +++ b/packages/rs-unified-sdk-jni/src/wallet_manager.rs @@ -3913,6 +3913,12 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_WalletManagerNative_w }) } +/// Constructor of `TrackedAssetLockNativeData`: outpoint txid and vout, lock +/// type, status, registration index, instant-lock flag, chain-lock height, the +/// recorded identity recipient (`null` when the row has none) and whether the +/// lock is an unassigned unbound top-up. +const TRACKED_ASSET_LOCK_ROW_CONSTRUCTOR: &str = "([BIIBIZI[BZ)V"; + /// Copy the manager-owned tracked-asset-lock snapshot into Kotlin value /// objects. No Rust pointer escapes this call; the paired list allocation is /// freed by [`TrackedAssetLockListGuard`] on success and every failure path. @@ -3980,9 +3986,16 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_WalletManagerNative_t for (index, row) in native_rows.iter().enumerate() { let built = env.with_local_frame(8, |env| -> Result<(), jni::errors::Error> { let txid = env.byte_array_from_slice(&row.outpoint_txid)?; + // The recorded recipient crosses only when the row has one; + // its zero-filled bytes otherwise mean nothing. + let identity_recipient: JObject = if row.has_identity_recipient { + env.byte_array_from_slice(&row.identity_recipient)?.into() + } else { + JObject::null() + }; let object = env.new_object( &row_class, - "([BIIBIZI)V", + TRACKED_ASSET_LOCK_ROW_CONSTRUCTOR, &[ JValue::Object(txid.as_ref()), JValue::Int(row.outpoint_vout as jint), @@ -3991,6 +4004,8 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_WalletManagerNative_t JValue::Int(row.registration_index as jint), JValue::Bool(row.instant_lock_present as u8), JValue::Int(row.chain_lock_height as jint), + JValue::Object(&identity_recipient), + JValue::Bool(row.identity_recipient_unassigned as u8), ], )?; env.set_object_array_element(&rows, index as i32, object) From aedcc78e2aa21f25fe921f2e2d605766d6092a9f Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sat, 14 Nov 2026 16:45:53 -0800 Subject: [PATCH 2/3] fix(kotlin-sdk): return a completed recipient top-up to a cancelled caller topUpExternalIdentityFromCore and resumeTopUpToRecordedRecipient ran under gate.op, whose withContext drops a result that arrives after the caller was cancelled. The blocking native call cannot observe cancellation, so a top-up could complete and consume its lock while the caller saw only a CancellationException; a retry with a new lock would pay the identity twice. Both now use opReturningCompletedResult, as the other credit-moving calls do. Co-Authored-By: Claude Opus 5.5 --- .../dashsdk/credits/IdentityCredits.kt | 14 +++- .../dashsdk/credits/RecipientTopUpTest.kt | 80 +++++++++++++++++++ 2 files changed, 92 insertions(+), 2 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index 9ecfa0c3eae..42c4e6552ed 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -1,6 +1,7 @@ package org.dashfoundation.dashsdk.credits import org.dashfoundation.dashsdk.wallet.op +import org.dashfoundation.dashsdk.wallet.opReturningCompletedResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -390,6 +391,12 @@ class IdentityCredits internal constructor( * built a failure may leave it tracked, recording [identityId]: never * retry with a new lock; resume that one with * [resumeTopUpToRecordedRecipient], or the identity may be paid twice. + * + * The native call cannot observe cancellation, so a top-up can complete + * after the caller was cancelled; its balance is then still returned + * ([opReturningCompletedResult][org.dashfoundation.dashsdk.wallet.opReturningCompletedResult]), + * so a completed payment is never hidden. Handle it before suspending + * again. */ suspend fun topUpExternalIdentityFromCore( walletHandle: Long, @@ -397,7 +404,7 @@ class IdentityCredits internal constructor( amountDuffs: Long, accountIndex: Int, coreSignerHandle: Long, - ): Long = gate.op { + ): Long = gate.opReturningCompletedResult { require(identityId.size == 32) { "identityId must be exactly 32 bytes, got ${identityId.size}" } @@ -428,12 +435,15 @@ class IdentityCredits internal constructor( * [AssetLockRecipientUnknown][org.dashfoundation.dashsdk.errors.DashSdkError.PlatformWallet.AssetLockRecipientUnknown]: * assign it one with [assignTopUpRecipient] first. Rust decides which * locks it resumes; nothing is filtered here. + * + * Like [topUpExternalIdentityFromCore], a resume that completes after the + * caller was cancelled still returns its result. */ suspend fun resumeTopUpToRecordedRecipient( walletHandle: Long, lock: TrackedAssetLock, coreSignerHandle: Long, - ): IdentityTopUpResult = gate.op { + ): IdentityTopUpResult = gate.opReturningCompletedResult { val native = mapNativeErrors { recipientTopUpNative.resumeTopUpToRecordedRecipient( walletHandle, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt index 7c65714b821..d9c3758eb1a 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt @@ -1,6 +1,13 @@ package org.dashfoundation.dashsdk.credits +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout import org.dashfoundation.dashsdk.errors.DashSdkError import org.dashfoundation.dashsdk.ffi.DashSDKException import org.dashfoundation.dashsdk.ffi.IdentityTopUpNativeResult @@ -181,4 +188,77 @@ class RecipientTopUpTest { ) assertTrue(native.calls.isEmpty()) } + + /** Blocks every payment until [release], as a native call that cannot see cancellation. */ + private class BlockingNative : RecipientTopUpNative { + val entered = CountDownLatch(1) + val release = CountDownLatch(1) + + private fun block() { + entered.countDown() + release.await() + } + + override fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long { + block() + return 9_000L + } + + override fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + coreSignerHandle: Long, + ): IdentityTopUpNativeResult { + block() + return IdentityTopUpNativeResult(ByteArray(32) { 7 }, 4_000L) + } + + override fun assignTopUpRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + ) = Unit + } + + /** + * A payment that completes after its caller was cancelled is still + * returned: dropping it would hide a top-up that happened, and a retry + * with a new lock would pay the identity twice. + */ + @Test + fun shouldReturnACompletedPaymentToACancelledCaller() = runBlocking { + val payments: List Long>> = listOf( + 9_000L to { it.topUpExternalIdentityFromCore(1L, ByteArray(32) { 3 }, 60_000L, 0, 2L) }, + 4_000L to { + it.resumeTopUpToRecordedRecipient( + 1L, + lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, ByteArray(32) { 7 }), + 2L, + ).newBalance + }, + ) + for ((expected, pay) in payments) { + val native = BlockingNative() + val credits = IdentityCredits(recipientTopUpNative = native) + val received = CompletableDeferred() + val caller = launch(Dispatchers.Default) { + received.complete(pay(credits)) + } + assertTrue("payment never started", native.entered.await(5, TimeUnit.SECONDS)) + caller.cancel() + native.release.countDown() + withTimeout(5_000) { caller.join() } + + assertTrue("completed payment was dropped", received.isCompleted) + assertEquals(expected, received.await()) + } + } } From 6d58b2addcaa3aae9016cef3382db48828d5f961 Mon Sep 17 00:00:00 2001 From: HashEngineering Date: Sun, 15 Nov 2026 08:35:35 -0800 Subject: [PATCH 3/3] refactor(kotlin-sdk): simplify the recipient top-up bindings and sidecar code - IdentityCredits takes one TopUpNative seam instead of two. - JNI sidecars live in one ASSET_LOCK_SIDECARS table; each width is stated once and two generic trampolines replace six forwarding ones. - Sidecar loads and the pre-persist conflict check select only the sidecar columns instead of the whole row with its transaction and proof bytes. - topUpIdentityWithExistingAssetLock uses read_outpoint; drop a dead check, an alias and copies of freshly read arrays. - Example app uses toHex() and reads the selected unassigned lock once. Co-Authored-By: Claude Opus 5.5 --- .../assetlock/IdentityAssetLockRecovery.kt | 5 +- .../ui/credits/TopUpIdentityFromCoreScreen.kt | 6 +- .../dashsdk/credits/IdentityCredits.kt | 55 ++-- .../PlatformWalletPersistenceHandler.kt | 26 +- .../dashsdk/persistence/dao/AssetLockDao.kt | 22 +- .../credits/IdentityTopUpRecoveryTest.kt | 30 +- .../dashsdk/credits/RecipientTopUpTest.kt | 18 +- .../dashsdk/credits/UnexpectedTopUpNative.kt | 40 +++ .../dashsdk/identity/InvitationReclaimTest.kt | 21 +- packages/rs-unified-sdk-jni/src/credits.rs | 10 +- .../rs-unified-sdk-jni/src/persistence.rs | 308 +++++++----------- 11 files changed, 272 insertions(+), 269 deletions(-) create mode 100644 packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/UnexpectedTopUpNative.kt diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt index e5ad810d156..a276921d893 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/assetlock/IdentityAssetLockRecovery.kt @@ -1,6 +1,7 @@ package org.dashfoundation.example.services.assetlock import org.dashfoundation.dashsdk.wallet.TrackedAssetLock +import org.dashfoundation.example.util.toHex /** Pure presentation filtering; Rust remains the recovery state machine. */ object IdentityAssetLockRecovery { @@ -47,7 +48,7 @@ object IdentityAssetLockRecovery { /** Display-only; submission passes the snapshot's original bytes/vout. */ fun label(lock: TrackedAssetLock): String = - lock.outpointTxid.reversedArray().joinToString("") { "%02x".format(it) }.take(8) + + lock.outpointTxid.reversedArray().toHex().take(8) + ":${lock.outpointVout} · ${lock.status.name.lowercase().replace('_', ' ')}" + - (lock.identityRecipient?.let { " → " + it.joinToString("") { b -> "%02x".format(b) }.take(8) } ?: "") + (lock.identityRecipient?.let { " → " + it.toHex().take(8) } ?: "") } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt index 63b3dd955aa..9447f1fb30f 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/credits/TopUpIdentityFromCoreScreen.kt @@ -201,9 +201,10 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon ) } if (unassignedLocks.isNotEmpty()) { + val selectedLock = selectedUnassignedLock ?: unassignedLocks.first() UnassignedTopUpLocks( locks = unassignedLocks, - selected = selectedUnassignedLock ?: unassignedLocks.first(), + selected = selectedLock, onSelected = { selectedUnassignedLock = it }, identityHex = assignIdentityHex, onIdentityHexChange = { assignIdentityHex = it }, @@ -211,13 +212,12 @@ fun TopUpIdentityFromCoreScreen(identityIdHex: String, navController: NavHostCon onAssign = assign@{ val mgr = manager ?: return@assign val w = wallet ?: return@assign - val lock = selectedUnassignedLock ?: unassignedLocks.first() isAssigning = true scope.launch { try { mgr.identityCredits.assignTopUpRecipient( walletHandle = w.handle, - lock = lock, + lock = selectedLock, identityId = assignIdentityHex.hexToBytes(), ) reloadKey++ diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt index 42c4e6552ed..2e94a3f3162 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/credits/IdentityCredits.kt @@ -10,8 +10,13 @@ import org.dashfoundation.dashsdk.ffi.CreditsNative import org.dashfoundation.dashsdk.ffi.IdentityTopUpNativeResult import org.dashfoundation.dashsdk.wallet.TrackedAssetLock -internal fun interface ResumeTopUpNativeCall { - fun call( +/** + * The JNI calls behind [IdentityCredits]' top-ups that resume or pay through + * an asset lock, as one seam so unit tests can stand in for the native + * library, which Robolectric cannot load. Production uses [Jni]. + */ +internal interface TopUpNative { + fun topUpIdentityWithExistingAssetLock( walletHandle: Long, outpointTxid: ByteArray, outpointVout: Int, @@ -19,14 +24,7 @@ internal fun interface ResumeTopUpNativeCall { coreSignerHandle: Long, consumeInvitationVoucher: Boolean, ): Long -} -/** - * The JNI calls behind the top-ups to any identity, as one seam so unit tests - * can stand in for the native library, which Robolectric cannot load. - * Production uses [CreditsNative]. - */ -internal interface RecipientTopUpNative { fun topUpExternalIdentityFromCore( walletHandle: Long, identityId: ByteArray, @@ -50,7 +48,23 @@ internal interface RecipientTopUpNative { ) /** [CreditsNative]'s exports. */ - object Jni : RecipientTopUpNative { + object Jni : TopUpNative { + override fun topUpIdentityWithExistingAssetLock( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + coreSignerHandle: Long, + consumeInvitationVoucher: Boolean, + ): Long = CreditsNative.topUpIdentityWithExistingAssetLock( + walletHandle, + outpointTxid, + outpointVout, + identityId, + coreSignerHandle, + consumeInvitationVoucher, + ) + override fun topUpExternalIdentityFromCore( walletHandle: Long, identityId: ByteArray, @@ -164,9 +178,7 @@ data class FundingInput( */ class IdentityCredits internal constructor( private val gate: org.dashfoundation.dashsdk.wallet.TeardownGate? = null, - private val resumeTopUpNative: ResumeTopUpNativeCall = - ResumeTopUpNativeCall(CreditsNative::topUpIdentityWithExistingAssetLock), - private val recipientTopUpNative: RecipientTopUpNative = RecipientTopUpNative.Jni, + private val native: TopUpNative = TopUpNative.Jni, ) { /** @@ -192,7 +204,7 @@ class IdentityCredits internal constructor( "top-up recovery requires funding type 1 or 2, got ${lock.fundingType.raw}" } mapNativeErrors { - resumeTopUpNative.call( + native.topUpIdentityWithExistingAssetLock( walletHandle = walletHandle, outpointTxid = lock.outpointTxid, outpointVout = lock.outpointVout, @@ -240,7 +252,7 @@ class IdentityCredits internal constructor( } require(outPointVout >= 0) { "outPointVout must be non-negative, got $outPointVout" } mapNativeErrors { - resumeTopUpNative.call( + native.topUpIdentityWithExistingAssetLock( walletHandle = walletHandle, outpointTxid = outPointTxid, outpointVout = outPointVout, @@ -409,7 +421,7 @@ class IdentityCredits internal constructor( "identityId must be exactly 32 bytes, got ${identityId.size}" } mapNativeErrors { - recipientTopUpNative.topUpExternalIdentityFromCore( + native.topUpExternalIdentityFromCore( walletHandle, identityId, amountDuffs, @@ -444,18 +456,15 @@ class IdentityCredits internal constructor( lock: TrackedAssetLock, coreSignerHandle: Long, ): IdentityTopUpResult = gate.opReturningCompletedResult { - val native = mapNativeErrors { - recipientTopUpNative.resumeTopUpToRecordedRecipient( + val paid = mapNativeErrors { + native.resumeTopUpToRecordedRecipient( walletHandle, lock.outpointTxid, lock.outpointVout, coreSignerHandle, ) } - check(native.identityId.size == 32) { - "native returned a ${native.identityId.size}-byte identity id" - } - IdentityTopUpResult(native.identityId.copyOf(), native.newBalance) + IdentityTopUpResult(paid.identityId, paid.newBalance) } /** @@ -481,7 +490,7 @@ class IdentityCredits internal constructor( "identityId must be exactly 32 bytes, got ${identityId.size}" } mapNativeErrors { - recipientTopUpNative.assignTopUpRecipient( + native.assignTopUpRecipient( walletHandle, lock.outpointTxid, lock.outpointVout, 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 6f7c8ca55e8..b0290178982 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 @@ -35,6 +35,7 @@ import org.dashfoundation.dashsdk.ffi.ShieldedViewingKeyData import org.dashfoundation.dashsdk.ffi.TrackedAssetLockRestoreData import org.dashfoundation.dashsdk.ffi.UnresolvedAssetLockTxRecordData import org.dashfoundation.dashsdk.ffi.WalletRestoreData +import org.dashfoundation.dashsdk.persistence.dao.AssetLockSidecars import org.dashfoundation.dashsdk.persistence.entities.AccountEntity import org.dashfoundation.dashsdk.persistence.entities.AssetLockEntity import org.dashfoundation.dashsdk.persistence.entities.CoreAddressEntity @@ -2433,7 +2434,6 @@ class PlatformWalletPersistenceHandler( // their own callbacks after this upsert; a later upsert of the same // row must carry them forward, never clear them (the immutability // triggers would refuse it). Keyed by outpoint, as Swift's is. - val carried = existing db.assetLockDao().upsert( AssetLockEntity( outPointHex = outPointHex, @@ -2447,9 +2447,9 @@ class PlatformWalletPersistenceHandler( proofBytes = proofBytes, createdAt = existing?.createdAt ?: java.util.Date(), updatedAt = now(), - operationId = carried?.operationId, - shieldedRecipientRaw43 = carried?.shieldedRecipientRaw43, - identityRecipientId = carried?.identityRecipientId, + operationId = existing?.operationId, + shieldedRecipientRaw43 = existing?.shieldedRecipientRaw43, + identityRecipientId = existing?.identityRecipientId, ), ) // Spend-visibility reconcile: an asset-lock tx burns its value @@ -2565,7 +2565,7 @@ class PlatformWalletPersistenceHandler( val stored = value.copyOf() val committed = runBlockingResult { val dao = database.assetLockDao() - val row = dao.getByWalletAndOutPointHex(walletId, outPointHex) + val row = dao.getSidecarsByWalletAndOutPointHex(walletId, outPointHex) val conflicting = row != null && sidecar.conflicts(row, stored) val duplicate = sidecar == AssetLockSidecar.OPERATION_ID && dao.countOtherRowsWithOperationId(walletId, stored, outPointHex) > 0 @@ -2580,10 +2580,11 @@ class PlatformWalletPersistenceHandler( val row = checkNotNull(dao.getByWalletAndOutPointHex(walletId, outPointHex)) { "asset-lock ${sidecar.label}: no row for $outPointHex" } - check(!sidecar.conflicts(row, stored)) { + val sidecars = row.sidecars() + check(!sidecar.conflicts(sidecars, stored)) { "asset lock ${sidecar.label} cannot change ($outPointHex)" } - if (sidecar.read(row) == null) { + if (sidecar.read(sidecars) == null) { dao.upsert(sidecar.write(row, stored)) } } @@ -2604,21 +2605,21 @@ class PlatformWalletPersistenceHandler( require(outPoint.size == 36) { "outpoint must be 36 bytes, got ${outPoint.size}" } val outPointHex = encodeOutPointHex(outPoint) val row = runBlockingResult { - database.assetLockDao().getByWalletAndOutPointHex(walletId, outPointHex) + database.assetLockDao().getSidecarsByWalletAndOutPointHex(walletId, outPointHex) } checkNotNull(row) { "asset-lock ${sidecar.label}: no row for $outPointHex" } sidecar.read(row)?.also { value -> check(value.size == sidecar.size) { "asset-lock ${sidecar.label} for $outPointHex is ${value.size} bytes, not ${sidecar.size}" } - }?.copyOf() + } } /** One immutable `asset_locks` sidecar column and its fixed width. */ private enum class AssetLockSidecar( val label: String, val size: Int, - val read: (AssetLockEntity) -> ByteArray?, + val read: (AssetLockSidecars) -> ByteArray?, val write: (AssetLockEntity, ByteArray) -> AssetLockEntity, ) { OPERATION_ID( @@ -2642,10 +2643,13 @@ class PlatformWalletPersistenceHandler( ; /** Whether [row] already records a value other than [value]. */ - fun conflicts(row: AssetLockEntity, value: ByteArray): Boolean = + fun conflicts(row: AssetLockSidecars, value: ByteArray): Boolean = read(row)?.contentEquals(value) == false } + private fun AssetLockEntity.sidecars() = + AssetLockSidecars(operationId, shieldedRecipientRaw43, identityRecipientId) + // ── Invitations (DIP-13) ────────────────────────────────────────── override fun onPersistInvitationUpsert( diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt index b71909a1363..cb08101d073 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/AssetLockDao.kt @@ -166,10 +166,23 @@ interface AssetLockDao { ) suspend fun fundingTypeForTxid(txidHex: String): Int? - /** The row of [walletId] at [outPointHex], for the sidecar persist and load callbacks. */ + /** The row of [walletId] at [outPointHex], for the staged sidecar write. */ @Query("SELECT * FROM asset_locks WHERE walletId = :walletId AND outPointHex = :outPointHex") suspend fun getByWalletAndOutPointHex(walletId: ByteArray, outPointHex: String): AssetLockEntity? + /** + * The sidecar columns of the row of [walletId] at [outPointHex], without + * its transaction and proof blobs; null when there is no such row. + */ + @Query( + "SELECT operationId, shieldedRecipientRaw43, identityRecipientId FROM asset_locks " + + "WHERE walletId = :walletId AND outPointHex = :outPointHex" + ) + suspend fun getSidecarsByWalletAndOutPointHex( + walletId: ByteArray, + outPointHex: String, + ): AssetLockSidecars? + /** * Whether another row of [walletId] already records [operationId]: the * `(walletId, operationId)` uniqueness the index enforces, checked first so @@ -220,3 +233,10 @@ interface AssetLockDao { @Query("SELECT COUNT(*) FROM asset_locks WHERE walletId = :walletId") fun countByWallet(walletId: ByteArray): Flow } + +/** The sidecar columns of one [AssetLockEntity] row. */ +class AssetLockSidecars( + val operationId: ByteArray?, + val shieldedRecipientRaw43: ByteArray?, + val identityRecipientId: ByteArray?, +) diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityTopUpRecoveryTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityTopUpRecoveryTest.kt index 93ac224a45f..7053c0ec82b 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityTopUpRecoveryTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/IdentityTopUpRecoveryTest.kt @@ -13,9 +13,18 @@ class IdentityTopUpRecoveryTest { fun `topup resume accepts types one and two and always refuses voucher consumption`() = runTest { val calls = mutableListOf>() val credits = IdentityCredits( - resumeTopUpNative = ResumeTopUpNativeCall { _, _, vout, _, _, consume -> - calls += Triple(vout, calls.size + 1, consume) - 123L + native = object : UnexpectedTopUpNative() { + override fun topUpIdentityWithExistingAssetLock( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + coreSignerHandle: Long, + consumeInvitationVoucher: Boolean, + ): Long { + calls += Triple(outpointVout, calls.size + 1, consumeInvitationVoucher) + return 123L + } }, ) for (type in listOf( @@ -36,9 +45,18 @@ class IdentityTopUpRecoveryTest { fun `topup rejects registration lock before JNI`() = runTest { var called = false val credits = IdentityCredits( - resumeTopUpNative = ResumeTopUpNativeCall { _, _, _, _, _, _ -> - called = true - 0 + native = object : UnexpectedTopUpNative() { + override fun topUpIdentityWithExistingAssetLock( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + coreSignerHandle: Long, + consumeInvitationVoucher: Boolean, + ): Long { + called = true + return 0 + } }, ) val failure = runCatching { diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt index d9c3758eb1a..93e0a4a47a9 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/RecipientTopUpTest.kt @@ -47,7 +47,7 @@ class RecipientTopUpTest { val resumeResult: IdentityTopUpNativeResult = IdentityTopUpNativeResult(ByteArray(32) { 7 }, 4_000L), val failure: DashSDKException? = null, - ) : RecipientTopUpNative { + ) : UnexpectedTopUpNative() { val calls = mutableListOf>() override fun topUpExternalIdentityFromCore( @@ -89,7 +89,7 @@ class RecipientTopUpTest { val native = FakeNative() val identity = ByteArray(32) { 3 } - val balance = IdentityCredits(recipientTopUpNative = native) + val balance = IdentityCredits(native = native) .topUpExternalIdentityFromCore(1L, identity, 60_000L, 0, 2L) assertEquals(9_000L, balance) @@ -105,7 +105,7 @@ class RecipientTopUpTest { fun shouldResumeEveryIdentityTopUpLockByOutpointWithoutNamingAnIdentity() = runTest { val paid = ByteArray(32) { 7 } val native = FakeNative(resumeResult = IdentityTopUpNativeResult(paid, 4_000L)) - val credits = IdentityCredits(recipientTopUpNative = native) + val credits = IdentityCredits(native = native) // Bound, unbound with a recipient, and unassigned alike: Rust decides. for (lock in listOf( @@ -134,7 +134,7 @@ class RecipientTopUpTest { failure = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 81, "assign a recipient"), ) val failure = runCatching { - IdentityCredits(recipientTopUpNative = native).resumeTopUpToRecordedRecipient( + IdentityCredits(native = native).resumeTopUpToRecordedRecipient( 1L, lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, unassigned = true), 2L, @@ -150,7 +150,7 @@ class RecipientTopUpTest { val native = FakeNative() val unassigned = lock(TrackedAssetLock.FundingType.IDENTITY_TOP_UP_NOT_BOUND, unassigned = true) - IdentityCredits(recipientTopUpNative = native).assignTopUpRecipient(1L, unassigned, identity) + IdentityCredits(native = native).assignTopUpRecipient(1L, unassigned, identity) val call = native.calls.single() assertEquals(listOf("assign", 1L), call.take(2)) @@ -162,7 +162,7 @@ class RecipientTopUpTest { failure = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 61, "cannot be resumed to"), ) val failure = runCatching { - IdentityCredits(recipientTopUpNative = mismatch).assignTopUpRecipient(1L, unassigned, identity) + IdentityCredits(native = mismatch).assignTopUpRecipient(1L, unassigned, identity) }.exceptionOrNull() assertTrue(failure is DashSdkError.PlatformWallet.AssetLockRecipientMismatch) } @@ -170,7 +170,7 @@ class RecipientTopUpTest { @Test fun shouldRefuseAnIdentityIdThatIsNot32BytesBeforeJni() = runTest { val native = FakeNative() - val credits = IdentityCredits(recipientTopUpNative = native) + val credits = IdentityCredits(native = native) assertTrue( runCatching { @@ -190,7 +190,7 @@ class RecipientTopUpTest { } /** Blocks every payment until [release], as a native call that cannot see cancellation. */ - private class BlockingNative : RecipientTopUpNative { + private class BlockingNative : UnexpectedTopUpNative() { val entered = CountDownLatch(1) val release = CountDownLatch(1) @@ -247,7 +247,7 @@ class RecipientTopUpTest { ) for ((expected, pay) in payments) { val native = BlockingNative() - val credits = IdentityCredits(recipientTopUpNative = native) + val credits = IdentityCredits(native = native) val received = CompletableDeferred() val caller = launch(Dispatchers.Default) { received.complete(pay(credits)) diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/UnexpectedTopUpNative.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/UnexpectedTopUpNative.kt new file mode 100644 index 00000000000..be00352e558 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/credits/UnexpectedTopUpNative.kt @@ -0,0 +1,40 @@ +package org.dashfoundation.dashsdk.credits + +import org.dashfoundation.dashsdk.ffi.IdentityTopUpNativeResult + +/** + * A [TopUpNative] that fails every call; tests override the calls they + * expect, so any other JNI call fails the test. + */ +internal open class UnexpectedTopUpNative : TopUpNative { + override fun topUpIdentityWithExistingAssetLock( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + coreSignerHandle: Long, + consumeInvitationVoucher: Boolean, + ): Long = throw AssertionError("unexpected topUpIdentityWithExistingAssetLock") + + override fun topUpExternalIdentityFromCore( + walletHandle: Long, + identityId: ByteArray, + amountDuffs: Long, + accountIndex: Int, + coreSignerHandle: Long, + ): Long = throw AssertionError("unexpected topUpExternalIdentityFromCore") + + override fun resumeTopUpToRecordedRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + coreSignerHandle: Long, + ): IdentityTopUpNativeResult = throw AssertionError("unexpected resumeTopUpToRecordedRecipient") + + override fun assignTopUpRecipient( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + ): Unit = throw AssertionError("unexpected assignTopUpRecipient") +} diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/InvitationReclaimTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/InvitationReclaimTest.kt index c1464a7f428..8eaaa6e2c99 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/InvitationReclaimTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/identity/InvitationReclaimTest.kt @@ -2,7 +2,7 @@ package org.dashfoundation.dashsdk.identity import kotlinx.coroutines.test.runTest import org.dashfoundation.dashsdk.credits.IdentityCredits -import org.dashfoundation.dashsdk.credits.ResumeTopUpNativeCall +import org.dashfoundation.dashsdk.credits.UnexpectedTopUpNative import org.dashfoundation.dashsdk.ffi.IdentityRegistrationNativeResult import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue @@ -23,11 +23,20 @@ class InvitationReclaimTest { var capturedVout = -1 var capturedConsume = false val credits = IdentityCredits( - resumeTopUpNative = ResumeTopUpNativeCall { _, txid, vout, _, _, consume -> - capturedTxid = txid.copyOf() - capturedVout = vout - capturedConsume = consume - 777_000L + native = object : UnexpectedTopUpNative() { + override fun topUpIdentityWithExistingAssetLock( + walletHandle: Long, + outpointTxid: ByteArray, + outpointVout: Int, + identityId: ByteArray, + coreSignerHandle: Long, + consumeInvitationVoucher: Boolean, + ): Long { + capturedTxid = outpointTxid.copyOf() + capturedVout = outpointVout + capturedConsume = consumeInvitationVoucher + return 777_000L + } }, ) diff --git a/packages/rs-unified-sdk-jni/src/credits.rs b/packages/rs-unified-sdk-jni/src/credits.rs index 91cc1575e41..5a1c813e4c4 100644 --- a/packages/rs-unified-sdk-jni/src/credits.rs +++ b/packages/rs-unified-sdk-jni/src/credits.rs @@ -304,13 +304,9 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpId consume_invitation_voucher: jboolean, ) -> jlong { guard(&mut env, 0i64, |env| { - let Some(txid) = read_id32(env, &outpoint_txid, "outpointTxid") else { + let Some(outpoint) = read_outpoint(env, &outpoint_txid, outpoint_vout) else { return 0; }; - if outpoint_vout < 0 { - throw_sdk_exception(env, 1, "outpointVout must be non-negative"); - return 0; - } let Some(id) = read_id32(env, &identity_id, "identityId") else { return 0; }; @@ -318,10 +314,6 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_CreditsNative_topUpId throw_sdk_exception(env, 1, "coreSignerHandle must be non-zero"); return 0; } - let outpoint = OutPointFFI { - txid, - vout: outpoint_vout as u32, - }; let mut out_balance = 0u64; let result = unsafe { platform_wallet_ffi::platform_wallet_topup_identity_with_existing_asset_lock_signer( diff --git a/packages/rs-unified-sdk-jni/src/persistence.rs b/packages/rs-unified-sdk-jni/src/persistence.rs index c0abd8c7513..8417249973f 100644 --- a/packages/rs-unified-sdk-jni/src/persistence.rs +++ b/packages/rs-unified-sdk-jni/src/persistence.rs @@ -265,9 +265,21 @@ pub(crate) fn build_extension(env: &mut JNIEnv, bridge: &JObject) -> Persistence "onPersistContactUpsert", CONTACT_UPSERT_DESCRIPTOR, ), - asset_lock_operation_ids: overrides_sidecar(env, bridge, &OPERATION_ID_SIDECAR), - asset_lock_shielded_recipients: overrides_sidecar(env, bridge, &SHIELDED_RECIPIENT_SIDECAR), - asset_lock_identity_recipients: overrides_sidecar(env, bridge, &IDENTITY_RECIPIENT_SIDECAR), + asset_lock_operation_ids: overrides_sidecar( + env, + bridge, + &ASSET_LOCK_SIDECARS[OPERATION_ID], + ), + asset_lock_shielded_recipients: overrides_sidecar( + env, + bridge, + &ASSET_LOCK_SIDECARS[SHIELDED_RECIPIENT], + ), + asset_lock_identity_recipients: overrides_sidecar( + env, + bridge, + &ASSET_LOCK_SIDECARS[IDENTITY_RECIPIENT], + ), }) } @@ -396,22 +408,22 @@ fn extension_for(overrides: BridgeOverrides) -> PersistenceCallbacksExtension { // present, and the host declares the bit. on_persist_asset_lock_operation_id_fn: overrides .asset_lock_operation_ids - .then_some(tramp_persist_asset_lock_operation_id), + .then_some(tramp_persist_asset_lock_sidecar::), on_load_asset_lock_operation_id_fn: overrides .asset_lock_operation_ids - .then_some(tramp_load_asset_lock_operation_id), + .then_some(tramp_load_asset_lock_sidecar::), on_persist_asset_lock_shielded_recipient_fn: overrides .asset_lock_shielded_recipients - .then_some(tramp_persist_asset_lock_shielded_recipient), + .then_some(tramp_persist_asset_lock_sidecar::), on_load_asset_lock_shielded_recipient_fn: overrides .asset_lock_shielded_recipients - .then_some(tramp_load_asset_lock_shielded_recipient), + .then_some(tramp_load_asset_lock_sidecar::), on_persist_asset_lock_identity_recipient_fn: overrides .asset_lock_identity_recipients - .then_some(tramp_persist_asset_lock_identity_recipient), + .then_some(tramp_persist_asset_lock_sidecar::), on_load_asset_lock_identity_recipient_fn: overrides .asset_lock_identity_recipients - .then_some(tramp_load_asset_lock_identity_recipient), + .then_some(tramp_load_asset_lock_sidecar::), ..Default::default() } } @@ -2251,55 +2263,63 @@ const ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR: &str = "([B[B[B)I"; /// methods: `(walletId, outPoint) -> value`, null when the row records none. const ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR: &str = "([B[B)[B"; -/// Width of the raw Orchard recipient `LoadAssetLockShieldedRecipientFn` -/// writes (`out_recipient_raw_43`). -const SHIELDED_RECIPIENT_LEN: usize = 43; - /// One additive asset-lock sidecar (`PersistAssetLock*Fn` / /// `LoadAssetLock*Fn` in `platform_wallet_ffi::persistence`): the bridge -/// methods that persist and load it and its fixed width. +/// methods that persist and load it and its fixed width, which is both the +/// width persist reads and the only width load accepts. struct AssetLockSidecar { persist_method: &'static str, load_method: &'static str, len: usize, } -/// The 16-byte operation UUID (`ASSET_LOCK_OPERATION_IDS`). -const OPERATION_ID_SIDECAR: AssetLockSidecar = AssetLockSidecar { - persist_method: "onPersistAssetLockOperationId", - load_method: "onLoadAssetLockOperationId", - len: 16, -}; - -/// The raw 43-byte Orchard recipient (`ASSET_LOCK_SHIELDED_RECIPIENTS`). -const SHIELDED_RECIPIENT_SIDECAR: AssetLockSidecar = AssetLockSidecar { - persist_method: "onPersistAssetLockShieldedRecipient", - load_method: "onLoadAssetLockShieldedRecipient", - len: SHIELDED_RECIPIENT_LEN, -}; - -/// The 32-byte identity an unbound top-up pays -/// (`ASSET_LOCK_IDENTITY_RECIPIENTS`). -const IDENTITY_RECIPIENT_SIDECAR: AssetLockSidecar = AssetLockSidecar { - persist_method: "onPersistAssetLockIdentityRecipient", - load_method: "onLoadAssetLockIdentityRecipient", - len: 32, -}; +/// Index in [`ASSET_LOCK_SIDECARS`] of the 16-byte operation UUID +/// (`ASSET_LOCK_OPERATION_IDS`). +const OPERATION_ID: usize = 0; +/// Index in [`ASSET_LOCK_SIDECARS`] of the raw 43-byte Orchard recipient +/// (`ASSET_LOCK_SHIELDED_RECIPIENTS`, `out_recipient_raw_43`). +const SHIELDED_RECIPIENT: usize = 1; +/// Index in [`ASSET_LOCK_SIDECARS`] of the 32-byte identity an unbound +/// top-up pays (`ASSET_LOCK_IDENTITY_RECIPIENTS`). +const IDENTITY_RECIPIENT: usize = 2; + +/// Every asset-lock sidecar, indexed by [`OPERATION_ID`], +/// [`SHIELDED_RECIPIENT`] and [`IDENTITY_RECIPIENT`]; the trampolines take +/// the index as a const generic. +const ASSET_LOCK_SIDECARS: [AssetLockSidecar; 3] = [ + AssetLockSidecar { + persist_method: "onPersistAssetLockOperationId", + load_method: "onLoadAssetLockOperationId", + len: 16, + }, + AssetLockSidecar { + persist_method: "onPersistAssetLockShieldedRecipient", + load_method: "onLoadAssetLockShieldedRecipient", + len: 43, + }, + AssetLockSidecar { + persist_method: "onPersistAssetLockIdentityRecipient", + load_method: "onLoadAssetLockIdentityRecipient", + len: 32, + }, +]; -/// Hand one sidecar value to the bridge. The bridge's return is the -/// callback's: non-zero (a different value already stored, no row, no open -/// round) fails the round. +/// `PersistAssetLock*Fn` for the sidecar at index `S` of +/// [`ASSET_LOCK_SIDECARS`]. The bridge's return is the callback's: non-zero +/// (a different value already stored, no row, no open round) fails the +/// round. /// /// # Safety /// `wallet_id` points to 32 readable bytes, `out_point` to 36 and `value` to -/// `sidecar.len`, for the duration of the call. -unsafe fn persist_asset_lock_sidecar( +/// the sidecar's `len`, for the duration of the call. +unsafe extern "C" fn tramp_persist_asset_lock_sidecar( context: *mut c_void, wallet_id: *const u8, out_point: *const u8, value: *const u8, - sidecar: &AssetLockSidecar, ) -> i32 { + // An out-of-range `S` fails to compile rather than panicking across the FFI. + let sidecar = const { &ASSET_LOCK_SIDECARS[S] }; if wallet_id.is_null() || out_point.is_null() || value.is_null() { return ERR_JNI; } @@ -2317,23 +2337,26 @@ unsafe fn persist_asset_lock_sidecar( }) } -/// Ask the bridge for one sidecar value and write it out. A JVM `null` is a -/// row recording none (`*out_found = false`, success). An exception (a -/// missing or unreadable row) or a value of the wrong width returns -/// `ERR_JNI`, which fails the whole native load rather than reading as a lock -/// without the value. +/// `LoadAssetLock*Fn` for the sidecar at index `S` of +/// [`ASSET_LOCK_SIDECARS`]: ask the bridge for the value and write it out. A +/// JVM `null` is a row recording none (`*out_found = false`, success). An +/// exception (a missing or unreadable row) or a value of the wrong width +/// returns `ERR_JNI`, which fails the whole native load rather than reading +/// as a lock without the value. /// /// # Safety /// `wallet_id` points to 32 readable bytes and `out_point` to 36; -/// `out_found` is writable and `out_value` points to `N` writable bytes. -unsafe fn load_asset_lock_sidecar( +/// `out_found` is writable and `out_value` points to the sidecar's `len` +/// writable bytes. +unsafe extern "C" fn tramp_load_asset_lock_sidecar( context: *mut c_void, wallet_id: *const u8, out_point: *const u8, out_found: *mut bool, out_value: *mut u8, - sidecar: &AssetLockSidecar, ) -> i32 { + // An out-of-range `S` fails to compile rather than panicking across the FFI. + let sidecar = const { &ASSET_LOCK_SIDECARS[S] }; if wallet_id.is_null() || out_point.is_null() || out_found.is_null() || out_value.is_null() { return ERR_JNI; } @@ -2357,10 +2380,10 @@ unsafe fn load_asset_lock_sidecar( let Some(loaded) = loaded else { return ERR_JNI; }; - match sidecar_value::(loaded) { + match sidecar_value(loaded, sidecar.len) { Ok(None) => 0, Ok(Some(value)) => { - ptr::copy_nonoverlapping(value.as_ptr(), out_value, N); + ptr::copy_nonoverlapping(value.as_ptr(), out_value, sidecar.len); *out_found = true; 0 } @@ -2368,108 +2391,13 @@ unsafe fn load_asset_lock_sidecar( } } -/// The `N`-byte value a sidecar load returned: `None` for a row recording +/// The `len`-byte value a sidecar load returned: `None` for a row recording /// none, an error for a value of any other width. -fn sidecar_value(loaded: Option>) -> Result, ()> { - loaded - .map(|value| <[u8; N]>::try_from(value.as_slice()).map_err(|_| ())) - .transpose() -} - -unsafe extern "C" fn tramp_persist_asset_lock_operation_id( - context: *mut c_void, - wallet_id: *const u8, - out_point: *const u8, - operation_id: *const u8, -) -> i32 { - persist_asset_lock_sidecar( - context, - wallet_id, - out_point, - operation_id, - &OPERATION_ID_SIDECAR, - ) -} - -unsafe extern "C" fn tramp_load_asset_lock_operation_id( - context: *mut c_void, - wallet_id: *const u8, - out_point: *const u8, - out_found: *mut bool, - out_operation_id: *mut u8, -) -> i32 { - load_asset_lock_sidecar::<16>( - context, - wallet_id, - out_point, - out_found, - out_operation_id, - &OPERATION_ID_SIDECAR, - ) -} - -unsafe extern "C" fn tramp_persist_asset_lock_shielded_recipient( - context: *mut c_void, - wallet_id: *const u8, - out_point: *const u8, - recipient_raw_43: *const u8, -) -> i32 { - persist_asset_lock_sidecar( - context, - wallet_id, - out_point, - recipient_raw_43, - &SHIELDED_RECIPIENT_SIDECAR, - ) -} - -unsafe extern "C" fn tramp_load_asset_lock_shielded_recipient( - context: *mut c_void, - wallet_id: *const u8, - out_point: *const u8, - out_found: *mut bool, - out_recipient_raw_43: *mut u8, -) -> i32 { - load_asset_lock_sidecar::( - context, - wallet_id, - out_point, - out_found, - out_recipient_raw_43, - &SHIELDED_RECIPIENT_SIDECAR, - ) -} - -unsafe extern "C" fn tramp_persist_asset_lock_identity_recipient( - context: *mut c_void, - wallet_id: *const u8, - out_point: *const u8, - identity_id_32: *const u8, -) -> i32 { - persist_asset_lock_sidecar( - context, - wallet_id, - out_point, - identity_id_32, - &IDENTITY_RECIPIENT_SIDECAR, - ) -} - -unsafe extern "C" fn tramp_load_asset_lock_identity_recipient( - context: *mut c_void, - wallet_id: *const u8, - out_point: *const u8, - out_found: *mut bool, - out_identity_id_32: *mut u8, -) -> i32 { - load_asset_lock_sidecar::<32>( - context, - wallet_id, - out_point, - out_found, - out_identity_id_32, - &IDENTITY_RECIPIENT_SIDECAR, - ) +fn sidecar_value(loaded: Option>, len: usize) -> Result>, ()> { + match loaded { + Some(value) if value.len() != len => Err(()), + loaded => Ok(loaded), + } } // ── Invitations (DIP-13) ────────────────────────────────────────────── @@ -5555,27 +5483,27 @@ const BRIDGE_METHOD_TABLE: &[(&str, &str)] = &[ // (`overrides_sidecar`), so a drifted descriptor would silently drop the // slots and the capability. ( - OPERATION_ID_SIDECAR.persist_method, + ASSET_LOCK_SIDECARS[OPERATION_ID].persist_method, ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, ), ( - OPERATION_ID_SIDECAR.load_method, + ASSET_LOCK_SIDECARS[OPERATION_ID].load_method, ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, ), ( - SHIELDED_RECIPIENT_SIDECAR.persist_method, + ASSET_LOCK_SIDECARS[SHIELDED_RECIPIENT].persist_method, ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, ), ( - SHIELDED_RECIPIENT_SIDECAR.load_method, + ASSET_LOCK_SIDECARS[SHIELDED_RECIPIENT].load_method, ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, ), ( - IDENTITY_RECIPIENT_SIDECAR.persist_method, + ASSET_LOCK_SIDECARS[IDENTITY_RECIPIENT].persist_method, ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, ), ( - IDENTITY_RECIPIENT_SIDECAR.load_method, + ASSET_LOCK_SIDECARS[IDENTITY_RECIPIENT].load_method, ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, ), ("onPersistInvitationUpsert", "([B[BIJIIZI)I"), @@ -5960,39 +5888,21 @@ mod tests { method_descriptor(&names(&["[B", "[B"]), "[B"), ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR ); - assert_eq!(OPERATION_ID_SIDECAR.len, 16); - assert_eq!(SHIELDED_RECIPIENT_SIDECAR.len, 43); - assert_eq!(IDENTITY_RECIPIENT_SIDECAR.len, 32); - for (name, descriptor) in [ - ( - OPERATION_ID_SIDECAR.persist_method, - ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, - ), - ( - OPERATION_ID_SIDECAR.load_method, - ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, - ), - ( - SHIELDED_RECIPIENT_SIDECAR.persist_method, - ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, - ), - ( - SHIELDED_RECIPIENT_SIDECAR.load_method, - ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, - ), - ( - IDENTITY_RECIPIENT_SIDECAR.persist_method, - ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, - ), - ( - IDENTITY_RECIPIENT_SIDECAR.load_method, - ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR, - ), - ] { - assert!( - BRIDGE_METHOD_TABLE.contains(&(name, descriptor)), - "{name} {descriptor} is checked by the descriptor smoke test" - ); + // Every sidecar's pair is in the table the descriptor smoke test + // resolves against the bridge class. + for sidecar in &ASSET_LOCK_SIDECARS { + for (name, descriptor) in [ + ( + sidecar.persist_method, + ASSET_LOCK_SIDECAR_PERSIST_DESCRIPTOR, + ), + (sidecar.load_method, ASSET_LOCK_SIDECAR_LOAD_DESCRIPTOR), + ] { + assert!( + BRIDGE_METHOD_TABLE.contains(&(name, descriptor)), + "{name} {descriptor} is checked by the descriptor smoke test" + ); + } } } @@ -6000,11 +5910,11 @@ mod tests { /// refuses a value of any other width, which fails the native load. #[test] fn should_accept_only_a_null_or_an_exact_width_sidecar_value() { - assert_eq!(sidecar_value::<32>(None), Ok(None)); - assert_eq!(sidecar_value::<32>(Some(vec![7; 32])), Ok(Some([7; 32]))); - assert_eq!(sidecar_value::<32>(Some(vec![7; 31])), Err(())); - assert_eq!(sidecar_value::<32>(Some(vec![7; 33])), Err(())); - assert_eq!(sidecar_value::<16>(Some(Vec::new())), Err(())); + assert_eq!(sidecar_value(None, 32), Ok(None)); + assert_eq!(sidecar_value(Some(vec![7; 32]), 32), Ok(Some(vec![7; 32]))); + assert_eq!(sidecar_value(Some(vec![7; 31]), 32), Err(())); + assert_eq!(sidecar_value(Some(vec![7; 33]), 32), Err(())); + assert_eq!(sidecar_value(Some(Vec::new()), 16), Err(())); } /// Null pointers from native are refused before the JVM is reached. @@ -6016,7 +5926,7 @@ mod tests { let mut value = [0u8; 32]; unsafe { assert_eq!( - tramp_persist_asset_lock_identity_recipient( + tramp_persist_asset_lock_sidecar::( ptr::null_mut(), id.as_ptr(), out_point.as_ptr(), @@ -6025,7 +5935,7 @@ mod tests { ERR_JNI ); assert_eq!( - tramp_load_asset_lock_identity_recipient( + tramp_load_asset_lock_sidecar::( ptr::null_mut(), id.as_ptr(), out_point.as_ptr(), @@ -6035,7 +5945,7 @@ mod tests { ERR_JNI ); assert_eq!( - tramp_load_asset_lock_identity_recipient( + tramp_load_asset_lock_sidecar::( ptr::null_mut(), ptr::null(), out_point.as_ptr(),