diff --git a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md index 76c3b3c359e..9f3a6548066 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md +++ b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md @@ -211,6 +211,7 @@ Most Platform actions have hard preconditions. Establish these fixtures before s | DOC-13 | Aggregation β€” sum of a numeric property | Platform | Uncommon | πŸ§ͺ | | **Sum / Average Documents** screen (op selector β†’ **Sum**) β†’ `dash_sdk_document_sum`. | | DOC-14 | Aggregation β€” average of a numeric property | Platform | Uncommon | πŸ§ͺ | | Same screen (op selector β†’ **Average**) β†’ `dash_sdk_document_average`. | | DOC-15 | Document transfer / purchase across wallets | Platform | Uncommon | βœ… | multiwallet | A creates + lists a document (`DOC-02`/`DOC-06`); B transfers/purchases it (`DOC-05`/`DOC-07`). | +| DOC-16 | Erase a deleted keep-history document's revisions | Platform | Thorough | πŸ§ͺ | | **Browse Documents** β†’ document β†’ **Actions…** β†’ **Erase Document…** (or the **Erase Document** catalog entry) β†’ `DocumentTransactions.erase` β†’ `platform_wallet_document_erase`. Needs a `documentsKeepHistory` type with `canBeErased: true` and a document already deleted via `DOC-04`; the first erase must be signed by the owner, later ones by any identity, each removing up to 100 revisions. Not driven on a device; no such type exists on testnet yet. | ### 4.8 Tokens β€” `Domain=Token` diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/transitions/StateTransitionDefinitions.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/transitions/StateTransitionDefinitions.kt index 9ac7a012499..971625ea16d 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/transitions/StateTransitionDefinitions.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/services/transitions/StateTransitionDefinitions.kt @@ -243,6 +243,19 @@ object StateTransitionDefinitions { executable = true, dedicatedRoute = DedicatedTransition.DOCUMENT_ACTIONS, ), + TransitionDefinition( + key = "documentErase", + category = TransitionCategory.DOCUMENT, + label = "Erase Document", + description = "Erase the retained revisions of a deleted keep-history document", + inputs = listOf( + TransitionInput("contractId", contractPicker, "Data contract", true), + TransitionInput("documentType", docTypePicker, "Document type", true), + TransitionInput("documentId", docPicker, "Document ID", false), + ), + executable = true, + dedicatedRoute = DedicatedTransition.DOCUMENT_ACTIONS, + ), TransitionDefinition( key = "documentTransfer", category = TransitionCategory.DOCUMENT, diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/ContractJson.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/ContractJson.kt index 7222465afcb..4cee8ffb8c2 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/ContractJson.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/ContractJson.kt @@ -87,6 +87,12 @@ internal fun JsonObject.objectField(key: String): JsonObject? = this[key] as? Js internal data class DocumentTypeCapabilities( val documentsMutable: Boolean, val canBeDeleted: Boolean, + /** + * Whether a deleted document's retained revisions may be erased. Only + * a keep-history type can set it, it has no contract-config default, + * and it is off unless the schema says otherwise. + */ + val canBeErased: Boolean, ) /** @@ -111,6 +117,7 @@ internal fun documentTypeCapabilities( ?: config?.boolField("documentsMutableContractDefault") ?: true, canBeDeleted = schema?.boolField("canBeDeleted") ?: config?.boolField("documentsCanBeDeletedContractDefault") ?: true, + canBeErased = schema?.boolField("canBeErased") ?: false, ) /** diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentActionsScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentActionsScreen.kt index 89b30ee1db1..fdccdbda59f 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentActionsScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentActionsScreen.kt @@ -35,11 +35,15 @@ import androidx.compose.ui.platform.testTag import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonObject import org.dashfoundation.dashsdk.persistence.entities.IdentityEntity +import org.dashfoundation.dashsdk.queries.DocumentLifecycle +import org.dashfoundation.dashsdk.queries.DocumentLifecycleState +import org.dashfoundation.dashsdk.queries.describeEraseProgress import org.dashfoundation.example.di.LocalAppContainer import org.dashfoundation.example.di.LocalAppState import org.dashfoundation.example.ui.components.AccessiblePicker @@ -57,10 +61,11 @@ import org.dashfoundation.example.util.truncateMiddle /** * Owned-document actions for one document β€” the DOC-03 replace / DOC-04 - * delete / DOC-05 transfer flows the iOS document ops menu ships - * (`ManagedPlatformWallet.replaceDocument` / `deleteDocument` / - * `transferDocument`). Reached from a document row's "Actions…" button and - * from the document replace/delete/transfer transition-catalog entries. + * delete / DOC-05 transfer flows the iOS document ops menu ships, plus the + * erase (`ManagedPlatformWallet.replaceDocument` / `deleteDocument` / + * `eraseDocument` / `transferDocument`). Reached from a document row's + * "Actions…" button and from the document replace/delete/erase/transfer + * transition-catalog entries. * * The document is probed by id (debounced, like [DocumentWithPriceScreen]) so * the acting-identity ownership badge and the replace-field prefill reflect @@ -120,11 +125,13 @@ fun DocumentActionsScreen( var recipient by remember { mutableStateOf(null) } var showDeleteConfirm by remember { mutableStateOf(false) } + var showEraseConfirm by remember { mutableStateOf(false) } var isSubmitting by remember { mutableStateOf(false) } var error by remember { mutableStateOf(null) } var replaceSuccess by remember { mutableStateOf(null) } var deleteSuccess by remember { mutableStateOf(null) } + var eraseSuccess by remember { mutableStateOf(null) } var transferSuccess by remember { mutableStateOf(null) } val schema = remember(contract?.lastUpdated, typeName) { @@ -148,6 +155,7 @@ fun DocumentActionsScreen( val documentsMutable = capabilities.documentsMutable val immutability = remember(schema) { documentTypeImmutability(schema) } val canBeDeleted = capabilities.canBeDeleted + val canBeErased = capabilities.canBeErased // Default acting identity to the on-chain owner when it's one of ours, // else the first identity β€” replace/delete/transfer require ownership. @@ -492,6 +500,46 @@ fun DocumentActionsScreen( ) { showDeleteConfirm = true } } + // ── Erase ───────────────────────────────────────────────────── + // A deleted document is invisible to the probe above, so the + // erase cannot be ownership-gated here; consensus refuses a + // first erase from anyone but the owner (a paid rejection) and + // accepts later ones from any identity. + FormSection(title = "Erase") { + Text( + "Remove the retained revisions of a document that has already " + + "been deleted. Each erase removes up to 100 revisions; the " + + "lifecycle read after each one says how many remain.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.testTag("documentActions.erase"), + ) + eraseSuccess?.let { + Text( + it, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.testTag("eraseDocument.success"), + ) + } + if (!canBeErased) { + Text( + "This document type cannot be erased β€” an erase will be " + + "rejected by consensus (fees are still charged).", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + SubmitButton( + text = "Erase Document…", + isLoading = false, + enabled = !isSubmitting && actingIdentity != null && manager != null && + canBeErased && documentIdText.isNotBlank(), + modifier = Modifier + .fillMaxWidth() + .testTag("eraseDocument.button"), + ) { showEraseConfirm = true } + } + // ── Transfer (DOC-05) ───────────────────────────────────────── FormSection(title = "Transfer") { Text( @@ -603,9 +651,109 @@ fun DocumentActionsScreen( ) } + if (showEraseConfirm) { + AlertDialog( + onDismissRequest = { showEraseConfirm = false }, + title = { Text("Erase document history?") }, + text = { + Text( + "This removes up to 100 retained revisions of the deleted document " + + "${truncateMiddle(documentIdText.trim(), 8, 6)}. " + + "Signing identity: $actingB58. " + + "This cannot be undone.", + ) + }, + confirmButton = { + TextButton( + onClick = { + showEraseConfirm = false + val signer = actingIdentity ?: return@TextButton + val docIdBytes = Base58.decodeIdentifier(documentIdText.trim()) + ?: return@TextButton + submitDocumentTransaction( + begin = { isSubmitting = true; eraseSuccess = null }, + end = { isSubmitting = false }, + fail = { error = it }, + scope = scope, + ) { + val (wallet, mgr, signingKeyId) = resolveSigning(container, signer) + val docIdB58 = Base58.encode(docIdBytes) + eraseSuccess = eraseAndDescribe( + readLifecycle = { + sdk?.documents?.lifecycle(contractIdBase58, typeName, docIdB58) + }, + ) { + mgr.documentTransactions.erase( + walletHandle = wallet, + ownerId = signer.identityId, + contractId = contractIdBytes, + documentType = typeName, + documentId = docIdBytes, + signingKeyId = signingKeyId, + signerHandle = mgr.signerHandle, + ) + } + } + }, + modifier = Modifier.testTag("eraseDocument.confirm"), + ) { Text("Erase") } + }, + dismissButton = { + TextButton(onClick = { showEraseConfirm = false }) { Text("Cancel") } + }, + ) + } + ErrorAlertDialog(message = error, onDismiss = { error = null }) } +/** + * Submit the erase, then say what it achieved, from the lifecycle read before + * it and the one read after. Extracted from [DocumentActionsScreen] so the + * failure split is unit-testable. + * + * An ACTIVE or ABSENT lifecycle read returns without invoking [erase]. ABSENT + * means no retained revisions exist; it does not establish a completed erase. + * + * Only [erase] decides whether the submission succeeded. The erase result + * itself observes only that the document is absent from ordinary reads, which + * it already was, so the lifecycle is the account of what was removed β€” but it + * is an observation of an already-broadcast, already-confirmed transition. A + * read that fails therefore leaves the erase successful and merely unreported; + * surfacing it as a failure would invite a second, fee-bearing erase. A + * [CancellationException] still propagates so structured concurrency is intact. + */ +internal suspend fun eraseAndDescribe( + readLifecycle: suspend () -> DocumentLifecycle?, + erase: suspend () -> Unit, +): String { + suspend fun observe(): DocumentLifecycle? = try { + readLifecycle() + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + null + } + + val before = observe() + if (before?.state == DocumentLifecycleState.ACTIVE || before?.state == DocumentLifecycleState.ABSENT) { + val progress = if (before.state == DocumentLifecycleState.ABSENT) { + "No retained revisions exist." + } else { + describeEraseProgress(before, before) + } + return "Erase not submitted. Lifecycle: ${before.state}. $progress" + } + erase() + val after = observe() + return "Erase submitted; document absence observed. " + + if (after != null) { + describeEraseProgress(before, after) + } else { + "Lifecycle not read; query the document history to see what remains." + } +} + /** The owner + current field values [DocumentActionsScreen]'s probe reads. */ private data class ProbedActionDocument( val ownerBase58: String?, diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt index 56e4b3ef4ed..71f6ed28905 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/DocumentTypeDetailsScreen.kt @@ -201,6 +201,10 @@ fun DocumentTypeDetailsScreen( "Can Be Deleted", if (capabilities.canBeDeleted) "Yes" else "No", ) + LabeledContent( + "Can Be Erased", + if (capabilities.canBeErased) "Yes" else "No", + ) LabeledContent( "Transferable", if ((schema.intField("transferable") ?: 0) > 0) "Yes" else "No", diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/DocumentTypeCapabilitiesTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/DocumentTypeCapabilitiesTest.kt index d3e0f2e903a..1e650ca8afb 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/DocumentTypeCapabilitiesTest.kt +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/DocumentTypeCapabilitiesTest.kt @@ -66,4 +66,23 @@ class DocumentTypeCapabilitiesTest { val config = buildJsonObject { put("documentsCanBeDeletedContractDefault", false) } assertTrue(documentTypeCapabilities(schema, config).canBeDeleted) } + + @Test + fun canBeErasedIsOffUnlessTheSchemaSetsIt() { + // Erasure has no contract-config default: a type that does not say + // `canBeErased` cannot be erased, however deletable it is, so the + // Erase action must stay disabled for it. + val deletable = buildJsonObject { + put("documentsKeepHistory", true) + put("canBeDeleted", true) + } + assertFalse(documentTypeCapabilities(deletable, config = null).canBeErased) + + val erasable = buildJsonObject { + put("documentsKeepHistory", true) + put("canBeDeleted", true) + put("canBeErased", true) + } + assertTrue(documentTypeCapabilities(erasable, config = null).canBeErased) + } } diff --git a/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/EraseAndDescribeTest.kt b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/EraseAndDescribeTest.kt new file mode 100644 index 00000000000..6ecaeaf8604 --- /dev/null +++ b/packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/EraseAndDescribeTest.kt @@ -0,0 +1,145 @@ +package org.dashfoundation.example.ui.contracts + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runTest +import org.dashfoundation.dashsdk.queries.DocumentLifecycle +import org.dashfoundation.dashsdk.queries.DocumentLifecycleState +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Pins the failure split in [eraseAndDescribe]: the erase decides the + * submission, the lifecycle reads only describe it. + * + * A failed lifecycle observation must not report a broadcast as failed or + * invite another fee-bearing submission. An ACTIVE or ABSENT observation + * before the broadcast must instead explain why no submission is needed. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class EraseAndDescribeTest { + + private fun lifecycle(state: DocumentLifecycleState, remaining: Long) = DocumentLifecycle( + state = state, + remainingRevisions = remaining.toULong(), + deletedAtMs = if (state == DocumentLifecycleState.DELETED || state == DocumentLifecycleState.ERASING) { + 1_700_000_000_001uL + } else { + 0uL + }, + erasingStartedAtMs = if (state == DocumentLifecycleState.ERASING) 1_700_000_000_002uL else 0uL, + erasingFromTimeMs = if (state == DocumentLifecycleState.ERASING) 1_700_000_000_000uL else 0uL, + erasingFromRevision = if (state == DocumentLifecycleState.ERASING) 7uL else 0uL, + ) + + @Test + fun activeOrAbsentLifecycleSkipsThePaidErase() = runTest { + for (state in listOf(DocumentLifecycleState.ACTIVE, DocumentLifecycleState.ABSENT)) { + var erases = 0 + var reads = 0 + val message = eraseAndDescribe( + readLifecycle = { reads++; lifecycle(state, 0) }, + erase = { erases++ }, + ) + assertEquals("no erase is needed for $state", 0, erases) + assertEquals("no post-broadcast read is needed", 1, reads) + assertTrue(message, message.startsWith("Erase not submitted")) + assertTrue(message, message.contains(state.name)) + if (state == DocumentLifecycleState.ABSENT) { + assertTrue(message, message.contains("No retained revisions exist")) + assertFalse(message, message.contains("Erasure complete")) + } + } + } + + @Test + fun lifecycleReadFailureAfterBroadcast_stillReportsSuccess() = runTest { + var eraseCount = 0 + var reads = 0 + + val message = eraseAndDescribe( + readLifecycle = { + reads++ + if (reads == 1) { + lifecycle(DocumentLifecycleState.DELETED, 150) + } else { + throw IllegalStateException("DAPI timeout") // after the broadcast + } + }, + erase = { eraseCount++ }, + ) + + assertEquals("the erase must have been submitted exactly once", 1, eraseCount) + assertTrue(message, message.startsWith("Erase submitted")) + assertTrue(message, message.contains("Lifecycle not read")) + } + + @Test + fun lifecycleReadFailureBeforeBroadcast_stillSubmitsAndDescribes() = runTest { + var eraseCount = 0 + var reads = 0 + + val message = eraseAndDescribe( + readLifecycle = { + reads++ + if (reads == 1) throw IllegalStateException("DAPI timeout") + lifecycle(DocumentLifecycleState.ERASING, 50) + }, + erase = { eraseCount++ }, + ) + + assertEquals(1, eraseCount) + assertTrue(message, message.contains("Erasure in progress: 50")) + } + + @Test + fun eraseFailureIsNotDressedUpAsASubmission() = runTest { + var reads = 0 + val thrown = runCatching { + eraseAndDescribe( + readLifecycle = { reads++; lifecycle(DocumentLifecycleState.DELETED, 150) }, + erase = { throw IllegalStateException("broadcast rejected") }, + ) + }.exceptionOrNull() + + assertTrue("the erase's own failure must reach the caller", thrown is IllegalStateException) + assertEquals("the closing read must not run after a failed erase", 1, reads) + } + + @Test + fun cancellationIsNotSwallowedByTheReadGuard() = runTest { + var eraseCount = 0 + val thrown = runCatching { + eraseAndDescribe( + readLifecycle = { throw CancellationException("screen disposed") }, + erase = { eraseCount++ }, + ) + }.exceptionOrNull() + + assertTrue( + "cancellation must propagate so structured concurrency is intact", + thrown is CancellationException, + ) + assertEquals("a cancelled read must not go on to submit the erase", 0, eraseCount) + } + + @Test + fun completedErasureIsDescribedFromTheLifecycleReads() = runTest { + var reads = 0 + val message = eraseAndDescribe( + readLifecycle = { + reads++ + if (reads == 1) { + lifecycle(DocumentLifecycleState.DELETED, 100) + } else { + lifecycle(DocumentLifecycleState.ABSENT, 0) + } + }, + erase = {}, + ) + + assertTrue(message, message.contains("Erasure complete")) + } +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentTransactions.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentTransactions.kt index 866dfffea82..16223d93864 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentTransactions.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentTransactions.kt @@ -222,6 +222,51 @@ class DocumentTransactions internal constructor( } } + /** + * Erase + broadcast a chunk of the retained revisions of the already + * deleted [documentId] on [contractId]'s [documentType] β€” signed via + * [signerHandle] with key [signingKeyId] of [ownerId]. Mirrors Swift + * `ManagedPlatformWallet.eraseDocument`. Only valid for a keep-history + * type whose schema sets `canBeErased`, and only after the document has + * been deleted; the first erase must be signed by the document's owner, + * later ones by any identity. One call removes a bounded chunk of + * revisions. + * + * A return means the transition was broadcast and Platform proved the + * document absent from ordinary reads β€” which it already was before the + * erase β€” so it observes the affected state rather than proving that + * this erase removed a revision. Read `Documents.lifecycle` (or + * `Documents.history`) for the current state and the exact number of + * revisions still retained, and erase again while there are any. + * + * @return the document's 32-byte id whose absence was observed. + */ + suspend fun erase( + walletHandle: Long, + ownerId: ByteArray, + contractId: ByteArray, + documentType: String, + documentId: ByteArray, + signingKeyId: Int, + signerHandle: Long, + ): ByteArray = gate.op { + require(ownerId.size == 32) { "ownerId must be 32 bytes" } + require(contractId.size == 32) { "contractId must be 32 bytes" } + require(documentId.size == 32) { "documentId must be 32 bytes" } + require(signingKeyId >= 0) { "signingKeyId must be non-negative, got $signingKeyId" } + mapNativeErrors { + TransactionsNative.documentErase( + walletHandle, + ownerId, + contractId, + documentType, + documentId, + signingKeyId, + signerHandle, + ) + } + } + /** * Transfer + broadcast [documentId] on [contractId]'s [documentType], * from [ownerId] to [recipientId] β€” signed via [signerHandle] with key diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt index 250db3a5144..4a4e68cd2d4 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/QueriesNative.kt @@ -147,6 +147,24 @@ internal object QueriesNative { startAt: Int, ): String? + /** + * JSON page of a keep-history document's revisions plus its lifecycle + * block, from `dash_sdk_document_fetch_history`. [filter] is the C + * enum discriminant (0 start-at time, 1 start-after cursor, 2 start-at + * revision, 3 single revision); [timeMs] / [revision] are read according + * to it; [limit] 0 takes the server default. + */ + external fun documentHistory( + sdk: Long, + contractId: String, + documentType: String, + documentId: String, + filter: Int, + timeMs: Long, + revision: Long, + limit: Int, + ): String? + /** JSON count result (optionally grouped). */ external fun documentCount( sdk: Long, diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/TransactionsNative.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/TransactionsNative.kt index a328b0e9396..5f8e979746c 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/TransactionsNative.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/TransactionsNative.kt @@ -181,6 +181,26 @@ internal object TransactionsNative { signerHandle: Long, ): ByteArray + /** + * Erase + broadcast a chunk of the retained revisions of the already + * deleted [documentId] on [contractId]'s [documentType], signed via + * [signerHandle] with key [signingKeyId] of [ownerId]. Bridges + * `platform_wallet_document_erase` (Swift + * `ManagedPlatformWallet.eraseDocument`). The first erase of a document + * must be signed by its owner; later ones may be signed by any + * identity. Erase returns no document body, so this returns the erased + * document's 32-byte id for confirmation. + */ + external fun documentErase( + walletHandle: Long, + ownerId: ByteArray, + contractId: ByteArray, + documentType: String, + documentId: ByteArray, + signingKeyId: Int, + signerHandle: Long, + ): ByteArray + /** * Transfer + broadcast [documentId] on [contractId]'s [documentType], * from [ownerId] to [recipientId], signed via [signerHandle] with key diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentHistory.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentHistory.kt new file mode 100644 index 00000000000..80a4ff29265 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/DocumentHistory.kt @@ -0,0 +1,122 @@ +package org.dashfoundation.dashsdk.queries + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * Which revisions of a keep-history document [Documents.history] reads. + * Exactly one filter applies per call. [code] is the discriminant of the + * FFI's `DashSDKDocumentHistoryFilter`; [timeMs] and [revision] carry the + * filter's operands, zero where the filter has none. + */ +sealed class DocumentHistoryFilter( + internal val code: Int, + internal val timeMs: Long, + internal val revision: Long, +) { + /** Revisions written at or after [ms], oldest first; 0 is the first page of everything. */ + class StartAtTime(ms: Long) : DocumentHistoryFilter(0, ms, 0) + + /** Revisions after the complete cursor of the last entry received. */ + class StartAfter(timeMs: Long, revision: Long) : DocumentHistoryFilter(1, timeMs, revision) + + /** Revisions from history sequence number [revision] onwards. */ + class StartAtRevision(revision: Long) : DocumentHistoryFilter(2, 0, revision) + + /** Exactly the revision at history sequence number [revision]; limit must be 1. */ + class Revision(revision: Long) : DocumentHistoryFilter(3, 0, revision) +} + +/** Where a keep-history document stands, as the history query authenticates it. */ +enum class DocumentLifecycleState { + /** Visible to ordinary reads. */ + ACTIVE, + + /** Deleted with its revisions retained. */ + DELETED, + + /** An authorized erasure has begun and revisions are being removed. */ + ERASING, + + /** Nothing is left. */ + ABSENT, +} + +/** + * The `lifecycle` block of a [Documents.history] page. Times are epoch + * milliseconds. Deletion time is set only while DELETED or ERASING; erase + * times and the erase cursor are set only while ERASING. They are zero otherwise. + */ +data class DocumentLifecycle( + val state: DocumentLifecycleState, + /** Exact count of revisions still retained; zero when absent. */ + val remainingRevisions: ULong, + val deletedAtMs: ULong, + val erasingStartedAtMs: ULong, + val erasingFromTimeMs: ULong, + val erasingFromRevision: ULong, +) { + companion object { + /** + * Parse the lifecycle block out of a history page JSON object; null + * when the block, its state, or any of its numbers is missing or + * malformed, so a partial block is never read as zeros. + */ + fun fromHistoryJson(historyJson: String): DocumentLifecycle? = try { + val root = Json.parseToJsonElement(historyJson).jsonObject + (root["lifecycle"] as? JsonObject)?.let(::fromLifecycleObject) + } catch (_: Exception) { + null + } + + private fun fromLifecycleObject(obj: JsonObject): DocumentLifecycle? { + val state = obj["state"]?.jsonPrimitive?.takeIf { it.isString }?.content + ?.let { name -> DocumentLifecycleState.entries.firstOrNull { it.name == name } } + ?: return null + // Rust serializes these as unsigned integers: a JSON string or a + // negative number is a malformed block, not a value to display. + fun number(key: String): ULong? = obj[key]?.jsonPrimitive + ?.takeUnless { it.isString } + ?.content?.toULongOrNull() + return DocumentLifecycle( + state = state, + remainingRevisions = number("remaining_revisions") ?: return null, + deletedAtMs = number("deleted_at_ms") ?: return null, + erasingStartedAtMs = number("erasing_started_at_ms") ?: return null, + erasingFromTimeMs = number("erasing_from_time_ms") ?: return null, + erasingFromRevision = number("erasing_from_revision") ?: return null, + ) + } + } +} + +/** + * Describe what an erase achieved, from the lifecycle read [before] it was + * submitted (null when not read) and the one read [after] its absence was + * observed. The erase result itself proves only that the document is absent + * from ordinary reads, which it already was, so the words come from the + * lifecycle: a document still DELETED with the same retained count is + * reported as not established, never as an accepted or completed erase. + */ +fun describeEraseProgress(before: DocumentLifecycle?, after: DocumentLifecycle): String = when (after.state) { + DocumentLifecycleState.ABSENT -> + "Erasure complete: no retained revisions remain." + DocumentLifecycleState.ERASING -> + "Erasure in progress: ${after.remainingRevisions} revisions still retained; " + + "submit another erase to continue." + DocumentLifecycleState.DELETED -> + if (before != null && before.state == DocumentLifecycleState.DELETED && + before.remainingRevisions == after.remainingRevisions + ) { + "Not established: the document is still DELETED with " + + "${after.remainingRevisions} revisions retained, so the history shows " + + "nothing this erase removed." + } else { + "The document is DELETED with ${after.remainingRevisions} revisions retained; " + + "no erasure has been recorded." + } + DocumentLifecycleState.ACTIVE -> + "The document is active; an erase applies only after it has been deleted." +} diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt index f26540d32d1..e10a6c0650a 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/queries/PlatformQueries.kt @@ -898,6 +898,52 @@ class Documents internal constructor(private val sdk: Sdk) { } } + /** + * Read a page of a keep-history document's revision history with its + * lifecycle block (see [DocumentLifecycle]); returns the JSON object + * `{"entries":[{"time_ms","revision","document"}],"lifecycle":{…}}` or + * null when the response is missing. [contractId] is base58 and is + * resolved through the SDK's current context provider. Exactly one + * [filter] applies; [limit] is at most ten, 0 for the default. Needs the + * protocol-15 history layout: a page served from the earlier layout has no + * lifecycle block and the FFI refuses it. + */ + suspend fun history( + contractId: String, + documentType: String, + documentId: String, + filter: DocumentHistoryFilter = DocumentHistoryFilter.StartAtTime(0), + limit: Int = 0, + ): String? = sdk.queryGate.op { + require(limit >= 0) { "limit must be non-negative, got $limit" } + mapNativeErrors { + QueriesNative.documentHistory( + sdk.handle, + contractId, + documentType, + documentId, + filter.code, + filter.timeMs, + filter.revision, + limit, + ) + } + } + + /** + * Read where a keep-history document stands right now: its lifecycle + * state and the exact number of revisions still retained. A current + * observation, not the outcome of any particular transition; the erase + * result itself only observes absence (see `DocumentTransactions.erase`). + */ + suspend fun lifecycle( + contractId: String, + documentType: String, + documentId: String, + ): DocumentLifecycle? = + history(contractId, documentType, documentId, DocumentHistoryFilter.StartAtTime(0), 1) + ?.let(DocumentLifecycle::fromHistoryJson) + /** Count documents; returns the JSON count result. */ suspend fun count( contract: DataContractRef, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentHistoryTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentHistoryTest.kt new file mode 100644 index 00000000000..8488b027d68 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/queries/DocumentHistoryTest.kt @@ -0,0 +1,96 @@ +package org.dashfoundation.dashsdk.queries + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Pins the lifecycle parsing behind `Documents.lifecycle` and the wording + * `describeEraseProgress` produces for the DocumentActionsScreen erase + * section. The erase transition's own result only observes that the document + * is absent from ordinary reads, which it already was before the erase, so a + * lifecycle that is still DELETED with the same retained count must never be + * presented as an accepted or completed erase. + */ +class DocumentHistoryTest { + + private fun page(state: String, remaining: Long, erasingStarted: Long = 0) = + """{"entries":[],"lifecycle":{"state":"$state","remaining_revisions":$remaining,""" + + """"deleted_at_ms":1700000000001,"erasing_started_at_ms":$erasingStarted,""" + + """"erasing_from_time_ms":1700000000000,"erasing_from_revision":7}}""" + + @Test + fun parsesEveryLifecycleFieldExactly() { + val lifecycle = DocumentLifecycle.fromHistoryJson(page("ERASING", 37, 1700000000002))!! + assertEquals(DocumentLifecycleState.ERASING, lifecycle.state) + assertEquals(37uL, lifecycle.remainingRevisions) + assertEquals(1700000000001uL, lifecycle.deletedAtMs) + assertEquals(1700000000002uL, lifecycle.erasingStartedAtMs) + assertEquals(1700000000000uL, lifecycle.erasingFromTimeMs) + assertEquals(7uL, lifecycle.erasingFromRevision) + } + + @Test + fun partialOrUnknownLifecycleIsNullNotZeros() { + assertNull(DocumentLifecycle.fromHistoryJson("""{"entries":[]}""")) + assertNull(DocumentLifecycle.fromHistoryJson("""{"lifecycle":{"state":"DELETED"}}""")) + assertNull(DocumentLifecycle.fromHistoryJson("""{"lifecycle":{"state":"GONE","remaining_revisions":0,"deleted_at_ms":0,"erasing_started_at_ms":0,"erasing_from_time_ms":0,"erasing_from_revision":0}}""")) + } + + @Test + fun negativeOrStringTypedNumbersAreMalformedNotValues() { + // Rust serializes every lifecycle number as an unsigned integer, so a + // string or a negative number is a malformed block, never a count. + val stringTyped = page("DELETED", 5).replace("\"remaining_revisions\":5", "\"remaining_revisions\":\"5\"") + assertNull(DocumentLifecycle.fromHistoryJson(stringTyped)) + assertNull(DocumentLifecycle.fromHistoryJson(page("DELETED", -1))) + val negativeTime = page("DELETED", 5).replace("\"deleted_at_ms\":1700000000001", "\"deleted_at_ms\":-1") + assertNull(DocumentLifecycle.fromHistoryJson(negativeTime)) + assertEquals(0uL, DocumentLifecycle.fromHistoryJson(page("DELETED", 0))!!.remainingRevisions) + } + + @Test + fun preservesEveryUnsigned64BitLifecycleNumber() { + for (value in listOf("9007199254740993", "9223372036854775808", "18446744073709551615")) { + val fields = listOf("remaining_revisions", "deleted_at_ms", "erasing_started_at_ms", + "erasing_from_time_ms", "erasing_from_revision") + val numbers = fields.joinToString(",") { "\"$it\":$value" } + val lifecycle = DocumentLifecycle.fromHistoryJson("""{"lifecycle":{"state":"ERASING",$numbers}}""")!! + for (actual in listOf(lifecycle.remainingRevisions, lifecycle.deletedAtMs, + lifecycle.erasingStartedAtMs, lifecycle.erasingFromTimeMs, lifecycle.erasingFromRevision)) { + assertEquals(value, actual.toString()) + } + } + } + + @Test + fun rejectsMalformedOrOutOfRangeUnsignedNumbers() { + for (value in listOf("18446744073709551616", "1.5", "true", "false")) { + assertNull(DocumentLifecycle.fromHistoryJson(page("ERASING", 5) + .replace("\"remaining_revisions\":5", "\"remaining_revisions\":$value"))) + } + assertNull(DocumentLifecycle.fromHistoryJson(page("ERASING", 5) + .replace("\"state\":\"ERASING\"", "\"state\":ERASING"))) + } + + @Test + fun unchangedDeletedLifecycleIsNotPresentedAsAConfirmedErase() { + val before = DocumentLifecycle.fromHistoryJson(page("DELETED", 5))!! + val after = DocumentLifecycle.fromHistoryJson(page("DELETED", 5))!! + val text = describeEraseProgress(before, after) + assertTrue(text, text.startsWith("Not established")) + assertFalse(text, text.contains("accepted", ignoreCase = true)) + assertFalse(text, text.contains("complete", ignoreCase = true)) + } + + @Test + fun progressAndCompletionComeOnlyFromTheLifecycle() { + val before = DocumentLifecycle.fromHistoryJson(page("DELETED", 150))!! + val erasing = DocumentLifecycle.fromHistoryJson(page("ERASING", 50, 1))!! + assertTrue(describeEraseProgress(before, erasing).startsWith("Erasure in progress: 50")) + val absent = DocumentLifecycle.fromHistoryJson(page("ABSENT", 0, 1))!! + assertTrue(describeEraseProgress(erasing, absent).startsWith("Erasure complete")) + } +} diff --git a/packages/rs-platform-wallet-ffi/src/document.rs b/packages/rs-platform-wallet-ffi/src/document.rs index 36906327234..726cff61cae 100644 --- a/packages/rs-platform-wallet-ffi/src/document.rs +++ b/packages/rs-platform-wallet-ffi/src/document.rs @@ -388,6 +388,82 @@ pub unsafe extern "C" fn platform_wallet_document_delete_by_values( PlatformWalletFFIResult::ok() } +/// Erase + broadcast a chunk of the retained revisions of the already +/// deleted `document_id` on `contract_id`'s `document_type_name`, signed +/// via the external `signer_handle` with key `signing_key_id` of +/// `owner_identity_id`. +/// +/// Goes through `IdentityWallet::erase_document_with_signer`. The first +/// erase of a document must be signed by its owner; the erases after it +/// may be signed by any identity, so `owner_identity_id` is the signing +/// identity rather than necessarily the document's owner. On success the +/// document's 32-byte id is written to `out_document_id`: the transition +/// was broadcast and Platform proved the document absent from ordinary +/// reads, which it already was before the erase, so success observes the +/// affected state rather than proving this erase removed a revision. +/// Erase returns no document body, so there is no JSON out-param; the +/// lifecycle state and the number of revisions still retained are read +/// from the document's history. +/// +/// # Safety +/// `owner_identity_id`, `contract_id`, and `document_id` must each point to +/// 32 readable bytes. `document_type_name` must be a valid NUL-terminated +/// string. `signer_handle` must refer to a live signer whose callbacks and +/// context remain valid for this blocking call. `out_document_id` must +/// point to 32 writable bytes. The buffers must not be mutated concurrently +/// and the output buffer must not overlap any input. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_document_erase( + wallet_handle: Handle, + owner_identity_id: *const u8, + contract_id: *const u8, + document_type_name: *const c_char, + document_id: *const u8, + signing_key_id: u32, + signer_handle: *mut SignerHandle, + out_document_id: *mut u8, +) -> PlatformWalletFFIResult { + check_ptr!(signer_handle); + check_ptr!(document_type_name); + check_ptr!(out_document_id); + + let owner_id = unwrap_result_or_return!(read_identifier(owner_identity_id)); + let contract_id_value = unwrap_result_or_return!(read_identifier(contract_id)); + let document_id_value = unwrap_result_or_return!(read_identifier(document_id)); + + let document_type_str = + unwrap_result_or_return!(CStr::from_ptr(document_type_name).to_str()).to_string(); + + let signer_addr = signer_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let identity_wallet = wallet.identity().clone(); + let result: Result = block_on_worker(async move { + let signer: &VTableSigner = &*(signer_addr as *const VTableSigner); + let erased_id: Identifier = identity_wallet + .erase_document_with_signer( + &owner_id, + &contract_id_value, + &document_type_str, + &document_id_value, + signing_key_id, + signer, + ) + .await?; + Ok::<_, PlatformWalletError>(erased_id) + }); + result + }); + let result = unwrap_option_or_return!(option); + let erased_id = unwrap_result_or_return!(result); + + let bytes = erased_id.to_buffer(); + let dst = slice::from_raw_parts_mut(out_document_id, 32); + dst.copy_from_slice(&bytes); + PlatformWalletFFIResult::ok() +} + /// Transfer + broadcast `document_id` on `contract_id`'s /// `document_type_name`, from `owner_identity_id` to `recipient_id`, /// signed via the external `signer_handle` with key `signing_key_id`. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 1307394d874..773011742b1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -53,10 +53,10 @@ use dpp::state_transition::batch_transition::methods::StateTransitionCreationOpt use dpp::ProtocolError; use dash_sdk::platform::documents::transitions::{ - DocumentDeleteResult, DocumentDeleteTransitionBuilder, DocumentPurchaseResult, - DocumentPurchaseTransitionBuilder, DocumentReplaceResult, DocumentReplaceTransitionBuilder, - DocumentSetPriceResult, DocumentSetPriceTransitionBuilder, DocumentTransferResult, - DocumentTransferTransitionBuilder, + DocumentDeleteResult, DocumentDeleteTransitionBuilder, DocumentEraseResult, + DocumentEraseTransitionBuilder, DocumentPurchaseResult, DocumentPurchaseTransitionBuilder, + DocumentReplaceResult, DocumentReplaceTransitionBuilder, DocumentSetPriceResult, + DocumentSetPriceTransitionBuilder, DocumentTransferResult, DocumentTransferTransitionBuilder, }; use dash_sdk::platform::transition::put_document::PutDocument; use dash_sdk::platform::transition::put_settings::PutSettings; @@ -751,6 +751,74 @@ impl IdentityWallet { Ok(deleted_id) } + /// Erase a chunk of the retained revisions of an already deleted + /// document on `contract_id`'s `document_type_name` and broadcast. + /// + /// Sibling of `delete_document_with_signer`. The document type must + /// keep history and allow erasure, and the document must already be + /// deleted. The first erase must be signed by the document's owner + /// and commits the document to erasure; every erase after that may be + /// signed by any identity, so `owner_identity_id` is the identity + /// signing and paying for this chunk rather than necessarily the + /// document's owner. One transition removes a bounded chunk of + /// revisions; read the document's history to see how many remain and + /// submit another erase while there are any. + /// + /// Signs with the explicit `signing_key_id` (AUTHENTICATION + + /// ECDSA) and broadcasts via `Sdk::document_erase` on the + /// platform-wallet 8 MB worker stack. Returns the document's + /// `Identifier` once Platform has proved it absent from ordinary + /// reads. That absence predates the erase, so the return is an + /// observation of the affected state, not evidence that this erase + /// removed any revision; progress is read from the document's + /// history, whose lifecycle block carries the state and the exact + /// number of revisions still retained. + pub async fn erase_document_with_signer( + &self, + owner_identity_id: &Identifier, + contract_id: &Identifier, + document_type_name: &str, + document_id: &Identifier, + signing_key_id: u32, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { + let data_contract = self + .fetch_contract_arc_for_document_op(contract_id, document_type_name) + .await?; + + let signing_key = self + .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) + .await?; + + // Erase is keyed by (document_id, owner_id) like delete; the + // document is no longer visible to ordinary reads, so there is + // nothing to fetch first. + let builder = DocumentEraseTransitionBuilder::new( + data_contract, + document_type_name.to_string(), + *document_id, + *owner_identity_id, + ); + let DocumentEraseResult::AbsentAsOfProof(absent_id) = self + .sdk + .document_erase(builder, &signing_key, &SignerRef(signer)) + .await + .map_err(|e| { + // Preserve a structured key-unavailable signer failure so the + // FFI boundary can still restore code 31; only genuine + // operation failures get stringified into `InvalidIdentityData`. + preserve_signer_key_unavailable_or(e, |e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to erase document: {e}" + )) + }) + })?; + Ok(absent_id) + } + /// Transfer an existing document on `contract_id`'s /// `document_type_name` to `recipient_id` and broadcast. /// diff --git a/packages/rs-sdk-ffi/README.md b/packages/rs-sdk-ffi/README.md index 186094081a6..1bcb3013ced 100644 --- a/packages/rs-sdk-ffi/README.md +++ b/packages/rs-sdk-ffi/README.md @@ -183,7 +183,9 @@ result = lib.dash_sdk_create(byref(config)) - `dash_sdk_document_create()` - Create a new document - `dash_sdk_document_update()` - Update an existing document - `dash_sdk_document_delete()` - Delete a document +- `dash_sdk_document_erase()` - Erase the retained revisions of a deleted keep-history document - `dash_sdk_document_fetch()` - Fetch documents by query +- `dash_sdk_document_fetch_history()` - Fetch a document's revision history and lifecycle state #### Data Contract Operations - `dash_sdk_data_contract_create()` - Create a new data contract diff --git a/packages/rs-sdk-ffi/cbindgen.toml b/packages/rs-sdk-ffi/cbindgen.toml index e06726718e8..5eaef307b7f 100644 --- a/packages/rs-sdk-ffi/cbindgen.toml +++ b/packages/rs-sdk-ffi/cbindgen.toml @@ -15,7 +15,7 @@ documentation_style = "c99" [defines] [export] -include = ["dash_sdk_*", "dash_core_*", "dash_unified_sdk_*"] +include = ["dash_sdk_*", "dash_core_*", "dash_unified_sdk_*", "DashSDKDocumentHistoryFilter"] prefix = "" item_types = ["enums", "structs", "unions", "typedefs", "opaque", "functions"] diff --git a/packages/rs-sdk-ffi/src/document/erase.rs b/packages/rs-sdk-ffi/src/document/erase.rs new file mode 100644 index 00000000000..ded4dbc41bd --- /dev/null +++ b/packages/rs-sdk-ffi/src/document/erase.rs @@ -0,0 +1,720 @@ +//! Document erase operations +//! +//! An erase removes the retained revisions of a document that has already +//! been deleted on a keep-history type whose schema allows erasure. One +//! transition removes a bounded chunk of revisions; a document retaining +//! more needs several. The first erase must be signed by the document's +//! owner and commits the document to erasure; every erase after that may be +//! signed by any identity. Erase carries no token payment. + +use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; +use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::prelude::{Identifier, UserFeeIncrease}; +use dash_sdk::platform::documents::transitions::{ + DocumentEraseResult, DocumentEraseTransitionBuilder, +}; +use dash_sdk::platform::IdentityPublicKey; +use std::ffi::CStr; +use std::os::raw::c_char; +use tracing::{debug, error, info}; + +use crate::document::helpers::convert_state_transition_creation_options; +use crate::sdk::SDKWrapper; +use crate::types::{ + DashSDKPutSettings, DashSDKStateTransitionCreationOptions, SDKHandle, SignerHandle, +}; +use crate::{DashSDKError, DashSDKErrorCode, DashSDKResult, FFIError}; + +/// Build and sign an erase transition for a deleted document, returning the +/// serialized state transition without broadcasting it +/// +/// `owner_id` is the identity signing and paying for this erase. It must be +/// the document's owner for the first erase of a document and may be any +/// identity for the erases that follow. +/// +/// # Safety +/// - `sdk_handle` must be a valid, non-null pointer to an initialized `SDKHandle`. +/// - `document_id`, `owner_id`, `data_contract_id`, and `document_type_name` must be valid, non-null pointers to +/// NUL-terminated C strings that remain valid for the duration of the call. +/// - `identity_public_key_handle` and `signer_handle` must be valid, non-null pointers to initialized structures. +/// - Optional pointers (`put_settings`, `state_transition_creation_options`) may be null; when non-null they must be valid. +/// - On success, the result contains heap-allocated data that must be freed using SDK-provided routines. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_document_erase( + sdk_handle: *mut SDKHandle, + document_id: *const c_char, + owner_id: *const c_char, + data_contract_id: *const c_char, + document_type_name: *const c_char, + identity_public_key_handle: *const crate::types::IdentityPublicKeyHandle, + signer_handle: *const SignerHandle, + put_settings: *const DashSDKPutSettings, + state_transition_creation_options: *const DashSDKStateTransitionCreationOptions, +) -> DashSDKResult { + // Validate required parameters + if sdk_handle.is_null() + || document_id.is_null() + || owner_id.is_null() + || data_contract_id.is_null() + || document_type_name.is_null() + || identity_public_key_handle.is_null() + || signer_handle.is_null() + { + return DashSDKResult::error(DashSDKError::new( + DashSDKErrorCode::InvalidParameter, + "One or more required parameters is null".to_string(), + )); + } + + let wrapper = &*(sdk_handle as *const SDKWrapper); + + let document_id_str = match CStr::from_ptr(document_id).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let owner_id_str = match CStr::from_ptr(owner_id).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let contract_id_str = match CStr::from_ptr(data_contract_id).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let document_type_name_str = match CStr::from_ptr(document_type_name).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let identity_public_key = &*(identity_public_key_handle as *const IdentityPublicKey); + let signer = &*(signer_handle as *const crate::signer::VTableSigner); + + let result: Result, FFIError> = wrapper.runtime.block_on(async { + // Parse identifiers (base58 encoded) + let doc_id = Identifier::from_string(document_id_str, Encoding::Base58) + .map_err(|e| FFIError::InternalError(format!("Invalid document ID: {}", e)))?; + + let owner_identifier = Identifier::from_string(owner_id_str, Encoding::Base58) + .map_err(|e| FFIError::InternalError(format!("Invalid owner ID: {}", e)))?; + + let contract_id = Identifier::from_string(contract_id_str, Encoding::Base58) + .map_err(|e| FFIError::InternalError(format!("Invalid contract ID: {}", e)))?; + + // Resolve the contract through the SDK's current context provider. + let data_contract = wrapper.data_contract(&contract_id)?; + + // Convert FFI types to Rust types + let settings = crate::identity::convert_put_settings(put_settings); + let creation_options = + convert_state_transition_creation_options(state_transition_creation_options); + + // Extract user fee increase from put_settings or use default + let user_fee_increase: UserFeeIncrease = if put_settings.is_null() { + 0 + } else { + (*put_settings).user_fee_increase + }; + + let mut builder = DocumentEraseTransitionBuilder::new( + data_contract.clone(), + document_type_name_str.to_string(), + doc_id, + owner_identifier, + ); + + if let Some(settings) = settings { + builder = builder.with_settings(settings); + } + + if user_fee_increase > 0 { + builder = builder.with_user_fee_increase(user_fee_increase); + } + + if let Some(options) = creation_options { + builder = builder.with_state_transition_creation_options(options); + } + + let state_transition = builder + .sign( + &wrapper.sdk, + identity_public_key, + signer, + wrapper.sdk.version(), + ) + .await + .map_err(|e| FFIError::sdk_call_failed("Failed to create erase transition", e))?; + + // Serialize the state transition with bincode + let config = bincode::config::standard(); + let serialized = bincode::encode_to_vec(&state_transition, config).map_err(|e| { + FFIError::InternalError(format!("Failed to serialize state transition: {}", e)) + })?; + debug!( + size = serialized.len(), + "[DOCUMENT ERASE] serialized transition size (bytes)" + ); + debug!(hex = %hex::encode(&serialized), "[DOCUMENT ERASE] state transition hex"); + Ok(serialized) + }); + + match result { + Ok(serialized_data) => DashSDKResult::success_binary(serialized_data), + Err(e) => DashSDKResult::error(e.into()), + } +} + +/// Erase a chunk of a deleted document's retained revisions, then wait until +/// the document's absence is observed under a proof +/// +/// Success means the transition was broadcast and Platform proved the document +/// absent from ordinary reads as of the proof's block. The document already +/// was absent before the erase ran, so this is an observation of the state the +/// erase affected, not evidence that this erase removed any revision. Whether +/// and how far the erasure progressed is read separately from the document's +/// history (`dash_sdk_document_fetch_history`): its lifecycle block reports +/// the state and the exact number of revisions still retained. Submit another +/// erase while revisions remain. +/// +/// # Safety +/// - Same requirements as `dash_sdk_document_erase` regarding pointer validity and lifetimes. +/// - The function may block while waiting for confirmation; input pointers must remain valid throughout. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_document_erase_and_wait( + sdk_handle: *mut SDKHandle, + document_id: *const c_char, + owner_id: *const c_char, + data_contract_id: *const c_char, + document_type_name: *const c_char, + identity_public_key_handle: *const crate::types::IdentityPublicKeyHandle, + signer_handle: *const SignerHandle, + put_settings: *const DashSDKPutSettings, + state_transition_creation_options: *const DashSDKStateTransitionCreationOptions, +) -> DashSDKResult { + // Validate required parameters + if sdk_handle.is_null() + || document_id.is_null() + || owner_id.is_null() + || data_contract_id.is_null() + || document_type_name.is_null() + || identity_public_key_handle.is_null() + || signer_handle.is_null() + { + return DashSDKResult::error(DashSDKError::new( + DashSDKErrorCode::InvalidParameter, + "One or more required parameters is null".to_string(), + )); + } + + info!("[DOCUMENT ERASE] starting document erase operation"); + + let wrapper = &*(sdk_handle as *const SDKWrapper); + let signer = &*(signer_handle as *const crate::signer::VTableSigner); + + let document_id_str = match CStr::from_ptr(document_id).to_str() { + Ok(s) => s, + Err(e) => { + error!(error = %e, "[DOCUMENT ERASE] failed to parse document ID"); + return DashSDKResult::error(FFIError::from(e).into()); + } + }; + + let owner_id_str = match CStr::from_ptr(owner_id).to_str() { + Ok(s) => s, + Err(e) => { + error!(error = %e, "[DOCUMENT ERASE] failed to parse owner ID"); + return DashSDKResult::error(FFIError::from(e).into()); + } + }; + + let contract_id_str = match CStr::from_ptr(data_contract_id).to_str() { + Ok(s) => s, + Err(e) => { + error!(error = %e, "[DOCUMENT ERASE] failed to parse contract ID"); + return DashSDKResult::error(FFIError::from(e).into()); + } + }; + + let document_type_name_str = match CStr::from_ptr(document_type_name).to_str() { + Ok(s) => s, + Err(e) => { + error!(error = %e, "[DOCUMENT ERASE] failed to parse document type name"); + return DashSDKResult::error(FFIError::from(e).into()); + } + }; + + let identity_public_key = &*(identity_public_key_handle as *const IdentityPublicKey); + + debug!( + document_type = document_type_name_str, + "[DOCUMENT ERASE] document type" + ); + debug!( + document_id = document_id_str, + "[DOCUMENT ERASE] document id" + ); + debug!(owner_id = owner_id_str, "[DOCUMENT ERASE] owner id"); + + let result: Result = wrapper.runtime.block_on(async { + // Parse identifiers (base58 encoded) + let doc_id = Identifier::from_string(document_id_str, Encoding::Base58) + .map_err(|e| FFIError::InternalError(format!("Invalid document ID: {}", e)))?; + + let owner_identifier = Identifier::from_string(owner_id_str, Encoding::Base58) + .map_err(|e| FFIError::InternalError(format!("Invalid owner ID: {}", e)))?; + + let contract_id = Identifier::from_string(contract_id_str, Encoding::Base58) + .map_err(|e| FFIError::InternalError(format!("Invalid contract ID: {}", e)))?; + + // Resolve the contract through the SDK's current context provider. + let data_contract = wrapper.data_contract(&contract_id)?; + + // Convert FFI types to Rust types + let settings = crate::identity::convert_put_settings(put_settings); + let creation_options = + convert_state_transition_creation_options(state_transition_creation_options); + + // Extract user fee increase from put_settings or use default + let user_fee_increase: UserFeeIncrease = if put_settings.is_null() { + 0 + } else { + (*put_settings).user_fee_increase + }; + + debug!("[DOCUMENT ERASE] building document erase transition"); + + let mut builder = DocumentEraseTransitionBuilder::new( + data_contract.clone(), + document_type_name_str.to_string(), + doc_id, + owner_identifier, + ); + + if let Some(settings) = settings { + debug!("[DOCUMENT ERASE] adding put settings"); + builder = builder.with_settings(settings); + } + + if user_fee_increase > 0 { + debug!(user_fee_increase, "[DOCUMENT ERASE] setting user fee increase"); + builder = builder.with_user_fee_increase(user_fee_increase); + } + + if let Some(options) = creation_options { + debug!("[DOCUMENT ERASE] adding state transition creation options"); + builder = builder.with_state_transition_creation_options(options); + } + + debug!("[DOCUMENT ERASE] calling SDK document_erase"); + debug!(key_id = identity_public_key.id(), purpose = ?identity_public_key.purpose(), security_level = ?identity_public_key.security_level(), key_type = ?identity_public_key.key_type(), "[DOCUMENT ERASE] identity public key info"); + + let result = wrapper + .sdk + .document_erase(builder, identity_public_key, signer) + .await + .map_err(|e| { + error!(error = %e, key_id = identity_public_key.id(), "[DOCUMENT ERASE] SDK call failed"); + FFIError::sdk_call_failed("Failed to erase document and wait", e) + })?; + + info!("[DOCUMENT ERASE] SDK call completed successfully"); + + let DocumentEraseResult::AbsentAsOfProof(absent_id) = result; + + Ok(absent_id) + }); + + match result { + Ok(_absent_id) => { + info!("[DOCUMENT ERASE] erase broadcast; document absence observed under proof"); + DashSDKResult::success(std::ptr::null_mut()) + } + Err(e) => { + error!(error = ?e, "[DOCUMENT ERASE] document erase failed"); + DashSDKResult::error(e.into()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::test_utils::*; + use crate::DashSDKErrorCode; + + use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; + use dash_sdk::platform::IdentityPublicKey; + + use std::ffi::{CStr, CString}; + use std::ptr; + + fn assert_erase_uses_current_context_provider(wait_for_result: bool, expected_context: &str) { + let contract = create_mock_data_contract(); + let contract_id = CString::new(contract.id().to_string(Encoding::Base58)).unwrap(); + let sdk_handle = create_mock_sdk_handle_with_current_contracts(vec![*contract]); + let document_id = + CString::new(Identifier::new([2; 32]).to_string(Encoding::Base58)).unwrap(); + let owner_id = CString::new(Identifier::new([1; 32]).to_string(Encoding::Base58)).unwrap(); + let document_type_name = CString::new("missing_document_type").unwrap(); + let public_key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + let erase = if wait_for_result { + dash_sdk_document_erase_and_wait + } else { + dash_sdk_document_erase + }; + + let result = unsafe { + erase( + sdk_handle, + document_id.as_ptr(), + owner_id.as_ptr(), + contract_id.as_ptr(), + document_type_name.as_ptr(), + ptr::from_ref(public_key.as_ref()).cast(), + ptr::from_ref(signer.as_ref()).cast(), + ptr::null(), + ptr::null(), + ) + }; + assert!(!result.error.is_null()); + let (code, message) = unsafe { + let error = &*result.error; + let details = ( + error.code, + CStr::from_ptr(error.message).to_string_lossy().into_owned(), + ); + crate::dash_sdk_error_free(result.error); + details + }; + destroy_mock_sdk_handle(sdk_handle); + + assert_eq!(code, DashSDKErrorCode::InternalError); + assert!(message.contains(expected_context), "{message}"); + assert!(message.contains("document type not found"), "{message}"); + } + + #[test] + fn should_sign_erase_using_the_current_context_provider() { + assert_erase_uses_current_context_provider(false, "Failed to create erase transition"); + } + + #[test] + fn should_erase_and_wait_using_the_current_context_provider() { + assert_erase_uses_current_context_provider(true, "Failed to erase document and wait"); + } + + #[test] + fn test_erase_with_null_sdk_handle() { + let identity_public_key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + + let document_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type_name = CString::new("testDoc").unwrap(); + + let identity_public_key_handle = + Box::into_raw(identity_public_key) as *const crate::types::IdentityPublicKeyHandle; + let signer_handle = Box::into_raw(signer) as *const SignerHandle; + + let put_settings = create_put_settings(); + + let result = unsafe { + dash_sdk_document_erase( + ptr::null_mut(), // null SDK handle + document_id.as_ptr(), + owner_id.as_ptr(), + contract_id.as_ptr(), + document_type_name.as_ptr(), + identity_public_key_handle, + signer_handle, + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + let error_msg = CStr::from_ptr(error.message).to_str().unwrap(); + assert!(error_msg.contains("null")); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(identity_public_key_handle as *mut IdentityPublicKey); + let _ = Box::from_raw(signer_handle as *mut crate::signer::VTableSigner); + } + } + + #[test] + fn test_erase_with_null_document() { + let sdk_handle = create_mock_sdk_handle(); + let identity_public_key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type_name = CString::new("testDoc").unwrap(); + + let identity_public_key_handle = + Box::into_raw(identity_public_key) as *const crate::types::IdentityPublicKeyHandle; + let signer_handle = Box::into_raw(signer) as *const SignerHandle; + + let put_settings = create_put_settings(); + + let result = unsafe { + dash_sdk_document_erase( + sdk_handle, + ptr::null(), // null document_id + owner_id.as_ptr(), + contract_id.as_ptr(), + document_type_name.as_ptr(), + identity_public_key_handle, + signer_handle, + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(identity_public_key_handle as *mut IdentityPublicKey); + let _ = Box::from_raw(signer_handle as *mut crate::signer::VTableSigner); + } + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn test_erase_with_null_data_contract() { + let sdk_handle = create_mock_sdk_handle(); + let identity_public_key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + + let document_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let document_type_name = CString::new("testDoc").unwrap(); + + let identity_public_key_handle = + Box::into_raw(identity_public_key) as *const crate::types::IdentityPublicKeyHandle; + let signer_handle = Box::into_raw(signer) as *const SignerHandle; + + let put_settings = create_put_settings(); + + let result = unsafe { + dash_sdk_document_erase( + sdk_handle, + document_id.as_ptr(), + owner_id.as_ptr(), + ptr::null(), // null data contract ID + document_type_name.as_ptr(), + identity_public_key_handle, + signer_handle, + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(identity_public_key_handle as *mut IdentityPublicKey); + let _ = Box::from_raw(signer_handle as *mut crate::signer::VTableSigner); + } + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn test_erase_with_null_document_type_name() { + let sdk_handle = create_mock_sdk_handle(); + let identity_public_key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + + let document_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + + let identity_public_key_handle = + Box::into_raw(identity_public_key) as *const crate::types::IdentityPublicKeyHandle; + let signer_handle = Box::into_raw(signer) as *const SignerHandle; + + let put_settings = create_put_settings(); + + let result = unsafe { + dash_sdk_document_erase( + sdk_handle, + document_id.as_ptr(), + owner_id.as_ptr(), + contract_id.as_ptr(), + ptr::null(), // null document type name + identity_public_key_handle, + signer_handle, + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(identity_public_key_handle as *mut IdentityPublicKey); + let _ = Box::from_raw(signer_handle as *mut crate::signer::VTableSigner); + } + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn test_erase_with_null_identity_public_key() { + let sdk_handle = create_mock_sdk_handle(); + let signer = create_mock_signer(); + + let document_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type_name = CString::new("testDoc").unwrap(); + + let signer_handle = Box::into_raw(signer) as *const SignerHandle; + + let put_settings = create_put_settings(); + + let result = unsafe { + dash_sdk_document_erase( + sdk_handle, + document_id.as_ptr(), + owner_id.as_ptr(), + contract_id.as_ptr(), + document_type_name.as_ptr(), + ptr::null(), // null identity public key handle + signer_handle, + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(signer_handle as *mut crate::signer::VTableSigner); + } + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn test_erase_with_null_signer() { + let sdk_handle = create_mock_sdk_handle(); + let identity_public_key = create_mock_identity_public_key(); + + let document_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type_name = CString::new("testDoc").unwrap(); + + let identity_public_key_handle = + Box::into_raw(identity_public_key) as *const crate::types::IdentityPublicKeyHandle; + + let put_settings = create_put_settings(); + + let result = unsafe { + dash_sdk_document_erase( + sdk_handle, + document_id.as_ptr(), + owner_id.as_ptr(), + contract_id.as_ptr(), + document_type_name.as_ptr(), + identity_public_key_handle, + ptr::null(), // null signer + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(identity_public_key_handle as *mut IdentityPublicKey); + } + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn test_erase_and_wait_with_null_parameters() { + let sdk_handle = create_mock_sdk_handle(); + let identity_public_key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + + let document_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let owner_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type_name = CString::new("testDoc").unwrap(); + + let identity_public_key_handle = + Box::into_raw(identity_public_key) as *const crate::types::IdentityPublicKeyHandle; + let signer_handle = Box::into_raw(signer) as *const SignerHandle; + + let put_settings = create_put_settings(); + + // Test with null SDK handle + let result = unsafe { + dash_sdk_document_erase_and_wait( + ptr::null_mut(), + document_id.as_ptr(), + owner_id.as_ptr(), + contract_id.as_ptr(), + document_type_name.as_ptr(), + identity_public_key_handle, + signer_handle, + &put_settings, + ptr::null(), + ) + }; + + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + + // Clean up + unsafe { + let _ = Box::from_raw(identity_public_key_handle as *mut IdentityPublicKey); + let _ = Box::from_raw(signer_handle as *mut crate::signer::VTableSigner); + } + destroy_mock_sdk_handle(sdk_handle); + } +} diff --git a/packages/rs-sdk-ffi/src/document/mod.rs b/packages/rs-sdk-ffi/src/document/mod.rs index 2a388bae42d..0e7a4a2addf 100644 --- a/packages/rs-sdk-ffi/src/document/mod.rs +++ b/packages/rs-sdk-ffi/src/document/mod.rs @@ -2,6 +2,7 @@ mod create; mod delete; +mod erase; mod helpers; mod price; mod purchase; @@ -14,6 +15,7 @@ mod util; // Re-export functions from submodules pub use create::{dash_sdk_document_create, DashSDKDocumentCreateParams}; pub use delete::{dash_sdk_document_delete, dash_sdk_document_delete_and_wait}; +pub use erase::{dash_sdk_document_erase, dash_sdk_document_erase_and_wait}; pub use price::{ dash_sdk_document_update_price_of_document, dash_sdk_document_update_price_of_document_and_wait, }; @@ -23,8 +25,8 @@ pub use queries::average::dash_sdk_document_average; pub use queries::info::dash_sdk_document_get_info; pub use queries::sum::dash_sdk_document_sum; pub use queries::{ - dash_sdk_document_count, dash_sdk_document_fetch, dash_sdk_document_search, - DashSDKDocumentSearchParams, + dash_sdk_document_count, dash_sdk_document_fetch, dash_sdk_document_fetch_history, + dash_sdk_document_search, DashSDKDocumentHistoryFilter, DashSDKDocumentSearchParams, }; pub use replace::{ dash_sdk_document_replace_on_platform, dash_sdk_document_replace_on_platform_and_wait, diff --git a/packages/rs-sdk-ffi/src/document/queries/history.rs b/packages/rs-sdk-ffi/src/document/queries/history.rs new file mode 100644 index 00000000000..68b7863b616 --- /dev/null +++ b/packages/rs-sdk-ffi/src/document/queries/history.rs @@ -0,0 +1,582 @@ +//! Document history query operations +//! +//! Reads the retained revisions of a document on a keep-history type +//! together with the authenticated lifecycle metadata: whether the document +//! is active, deleted, being erased, or absent, and how many revisions +//! remain. + +use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; +use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::dpp::prelude::Identifier; +use dash_sdk::dpp::serialization::ValueConvertible; +use dash_sdk::platform::documents::document_history_query::{ + DocumentHistoryFilter, DocumentHistoryQuery, +}; +use dash_sdk::platform::Fetch; +use drive_proof_verifier::types::{DocumentHistory, DocumentHistoryState}; +use serde::Serialize; +use std::ffi::{CStr, CString}; +use std::os::raw::{c_char, c_uint}; + +use crate::sdk::SDKWrapper; +use crate::types::SDKHandle; +use crate::{DashSDKError, DashSDKErrorCode, DashSDKResult, FFIError}; + +/// Which revisions of a document's history to read +/// +/// Exactly one filter applies to a `dash_sdk_document_fetch_history` +/// call; the filter decides which of `time_ms` and `revision` are read. +/// The variants carry a `History` prefix because cbindgen exports them as +/// bare C constants. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DashSDKDocumentHistoryFilter { + /// Revisions written at or after `time_ms`, oldest first. Pass 0 for + /// the first page of a document's whole history. + HistoryStartAtTime = 0, + /// Revisions after the complete cursor (`time_ms`, `revision`) of the + /// last entry received, for the pages after the first. + HistoryStartAfter = 1, + /// Revisions from history sequence `revision` onwards. + HistoryStartAtRevision = 2, + /// Exactly the revision at history sequence `revision`; the limit must + /// be one. + HistoryRevision = 3, +} + +#[derive(Serialize)] +struct DocumentHistoryEntryJson { + time_ms: u64, + revision: u64, + document: serde_json::Value, +} + +#[derive(Serialize)] +struct DocumentHistoryLifecycleJson { + state: &'static str, + remaining_revisions: u64, + deleted_at_ms: u64, + erasing_started_at_ms: u64, + erasing_from_time_ms: u64, + erasing_from_revision: u64, +} + +#[derive(Serialize)] +struct DocumentHistoryJson { + entries: Vec, + lifecycle: DocumentHistoryLifecycleJson, +} + +/// Serialize a verified history page as the JSON the FFI hands to callers. +/// +/// Documents are the canonical query-side shape every other document read +/// returns (`$id` and `$ownerId` as base58 strings, `$formatVersion` +/// present). A history response always authenticates lifecycle metadata; +/// a response without it came from a legacy protocol and is refused rather +/// than reported as a document with no lifecycle. +fn document_history_to_json(history: DocumentHistory) -> Result { + let mut entries = Vec::with_capacity(history.entries.len()); + for entry in history.entries { + let doc_value = entry.document.to_object().map_err(|e| { + FFIError::InternalError(format!("Failed to convert document to JSON: {}", e)) + })?; + let document = serde_json::to_value(&doc_value) + .map_err(|e| FFIError::InternalError(format!("Failed to serialize document: {}", e)))?; + entries.push(DocumentHistoryEntryJson { + time_ms: entry.time_ms, + revision: entry.revision, + document, + }); + } + + let lifecycle = history.lifecycle.ok_or_else(|| { + FFIError::InternalError( + "history response did not authenticate lifecycle metadata".to_string(), + ) + })?; + + let result = DocumentHistoryJson { + entries, + lifecycle: DocumentHistoryLifecycleJson { + state: match lifecycle.state { + DocumentHistoryState::Active => "ACTIVE", + DocumentHistoryState::Deleted => "DELETED", + DocumentHistoryState::Erasing => "ERASING", + DocumentHistoryState::Absent => "ABSENT", + }, + remaining_revisions: lifecycle.remaining_revisions, + deleted_at_ms: lifecycle.times.deleted_at_ms, + erasing_started_at_ms: lifecycle.times.erasing_started_at_ms, + erasing_from_time_ms: lifecycle.times.erasing_from_time_ms, + erasing_from_revision: lifecycle.times.erasing_from_revision, + }, + }; + + serde_json::to_string(&result) + .map_err(|e| FFIError::InternalError(format!("Failed to serialize result: {}", e))) +} + +/// Fetch a page of a document's revision history with its lifecycle state +/// +/// # Parameters +/// - `sdk_handle`: SDK handle +/// - `contract_id`: Base58-encoded contract ID (resolved through the SDK's current context provider) +/// - `document_type`: Name of a keep-history document type in that contract +/// - `document_id`: Base58-encoded document ID +/// - `filter`: A `DashSDKDocumentHistoryFilter` value (0..=3); decides how `time_ms` and `revision` are used +/// - `time_ms`: Inclusive lower time bound (`StartAtTime`) or cursor time (`StartAfter`) +/// - `revision`: Cursor revision (`StartAfter`), first revision (`StartAtRevision`), or the revision (`Revision`) +/// - `limit`: Maximum number of entries, at most ten (0 for the default) +/// +/// # Returns +/// A JSON object: +/// `{"entries":[{"time_ms":…,"revision":…,"document":{…}}],"lifecycle":{"state":"ACTIVE"|"DELETED"|"ERASING"|"ABSENT","remaining_revisions":…,"deleted_at_ms":…,"erasing_started_at_ms":…,"erasing_from_time_ms":…,"erasing_from_revision":…}}`. +/// Deletion time is set only while `DELETED` or `ERASING`; erase times and +/// the erase cursor are set only while `ERASING`. They are zero otherwise. +/// An absent document yields no entries and the `ABSENT` state. +/// The read needs the history layout of protocol version 15: a page served +/// from the earlier layout carries no lifecycle block and is refused. +/// +/// # Safety +/// - `sdk_handle`, `contract_id`, `document_type`, and `document_id` must be valid, non-null pointers. +/// - The three strings must be NUL-terminated and valid for the duration of the call. +/// - On success, returns a heap-allocated C string pointer inside `DashSDKResult`; caller must free it using SDK routines. +#[no_mangle] +pub unsafe extern "C" fn dash_sdk_document_fetch_history( + sdk_handle: *const SDKHandle, + contract_id: *const c_char, + document_type: *const c_char, + document_id: *const c_char, + filter: c_uint, + time_ms: u64, + revision: u64, + limit: c_uint, +) -> DashSDKResult { + if sdk_handle.is_null() + || contract_id.is_null() + || document_type.is_null() + || document_id.is_null() + { + return DashSDKResult::error(DashSDKError::new( + DashSDKErrorCode::InvalidParameter, + "One or more required parameters is null".to_string(), + )); + } + + let filter = match filter { + 0 => DocumentHistoryFilter::StartAtTime(time_ms), + 1 => DocumentHistoryFilter::StartAfter { time_ms, revision }, + 2 => DocumentHistoryFilter::StartAtRevision(revision), + 3 => DocumentHistoryFilter::Revision(revision), + _ => { + return DashSDKResult::error(DashSDKError::new( + DashSDKErrorCode::InvalidParameter, + "Unknown document history filter".to_string(), + )); + } + }; + + let wrapper = &*(sdk_handle as *const SDKWrapper); + + let contract_id_str = match CStr::from_ptr(contract_id).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let document_type_str = match CStr::from_ptr(document_type).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let document_id_str = match CStr::from_ptr(document_id).to_str() { + Ok(s) => s, + Err(e) => return DashSDKResult::error(FFIError::from(e).into()), + }; + + let result: Result = wrapper.runtime.block_on(async { + let contract_id = Identifier::from_string(contract_id_str, Encoding::Base58) + .map_err(|e| FFIError::InvalidParameter(format!("Invalid contract ID: {e}")))?; + + let document_id = Identifier::from_string(document_id_str, Encoding::Base58) + .map_err(|e| FFIError::InvalidParameter(format!("Invalid document ID: {e}")))?; + + // Check the document type in a pre-flight lookup through the SDK's + // current context provider. Fetch also uses it to verify the history. + let data_contract = wrapper.data_contract(&contract_id)?; + + data_contract + .document_type_for_name(document_type_str) + .map_err(|e| FFIError::NotFound(format!("Document type not found: {}", e)))?; + + let query = DocumentHistoryQuery { + data_contract_id: contract_id, + document_type_name: document_type_str.to_string(), + document_id, + filter, + limit: if limit == 0 { None } else { Some(limit) }, + }; + + let history = DocumentHistory::fetch(&wrapper.sdk, query) + .await + .map_err(FFIError::from)? + .ok_or_else(|| { + FFIError::InternalError("Document history response is missing".to_string()) + })?; + + document_history_to_json(history) + }); + + match result { + Ok(json) => { + let c_str = match CString::new(json) { + Ok(s) => s, + Err(e) => { + return DashSDKResult::error( + FFIError::InternalError(format!("Failed to create CString: {}", e)).into(), + ) + } + }; + DashSDKResult::success_string(c_str.into_raw()) + } + Err(e) => DashSDKResult::error(e.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_utils::test_utils::*; + use dash_sdk::dpp::document::{Document, DocumentV0}; + use dash_sdk::dpp::platform_value::Value; + use drive_proof_verifier::types::{DocumentHistoryEntry, DocumentHistoryLifecycle}; + use std::collections::BTreeMap; + use std::ptr; + + #[test] + fn should_fetch_history_using_the_current_context_provider() { + let contract = create_mock_data_contract(); + let contract_id = CString::new(contract.id().to_string(Encoding::Base58)).unwrap(); + let sdk_handle = create_mock_sdk_handle_with_current_contracts(vec![*contract]); + let document_id = + CString::new(Identifier::new([2; 32]).to_string(Encoding::Base58)).unwrap(); + let document_type = CString::new("missing_document_type").unwrap(); + + let result = unsafe { + dash_sdk_document_fetch_history( + sdk_handle, + contract_id.as_ptr(), + document_type.as_ptr(), + document_id.as_ptr(), + DashSDKDocumentHistoryFilter::HistoryStartAtTime as c_uint, + 0, + 0, + 1, + ) + }; + assert!(!result.error.is_null()); + let (code, message) = unsafe { + let error = &*result.error; + let details = ( + error.code, + CStr::from_ptr(error.message).to_string_lossy().into_owned(), + ); + crate::dash_sdk_error_free(result.error); + details + }; + destroy_mock_sdk_handle(sdk_handle); + + assert_eq!(code, DashSDKErrorCode::NotFound, "{message}"); + assert!(message.contains("Document type not found"), "{message}"); + assert!(message.contains("document type not found"), "{message}"); + } + + fn revision_document(revision: u64) -> Document { + let mut properties = BTreeMap::new(); + properties.insert( + "message".to_string(), + Value::Text(format!("rev {revision}")), + ); + Document::V0(DocumentV0 { + contract_version: None, + id: Identifier::from([2u8; 32]), + owner_id: Identifier::from([1u8; 32]), + properties, + revision: Some(revision), + created_at: None, + updated_at: None, + transferred_at: None, + moderated_at: None, + moderated_by: None, + created_at_block_height: None, + updated_at_block_height: None, + transferred_at_block_height: None, + created_at_core_block_height: None, + updated_at_core_block_height: None, + transferred_at_core_block_height: None, + creator_id: None, + }) + } + + #[test] + fn should_reject_unknown_history_filter_without_fetching() { + let sdk_handle = create_mock_sdk_handle(); + let contract_id = CString::new("invalid contract ID").unwrap(); + let document_type = CString::new("note").unwrap(); + let document_id = CString::new("invalid document ID").unwrap(); + + for filter in [4, c_uint::MAX] { + let result = unsafe { + dash_sdk_document_fetch_history( + sdk_handle, + contract_id.as_ptr(), + document_type.as_ptr(), + document_id.as_ptr(), + filter, + 0, + 0, + 0, + ) + }; + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + assert_eq!( + CStr::from_ptr(error.message).to_str().unwrap(), + "Unknown document history filter" + ); + crate::dash_sdk_error_free(result.error); + } + } + + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn should_accept_named_history_filters_before_validating_contract_id() { + let sdk_handle = create_mock_sdk_handle(); + let contract_id = CString::new("invalid contract ID").unwrap(); + let document_type = CString::new("note").unwrap(); + let document_id = CString::new("invalid document ID").unwrap(); + + for filter in [ + DashSDKDocumentHistoryFilter::HistoryStartAtTime, + DashSDKDocumentHistoryFilter::HistoryStartAfter, + DashSDKDocumentHistoryFilter::HistoryStartAtRevision, + DashSDKDocumentHistoryFilter::HistoryRevision, + ] { + let result = unsafe { + dash_sdk_document_fetch_history( + sdk_handle, + contract_id.as_ptr(), + document_type.as_ptr(), + document_id.as_ptr(), + filter as c_uint, + 123, + 7, + 1, + ) + }; + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + assert!(CStr::from_ptr(error.message) + .to_str() + .unwrap() + .starts_with("Invalid parameter: Invalid contract ID:")); + crate::dash_sdk_error_free(result.error); + } + } + + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn should_classify_a_malformed_history_document_id_as_invalid_parameter() { + let sdk_handle = create_mock_sdk_handle(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type = CString::new("note").unwrap(); + let document_id = CString::new("not-base58-0OIl").unwrap(); + + let result = unsafe { + dash_sdk_document_fetch_history( + sdk_handle, + contract_id.as_ptr(), + document_type.as_ptr(), + document_id.as_ptr(), + DashSDKDocumentHistoryFilter::HistoryStartAtTime as c_uint, + 0, + 0, + 1, + ) + }; + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + assert!(CStr::from_ptr(error.message) + .to_str() + .unwrap() + .starts_with("Invalid parameter: Invalid document ID:")); + crate::dash_sdk_error_free(result.error); + } + destroy_mock_sdk_handle(sdk_handle); + } + + #[test] + fn test_fetch_history_with_null_parameters() { + let sdk_handle = create_mock_sdk_handle(); + let contract_id = CString::new("GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec").unwrap(); + let document_type = CString::new("note").unwrap(); + let document_id = CString::new("4EfA9Jrvv3nnCFdSf7fad59851iiTRZ6Wcu6YVJ4iSeF").unwrap(); + + let null_cases: [( + *const SDKHandle, + *const c_char, + *const c_char, + *const c_char, + ); 4] = [ + ( + ptr::null(), + contract_id.as_ptr(), + document_type.as_ptr(), + document_id.as_ptr(), + ), + ( + sdk_handle, + ptr::null(), + document_type.as_ptr(), + document_id.as_ptr(), + ), + ( + sdk_handle, + contract_id.as_ptr(), + ptr::null(), + document_id.as_ptr(), + ), + ( + sdk_handle, + contract_id.as_ptr(), + document_type.as_ptr(), + ptr::null(), + ), + ]; + + for (handle, contract, doc_type, doc_id) in null_cases { + let result = unsafe { + dash_sdk_document_fetch_history( + handle, + contract, + doc_type, + doc_id, + DashSDKDocumentHistoryFilter::HistoryStartAtTime as c_uint, + 0, + 0, + 0, + ) + }; + assert!(!result.error.is_null()); + unsafe { + let error = &*result.error; + assert_eq!(error.code, DashSDKErrorCode::InvalidParameter); + crate::dash_sdk_error_free(result.error); + } + } + + destroy_mock_sdk_handle(sdk_handle); + } + + /// Two revisions written in one block keep their distinct cursors, the + /// document is the canonical query-side shape, and every lifecycle time + /// crosses the boundary exactly. + #[test] + fn test_history_json_keeps_cursors_lifecycle_and_canonical_documents() { + use drive_proof_verifier::types::DocumentHistoryLifecycleTimes; + + let history = DocumentHistory { + entries: (1..=2) + .map(|revision| DocumentHistoryEntry { + time_ms: 1_700_000_000_000, + revision, + document: revision_document(revision), + }) + .collect(), + lifecycle: Some(DocumentHistoryLifecycle { + state: DocumentHistoryState::Erasing, + remaining_revisions: 2, + times: DocumentHistoryLifecycleTimes { + deleted_at_ms: 1_700_000_000_001, + erasing_started_at_ms: 1_700_000_000_002, + erasing_from_time_ms: 1_700_000_000_000, + erasing_from_revision: 2, + }, + }), + }; + + let json: serde_json::Value = + serde_json::from_str(&document_history_to_json(history).unwrap()).unwrap(); + + let entries = json["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 2); + assert_eq!( + entries[0]["time_ms"], + serde_json::json!(1_700_000_000_000u64) + ); + assert_eq!(entries[0]["revision"], serde_json::json!(1)); + assert_eq!(entries[1]["revision"], serde_json::json!(2)); + assert_eq!(entries[1]["document"]["$revision"], serde_json::json!(2)); + assert_eq!( + entries[1]["document"]["message"], + serde_json::json!("rev 2") + ); + assert!(entries[1]["document"]["$id"].is_string()); + assert!(entries[1]["document"]["$ownerId"].is_string()); + + let lifecycle = &json["lifecycle"]; + assert_eq!(lifecycle["state"], serde_json::json!("ERASING")); + assert_eq!(lifecycle["remaining_revisions"], serde_json::json!(2)); + assert_eq!( + lifecycle["deleted_at_ms"], + serde_json::json!(1_700_000_000_001u64) + ); + assert_eq!( + lifecycle["erasing_started_at_ms"], + serde_json::json!(1_700_000_000_002u64) + ); + assert_eq!( + lifecycle["erasing_from_time_ms"], + serde_json::json!(1_700_000_000_000u64) + ); + assert_eq!(lifecycle["erasing_from_revision"], serde_json::json!(2)); + } + + /// An absent document reports the `ABSENT` state with no entries; a + /// response without lifecycle metadata is a legacy response and refused. + #[test] + fn test_history_json_reports_absent_and_refuses_legacy_responses() { + let absent = DocumentHistory { + entries: vec![], + lifecycle: Some(DocumentHistoryLifecycle { + state: DocumentHistoryState::Absent, + remaining_revisions: 0, + times: Default::default(), + }), + }; + let json: serde_json::Value = + serde_json::from_str(&document_history_to_json(absent).unwrap()).unwrap(); + assert_eq!(json["entries"].as_array().unwrap().len(), 0); + assert_eq!(json["lifecycle"]["state"], serde_json::json!("ABSENT")); + assert_eq!( + json["lifecycle"]["remaining_revisions"], + serde_json::json!(0) + ); + assert_eq!(json["lifecycle"]["deleted_at_ms"], serde_json::json!(0)); + + let legacy = DocumentHistory { + entries: vec![], + lifecycle: None, + }; + assert!(document_history_to_json(legacy).is_err()); + } +} diff --git a/packages/rs-sdk-ffi/src/document/queries/mod.rs b/packages/rs-sdk-ffi/src/document/queries/mod.rs index 71d0a2fabce..258bd64b15c 100644 --- a/packages/rs-sdk-ffi/src/document/queries/mod.rs +++ b/packages/rs-sdk-ffi/src/document/queries/mod.rs @@ -5,6 +5,7 @@ pub mod average; pub mod count; pub mod fetch; +pub mod history; pub mod info; pub mod search; /// Sum-side FFI entry (`dash_sdk_document_sum`). Wraps the rs-sdk @@ -13,6 +14,7 @@ pub mod sum; pub use count::dash_sdk_document_count; pub use fetch::dash_sdk_document_fetch; +pub use history::{dash_sdk_document_fetch_history, DashSDKDocumentHistoryFilter}; pub use search::{dash_sdk_document_search, DashSDKDocumentSearchParams}; // `sum::dash_sdk_document_sum` and `average::dash_sdk_document_average` // are exported via their `#[no_mangle] extern "C"` declarations; no diff --git a/packages/rs-sdk-ffi/src/test_utils.rs b/packages/rs-sdk-ffi/src/test_utils.rs index 7118a4624be..b8bb20bc143 100644 --- a/packages/rs-sdk-ffi/src/test_utils.rs +++ b/packages/rs-sdk-ffi/src/test_utils.rs @@ -4,6 +4,7 @@ pub mod test_utils { use crate::sdk::SDKWrapper; use crate::signer::{SignCompletionCallback, SignerVTable, VTableSigner}; use crate::types::{DashSDKPutSettings, SDKHandle}; + use dash_context_provider::{ContractSource, SpvContextProvider}; use dash_sdk::dpp::data_contract::DataContractFactory; use dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; use dash_sdk::dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel}; @@ -11,8 +12,10 @@ pub mod test_utils { use dash_sdk::dpp::platform_value::BinaryData; use dash_sdk::dpp::prelude::{DataContract, Identifier}; use dash_sdk::platform::transition::put_settings::PutSettings; + use rs_sdk_trusted_context_provider::LocalContextResolver; use std::ffi::CString; use std::os::raw::c_void; + use std::sync::Arc; // Helper function to create a mock SDK handle pub fn create_mock_sdk_handle() -> *mut SDKHandle { @@ -20,6 +23,24 @@ pub mod test_utils { Box::into_raw(wrapper) as *mut SDKHandle } + /// A current SPV provider that resolves local contracts without a trusted-provider cache. + pub fn create_mock_sdk_handle_with_current_contracts( + contracts: Vec, + ) -> *mut SDKHandle { + let local_contracts = LocalContextResolver::new(); + local_contracts.add_known_contracts(contracts); + let wrapper = SDKWrapper::new_mock(); + assert!(wrapper.trusted_provider.is_none()); + wrapper + .sdk + .set_context_provider(SpvContextProvider::new( + Arc::new(local_contracts) as Arc, + wrapper.sdk.network, + )) + .expect("a provider for the mock SDK's network"); + Box::into_raw(Box::new(wrapper)) as *mut SDKHandle + } + // Helper function to destroy a mock SDK handle pub fn destroy_mock_sdk_handle(handle: *mut SDKHandle) { unsafe { diff --git a/packages/rs-unified-sdk-jni/src/queries.rs b/packages/rs-unified-sdk-jni/src/queries.rs index 6e926f98546..dc7dcef046b 100644 --- a/packages/rs-unified-sdk-jni/src/queries.rs +++ b/packages/rs-unified-sdk-jni/src/queries.rs @@ -25,9 +25,9 @@ use rs_sdk_ffi::{ dash_sdk_data_contract_get_property_constraints, dash_sdk_data_contract_json_expand_property_type_shorthands, dash_sdk_data_contracts_fetch_by_range, dash_sdk_document_average, dash_sdk_document_count, - dash_sdk_document_search, dash_sdk_document_sum, dash_sdk_dpns_check_availability, - dash_sdk_dpns_get_usernames, dash_sdk_dpns_resolve, dash_sdk_dpns_search, - dash_sdk_evonode_get_proposed_epoch_blocks_by_ids, + dash_sdk_document_fetch_history, dash_sdk_document_search, dash_sdk_document_sum, + dash_sdk_dpns_check_availability, dash_sdk_dpns_get_usernames, dash_sdk_dpns_resolve, + dash_sdk_dpns_search, dash_sdk_evonode_get_proposed_epoch_blocks_by_ids, dash_sdk_evonode_get_proposed_epoch_blocks_by_range, dash_sdk_group_get_action_signers, dash_sdk_group_get_actions, dash_sdk_group_get_info, dash_sdk_identities_fetch_balances, dash_sdk_identities_fetch_contract_keys, dash_sdk_identity_fetch, @@ -45,7 +45,7 @@ use rs_sdk_ffi::{ dash_sdk_token_get_perpetual_distribution_last_claim, dash_sdk_token_get_pre_programmed_distributions, dash_sdk_token_get_statuses, dash_sdk_token_get_total_supply, dash_sdk_voting_get_vote_polls_by_end_date, - DashSDKDocumentSearchParams, DataContractHandle, SDKHandle, + DashSDKDocumentHistoryFilter, DashSDKDocumentSearchParams, DataContractHandle, SDKHandle, }; use std::ffi::{CStr, CString}; use std::os::raw::c_char; @@ -426,6 +426,67 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_QueriesNative_documen }) } +/// Read a page of a keep-history document's revision history with its +/// lifecycle block; returns the JSON object `dash_sdk_document_fetch_history` +/// produces. `filter` is the `DashSDKDocumentHistoryFilter` discriminant +/// (0 start-at time, 1 start-after cursor, 2 start-at revision, 3 single +/// revision); `time_ms` and `revision` are read according to it, and `limit` +/// zero takes the server default. Negative numbers are rejected before the +/// unsigned conversion. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_QueriesNative_documentHistory( + mut env: JNIEnv, + _class: JClass, + sdk: jlong, + contract_id: JString, + document_type: JString, + document_id: JString, + filter: jint, + time_ms: jlong, + revision: jlong, + limit: jint, +) -> jstring { + guard(&mut env, ptr::null_mut(), |env| { + let filter = match filter { + 0 => DashSDKDocumentHistoryFilter::HistoryStartAtTime, + 1 => DashSDKDocumentHistoryFilter::HistoryStartAfter, + 2 => DashSDKDocumentHistoryFilter::HistoryStartAtRevision, + 3 => DashSDKDocumentHistoryFilter::HistoryRevision, + _ => { + throw_sdk_exception(env, 1, "unknown document history filter"); + return ptr::null_mut(); + } + }; + if time_ms < 0 || revision < 0 || limit < 0 { + throw_sdk_exception( + env, + 1, + "history time, revision and limit must be non-negative", + ); + return ptr::null_mut(); + } + let contract_c = require_cstr!(env, contract_id); + let doc_type = require_cstr!(env, document_type); + let doc_id = require_cstr!(env, document_id); + let result = unsafe { + dash_sdk_document_fetch_history( + sdk as *const SDKHandle, + contract_c.as_ptr(), + doc_type.as_ptr(), + doc_id.as_ptr(), + filter as u32, + time_ms as u64, + revision as u64, + limit as u32, + ) + }; + unsafe { unwrap_string(env, result) } + .map(|s| s.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + /// Sum a numeric document property; returns a JSON result object. #[no_mangle] pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_QueriesNative_documentSum( diff --git a/packages/rs-unified-sdk-jni/src/transactions.rs b/packages/rs-unified-sdk-jni/src/transactions.rs index c9347bedfc8..f00982c1247 100644 --- a/packages/rs-unified-sdk-jni/src/transactions.rs +++ b/packages/rs-unified-sdk-jni/src/transactions.rs @@ -746,6 +746,71 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TransactionsNative_do }) } +/// Erase + broadcast a chunk of the retained revisions of the already +/// deleted `documentId` on `contractId`'s `documentType`, signed via +/// `signerHandle` with key `signingKeyId` of `ownerId` β€” the JNI bridge +/// over `platform_wallet_document_erase` (Swift +/// `ManagedPlatformWallet.eraseDocument`). The first erase of a document +/// must be signed by its owner; later ones may be signed by any identity. +/// +/// Erase returns no document body, so this returns the document's 32-byte +/// id as a `byte[]` once its absence is observed under a proof (which it +/// already was before the erase; progress is read from the history). +/// Null after throwing on error. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TransactionsNative_documentErase( + mut env: JNIEnv, + _class: JClass, + wallet_handle: jlong, + owner_id: JByteArray, + contract_id: JByteArray, + document_type: JString, + document_id: JByteArray, + signing_key_id: jint, + signer_handle: jlong, +) -> jni::sys::jbyteArray { + guard(&mut env, ptr::null_mut(), |env| { + if signing_key_id < 0 { + throw_sdk_exception(env, 1, "signingKeyId must be non-negative"); + return ptr::null_mut(); + } + let Some(owner) = read_id32(env, &owner_id, "ownerId") else { + return ptr::null_mut(); + }; + let Some(contract) = read_id32(env, &contract_id, "contractId") else { + return ptr::null_mut(); + }; + let Some(doc_id) = read_id32(env, &document_id, "documentId") else { + return ptr::null_mut(); + }; + let Some(doc_type) = read_cstring(env, &document_type, "documentType") else { + return ptr::null_mut(); + }; + + let mut out_id = [0u8; 32]; + let result = unsafe { + platform_wallet_ffi::platform_wallet_document_erase( + wallet_handle as Handle, + owner.as_ptr(), + contract.as_ptr(), + doc_type.as_ptr(), + doc_id.as_ptr(), + signing_key_id as u32, + signer_handle as *mut SignerHandle, + out_id.as_mut_ptr(), + ) + }; + if take_pwffi_error(env, result) { + return ptr::null_mut(); + } + + env.byte_array_from_slice(&out_id) + .map(|a| a.into_raw()) + .unwrap_or(ptr::null_mut()) + }) +} + /// Transfer + broadcast `documentId` on `contractId`'s `documentType`, /// from `ownerId` to `recipientId`, signed via `signerHandle` with key /// `signingKeyId` β€” the JNI bridge over `platform_wallet_document_transfer` diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift index 600e41d752a..b253238d40a 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift @@ -125,6 +125,133 @@ public struct PathElement: Sendable { } } +/// Which revisions of a keep-history document to read. Exactly one +/// filter applies per `documentGetHistory` call. +public enum DocumentHistoryFilter: Sendable { + /// Revisions written at or after the time, oldest first. Zero reads + /// the first page of the whole history. + case startAtTime(ms: UInt64) + /// Revisions after the complete cursor of the last entry received. + case startAfter(timeMs: UInt64, revision: UInt64) + /// Revisions from the history sequence number onwards. + case startAtRevision(UInt64) + /// Exactly the revision at the history sequence number; the limit + /// must be one. + case revision(UInt64) + + var ffiValue: UInt32 { + switch self { + case .startAtTime: return HistoryStartAtTime.rawValue + case .startAfter: return HistoryStartAfter.rawValue + case .startAtRevision: return HistoryStartAtRevision.rawValue + case .revision: return HistoryRevision.rawValue + } + } + + var timeMs: UInt64 { + switch self { + case .startAtTime(let ms): return ms + case .startAfter(let timeMs, _): return timeMs + case .startAtRevision, .revision: return 0 + } + } + + var revisionValue: UInt64 { + switch self { + case .startAtTime: return 0 + case .startAfter(_, let revision): return revision + case .startAtRevision(let revision), .revision(let revision): return revision + } + } +} + +/// Where a keep-history document stands in its lifecycle, as the history +/// query authenticates it. +public enum DocumentLifecycleState: String, Sendable { + /// Visible to ordinary reads. + case active = "ACTIVE" + /// Deleted with its revisions retained. + case deleted = "DELETED" + /// An authorized erasure has begun and revisions are being removed. + case erasing = "ERASING" + /// Nothing is left. + case absent = "ABSENT" +} + +/// The `lifecycle` block of a `documentGetHistory` result. +public struct DocumentHistoryLifecycle: Sendable { + public let state: DocumentLifecycleState + /// Exact count of revisions still retained (zero when absent). + public let remainingRevisions: UInt64 + /// Deletion time while deleted or erasing; zero otherwise. + public let deletedAtMs: UInt64 + /// Erase start time while erasing; zero otherwise. + public let erasingStartedAtMs: UInt64 + /// Newest retained revision's time when erasure began; zero unless erasing. + public let erasingFromTimeMs: UInt64 + /// History sequence number of that revision; zero unless erasing. + public let erasingFromRevision: UInt64 + + /// Parses the `lifecycle` dictionary of a `documentGetHistory` + /// result; nil when the block, its state, or any of its numbers is + /// missing, unknown, or not a non-negative integer, so a partial block + /// is never read as zeros. + public init?(json: [String: Any]) { + guard let stateRaw = json["state"] as? String, + let state = DocumentLifecycleState(rawValue: stateRaw) else { + return nil + } + func value(_ key: String) -> UInt64? { + // JSONSerialization preserves Rust's integer JSON in NSNumber. + // Reject booleans and parse its decimal representation exactly, + // avoiding Double rounding at the upper UInt64 boundary. + guard let number = json[key] as? NSNumber, + CFGetTypeID(number) != CFBooleanGetTypeID() else { + return nil + } + return UInt64(number.stringValue) + } + guard let remainingRevisions = value("remaining_revisions"), + let deletedAtMs = value("deleted_at_ms"), + let erasingStartedAtMs = value("erasing_started_at_ms"), + let erasingFromTimeMs = value("erasing_from_time_ms"), + let erasingFromRevision = value("erasing_from_revision") else { + return nil + } + self.state = state + self.remainingRevisions = remainingRevisions + self.deletedAtMs = deletedAtMs + self.erasingStartedAtMs = erasingStartedAtMs + self.erasingFromTimeMs = erasingFromTimeMs + self.erasingFromRevision = erasingFromRevision + } + + /// Words for what an erase achieved, from the lifecycle read before it + /// was submitted (nil when not read) and the one read after its absence + /// was observed. The erase result itself proves only that the document + /// is absent from ordinary reads, which it already was, so a document + /// still DELETED with the same retained count is reported as not + /// established, never as an accepted or completed erase. + public static func describeEraseProgress( + before: DocumentHistoryLifecycle?, + after: DocumentHistoryLifecycle + ) -> String { + switch after.state { + case .absent: + return "Erasure complete: no retained revisions remain." + case .erasing: + return "Erasure in progress: \(after.remainingRevisions) revisions still retained; submit another erase to continue." + case .deleted: + if let before, before.state == .deleted, before.remainingRevisions == after.remainingRevisions { + return "Not established: the document is still DELETED with \(after.remainingRevisions) revisions retained, so the history shows nothing this erase removed." + } + return "The document is DELETED with \(after.remainingRevisions) revisions retained; no erasure has been recorded." + case .active: + return "The document is active; an erase applies only after it has been deleted." + } + } +} + // MARK: - Platform Query Extensions for SDK @MainActor extension SDK { @@ -550,6 +677,60 @@ extension SDK { // MARK: - Document Queries + /// Read where a keep-history document stands right now: its lifecycle + /// state and the exact number of revisions still retained. A current + /// observation, not the outcome of any particular transition. + public func documentGetLifecycle( + dataContractId: String, + documentType: String, + documentId: String + ) async throws -> DocumentHistoryLifecycle { + let page = try await documentGetHistory( + dataContractId: dataContractId, + documentType: documentType, + documentId: documentId, + filter: .startAtTime(ms: 0), + limit: 1 + ) + guard let lifecycleJSON = page["lifecycle"] as? [String: Any], + let lifecycle = DocumentHistoryLifecycle(json: lifecycleJSON) else { + throw SDKError.serializationError("Document history response carried no complete lifecycle block") + } + return lifecycle + } + + /// Get a page of a keep-history document's revision history with its + /// lifecycle state. + /// + /// Returns the FFI's JSON object: `entries` (each with `time_ms`, + /// `revision` and the canonical `document`) and `lifecycle` (see + /// `DocumentHistoryLifecycle`). Pass the last entry's `time_ms` and + /// `revision` back as `.startAfter` for the next page. At most ten + /// entries per page; `limit` nil takes the default. Needs the protocol-15 + /// history layout: a page served from the earlier layout has no lifecycle + /// block and the FFI refuses it. + public nonisolated func documentGetHistory( + dataContractId: String, + documentType: String, + documentId: String, + filter: DocumentHistoryFilter = .startAtTime(ms: 0), + limit: UInt32? = nil + ) async throws -> sending [String: Any] { + let json = try await performBlockingQuery { handle in + try Self.consumeStringResult(dash_sdk_document_fetch_history( + handle, + dataContractId, + documentType, + documentId, + filter.ffiValue, + filter.timeMs, + filter.revisionValue, + limit ?? 0 + )) + } + return try Self.parseJSONObject(json) + } + /// List documents /// /// `nonisolated`: the contract fetch and the search both block on the diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift index a06225fe9dd..c25452c7c85 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift @@ -918,6 +918,103 @@ extension SDK { } } + /// Erase a chunk of the retained revisions of an already deleted + /// keep-history document. The first erase must be signed by the + /// document's owner; later ones may be signed by any identity, so + /// `ownerIdentity` is the signing identity. Returns once the transition + /// is broadcast and Platform has proved the document absent from + /// ordinary reads, which it already was, so a return observes the + /// affected state rather than proving this erase removed a revision; + /// `documentGetLifecycle` reports the state and how many revisions + /// remain. + public func documentErase( + contractId: String, + documentType: String, + documentId: String, + ownerIdentity: DPPIdentity, + signer: OpaquePointer + ) async throws { + let signerBox = SendableOpaque(signer) + let startTime = Date() + print("🧹 [DOCUMENT ERASE] Starting at \(startTime)") + print("🧹 [DOCUMENT ERASE] Contract: \(contractId), Type: \(documentType), Doc: \(documentId)") + + // Select the signing key on the MainActor (KeyManager is @MainActor) + // before dispatching the FFI work off-actor. + guard let signingKey = selectSigningKey(from: ownerIdentity, operation: "DOCUMENT ERASE", signer: signer) else { + throw SDKError.protocolError("No suitable key found for signing") + } + + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + DispatchQueue.global().async { [weak self] in + guard let self = self, let handle = self.handle else { + continuation.resume(throwing: SDKError.invalidState("SDK not initialized")) + return + } + + do { + // Prepare C strings + guard let documentIdCString = documentId.cString(using: .utf8), + let ownerIdCString = ownerIdentity.id.toBase58String().cString(using: .utf8), + let contractIdCString = contractId.cString(using: .utf8), + let documentTypeCString = documentType.cString(using: .utf8) else { + throw SDKError.serializationError("Failed to encode strings to C strings") + } + + // Key selection happened on the MainActor before dispatch. + let keyToUse = signingKey + + // Create public key handle + guard let keyHandle = createPublicKeyHandle(from: keyToUse, operation: "DOCUMENT ERASE") else { + throw SDKError.protocolError("Failed to create public key handle") + } + + defer { + dash_sdk_identity_public_key_destroy(keyHandle) + } + + // Call the FFI function with network timing + let networkStartTime = Date() + print("🧹 [DOCUMENT ERASE] Calling dash_sdk_document_erase_and_wait...") + print("🧹 [DOCUMENT ERASE] Document ID: \(documentId)") + print("🧹 [DOCUMENT ERASE] Signer ID: \(ownerIdentity.id.toBase58String())") + + let result = dash_sdk_document_erase_and_wait( + handle, + documentIdCString, + ownerIdCString, + contractIdCString, + documentTypeCString, + keyHandle, + signerBox.p, + nil, // put_settings + nil // state_transition_creation_options + ) + + let networkTime = Date().timeIntervalSince(networkStartTime) + print("🧹 [DOCUMENT ERASE] Network call completed in \(networkTime) seconds") + + if let error = result.error { + let errorMessage = String(cString: error.pointee.message) + let failure = SDKError.stateTransitionFailure( + errorMessage, ffiError: error.pointee, otherwise: SDKError.protocolError) + dash_sdk_error_free(error) + throw failure + } + + let totalTime = Date().timeIntervalSince(startTime) + print("βœ… [DOCUMENT ERASE] Broadcast done, absence observed. Total time: \(totalTime) seconds") + + continuation.resume() + } catch { + let totalTime = Date().timeIntervalSince(startTime) + print("❌ [DOCUMENT ERASE] Failed after \(totalTime) seconds: \(error)") + continuation.resume(throwing: error) + } + } + } + } + /// Transfer a document to another identity public func documentTransfer( contractId: String, diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/Models/StateTransitionDefinitions.swift b/packages/swift-sdk/Sources/SwiftDashSDK/Models/StateTransitionDefinitions.swift index 49bbb41c601..bc530cca3fd 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/Models/StateTransitionDefinitions.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/Models/StateTransitionDefinitions.swift @@ -400,6 +400,34 @@ public struct TransitionDefinitions { ] ), + "documentErase": TransitionDefinition( + key: "documentErase", + label: "Document Erase", + description: "Erase the retained revisions of a deleted keep-history document", + inputs: [ + TransitionInput( + name: "contractId", + type: "contractPicker", + label: "Data Contract", + required: true + ), + TransitionInput( + name: "documentType", + type: "documentTypePicker", + label: "Document Type", + required: true, + placeholder: "" // Will be filled with selected contractId + ), + TransitionInput( + name: "documentId", + type: "text", + label: "Document ID", + required: true, + placeholder: "ID of the deleted document" + ) + ] + ), + "documentTransfer": TransitionDefinition( key: "documentTransfer", label: "Document Transfer", diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index e8206d87778..f1b6599554e 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -4995,6 +4995,76 @@ extension ManagedPlatformWallet { }.value } + /// Erase + broadcast a chunk of the retained revisions of the already + /// deleted `documentId` on `contractId`'s `documentType`, signed with + /// the explicit AUTHENTICATION + ECDSA key `signingKeyId` of + /// `ownerIdentityId`. Returns the document's 32-byte id once Platform + /// has proved it absent from ordinary reads. That absence predates the + /// erase, so the return observes the affected state and is not + /// evidence that this erase removed a revision; read + /// `SDK.documentGetLifecycle` for the state and the exact number of + /// revisions still retained. + /// + /// Sibling to `deleteDocument`. Routes through + /// `IdentityWallet::erase_document_with_signer` (via + /// `platform_wallet_document_erase`). Only a keep-history document + /// type whose schema sets `canBeErased` can be erased, and only after + /// the document has been deleted: the first erase must be signed by + /// the document's owner, every later one may be signed by any + /// identity, so `ownerIdentityId` is the signing identity rather than + /// necessarily the owner. One erase removes a bounded chunk of + /// revisions; erase again while the lifecycle reports any. Erase + /// returns no document body, so there is no canonical JSON. + public func eraseDocument( + ownerIdentityId: Identifier, + contractId: Identifier, + documentType: String, + documentId: Identifier, + signingKeyId: UInt32, + signer: KeychainSigner + ) async throws -> Identifier { + let handle = self.handle + let signerHandle = signer.handle + let ownerBytes: [UInt8] = ownerIdentityId.withFFIBytes { ptr in + Array(UnsafeBufferPointer(start: ptr, count: 32)) + } + let contractBytes: [UInt8] = contractId.withFFIBytes { ptr in + Array(UnsafeBufferPointer(start: ptr, count: 32)) + } + let documentBytes: [UInt8] = documentId.withFFIBytes { ptr in + Array(UnsafeBufferPointer(start: ptr, count: 32)) + } + return try await Task.detached(priority: .userInitiated) { [self] in + var documentIdBytes = [UInt8](repeating: 0, count: 32) + + let result = withExtendedLifetime((self, signer)) { + ownerBytes.withUnsafeBufferPointer { ownerBp -> PlatformWalletFFIResult in + contractBytes.withUnsafeBufferPointer { contractBp -> PlatformWalletFFIResult in + documentType.withCString { typePtr in + documentBytes.withUnsafeBufferPointer { docBp -> PlatformWalletFFIResult in + documentIdBytes.withUnsafeMutableBufferPointer { outBp in + platform_wallet_document_erase( + handle, + ownerBp.baseAddress!, + contractBp.baseAddress!, + typePtr, + docBp.baseAddress!, + signingKeyId, + signerHandle, + outBp.baseAddress! + ) + } + } + } + } + } + } + + try result.check() + return Data(documentIdBytes) + }.value + } + /// Transfer + broadcast `documentId` on `contractId`'s /// `documentType`, from `ownerIdentityId` to `recipientId`, signed /// with the explicit AUTHENTICATION + ECDSA key `signingKeyId`. diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift index 8b0a1f695df..c5cf986c4de 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift @@ -86,12 +86,13 @@ struct DocumentsView: View { } } -/// The five ownership-gated document state-transition actions, carrying +/// The six ownership-gated document state-transition actions, carrying /// the document they operate on. `Identifiable` so it can drive a single /// hoisted `sheet(item:)` on `DocumentsView`. enum DocumentActionMode: Identifiable { case replace(PersistentDocument) case delete(PersistentDocument) + case erase(PersistentDocument) case transfer(PersistentDocument) case setPrice(PersistentDocument) case purchase(PersistentDocument) @@ -100,6 +101,7 @@ enum DocumentActionMode: Identifiable { switch self { case .replace(let d): return "replace-\(d.documentId)" case .delete(let d): return "delete-\(d.documentId)" + case .erase(let d): return "erase-\(d.documentId)" case .transfer(let d): return "transfer-\(d.documentId)" case .setPrice(let d): return "setPrice-\(d.documentId)" case .purchase(let d): return "purchase-\(d.documentId)" @@ -108,7 +110,7 @@ enum DocumentActionMode: Identifiable { var document: PersistentDocument { switch self { - case .replace(let d), .delete(let d), .transfer(let d), + case .replace(let d), .delete(let d), .erase(let d), .transfer(let d), .setPrice(let d), .purchase(let d): return d } @@ -283,6 +285,12 @@ struct DocumentDetailView: View { if ownerIsControlled { actions.append(.replace) actions.append(.delete) + // Erase applies to a keep-history document that has already + // been deleted, on a type whose schema sets `canBeErased` (off + // by default); the sheet spells out the precondition. + if (docType?.schema?["canBeErased"] as? Bool) == true { + actions.append(.erase) + } if docType?.documentsTransferable == true { actions.append(.transfer) } @@ -315,13 +323,14 @@ struct DocumentDetailView: View { } } -// MARK: - Document actions (replace / delete / transfer / set-price / purchase) +// MARK: - Document actions (replace / delete / erase / transfer / set-price / purchase) /// The menu entries the gated action menu surfaces. Maps to a /// `DocumentActionMode` once a concrete document is in hand. enum DocumentAction: String, Identifiable, CaseIterable { case replace case delete + case erase case transfer case setPrice case purchase @@ -332,6 +341,7 @@ enum DocumentAction: String, Identifiable, CaseIterable { switch self { case .replace: return "Replace…" case .delete: return "Delete…" + case .erase: return "Erase History…" case .transfer: return "Transfer…" case .setPrice: return "Set Price…" case .purchase: return "Purchase…" @@ -342,6 +352,7 @@ enum DocumentAction: String, Identifiable, CaseIterable { switch self { case .replace: return "pencil" case .delete: return "trash" + case .erase: return "trash.slash" case .transfer: return "arrow.left.arrow.right" case .setPrice: return "tag" case .purchase: return "cart" @@ -352,6 +363,7 @@ enum DocumentAction: String, Identifiable, CaseIterable { switch self { case .replace: return .replace(document) case .delete: return .delete(document) + case .erase: return .erase(document) case .transfer: return .transfer(document) case .setPrice: return .setPrice(document) case .purchase: return .purchase(document) @@ -370,6 +382,8 @@ struct DocumentActionSheet: View { ReplaceDocumentView(document: doc) case .delete(let doc): DeleteDocumentView(document: doc) + case .erase(let doc): + EraseDocumentView(document: doc) case .transfer(let doc): TransferDocumentView(document: doc) case .setPrice(let doc): @@ -848,6 +862,223 @@ struct DeleteDocumentView: View { } } +// MARK: Erase + +/// Erases the retained revisions of a keep-history document that has +/// already been deleted, one bounded chunk per broadcast. The row is still +/// local because the deletion happened elsewhere (another device or the +/// Settings builder). An ACTIVE or ABSENT lifecycle skips the broadcast. +/// +/// The erase result only observes that the document is absent from +/// ordinary reads, which it already was, so the sheet reads the lifecycle +/// before and after each broadcast and shows what that read says. It stays +/// open with the same id so further chunks can be submitted, and removes +/// the local row only once the lifecycle reports the document absent. +struct EraseDocumentView: View { + let document: PersistentDocument + private let documentIdText: String + private let documentTypeName: String + private let contractIdBase58: String + + init(document: PersistentDocument) { + self.document = document + self.documentIdText = document.documentId + self.documentTypeName = document.documentType + self.contractIdBase58 = document.contractIdBase58 + } + + @EnvironmentObject var appState: AppState + @EnvironmentObject var walletManager: PlatformWalletManager + @Environment(\.modelContext) private var modelContext + @Environment(\.dismiss) var dismiss + + @Query private var identities: [PersistentIdentity] + + @State private var isSubmitting = false + @State private var submissions = 0 + @State private var lifecycle: DocumentHistoryLifecycle? + @State private var progress: String? + @State private var persistWarning: String? + @State private var actionError: DocumentActionErrorBox? + + private var canSubmitAnother: Bool { + guard let lifecycle else { return submissions == 0 } + return lifecycle.state == .erasing || lifecycle.state == .deleted + } + + var body: some View { + NavigationStack { + Form { + Section { + DetailRow(label: "Document ID", value: documentIdText) + DetailRow(label: "Type", value: documentTypeName) + if let lifecycle { + DetailRow(label: "Lifecycle", value: lifecycle.state.rawValue) + DetailRow(label: "Revisions retained", value: String(lifecycle.remainingRevisions)) + } + } footer: { + Text("Removes up to 100 retained revisions of a document that has already been deleted on Platform. The document type must allow erasure, and only the owner may start it. If the initial lifecycle read fails, an erase may still be submitted for an active document; consensus rejects it and still charges a fee. A broadcast only observes that the document is absent from ordinary reads; the lifecycle read after it says what remains. This cannot be undone.") + } + if submissions > 0 || progress != nil { + Section { + VStack(alignment: .leading, spacing: 8) { + if submissions > 0 { + Label("Erase submitted; lifecycle read below", systemImage: "info.circle") + .foregroundColor(.secondary) + .font(.headline) + } + if let progress { + Text(progress) + .font(.caption) + .accessibilityIdentifier("documentErase.progress") + } + if let warning = persistWarning { + Label(warning, systemImage: "exclamationmark.triangle.fill") + .foregroundColor(.orange) + .font(.caption) + } + } + } + } + Section { + if canSubmitAnother { + Button(role: .destructive) { + submit() + } label: { + HStack { + if isSubmitting { + ProgressView().controlSize(.small) + Text("Broadcasting…") + } else { + Text(submissions == 0 ? "Erase / Broadcast" : "Erase next chunk") + } + } + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .accessibilityIdentifier("documentErase.submitButton") + .disabled(isSubmitting) + } + if submissions > 0 { + Button("Done") { dismiss() } + .frame(maxWidth: .infinity) + .accessibilityIdentifier("documentErase.doneButton") + .disabled(isSubmitting) + } + } + } + .navigationTitle("Erase Document History") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .navigationBarLeading) { + Button("Cancel") { dismiss() }.disabled(isSubmitting) + } + } + .interactiveDismissDisabled(isSubmitting) + .task { + let observed = try? await appState.sdk?.documentGetLifecycle( + dataContractId: contractIdBase58, + documentType: documentTypeName, + documentId: documentIdText + ) + // A skipped submission also has a newer lifecycle observation. + guard !isSubmitting, submissions == 0, progress == nil else { return } + lifecycle = observed + } + .alert(item: $actionError) { err in + Alert(title: Text("Erase failed"), message: Text(err.message), dismissButton: .default(Text("OK"))) + } + } + } + + private func ownerIdentity() -> PersistentIdentity? { + identities.first { + $0.network == appState.currentNetwork + && $0.wallet != nil + && $0.identityIdBase58 == document.ownerIdBase58 + } + } + + private func submit() { + guard let owner = ownerIdentity() else { + actionError = .init(message: DocumentActionError.identityNotFound.localizedDescription) + return + } + let docType = document.documentType_relation + let wallet: ManagedPlatformWallet + let signingKeyId: UInt32 + do { + (wallet, signingKeyId) = try DocumentActionRunner.resolveSigning( + for: owner, documentType: docType, walletManager: walletManager + ) + } catch { + actionError = .init(message: error.localizedDescription) + return + } + + isSubmitting = true + let signer = KeychainSigner(modelContainer: modelContext.container) + let ownerId = owner.identityId + let contractId = document.contractIdData + let contractIdBase58 = document.contractIdBase58 + let typeName = document.documentType + let docId = document.id + let docIdBase58 = document.documentId + let sdk = appState.sdk + + Task { + do { + let before = try? await sdk?.documentGetLifecycle( + dataContractId: contractIdBase58, documentType: typeName, documentId: docIdBase58 + ) + if let before, before.state == .active || before.state == .absent { + await MainActor.run { + lifecycle = before + progress = "Erase not submitted. " + (before.state == .absent + ? "No retained revisions exist." + : DocumentHistoryLifecycle.describeEraseProgress(before: before, after: before)) + isSubmitting = false + } + return + } + _ = try await wallet.eraseDocument( + ownerIdentityId: ownerId, + contractId: contractId, + documentType: typeName, + documentId: docId, + signingKeyId: signingKeyId, + signer: signer + ) + _ = signer + let after = try? await sdk?.documentGetLifecycle( + dataContractId: contractIdBase58, documentType: typeName, documentId: docIdBase58 + ) + await MainActor.run { + submissions += 1 + lifecycle = after + if let after { + progress = DocumentHistoryLifecycle.describeEraseProgress(before: before, after: after) + if after.state == .absent { + persistWarning = DocumentPersistence.applyDelete( + document: document, + modelContext: modelContext + ) + } + } else { + progress = "Lifecycle not read; use Platform Queries β†’ Get Document History to see what remains." + } + isSubmitting = false + } + } catch { + await MainActor.run { + actionError = .init(message: error.localizedDescription) + isSubmitting = false + } + } + } + } +} + // MARK: Transfer struct TransferDocumentView: View { diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift index 015e4bad5de..ff0aa774cd2 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/PlatformQueriesView.swift @@ -188,7 +188,8 @@ struct QueryCategoryDetailView: View { case .documents: return [ QueryDefinition(name: "getDocuments", label: "Get Documents", description: "Query documents from a data contract"), - QueryDefinition(name: "getDocument", label: "Get Document", description: "Fetch a specific document by ID") + QueryDefinition(name: "getDocument", label: "Get Document", description: "Fetch a specific document by ID"), + QueryDefinition(name: "getDocumentHistory", label: "Get Document History", description: "Read a keep-history document's revisions and lifecycle state") ] case .dpns: diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/QueryDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/QueryDetailView.swift index 4673aae9895..220d89040e1 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/QueryDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/QueryDetailView.swift @@ -373,6 +373,52 @@ struct QueryDetailView: View { let documentId = queryInputs["documentId"] ?? "" return try await sdk.documentGet(dataContractId: contractId, documentType: documentType, documentId: documentId) + case "getDocumentHistory": + let contractId = queryInputs["dataContractId"] ?? "" + let documentType = queryInputs["documentType"] ?? "" + let documentId = queryInputs["documentId"] ?? "" + // Every non-empty number must parse, and exactly one filter + // group may be given, so a typo or a half cursor is refused + // rather than silently read as the first page. + func number(_ name: String) throws -> UInt64? { + let raw = (queryInputs[name] ?? "").trimmingCharacters(in: .whitespaces) + if raw.isEmpty { return nil } + guard let value = UInt64(raw) else { + throw SDKError.invalidParameter("\(name) must be a non-negative integer") + } + return value + } + let limit = try number("limit").map { UInt32(clamping: $0) } + let startAtMs = try number("startAtMs") + let startAfterTimeMs = try number("startAfterTimeMs") + let startAfterRevision = try number("startAfterRevision") + let startAtRevision = try number("startAtRevision") + let revision = try number("revision") + if (startAfterTimeMs == nil) != (startAfterRevision == nil) { + throw SDKError.invalidParameter("Start After needs both its time and its revision") + } + let groups = [startAtMs != nil, startAfterTimeMs != nil, startAtRevision != nil, revision != nil] + if groups.filter({ $0 }).count > 1 { + throw SDKError.invalidParameter("Give only one of Start At, Start After, Start At Revision, or Revision") + } + let filter: DocumentHistoryFilter + if let revision { + filter = .revision(revision) + } else if let startAtRevision { + filter = .startAtRevision(startAtRevision) + } else if let timeMs = startAfterTimeMs, let rev = startAfterRevision { + filter = .startAfter(timeMs: timeMs, revision: rev) + } else { + filter = .startAtTime(ms: startAtMs ?? 0) + } + return try await sdk.documentGetHistory( + dataContractId: contractId, + documentType: documentType, + documentId: documentId, + filter: filter, + limit: limit + ) + // DPNS Queries case "getDpnsUsername": let identityId = queryInputs["identityId"] ?? "" @@ -921,6 +967,19 @@ struct QueryDetailView: View { QueryInput(name: "documentId", label: "Document ID", required: true) ] + case "getDocumentHistory": + return [ + QueryInput(name: "dataContractId", label: "Data Contract ID", required: true), + QueryInput(name: "documentType", label: "Document Type", required: true, placeholder: "A documentsKeepHistory type"), + QueryInput(name: "documentId", label: "Document ID", required: true), + QueryInput(name: "limit", label: "Limit (max 10)", required: false), + QueryInput(name: "startAtMs", label: "Start At (milliseconds)", required: false, placeholder: "First page: inclusive lower time bound"), + QueryInput(name: "startAfterTimeMs", label: "Start After Time (milliseconds)", required: false, placeholder: "Next page: last entry's time_ms"), + QueryInput(name: "startAfterRevision", label: "Start After Revision", required: false, placeholder: "Next page: last entry's revision"), + QueryInput(name: "startAtRevision", label: "Start At Revision", required: false, placeholder: "Revision range instead of time"), + QueryInput(name: "revision", label: "Revision", required: false, placeholder: "One revision (limit 1)") + ] + // DPNS Queries case "getDpnsUsername": return [ diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionCategoryView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionCategoryView.swift index 925c8bbba0f..4081d793140 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionCategoryView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionCategoryView.swift @@ -29,6 +29,7 @@ struct TransitionCategoryView: View { ("documentCreate", "Create Document", "Create a new document"), ("documentReplace", "Replace Document", "Replace an existing document"), ("documentDelete", "Delete Document", "Delete a document"), + ("documentErase", "Erase Document", "Erase a deleted keep-history document's revisions"), ("documentTransfer", "Transfer Document", "Transfer document ownership"), ("documentUpdatePrice", "Update Price", "Update document sale price"), ("documentPurchase", "Purchase Document", "Purchase a document") diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift index af716cacf88..6779a97b78d 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift @@ -578,6 +578,9 @@ struct TransitionDetailView: View { case "documentDelete": return try await executeDocumentDelete(sdk: sdk) + case "documentErase": + return try await executeDocumentErase(sdk: sdk) + case "documentTransfer": return try await executeDocumentTransfer(sdk: sdk) @@ -1223,6 +1226,88 @@ struct TransitionDetailView: View { return ["message": "Document deleted successfully"] } + private func executeDocumentErase(sdk: SDK) async throws -> Any { + guard !selectedIdentityId.isEmpty, + let signingIdentity = identities.first(where: { $0.identityIdBase58 == selectedIdentityId }) else { + throw SDKError.invalidParameter("No identity selected") + } + + guard let contractId = formInputs["contractId"], !contractId.isEmpty else { + throw SDKError.invalidParameter("Data contract is required") + } + + guard let documentType = formInputs["documentType"], !documentType.isEmpty else { + throw SDKError.invalidParameter("Document type is required") + } + + guard let documentId = formInputs["documentId"], !documentId.isEmpty else { + throw SDKError.invalidParameter("Document ID is required") + } + + // The selected identity signs and pays. It must own the document for + // the first erase; any identity may submit the ones after it. + let dppIdentity = DPPIdentity( + id: signingIdentity.identityId, + publicKeys: Dictionary(uniqueKeysWithValues: signingIdentity.identityPublicKeys.map { ($0.id, $0) }), + balance: UInt64(bitPattern: signingIdentity.balance), + revision: 0 + ) + + // External-signer pattern (see executeDataContractCreate for the + // architectural rationale). Rust calls back through the + // `KeychainSigner` trampoline when it needs a signature. + let signer = KeychainSigner(modelContainer: modelContext.container) + + // The erase result only observes that the document is absent from + // ordinary reads, which it already was; what the erase achieved is read + // from the lifecycle before and after. + let before = try? await sdk.documentGetLifecycle( + dataContractId: contractId, documentType: documentType, documentId: documentId + ) + + if let before, before.state == .active || before.state == .absent { + return [ + "message": "Erase not submitted", + "lifecycle": before.state.rawValue, + "remainingRevisions": before.remainingRevisions, + "progress": before.state == .absent + ? "No retained revisions exist." + : DocumentHistoryLifecycle.describeEraseProgress(before: before, after: before) + ] + } + + try await sdk.documentErase( + contractId: contractId, + documentType: documentType, + documentId: documentId, + ownerIdentity: dppIdentity, + signer: signer.handle + ) + _ = signer // keepalive across the await β€” see KeychainSigner lifetime contract + + // The erase is broadcast and confirmed by this point, so the closing + // lifecycle read fails on its own terms: an unreadable observation is + // reported as unread, never as a failed erase the user would pay to + // submit a second time. + let after = try? await sdk.documentGetLifecycle( + dataContractId: contractId, documentType: documentType, documentId: documentId + ) + + guard let after else { + return [ + "message": "Erase submitted; document absence observed under proof", + "progress": "Lifecycle not read; use Platform Queries β†’ Get Document History to see what remains." + ] + } + + return [ + "message": "Erase submitted; document absence observed under proof", + "lifecycle": after.state.rawValue, + "remainingRevisions": after.remainingRevisions, + "progress": DocumentHistoryLifecycle.describeEraseProgress(before: before, after: after) + ] + } + private func executeDocumentTransfer(sdk: SDK) async throws -> Any { guard !selectedIdentityId.isEmpty else { throw SDKError.invalidParameter("No identity selected") diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionInputView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionInputView.swift index 333f6b7ef39..da63a48d469 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionInputView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionInputView.swift @@ -257,6 +257,7 @@ struct TransitionInputView: View { let isCreateOperation = input.action?.contains("documentCreate") == true let isReplaceOperation = input.action?.contains("documentReplace") == true let isDeleteOperation = input.action?.contains("documentDelete") == true + let isEraseOperation = input.action?.contains("documentErase") == true let isMarketplaceOperation = isPurchaseOperation || isSetPriceOperation // Filter contracts based on operation type @@ -303,6 +304,15 @@ struct TransitionInputView: View { } return false } + } else if isEraseOperation { + // Only types whose schema sets `canBeErased` (off by default, + // read from the stored schema JSON) can be erased. + return dataContracts.filter { contract in + if let docTypes = contract.documentTypes { + return docTypes.contains { ($0.schema?["canBeErased"] as? Bool) == true } + } + return false + } } else { return dataContracts } @@ -319,6 +329,8 @@ struct TransitionInputView: View { return "No contracts with mutable documents" } else if isDeleteOperation { return "No contracts with deletable documents" + } else if isEraseOperation { + return "No contracts with erasable document types" } else { return "No contracts available" } @@ -389,6 +401,7 @@ struct TransitionInputView: View { let isCreateOperation = input.action?.contains("documentCreate") == true let isReplaceOperation = input.action?.contains("documentReplace") == true let isDeleteOperation = input.action?.contains("documentDelete") == true + let isEraseOperation = input.action?.contains("documentErase") == true let isMarketplaceOperation = isPurchaseOperation || isSetPriceOperation if contractId.isEmpty { @@ -417,6 +430,9 @@ struct TransitionInputView: View { } else if isDeleteOperation { // For document delete, only show deletable document types return docTypes.filter { $0.documentsCanBeDeleted } + } else if isEraseOperation { + // Only types whose schema sets `canBeErased` + return docTypes.filter { ($0.schema?["canBeErased"] as? Bool) == true } } else { return Array(docTypes) } @@ -433,6 +449,8 @@ struct TransitionInputView: View { return "No mutable document types in selected contract" } else if isDeleteOperation { return "No deletable document types in selected contract" + } else if isEraseOperation { + return "No erasable document types in selected contract" } else { return "No document types in selected contract" } diff --git a/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md b/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md index 1ec7625543c..466ef778879 100644 --- a/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md +++ b/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md @@ -225,6 +225,7 @@ The app is a full multi-wallet client: `PlatformWalletManager` holds N wallets c | DOC-13 | Aggregation β€” sum of a numeric property | Platform | Uncommon | πŸ§ͺ | aggregation, read-only | **Sum / Average Documents** read view (op selector β†’ **Sum**) β†’ Swift wrapper over FFI `dash_sdk_document_sum` (proof-verified). Total sum is `sums[""]` in the `{sums:{hexKey:i64}}` result; a `where`/`group_by` filter and the required numeric `sum property` are entered in the same view. Needs a contract doc type with a `summable` index on the numeric property. | | DOC-14 | Aggregation β€” average of a numeric property | Platform | Uncommon | πŸ§ͺ | aggregation, read-only | Same **Sum / Average Documents** read view (op selector β†’ **Average**) β†’ Swift wrapper over FFI `dash_sdk_document_average` (proof-verified) β†’ `{averages:{hexKey:{count,sum}}}`; the view divides `sum/count` for display. Needs a doc type with a `summable` index on the numeric property. | | DOC-15 | Document transfer / purchase across wallets | Platform | Uncommon | βœ… | multiwallet | A creates + lists a document (`DOC-02`/`DOC-06`); B transfers/purchases it (`DOC-05`/`DOC-07`). Ownership and credits move between A and B. Transfer half driven end-to-end this session via the production UI: the `card` doc `FgVSYG6sTZZ9…` moved from identity `BjJz3hdmg5Ec…` to a different seed-controlled identity `8267geu4…` (QA2), with ownership re-persisted. Purchase half shares `DOC-07`'s status (a fresh buy needs a counterparty-owned for-sale listing). | +| DOC-16 | Erase a deleted keep-history document's revisions | Platform | Thorough | πŸ§ͺ | | Primary route: **Settings β†’ Platform State Transitions β†’ Document Erase** (`TransitionDetailView` β†’ `dash_sdk_document_erase_and_wait`), which takes the deleted document's id as text: an in-app delete (`DOC-04`) removes the local row, so the Browse Documents route below cannot start after it. Secondary route: **Browse Documents** β†’ document β†’ **β‹―** β†’ **Erase History…** (shown when the type's schema sets `canBeErased`) β†’ `EraseDocumentView` β†’ `platform_wallet_document_erase` (`IdentityWallet::erase_document_with_signer`), for a row whose document was deleted elsewhere; the sheet stays open for further chunks and removes the row only once the lifecycle reports ABSENT. Both routes read the lifecycle before and after each broadcast (`SDK.documentGetLifecycle` over `dash_sdk_document_fetch_history`) and show that, because the erase result itself only proves the document absent from ordinary reads, which it already was: a still-DELETED lifecycle with the same retained count is reported as "Not established", ERASING with the remaining count as progress, ABSENT as complete. Needs a type with `canBeErased: true` and a document already deleted; the first erase must be signed by the owner, later ones by any identity, each removing up to 100 revisions. Not driven on a device; no such type exists on testnet yet. | ### 4.8 Tokens β€” `Domain=Token` diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift new file mode 100644 index 00000000000..f43f620690c --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift @@ -0,0 +1,111 @@ +import XCTest +@testable import SwiftDashSDK + +/// The lifecycle block is the only authenticated account of what an erase +/// removed, so a malformed number must be rejected rather than truncated into +/// a count or a timestamp the user then acts on. +final class DocumentHistoryLifecycleTests: XCTestCase { + + /// Parses through `JSONSerialization` the way the query path does: that + /// is what bridges JSON booleans and fractional numbers to `NSNumber`, + /// which a plain dictionary literal would not reproduce. + private func lifecycle(fromJSON json: String) throws -> DocumentHistoryLifecycle? { + let object = try JSONSerialization.jsonObject(with: Data(json.utf8)) + let dictionary = try XCTUnwrap(object as? [String: Any]) + return DocumentHistoryLifecycle(json: dictionary) + } + + private func json(remainingRevisions: String) -> String { + """ + { + "state": "ERASING", + "remaining_revisions": \(remainingRevisions), + "deleted_at_ms": 1700000000000, + "erasing_started_at_ms": 1700000001000, + "erasing_from_time_ms": 1699999999000, + "erasing_from_revision": 7 + } + """ + } + + func testParsesAWellFormedLifecycleBlock() throws { + let parsed = try XCTUnwrap(lifecycle(fromJSON: json(remainingRevisions: "42"))) + XCTAssertEqual(parsed.state, .erasing) + XCTAssertEqual(parsed.remainingRevisions, 42) + XCTAssertEqual(parsed.deletedAtMs, 1_700_000_000_000) + XCTAssertEqual(parsed.erasingStartedAtMs, 1_700_000_001_000) + XCTAssertEqual(parsed.erasingFromTimeMs, 1_699_999_999_000) + XCTAssertEqual(parsed.erasingFromRevision, 7) + } + + /// `true` bridges to an `NSNumber` whose `uint64Value` is 1, which would + /// otherwise be read as one retained revision. + func testRejectsABooleanInPlaceOfACount() throws { + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "true"))) + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "false"))) + } + + /// A fractional value would be truncated, reporting fewer revisions than + /// the number actually claims. + func testRejectsAFractionalCount() throws { + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "1.5"))) + } + + func testRejectsANegativeCount() throws { + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "-1"))) + } + + func testPreservesTheFullUInt64RangeFromRustJSON() throws { + for value in ["9007199254740993", "9223372036854775808", "18446744073709551615"] { + let parsed = try XCTUnwrap(lifecycle(fromJSON: json(remainingRevisions: value))) + XCTAssertEqual(parsed.remainingRevisions, UInt64(value)) + } + } + + func testRejectsANumberOutsideUInt64() throws { + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "1e40"))) + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "18446744073709551616"))) + } + + func testRejectsANumberSentAsAString() throws { + XCTAssertNil(try lifecycle(fromJSON: json(remainingRevisions: "\"42\""))) + } + + /// A partial block is rejected outright, so a missing field is never read + /// as a zero timestamp or a zero count. + func testRejectsAPartialBlock() throws { + XCTAssertNil(try lifecycle(fromJSON: #"{"state": "DELETED", "remaining_revisions": 3}"#)) + } + + func testRejectsAnUnknownState() throws { + let unknown = json(remainingRevisions: "1") + .replacingOccurrences(of: "\"ERASING\"", with: "\"PURGED\"") + XCTAssertNil(try lifecycle(fromJSON: unknown)) + } + + func testUnchangedDeletedHistoryDoesNotClaimEraseCompletion() throws { + let deletedJSON = json(remainingRevisions: "5") + .replacingOccurrences(of: "\"ERASING\"", with: "\"DELETED\"") + let before = try XCTUnwrap(lifecycle(fromJSON: deletedJSON)) + let after = try XCTUnwrap(lifecycle(fromJSON: deletedJSON)) + let text = DocumentHistoryLifecycle.describeEraseProgress(before: before, after: after) + XCTAssertTrue(text.hasPrefix("Not established")) + XCTAssertFalse(text.localizedCaseInsensitiveContains("complete")) + XCTAssertFalse(text.localizedCaseInsensitiveContains("accepted")) + } + + func testErasingHistoryShowsTheRemainingRevisions() throws { + let after = try XCTUnwrap(lifecycle(fromJSON: json(remainingRevisions: "50"))) + let text = DocumentHistoryLifecycle.describeEraseProgress(before: nil, after: after) + XCTAssertTrue(text.hasPrefix("Erasure in progress: 50")) + XCTAssertFalse(text.localizedCaseInsensitiveContains("complete")) + } + + func testAbsentHistoryConfirmsEraseCompletion() throws { + let absentJSON = json(remainingRevisions: "0") + .replacingOccurrences(of: "\"ERASING\"", with: "\"ABSENT\"") + let after = try XCTUnwrap(lifecycle(fromJSON: absentJSON)) + let text = DocumentHistoryLifecycle.describeEraseProgress(before: nil, after: after) + XCTAssertTrue(text.hasPrefix("Erasure complete")) + } +} diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift index 2ae4aa4681f..aaabc040fc6 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift @@ -155,4 +155,20 @@ final class PlatformQueryOffMainTests: XCTestCase { XCTFail("expected SDKError.invalidParameter, got \(error)") } } + + @MainActor + func testDocumentHistoryPreservesNativeErrors() async throws { + let sdk = try SDK(mockVectorsDirectory: nil) + do { + _ = try await sdk.documentGetHistory( + dataContractId: "not-base58-0OIl", + documentType: "note", + documentId: "not-base58-0OIl") + XCTFail("documentGetHistory should refuse a malformed id") + } catch SDKError.invalidParameter(let message) { + XCTAssertTrue(message.contains("Invalid contract ID")) + } catch { + XCTFail("expected the native SDKError.invalidParameter, got \(error)") + } + } } diff --git a/packages/swift-sdk/scripts/test_document_erase_preflight.py b/packages/swift-sdk/scripts/test_document_erase_preflight.py new file mode 100644 index 00000000000..4968ddb3c23 --- /dev/null +++ b/packages/swift-sdk/scripts/test_document_erase_preflight.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Run the Settings erase route against an offline SDK, without an iOS build.""" + +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +VIEW = (Path(__file__).resolve().parents[1] / "SwiftExampleApp" / + "SwiftExampleApp/Views/TransitionDetailView.swift") + + +@unittest.skipUnless(shutil.which("swiftc"), "Swift compiler unavailable") +class DocumentErasePreflightTests(unittest.TestCase): + def test_should_skip_active_and_absent_without_claiming_an_erase_completed(self): + source = VIEW.read_text() + start = source.index(" private func executeDocumentErase(") + end = source.index("\n private func executeDocumentTransfer(", start) + # Compile the actual route, including its reads and broadcast call. + # The stubs isolate presentation behavior from SwiftUI and the FFI. + harness = r''' +import Foundation + +enum SDKError: Error { case invalidParameter(String) } +enum LifecycleState: String, CaseIterable { case active, deleted, erasing, absent } +struct DocumentHistoryLifecycle { + let state: LifecycleState + let remainingRevisions: UInt64 + static func describeEraseProgress( + before: Self?, after: Self + ) -> String { + after.state == .absent ? "Erasure complete: no retained revisions remain." : "Retained revisions remain." + } +} +struct PublicKey { let id: UInt32 = 0 } +struct Identity { + let identityIdBase58 = "signer" + let identityId = "signer" + let identityPublicKeys = [PublicKey()] + let balance: Int64 = 100 +} +struct DPPIdentity { + let id: String + let publicKeys: [UInt32: PublicKey] + let balance: UInt64 + let revision: UInt32 +} +struct ModelContext { let container = 0 } +struct KeychainSigner { + init(modelContainer: Int) {} + let handle = 0 +} +@MainActor final class SDK { + let initialState: LifecycleState? + var reads = 0 + var broadcasts = 0 + init(_ state: LifecycleState?) { initialState = state } + func documentGetLifecycle( + dataContractId: String, documentType: String, documentId: String + ) async throws -> DocumentHistoryLifecycle { + reads += 1 + if reads == 1 { + guard let initialState else { throw SDKError.invalidParameter("Read unavailable") } + return DocumentHistoryLifecycle(state: initialState, remainingRevisions: 0) + } + return DocumentHistoryLifecycle(state: .absent, remainingRevisions: 0) + } + func documentErase( + contractId: String, documentType: String, documentId: String, + ownerIdentity: DPPIdentity, signer: Int + ) async throws { + broadcasts += 1 + } +} +@MainActor struct SettingsRoute { + let selectedIdentityId = "signer" + let identities = [Identity()] + let formInputs = ["contractId": "contract", "documentType": "note", "documentId": "doc"] + let modelContext = ModelContext() + func run(_ sdk: SDK) async throws -> [String: Any] { + try await executeDocumentErase(sdk: sdk) as! [String: Any] + } +''' + source[start:end] + r''' +} +@main struct Main { + @MainActor static func main() async throws { + var failures: [String] = [] + func require(_ condition: Bool, _ message: String) { + if !condition { failures.append(message) } + } + let states: [LifecycleState?] = [.active, .absent, .deleted, .erasing, nil] + for state in states { + let sdk = SDK(state) + let result = try await SettingsRoute().run(sdk) + let label = state?.rawValue ?? "unreadable" + if state == .active || state == .absent { + require(sdk.broadcasts == 0, "\(label): must not broadcast a paid erase") + require(sdk.reads == 1, "\(label): no closing read without a broadcast") + require(result["message"] as? String == "Erase not submitted", "\(label): explain the skip") + require(result["lifecycle"] as? String == label, "\(label): show the observed lifecycle") + require(result["remainingRevisions"] as? UInt64 == 0, "\(label): show retained revisions") + let progress = result["progress"] as? String ?? "" + require(!progress.isEmpty, "\(label): show progress") + if state == .absent { + require(progress.contains("No retained revisions exist"), "absent: describe the observation") + require(!progress.contains("Erasure complete"), "absent: an observation does not prove an erase completed") + } + } else { + require(sdk.broadcasts == 1, "\(label): continue the requested erase") + require(sdk.reads == 2, "\(label): describe the result after broadcast") + require(result["message"] as? String == "Erase submitted; document absence observed under proof", + "\(label): preserve submission status") + } + } + if !failures.isEmpty { + failures.forEach { print($0) } + exit(1) + } + print("Five erase preflight controls passed") + } +} +''' + with tempfile.TemporaryDirectory() as directory: + source_path = Path(directory) / "ErasePreflight.swift" + binary = Path(directory) / "erase-preflight" + source_path.write_text(harness) + compiled = subprocess.run( + ["swiftc", "-parse-as-library", str(source_path), "-o", str(binary)], + capture_output=True, text=True, check=False, + ) + self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr) + result = subprocess.run([str(binary)], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/wasm-dpp2/src/state_transitions/batch/document_transition.rs b/packages/wasm-dpp2/src/state_transitions/batch/document_transition.rs index 793390099c5..7dc8e1da111 100644 --- a/packages/wasm-dpp2/src/state_transitions/batch/document_transition.rs +++ b/packages/wasm-dpp2/src/state_transitions/batch/document_transition.rs @@ -1,5 +1,6 @@ use crate::state_transitions::batch::document_transitions::create::DocumentCreateTransitionWasm; use crate::state_transitions::batch::document_transitions::delete::DocumentDeleteTransitionWasm; +use crate::state_transitions::batch::document_transitions::erase::DocumentEraseTransitionWasm; use crate::state_transitions::batch::document_transitions::purchase::DocumentPurchaseTransitionWasm; use crate::state_transitions::batch::document_transitions::replace::DocumentReplaceTransitionWasm; use crate::state_transitions::batch::document_transitions::transfer::DocumentTransferTransitionWasm; @@ -120,6 +121,16 @@ impl DocumentTransitionWasm { } } + #[wasm_bindgen(getter = "eraseTransition")] + pub fn erase_transition(&self) -> WasmDppResult { + match self.0.clone() { + DocumentTransition::Erase(erase) => Ok(DocumentEraseTransitionWasm::from(erase)), + _ => Err(WasmDppError::invalid_argument( + "Document transition is not an erase transition", + )), + } + } + #[wasm_bindgen(getter = "purchaseTransition")] pub fn purchase_transition(&self) -> WasmDppResult { match self.0.clone() { diff --git a/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/erase.rs b/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/erase.rs new file mode 100644 index 00000000000..cd8f6f9ecab --- /dev/null +++ b/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/erase.rs @@ -0,0 +1,90 @@ +use crate::data_contract::document::DocumentWasm; +use crate::error::WasmDppResult; +use crate::impl_wasm_type_info; +use crate::state_transitions::batch::document_base_transition::DocumentBaseTransitionWasm; +use crate::state_transitions::batch::document_transition::DocumentTransitionWasm; +use crate::state_transitions::batch::generators::generate_erase_transition; +use crate::utils::{try_from_options, try_from_options_with, try_to_u64}; +use dpp::prelude::IdentityNonce; +use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; +use dpp::state_transition::batch_transition::document_base_transition::document_base_transition_trait::DocumentBaseTransitionAccessors; +use dpp::state_transition::batch_transition::DocumentEraseTransition; +use wasm_bindgen::prelude::wasm_bindgen; + +#[wasm_bindgen(typescript_custom_section)] +const DOCUMENT_ERASE_OPTIONS_TS: &str = r#" +export interface DocumentEraseTransitionOptions { + document: Document; + identityContractNonce: bigint; +} +"#; + +#[wasm_bindgen] +extern "C" { + #[wasm_bindgen(typescript_type = "DocumentEraseTransitionOptions")] + pub type DocumentEraseTransitionOptionsJs; +} + +#[wasm_bindgen(js_name = "DocumentEraseTransition")] +pub struct DocumentEraseTransitionWasm(DocumentEraseTransition); + +impl From for DocumentEraseTransitionWasm { + fn from(document_erase_transition: DocumentEraseTransition) -> Self { + DocumentEraseTransitionWasm(document_erase_transition) + } +} + +#[wasm_bindgen(js_class = DocumentEraseTransition)] +impl DocumentEraseTransitionWasm { + #[wasm_bindgen(constructor)] + pub fn constructor( + options: DocumentEraseTransitionOptionsJs, + ) -> WasmDppResult { + let document: DocumentWasm = try_from_options(&options, "document")?; + + let identity_contract_nonce: IdentityNonce = + try_from_options_with(&options, "identityContractNonce", |v| { + try_to_u64(v, "identityContractNonce") + })?; + + let rs_erase_transition = generate_erase_transition( + &document, + identity_contract_nonce, + document.document_type_name().to_string(), + ); + + Ok(DocumentEraseTransitionWasm(rs_erase_transition)) + } + + #[wasm_bindgen(getter = "base")] + pub fn base(&self) -> DocumentBaseTransitionWasm { + self.0.base().clone().into() + } + + #[wasm_bindgen(setter = "base")] + pub fn set_base(&mut self, base: &DocumentBaseTransitionWasm) { + self.0.set_base(base.clone().into()) + } + + #[wasm_bindgen(js_name = "toDocumentTransition")] + pub fn to_document_transition(&self) -> DocumentTransitionWasm { + let rs_transition = DocumentTransition::from(self.0.clone()); + + DocumentTransitionWasm::from(rs_transition) + } + + #[wasm_bindgen(js_name = "fromDocumentTransition")] + pub fn from_document_transition( + transition: &DocumentTransitionWasm, + ) -> WasmDppResult { + transition.erase_transition() + } +} + +impl From for DocumentEraseTransition { + fn from(document_erase_transition: DocumentEraseTransitionWasm) -> Self { + document_erase_transition.0 + } +} + +impl_wasm_type_info!(DocumentEraseTransitionWasm, DocumentEraseTransition); diff --git a/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/mod.rs b/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/mod.rs index f6ac52b077e..21609e70078 100644 --- a/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/mod.rs +++ b/packages/wasm-dpp2/src/state_transitions/batch/document_transitions/mod.rs @@ -1,5 +1,6 @@ pub mod create; pub mod delete; +pub mod erase; pub mod purchase; pub mod replace; pub mod transfer; diff --git a/packages/wasm-dpp2/src/state_transitions/batch/generators.rs b/packages/wasm-dpp2/src/state_transitions/batch/generators.rs index 1ccc4657459..46d15e5c371 100644 --- a/packages/wasm-dpp2/src/state_transitions/batch/generators.rs +++ b/packages/wasm-dpp2/src/state_transitions/batch/generators.rs @@ -17,9 +17,11 @@ use dpp::state_transition::batch_transition::document_base_transition::v1::Docum use dpp::state_transition::batch_transition::document_base_transition::v2::DocumentBaseTransitionV2; use dpp::state_transition::batch_transition::document_create_transition::DocumentCreateTransitionV0; use dpp::state_transition::batch_transition::document_delete_transition::DocumentDeleteTransitionV0; +use dpp::state_transition::batch_transition::document_erase_transition::DocumentEraseTransitionV0; use dpp::state_transition::batch_transition::document_replace_transition::DocumentReplaceTransitionV0; use dpp::state_transition::batch_transition::{ - DocumentCreateTransition, DocumentDeleteTransition, DocumentReplaceTransition, + DocumentCreateTransition, DocumentDeleteTransition, DocumentEraseTransition, + DocumentReplaceTransition, }; use dpp::tokens::token_payment_info::TokenPaymentInfo; @@ -96,6 +98,23 @@ pub fn generate_delete_transition( }) } +pub fn generate_erase_transition( + document: &DocumentWasm, + identity_contract_nonce: IdentityNonce, + document_type_name: String, +) -> DocumentEraseTransition { + DocumentEraseTransition::V0(DocumentEraseTransitionV0 { + base: document_base_transition( + document.document.id(), + identity_contract_nonce, + document_type_name, + document.data_contract_id.into(), + None, + None, + ), + }) +} + pub fn generate_replace_transition( document: &DocumentWasm, identity_contract_nonce: IdentityNonce, diff --git a/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts b/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts index 7e8ea72875f..c02d50d7257 100644 --- a/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts +++ b/packages/wasm-dpp2/tests/unit/DocumentsTransitions.spec.ts @@ -1,5 +1,6 @@ import { expect } from './helpers/chai.ts'; import { initWasm, wasm } from '../../dist/dpp.compressed.js'; +import type { DocumentEraseTransitionOptions } from '../../dist/dpp.compressed.js'; import { document, documentTypeName, revision, dataContractId, ownerId, id, } from './mocks/Document/index.js'; @@ -69,7 +70,7 @@ describe('DocumentsTransitions', () => { it('should have no action fee agreement when none is given', () => { const base = createBase(); - expect(base.actionFeeAgreement).to.be.undefined(); + expect(base.actionFeeAgreement).to.equal(undefined); }); it('should set the action fee agreement', () => { @@ -85,7 +86,7 @@ describe('DocumentsTransitions', () => { base.actionFeeAgreement = undefined; - expect(base.actionFeeAgreement).to.be.undefined(); + expect(base.actionFeeAgreement).to.equal(undefined); }); }); @@ -276,7 +277,7 @@ describe('DocumentsTransitions', () => { identityContractNonce: BigInt(1), }); - expect(createTransition.base.actionFeeAgreement).to.be.undefined(); + expect(createTransition.base.actionFeeAgreement).to.equal(undefined); }); }); @@ -588,6 +589,109 @@ describe('DocumentsTransitions', () => { }); }); + describe('DocumentEraseTransition', () => { + describe('constructor', () => { + it('should never forward token payment when erasing document history', () => { + const options: DocumentEraseTransitionOptions = { + document: createDocument(), + identityContractNonce: BigInt(1), + // @ts-expect-error Erasing history cannot pay with tokens. + tokenPaymentInfo: new wasm.TokenPaymentInfo({ tokenContractPosition: 0 }), + }; + const eraseTransition = new wasm.DocumentEraseTransition(options); + + expect(eraseTransition.base.tokenPaymentInfo).to.equal(undefined); + }); + + it('should create instance from document', () => { + const documentInstance = createDocument(); + const eraseTransition = new wasm.DocumentEraseTransition({ + document: documentInstance, + identityContractNonce: BigInt(1), + }); + + expect(documentInstance).to.be.an.instanceof(wasm.Document); + expect(eraseTransition).to.be.an.instanceof(wasm.DocumentEraseTransition); + }); + }); + + describe('toDocumentTransition()', () => { + it('should create DocumentTransition from EraseTransition', () => { + const documentInstance = createDocument(); + const eraseTransition = new wasm.DocumentEraseTransition({ + document: documentInstance, + identityContractNonce: BigInt(1), + }); + + const documentTransition = eraseTransition.toDocumentTransition(); + + expect(documentTransition).to.be.an.instanceof(wasm.DocumentTransition); + }); + }); + + describe('base', () => { + it('should return base', () => { + const documentInstance = createDocument(); + const eraseTransition = new wasm.DocumentEraseTransition({ + document: documentInstance, + identityContractNonce: BigInt(1), + }); + + expect(eraseTransition.base.constructor.name).to.equal('DocumentBaseTransition'); + }); + + it('should set base', () => { + const documentInstance = createDocument(); + const eraseTransition = new wasm.DocumentEraseTransition({ + document: documentInstance, + identityContractNonce: BigInt(1), + }); + + const newBase = new wasm.DocumentBaseTransition({ + documentId: documentInstance.id, + identityContractNonce: BigInt(12350), + documentTypeName: 'bbbbb', + dataContractId, + }); + + eraseTransition.base = newBase; + + expect(eraseTransition.base.identityContractNonce).to.equal(newBase.identityContractNonce); + expect(newBase).to.be.an.instanceof(wasm.DocumentBaseTransition); + }); + }); + + describe('BatchTransition serialization roundtrip', () => { + it('should serialize and deserialize through state transition', () => { + const documentInstance = createDocument(); + const eraseTransition = new wasm.DocumentEraseTransition({ + document: documentInstance, + identityContractNonce: BigInt(1), + }); + + const documentTransition = eraseTransition.toDocumentTransition(); + + const batchTransition = wasm.BatchTransition.fromBatchedTransitions( + [new wasm.BatchedTransition(documentTransition), new wasm.BatchedTransition(documentTransition)], + documentInstance.ownerId, + 1, + ); + + const st = batchTransition.toStateTransition(); + + const deserializedBatch = wasm.BatchTransition.fromStateTransition(st); + + const deserializedTransitions = deserializedBatch.transitions; + + expect(deserializedTransitions.length).to.equal(2); + + const deserializedEraseTransition = deserializedTransitions[0].toTransition().eraseTransition; + + expect(deserializedEraseTransition).to.be.an.instanceof(wasm.DocumentEraseTransition); + }); + }); + }); + describe('DocumentReplaceTransition', () => { describe('constructor', () => { it('should create instance from document', () => {