diff --git a/Cargo.lock b/Cargo.lock index 533e6c7cc37..6d8097914d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6700,6 +6700,7 @@ dependencies = [ "log", "platform-wallet-ffi", "rs-sdk-ffi", + "serde_json", "zeroize", ] diff --git a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md index 9f3a6548066..0a276aa692c 100644 --- a/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md +++ b/packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md @@ -211,7 +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. | +| DOC-16 | Erase a deleted keep-history document's revisions | Platform | Thorough | πŸ§ͺ | | Route: **Browse Documents** β†’ document β†’ **Actions…** β†’ **Erase Document…** (or the **Erase Document** catalog entry). The erase form calls the Rust wallet read/decide/select/submit/observe operation through `platform_wallet_document_erase_and_observe`. Rust loads the real contract, rejects ineligible types, skips ACTIVE/ABSENT, and submits nothing when the preflight/ownership read is unavailable. DELETED requires the newest retained revision's owner; ERASING accepts any submitting identity. Keys are selected in Rust using the actual requirement, contract bounds, expiry and supplied signer. A closing-read failure remains a submitted result with unavailable progress; outcome-unknown errors require reading history before any manual retry. Each call submits at most one chunk and never retries automatically. Display skipped/submitted reasons, remaining revisions and cautious progress wording. Needs an erasable keep-history type; not driven on a device or a live provider. | ### 4.8 Tokens β€” `Domain=Token` 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 fdccdbda59f..3d78aea35cf 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,14 +35,14 @@ 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.documents.DocumentEraseOutcome +import org.dashfoundation.dashsdk.documents.DocumentEraseNotSubmittedReason +import org.dashfoundation.dashsdk.errors.DashSdkError 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 @@ -63,7 +63,7 @@ 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, plus the * erase (`ManagedPlatformWallet.replaceDocument` / `deleteDocument` / - * `eraseDocument` / `transferDocument`). Reached from a document row's + * `eraseDocumentAndObserve` / `transferDocument`). Reached from a document row's * "Actions…" button and from the document replace/delete/erase/transfer * transition-catalog entries. * @@ -501,10 +501,9 @@ fun DocumentActionsScreen( } // ── 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. + // The probe above is for presentation. Rust checks the newest + // retained owner before starting erasure of a deleted document; + // any submitting identity may continue an erasing document. FormSection(title = "Erase") { Text( "Remove the retained revisions of a document that has already " + @@ -676,23 +675,25 @@ fun DocumentActionsScreen( 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, + val mgr = container.walletManagerStore.activeManager.value + ?: throw IllegalStateException("Wallet manager not active") + val wallet = signer.walletId?.toHex()?.let { mgr.wallets.value[it] } + ?: throw IllegalStateException("Identity has no loaded wallet linkage; cannot erase document history") + val outcome = try { + mgr.documentTransactions.eraseAndObserve( + walletHandle = wallet.handle, + submittingIdentityId = signer.identityId, contractId = contractIdBytes, documentType = typeName, documentId = docIdBytes, - signingKeyId = signingKeyId, signerHandle = mgr.signerHandle, ) + } catch (e: DashSdkError.PlatformWallet.TransactionBroadcastUnconfirmed) { + throw IllegalStateException( + "Erase outcome unknown; do not resubmit automatically; read history first.", e, + ) } + eraseSuccess = describeEraseOutcome(outcome) } }, modifier = Modifier.testTag("eraseDocument.confirm"), @@ -707,51 +708,19 @@ fun DocumentActionsScreen( 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" +/** Display the Rust outcome without making another submission decision. */ +internal fun describeEraseOutcome(outcome: DocumentEraseOutcome): String = when (outcome) { + is DocumentEraseOutcome.NotSubmitted -> "Erase not submitted. " + when (outcome.reason) { + DocumentEraseNotSubmittedReason.ACTIVE -> "The document is active." + DocumentEraseNotSubmittedReason.ABSENT -> "No retained revisions exist." + DocumentEraseNotSubmittedReason.NOT_NEWEST_OWNER -> + "The newest retained revision belongs to ${outcome.owner}. Select that identity." + DocumentEraseNotSubmittedReason.PREFLIGHT_UNAVAILABLE -> + "Lifecycle or ownership could not be read; read history before retrying." } - 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." - } + is DocumentEraseOutcome.Submitted -> "Erase submitted; document absence observed. " + + (outcome.after?.let { describeEraseProgress(outcome.before, it) } + ?: "Lifecycle not read; query the document history to see what remains.") } /** The owner + current field values [DocumentActionsScreen]'s probe reads. */ 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 index 6ecaeaf8604..a172e5fc238 100644 --- 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 @@ -1,145 +1,52 @@ package org.dashfoundation.example.ui.contracts -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.runTest +import org.dashfoundation.dashsdk.documents.DocumentEraseOutcome +import org.dashfoundation.dashsdk.documents.DocumentEraseNotSubmittedReason 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) +/** Presentation tests consume Rust decisions; they never simulate submission policy. */ 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")) - } - } + fun unavailablePreflightDoesNotClaimSubmission() { + val message = describeEraseOutcome(DocumentEraseOutcome.NotSubmitted( + DocumentEraseNotSubmittedReason.PREFLIGHT_UNAVAILABLE, null, null, + )) + assertTrue(message, message.startsWith("Erase not submitted")) + assertTrue(message, message.contains("read history before retrying")) } @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) + fun closingReadFailureDoesNotReportSubmissionFailure() { + val message = describeEraseOutcome(DocumentEraseOutcome.Submitted(null, null)) 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) + fun absentSkipIsNotReportedAsCompletedErasure() { + val message = describeEraseOutcome(DocumentEraseOutcome.NotSubmitted( + DocumentEraseNotSubmittedReason.ABSENT, null, null, + )) + assertTrue(message, message.contains("No retained revisions exist")) + assertFalse(message, message.contains("Erasure complete")) } @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) + fun ownerRefusalNamesTheIdentityRustReported() { + val message = describeEraseOutcome(DocumentEraseOutcome.NotSubmitted( + DocumentEraseNotSubmittedReason.NOT_NEWEST_OWNER, "owner", null, + )) + assertTrue(message, message.contains("belongs to owner")) } @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")) + fun submittedProgressUsesTheClosingObservation() { + val after = DocumentLifecycle(DocumentLifecycleState.ERASING, 50uL, 1uL, 2uL, 3uL, 4uL) + val message = describeEraseOutcome(DocumentEraseOutcome.Submitted(null, after)) + assertTrue(message, message.contains("Erasure in progress: 50")) } } diff --git a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt index 419de77c636..4895db7b6bd 100644 --- a/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt +++ b/packages/kotlin-sdk/sdk/src/androidTest/kotlin/org/dashfoundation/dashsdk/FfiSmokeTest.kt @@ -8,6 +8,7 @@ import org.dashfoundation.dashsdk.ffi.DashpayNative import org.dashfoundation.dashsdk.ffi.NativePersistenceBridge import org.dashfoundation.dashsdk.ffi.NativeLoader import org.dashfoundation.dashsdk.ffi.SdkNative +import org.dashfoundation.dashsdk.ffi.TransactionsNative import org.dashfoundation.dashsdk.ffi.SignerNative import org.dashfoundation.dashsdk.ffi.WalletManagerNative import org.dashfoundation.dashsdk.persistence.DashDatabase @@ -31,6 +32,17 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class FfiSmokeTest { + @Test + fun documentEraseAndObserveBindsAndRejectsInvalidInput() { + NativeLoader.ensureLoaded() + val error = assertThrows(DashSDKException::class.java) { + TransactionsNative.documentEraseAndObserve( + 0L, ByteArray(32), ByteArray(32), "note", ByteArray(32), 0L, + ) + } + assertEquals(1003, error.code) + } + @Test fun nativeLibraryLoadsAndReportsVersion() { NativeLoader.ensureLoaded() diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentEraseOutcome.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentEraseOutcome.kt new file mode 100644 index 00000000000..332e9a02793 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/documents/DocumentEraseOutcome.kt @@ -0,0 +1,64 @@ +package org.dashfoundation.dashsdk.documents + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.dashfoundation.dashsdk.queries.DocumentLifecycle + +/** A Rust decision about whether to submit the requested erase. */ +enum class DocumentEraseNotSubmittedReason { ACTIVE, ABSENT, NOT_NEWEST_OWNER, PREFLIGHT_UNAVAILABLE } + +/** The paid operation and its observations are separate facts. */ +sealed class DocumentEraseOutcome { + data class NotSubmitted( + val reason: DocumentEraseNotSubmittedReason, + val owner: String?, + val before: DocumentLifecycle?, + ) : DocumentEraseOutcome() + + data class Submitted( + val before: DocumentLifecycle?, + val after: DocumentLifecycle?, + ) : DocumentEraseOutcome() + + companion object { + internal fun fromJson(json: String): DocumentEraseOutcome = try { + val root = Json.parseToJsonElement(json).jsonObject + fun observation(key: String): DocumentLifecycle? { + val value = requireNotNull(root[key]) + if (value == JsonNull) return null + val obj = value as? JsonObject ?: error("invalid observation") + return requireNotNull(DocumentLifecycle.fromLifecycleObject(obj)) + } + val before = observation("before") + val after = observation("after") + val reasonValue = root.getValue("reason") + val reason = if (reasonValue == JsonNull) null else + DocumentEraseNotSubmittedReason.valueOf( + requireNotNull(reasonValue.jsonPrimitive.takeIf { it.isString }).content, + ) + val ownerValue = root.getValue("owner") + val owner = if (ownerValue == JsonNull) null else + requireNotNull(ownerValue.jsonPrimitive.takeIf { it.isString }).content + when (root.getValue("kind").jsonPrimitive.takeIf { it.isString }?.content) { + "NOT_SUBMITTED" -> { + requireNotNull(reason) + if (reason == DocumentEraseNotSubmittedReason.NOT_NEWEST_OWNER) { + requireNotNull(owner) + } + NotSubmitted(reason, owner, before) + } + "SUBMITTED" -> Submitted(before, after) + else -> error("unknown outcome") + } + } catch (e: Exception) { + throw DocumentEraseResultUnreadableException(e) + } + } +} + +/** An OK native result could not be decoded; it is unsafe to infer submission failure. */ +class DocumentEraseResultUnreadableException(cause: Throwable? = null) : + IllegalStateException("Erase result unreadable; read history before retrying.", cause) 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 16223d93864..d32623766c4 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,49 +222,24 @@ 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( + /** Rust owns eligibility, key selection, submission and lifecycle observations. */ + suspend fun eraseAndObserve( walletHandle: Long, - ownerId: ByteArray, + submittingIdentityId: ByteArray, contractId: ByteArray, documentType: String, documentId: ByteArray, - signingKeyId: Int, signerHandle: Long, - ): ByteArray = gate.op { - require(ownerId.size == 32) { "ownerId must be 32 bytes" } + ): DocumentEraseOutcome = gate.op { + require(submittingIdentityId.size == 32) { "submittingIdentityId 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, + val json = mapNativeErrors { + TransactionsNative.documentEraseAndObserve( + walletHandle, submittingIdentityId, contractId, documentType, documentId, signerHandle, ) } + DocumentEraseOutcome.fromJson(json) } /** 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 5f8e979746c..564442c8341 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,25 +181,15 @@ 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( + /** Bridges the Rust wallet's single read/decide/submit/observe operation. */ + external fun documentEraseAndObserve( walletHandle: Long, - ownerId: ByteArray, + submittingIdentityId: ByteArray, contractId: ByteArray, documentType: String, documentId: ByteArray, - signingKeyId: Int, signerHandle: Long, - ): ByteArray + ): String /** * Transfer + broadcast [documentId] on [contractId]'s [documentType], 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 index 80a4ff29265..1d5adb36b46 100644 --- 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 @@ -71,7 +71,7 @@ data class DocumentLifecycle( null } - private fun fromLifecycleObject(obj: JsonObject): DocumentLifecycle? { + internal fun fromLifecycleObject(obj: JsonObject): DocumentLifecycle? { val state = obj["state"]?.jsonPrimitive?.takeIf { it.isString }?.content ?.let { name -> DocumentLifecycleState.entries.firstOrNull { it.name == name } } ?: return null 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 e10a6c0650a..7cd50efbbef 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 @@ -933,8 +933,9 @@ class Documents internal constructor(private val sdk: Sdk) { /** * 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`). + * observation, not the outcome of any particular transition. The wallet's + * erase-and-observe operation returns its submission decision together + * with the lifecycle observations before and after submission. */ suspend fun lifecycle( contractId: String, diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/documents/DocumentEraseOutcomeTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/documents/DocumentEraseOutcomeTest.kt new file mode 100644 index 00000000000..fdc100c1ff2 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/documents/DocumentEraseOutcomeTest.kt @@ -0,0 +1,73 @@ +package org.dashfoundation.dashsdk.documents + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Test + +class DocumentEraseOutcomeTest { + private val lifecycle = """{"state":"ERASING","remaining_revisions":18446744073709551615,"deleted_at_ms":1,"erasing_started_at_ms":2,"erasing_from_time_ms":3,"erasing_from_revision":4}""" + + @Test + fun submittedWithUnavailableClosingReadRemainsSubmitted() { + val outcome = DocumentEraseOutcome.fromJson("""{"kind":"SUBMITTED","reason":null,"owner":null,"before":$lifecycle,"after":null}""") + as DocumentEraseOutcome.Submitted + assertEquals(ULong.MAX_VALUE, outcome.before!!.remainingRevisions) + assertNull(outcome.after) + } + + @Test + fun unavailablePreflightIsAnExplicitNotSubmittedReason() { + val outcome = DocumentEraseOutcome.fromJson("""{"kind":"NOT_SUBMITTED","reason":"PREFLIGHT_UNAVAILABLE","owner":null,"before":null,"after":null}""") + as DocumentEraseOutcome.NotSubmitted + assertEquals(DocumentEraseNotSubmittedReason.PREFLIGHT_UNAVAILABLE, outcome.reason) + assertNull(outcome.before) + } + + @Test + fun malformedObservationIsNeverTreatedAsUnavailable() { + for (json in listOf( + """{"kind":"SUBMITTED","reason":null,"owner":null,"before":{},"after":null}""", + """{"kind":"SUBMITTED","reason":null,"owner":null,"before":null}""", + """{"kind":"UNKNOWN","reason":null,"owner":null,"before":null,"after":null}""", + """{"kind":"NOT_SUBMITTED","reason":"UNKNOWN","owner":null,"before":null,"after":null}""", + """{"kind":"NOT_SUBMITTED","reason":"NOT_NEWEST_OWNER","owner":null,"before":null,"after":null}""", + )) { + val error = assertThrows(DocumentEraseResultUnreadableException::class.java) { + DocumentEraseOutcome.fromJson(json) + } + assertEquals("Erase result unreadable; read history before retrying.", error.message) + } + } + + @Test + fun submittedStillRejectsUnknownOrMissingTransportFields() { + for (fields in listOf( + "\"reason\":\"UNKNOWN\",\"owner\":null", + "\"reason\":null", + "\"owner\":null", + )) { + assertThrows(DocumentEraseResultUnreadableException::class.java) { + DocumentEraseOutcome.fromJson("{\"kind\":\"SUBMITTED\",$fields,\"before\":null,\"after\":null}") + } + } + } + + @Test + fun decoderDoesNotReimplementTheSubmissionDecision() { + for (reason in DocumentEraseNotSubmittedReason.entries) { + val outcome = DocumentEraseOutcome.fromJson("""{"kind":"NOT_SUBMITTED","reason":"${reason.name}","owner":"11111111111111111111111111111111","before":$lifecycle,"after":null}""") + as DocumentEraseOutcome.NotSubmitted + assertEquals(reason, outcome.reason) + } + } + @Test + fun nativeLifecycleFixtureDecodesThroughTheSharedParser() { + val json = requireNotNull(javaClass.getResource("/document_erase_outcome_from_native.json")).readText() + val result = DocumentEraseOutcome.fromJson(json) as DocumentEraseOutcome.Submitted + assertEquals(ULong.MAX_VALUE, result.before!!.remainingRevisions) + assertEquals(ULong.MAX_VALUE, result.before!!.erasingFromRevision) + assertNull(result.after) + } + +} diff --git a/packages/kotlin-sdk/sdk/src/test/resources/document_erase_outcome_from_native.json b/packages/kotlin-sdk/sdk/src/test/resources/document_erase_outcome_from_native.json new file mode 100644 index 00000000000..23eac5bff53 --- /dev/null +++ b/packages/kotlin-sdk/sdk/src/test/resources/document_erase_outcome_from_native.json @@ -0,0 +1 @@ +{"kind":"SUBMITTED","reason":null,"owner":null,"before":{"state":"ERASING","remaining_revisions":18446744073709551615,"deleted_at_ms":1,"erasing_started_at_ms":2,"erasing_from_time_ms":3,"erasing_from_revision":18446744073709551615},"after":null} diff --git a/packages/rs-platform-wallet-ffi/src/document.rs b/packages/rs-platform-wallet-ffi/src/document.rs index 726cff61cae..3a8c9d5055e 100644 --- a/packages/rs-platform-wallet-ffi/src/document.rs +++ b/packages/rs-platform-wallet-ffi/src/document.rs @@ -5,9 +5,13 @@ use std::os::raw::c_char; use std::ptr; use std::slice; +use dash_sdk::drive::query::document_history_drive_query::DocumentHistoryState; use dpp::document::{Document, DocumentV0Getters}; use dpp::prelude::Identifier; use dpp::serialization::ValueConvertible; +use platform_wallet::wallet::identity::network::{ + DocumentEraseNotSubmittedReason, DocumentEraseOutcome, DocumentLifecycleObservation, +}; use platform_wallet::PlatformWalletError; use rs_sdk_ffi::{SignerHandle, VTableSigner}; @@ -388,79 +392,170 @@ 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. +/// The operation populated an outcome only after all Rust work succeeded. +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum DocumentEraseOutcomeKindFFI { + #[default] + Unset = 0, + NotSubmitted = 1, + Submitted = 2, +} + +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum DocumentEraseNotSubmittedReasonFFI { + #[default] + None = 0, + Active = 1, + Absent = 2, + NotNewestOwner = 3, + PreflightUnavailable = 4, +} + +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum DocumentLifecycleObservationTagFFI { + #[default] + Unavailable = 0, + Active = 1, + Absent = 2, + Deleted = 3, + Erasing = 4, +} + +/// Unavailable has no lifecycle fields; observed tags preserve every u64 exactly. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DocumentLifecycleObservationFFI { + pub state: DocumentLifecycleObservationTagFFI, + pub remaining_revisions: u64, + pub deleted_at_ms: u64, + pub erasing_started_at_ms: u64, + pub erasing_from_time_ms: u64, + pub erasing_from_revision: u64, +} + +/// Caller-owned output, with no allocations to free. `owner` is present only +/// for NotNewestOwner. `after` is an observation only for Submitted. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DocumentEraseOutcomeFFI { + pub kind: DocumentEraseOutcomeKindFFI, + pub reason: DocumentEraseNotSubmittedReasonFFI, + pub owner: [u8; 32], + pub before: DocumentLifecycleObservationFFI, + pub after: DocumentLifecycleObservationFFI, +} + +impl From for DocumentLifecycleObservationFFI { + fn from(value: DocumentLifecycleObservation) -> Self { + let DocumentLifecycleObservation::Observed(lifecycle) = value else { + return Self::default(); + }; + let state = match lifecycle.state { + DocumentHistoryState::Active => DocumentLifecycleObservationTagFFI::Active, + DocumentHistoryState::Absent => DocumentLifecycleObservationTagFFI::Absent, + DocumentHistoryState::Deleted => DocumentLifecycleObservationTagFFI::Deleted, + DocumentHistoryState::Erasing => DocumentLifecycleObservationTagFFI::Erasing, + }; + Self { + state, + 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, + } + } +} + +impl From for DocumentEraseOutcomeFFI { + fn from(value: DocumentEraseOutcome) -> Self { + match value { + DocumentEraseOutcome::NotSubmitted { reason, before } => { + let (reason, owner) = match reason { + DocumentEraseNotSubmittedReason::Active => { + (DocumentEraseNotSubmittedReasonFFI::Active, [0; 32]) + } + DocumentEraseNotSubmittedReason::Absent => { + (DocumentEraseNotSubmittedReasonFFI::Absent, [0; 32]) + } + DocumentEraseNotSubmittedReason::PreflightUnavailable => ( + DocumentEraseNotSubmittedReasonFFI::PreflightUnavailable, + [0; 32], + ), + DocumentEraseNotSubmittedReason::NotNewestOwner { owner } => ( + DocumentEraseNotSubmittedReasonFFI::NotNewestOwner, + owner.to_buffer(), + ), + }; + Self { + kind: DocumentEraseOutcomeKindFFI::NotSubmitted, + reason, + owner, + before: before.into(), + ..Default::default() + } + } + DocumentEraseOutcome::Submitted { before, after } => Self { + kind: DocumentEraseOutcomeKindFFI::Submitted, + before: before.into(), + after: after.into(), + ..Default::default() + }, + } + } +} + +/// Run one Rust-owned preflight/select/submit/observe operation. An unreadable +/// preflight does not submit. An unavailable closing read stays Submitted. +/// Submission errors (including code 20, whose outcome is unknown) leave +/// `out` at Default; callers must read history before considering a retry. +/// The caller retains the signer and output for the duration of this call. /// /// # 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. +/// Identifier pointers address 32 readable bytes and the type is a readable +/// NUL-terminated UTF-8 string. The signer and its callbacks remain live for +/// this blocking call. `out` is aligned, writable, and does not overlap an +/// input. Inputs and output are not concurrently mutated. #[no_mangle] #[allow(clippy::too_many_arguments)] -pub unsafe extern "C" fn platform_wallet_document_erase( +pub unsafe extern "C" fn platform_wallet_document_erase_and_observe( wallet_handle: Handle, - owner_identity_id: *const u8, + submitting_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, + out: *mut DocumentEraseOutcomeFFI, ) -> PlatformWalletFFIResult { + check_ptr!(out); + *out = DocumentEraseOutcomeFFI::default(); 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 submitter = unwrap_result_or_return!(read_identifier(submitting_identity_id)); + let contract = unwrap_result_or_return!(read_identifier(contract_id)); + let document = unwrap_result_or_return!(read_identifier(document_id)); + let document_type = + unwrap_result_or_return!(CStr::from_ptr(document_type_name).to_str()).to_owned(); + let identity_wallet = unwrap_option_or_return!( + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| wallet.identity().clone()) + ); 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 = block_on_worker(async move { + let signer = &*(signer_addr as *const VTableSigner); + identity_wallet + .erase_document_and_observe_with_signer( + &submitter, + &contract, + &document_type, + &document, + signer, + ) + .await }); - 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); + *out = unwrap_result_or_return!(result).into(); PlatformWalletFFIResult::ok() } @@ -683,6 +778,7 @@ pub unsafe extern "C" fn platform_wallet_document_purchase( #[cfg(test)] mod tests { use super::*; + use crate::platform_wallet_ffi_result_free; use dpp::document::DocumentV0; use dpp::platform_value::Value; use std::collections::BTreeMap; @@ -784,4 +880,177 @@ mod tests { assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); } } + #[test] + fn should_initialize_erase_outcome_before_rejecting_invalid_inputs() { + let id = [1; 32]; + let name = CString::new("note").unwrap(); + let signer = ptr::NonNull::::dangling().as_ptr(); + for (owner, contract, doc, type_name, signer, expected) in [ + ( + ptr::null(), + id.as_ptr(), + id.as_ptr(), + name.as_ptr(), + signer, + 10, + ), + ( + id.as_ptr(), + ptr::null(), + id.as_ptr(), + name.as_ptr(), + signer, + 10, + ), + ( + id.as_ptr(), + id.as_ptr(), + ptr::null(), + name.as_ptr(), + signer, + 10, + ), + ( + id.as_ptr(), + id.as_ptr(), + id.as_ptr(), + ptr::null(), + signer, + 3, + ), + ( + id.as_ptr(), + id.as_ptr(), + id.as_ptr(), + name.as_ptr(), + ptr::null_mut(), + 3, + ), + ( + id.as_ptr(), + id.as_ptr(), + id.as_ptr(), + name.as_ptr(), + signer, + 98, + ), + ] { + let mut out = DocumentEraseOutcomeFFI { + kind: DocumentEraseOutcomeKindFFI::Submitted, + ..Default::default() + }; + let mut result = unsafe { + platform_wallet_document_erase_and_observe( + 0, owner, contract, type_name, doc, signer, &mut out, + ) + }; + assert_eq!(result.code as u32, expected); + assert_eq!(out.kind, DocumentEraseOutcomeKindFFI::Unset); + assert_eq!( + out.before.state, + DocumentLifecycleObservationTagFFI::Unavailable + ); + unsafe { + platform_wallet_ffi_result_free(&mut result); + } + } + let mut result = unsafe { + platform_wallet_document_erase_and_observe( + 0, + id.as_ptr(), + id.as_ptr(), + name.as_ptr(), + id.as_ptr(), + signer, + ptr::null_mut(), + ) + }; + assert_eq!(result.code as u32, 3); + unsafe { + platform_wallet_ffi_result_free(&mut result); + } + } + #[test] + fn should_marshal_every_erase_outcome_without_losing_observation_fields() { + use dash_sdk::drive::query::document_history_drive_query::{ + DocumentHistoryLifecycle, DocumentHistoryLifecycleTimes, DocumentHistoryState, + }; + use platform_wallet::wallet::identity::network::{ + DocumentEraseNotSubmittedReason, DocumentEraseOutcome, DocumentLifecycleObservation, + }; + assert_eq!(std::mem::size_of::(), 136); + assert_eq!(std::mem::align_of::(), 8); + for (state, tag) in [ + (DocumentHistoryState::Active, 1), + (DocumentHistoryState::Absent, 2), + (DocumentHistoryState::Deleted, 3), + (DocumentHistoryState::Erasing, 4), + ] { + let lifecycle = DocumentLifecycleObservation::Observed(DocumentHistoryLifecycle { + state, + remaining_revisions: u64::MAX, + times: DocumentHistoryLifecycleTimes { + deleted_at_ms: 1, + erasing_started_at_ms: 2, + erasing_from_time_ms: 3, + erasing_from_revision: u64::MAX, + }, + }); + let out = DocumentEraseOutcomeFFI::from(DocumentEraseOutcome::Submitted { + before: DocumentLifecycleObservation::Unavailable, + after: lifecycle, + }); + assert_eq!(out.kind, DocumentEraseOutcomeKindFFI::Submitted); + assert_eq!( + out.before.state, + DocumentLifecycleObservationTagFFI::Unavailable + ); + assert_eq!(out.after.state as u8, tag); + assert_eq!(out.after.remaining_revisions, u64::MAX); + assert_eq!(out.after.erasing_from_revision, u64::MAX); + assert_eq!( + ( + out.after.deleted_at_ms, + out.after.erasing_started_at_ms, + out.after.erasing_from_time_ms + ), + (1, 2, 3) + ); + } + for (reason, tag, owner) in [ + (DocumentEraseNotSubmittedReason::Active, 1, [0; 32]), + (DocumentEraseNotSubmittedReason::Absent, 2, [0; 32]), + ( + DocumentEraseNotSubmittedReason::NotNewestOwner { + owner: Identifier::from([7; 32]), + }, + 3, + [7; 32], + ), + ( + DocumentEraseNotSubmittedReason::PreflightUnavailable, + 4, + [0; 32], + ), + ] { + let out = DocumentEraseOutcomeFFI::from(DocumentEraseOutcome::NotSubmitted { + reason, + before: DocumentLifecycleObservation::Unavailable, + }); + assert_eq!(out.kind, DocumentEraseOutcomeKindFFI::NotSubmitted); + assert_eq!(out.reason as u8, tag); + assert_eq!(out.owner, owner); + assert_eq!( + out.after.state, + DocumentLifecycleObservationTagFFI::Unavailable + ); + } + assert_eq!( + PlatformWalletFFIResult::from(PlatformWalletError::DocumentEraseBusy).code as u32, + 6 + ); + } } + +#[cfg(test)] +mod erase_tests; diff --git a/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs b/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs new file mode 100644 index 00000000000..02e250e9b2e --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/document/erase_tests.rs @@ -0,0 +1,241 @@ +use super::*; +use crate::platform_wallet_ffi_result_free; +use std::sync::Arc; + +use dash_sdk::dapi_client::mock::MockResult; +use dash_sdk::dapi_client::transport::{TransportError, TransportRequest}; +use dash_sdk::dapi_client::{DapiClientError, DumpData, ExecutionError, ExecutionResponse}; +use dash_sdk::dapi_grpc::platform::v0::BroadcastStateTransitionResponse; +use dash_sdk::dapi_grpc::tonic::Status; +use dash_sdk::platform::documents::document_history_query::{ + DocumentHistoryFilter, DocumentHistoryQuery, +}; +use dash_sdk::platform::documents::transitions::DocumentEraseTransitionBuilder; +use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; +use dash_sdk::query_types::{ + DocumentHistory, DocumentHistoryLifecycle, DocumentHistoryState, IdentityContractNonceFetcher, +}; +use dash_sdk::{RequestSettings, SdkBuilder}; +use dpp::address_funds::AddressWitness; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::factory::DataContractFactory; +use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; +use dpp::identity::signer::Signer; +use dpp::identity::{IdentityPublicKey, IdentityV0, KeyType, Purpose, SecurityLevel}; +use dpp::platform_value::{platform_value, BinaryData}; +use dpp::version::PlatformVersion; +use dpp::ProtocolError; +use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use platform_wallet::events::{EventHandler, PlatformEventHandler}; +use platform_wallet::wallet::persister::NoPlatformPersistence; +use platform_wallet::PlatformWalletManager; +use tokio::task::block_in_place; + +#[derive(Debug)] +struct Signing(bool); +#[async_trait::async_trait] +impl Signer for Signing { + async fn sign(&self, _: &IdentityPublicKey, _: &[u8]) -> Result { + Ok(vec![7; 65].into()) + } + async fn sign_create_witness( + &self, + _: &IdentityPublicKey, + _: &[u8], + ) -> Result { + unreachable!() + } + fn can_sign_with(&self, _: &IdentityPublicKey) -> bool { + self.0 + } +} +struct Events; +impl EventHandler for Events {} +impl PlatformEventHandler for Events {} + +fn save(directory: &tempfile::TempDir, request: &R, response: &MockResult) { + let dump = DumpData::new(request, response); + dump.save(&directory.path().join(dump.filename().unwrap())) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn should_preserve_signer_unavailable_and_unknown_submission_through_the_erase_export() { + let version = PlatformVersion::latest(); + let contract = Arc::new( + DataContractFactory::new(version.protocol_version) + .unwrap() + .create_with_value_config( + Identifier::from([1; 32]), + 1, + platform_value!({ + "note": { "type": "object", "documentsKeepHistory": true, "canBeErased": true, + "properties": {"message": {"type": "string", "maxLength": 64, "position": 0}}, "additionalProperties": false } + }), + None, + None, + ) + .unwrap() + .data_contract_owned(), + ); + let owner = Identifier::from([3; 32]); + let document = Identifier::from([2; 32]); + let key: IdentityPublicKey = IdentityPublicKeyV0 { + id: 1, + purpose: Purpose::AUTHENTICATION, + security_level: SecurityLevel::HIGH, + key_type: KeyType::ECDSA_SECP256K1, + data: vec![7; 33].into(), + ..Default::default() + } + .into(); + for available in [false, true] { + let build_sdk = || { + SdkBuilder::new_mock() + .with_version(version) + .with_time_tolerance(None) + .with_settings(RequestSettings { + retries: Some(0), + ..Default::default() + }) + .build() + .unwrap() + }; + let mut sdk = build_sdk(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.as_ref().clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + DocumentHistoryQuery { + data_contract_id: contract.id(), + document_type_name: "note".into(), + document_id: document, + filter: DocumentHistoryFilter::StartAtTime(0), + limit: Some(1), + }, + Some(DocumentHistory { + entries: vec![], + lifecycle: Some(DocumentHistoryLifecycle { + state: DocumentHistoryState::Erasing, + remaining_revisions: 3, + times: Default::default(), + }), + }), + ) + .await + .unwrap(); + sdk.mock() + .expect_fetch::((owner, contract.id()), None) + .await + .unwrap(); + if available { + let mut signing_sdk = build_sdk(); + signing_sdk + .mock() + .expect_fetch::((owner, contract.id()), None) + .await + .unwrap(); + let transition = DocumentEraseTransitionBuilder::new( + contract.clone(), + "note".into(), + document, + owner, + ) + .sign(&signing_sdk, &key, &Signing(true), version) + .await + .unwrap(); + let broadcast = transition.broadcast_request_for_state_transition().unwrap(); + let wait = transition + .wait_for_state_transition_result_request() + .unwrap(); + let directory = tempfile::tempdir().unwrap(); + save( + &directory, + &broadcast, + &Ok(ExecutionResponse { + inner: BroadcastStateTransitionResponse {}, + retries: 0, + address: "http://127.0.0.1".parse().unwrap(), + }), + ); + let error: MockResult< + dash_sdk::dapi_grpc::platform::v0::WaitForStateTransitionResultRequest, + > = Err(ExecutionError { + inner: DapiClientError::Transport(TransportError::Grpc(Status::unavailable( + "closing stream unavailable", + ))), + address: None, + retries: 0, + possibly_accepted: false, + }); + save(&directory, &wait, &error); + sdk.mock().load_expectations_sync(directory.path()).unwrap(); + } + let manager = PlatformWalletManager::new( + Arc::new(sdk), + Arc::new(NoPlatformPersistence), + Arc::new(Events), + ); + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[7; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + wallet + .wallet_manager() + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + IdentityV0 { + id: owner, + public_keys: [(1, key.clone())].into(), + balance: 100_000_000, + revision: 0, + } + .into(), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + let handle = PLATFORM_WALLET_STORAGE.insert(wallet); + let signer = Box::new(VTableSigner::from_native(Arc::new(Signing(available)))); + let name = CString::new("note").unwrap(); + let mut out = DocumentEraseOutcomeFFI::default(); + let mut result = block_in_place(|| unsafe { + platform_wallet_document_erase_and_observe( + handle, + owner.as_bytes().as_ptr(), + contract.id().as_bytes().as_ptr(), + name.as_ptr(), + document.as_bytes().as_ptr(), + Box::as_ref(&signer) as *const VTableSigner as *mut SignerHandle, + &mut out, + ) + }); + assert_eq!( + result.code as u32, + if available { 20 } else { 31 }, + "{}", + if result.message.is_null() { + "No error message".into() + } else { + unsafe { CStr::from_ptr(result.message) }.to_string_lossy() + } + ); + assert_eq!(out.kind, DocumentEraseOutcomeKindFFI::Unset); + unsafe { + platform_wallet_ffi_result_free(&mut result); + } + PLATFORM_WALLET_STORAGE.remove(handle); + } +} diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 58194bf7197..94fa448f950 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -1045,6 +1045,9 @@ impl From for PlatformWalletFFIResult { // assigned a dedicated code yet β€” those still carry the // typed Display rendering as the message. let code = match &error { + PlatformWalletError::DocumentEraseBusy => { + PlatformWalletFFIResultCode::ErrorWalletOperation + } PlatformWalletError::IdentityBalanceUnavailable(_) => { PlatformWalletFFIResultCode::ErrorIdentityBalanceUnavailable } diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..7b7112803f2 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -21,6 +21,9 @@ pub use dash_sdk::platform::transition::asset_lock_submission::{ /// Errors that can occur in platform wallet operations #[derive(Debug, thiserror::Error)] pub enum PlatformWalletError { + #[error("An erase for this document is already in flight; read history before retrying")] + DocumentEraseBusy, + #[error("Wallet creation failed: {0}")] WalletCreation(String), 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 773011742b1..8b6868e08ab 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -71,7 +71,7 @@ use super::*; /// `Signer` trait bound on the SDK's `PutDocument` /// extension be satisfied with a `&S` instead of forcing the caller to /// hand over ownership / wrap in an `Arc` per call. -struct SignerRef<'a, S: ?Sized>(&'a S); +pub(super) struct SignerRef<'a, S: ?Sized>(pub(super) &'a S); impl<'a, S: ?Sized> std::fmt::Debug for SignerRef<'a, S> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document_erase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document_erase.rs new file mode 100644 index 00000000000..6c5aa2be451 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document_erase.rs @@ -0,0 +1,1454 @@ +//! One paid erase attempt, with its eligibility and observations owned by Rust. + +use std::collections::BTreeSet; +use std::future::Future; +use std::sync::{Arc, Mutex}; + +use dash_sdk::drive::query::document_history_drive_query::{ + DocumentHistoryFilter, DocumentHistoryLifecycle, DocumentHistoryState, +}; +use dash_sdk::platform::documents::document_history_query::DocumentHistoryQuery; +use dash_sdk::platform::documents::transitions::DocumentEraseTransitionBuilder; +use dash_sdk::platform::Fetch; +use dash_sdk::query_types::DocumentHistory; +use dash_sdk::Error as SdkError; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters}; +use dpp::data_contract::document_type::DocumentType; +use dpp::document::DocumentV0Getters; +use dpp::identity::signer::Signer; +use dpp::identity::{Identity, IdentityPublicKey, KeyType}; +use dpp::prelude::{DataContract, Identifier}; + +use super::document::SignerRef; +use super::{usable_authentication_key, IdentityWallet}; +use crate::error::{preserve_signer_key_unavailable_or, PlatformWalletError}; + +/// A proved lifecycle, or a read that could not establish one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DocumentLifecycleObservation { + Observed(DocumentHistoryLifecycle), + Unavailable, +} + +/// Why no paid transition was submitted. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DocumentEraseNotSubmittedReason { + Active, + Absent, + NotNewestOwner { owner: Identifier }, + PreflightUnavailable, +} + +/// Submission and observations are separate: an unavailable closing read does +/// not turn a submitted erase into a submission failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DocumentEraseOutcome { + NotSubmitted { + reason: DocumentEraseNotSubmittedReason, + before: DocumentLifecycleObservation, + }, + Submitted { + before: DocumentLifecycleObservation, + after: DocumentLifecycleObservation, + }, +} + +#[derive(Debug, PartialEq, Eq)] +enum DocumentEraseDecision { + NotSubmitted(DocumentEraseNotSubmittedReason), + Submit, +} + +fn decide( + before: &DocumentLifecycleObservation, + submitter: Identifier, + newest_owner: Option, +) -> DocumentEraseDecision { + use DocumentEraseNotSubmittedReason as Reason; + let reason = match before { + DocumentLifecycleObservation::Observed(lifecycle) => match lifecycle.state { + DocumentHistoryState::Active => Reason::Active, + DocumentHistoryState::Absent => Reason::Absent, + DocumentHistoryState::Erasing => return DocumentEraseDecision::Submit, + DocumentHistoryState::Deleted => match newest_owner { + Some(owner) if owner == submitter => return DocumentEraseDecision::Submit, + Some(owner) => Reason::NotNewestOwner { owner }, + None => Reason::PreflightUnavailable, + }, + }, + DocumentLifecycleObservation::Unavailable => Reason::PreflightUnavailable, + }; + DocumentEraseDecision::NotSubmitted(reason) +} + +/// Shared by cloned wallet handles, including calls that outlive a host await. +#[derive(Debug, Default)] +pub(crate) struct DocumentEraseGate(Mutex>); + +impl DocumentEraseGate { + fn enter( + &self, + contract: Identifier, + document: Identifier, + ) -> Result, PlatformWalletError> { + if !self + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert((contract, document)) + { + return Err(PlatformWalletError::DocumentEraseBusy); + } + Ok(DocumentEraseGuard { + gate: self, + key: (contract, document), + }) + } +} + +struct DocumentEraseGuard<'a> { + gate: &'a DocumentEraseGate, + key: (Identifier, Identifier), +} + +impl Drop for DocumentEraseGuard<'_> { + fn drop(&mut self) { + self.gate + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&self.key); + } +} + +fn select_erase_key( + identity: &Identity, + document_type: &DocumentType, + contract_id: Identifier, + signer: &impl Signer, +) -> Result { + usable_authentication_key( + identity, + signer, + contract_id, + document_type.name(), + &document_type + .security_level_requirement() + .document_signing_levels(), + &[KeyType::ECDSA_SECP256K1], + ) + .map_err(PlatformWalletError::Sdk)? + .cloned() + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData("No eligible document erase signing key".into()) + }) +} + +fn observation(history: Option<&DocumentHistory>) -> DocumentLifecycleObservation { + history + .and_then(|history| history.lifecycle.clone()) + .map(DocumentLifecycleObservation::Observed) + .unwrap_or(DocumentLifecycleObservation::Unavailable) +} + +fn validate_erasable_type(document_type: &DocumentType) -> Result<(), PlatformWalletError> { + if !document_type.documents_keep_history() + || !document_type.documents_can_be_erased() + || document_type.find_contested_index().is_some() + { + return Err(PlatformWalletError::InvalidIdentityData(format!( + "Document type {:?} does not permit history erasure", + document_type.name() + ))); + } + Ok(()) +} + +impl IdentityWallet { + /// Fetch/register the contract, establish a free proved preflight, select a + /// usable signer key, and submit at most once. Unreadable preflight fails + /// closed. A deleted document requires the newest retained revision owner; + /// any loaded identity may continue an erasing document. Key selection uses + /// the real type requirement and the supplied signer. An unconfirmed + /// submission is an error whose outcome is unknown; + /// neither that error nor a successful return triggers automatic retries. + /// An unproved consensus refusal after broadcast also has an unknown outcome. + /// When more than one revision remains, deleted histories with gaps or + /// more than 65,536 retained revisions return `PreflightUnavailable` because + /// the newest owner cannot be established. This operation does not walk + /// history pages. + pub async fn erase_document_and_observe_with_signer( + &self, + submitting_identity_id: &Identifier, + contract_id: &Identifier, + document_type_name: &str, + document_id: &Identifier, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { + self.erase_and_observe_with_submit( + submitting_identity_id, + contract_id, + document_type_name, + document_id, + signer, + |contract, key| async move { + let builder = DocumentEraseTransitionBuilder::new( + contract, + document_type_name.to_owned(), + *document_id, + *submitting_identity_id, + ); + self.sdk + .document_erase(builder, &key, &SignerRef(signer)) + .await + .map(|_| ()) + }, + ) + .await + } + + async fn read_erase_history(&self, query: DocumentHistoryQuery) -> Option { + match DocumentHistory::fetch(&self.sdk, query).await { + Ok(history) => history, + Err(error) => { + tracing::warn!(%error, "Document erase lifecycle observation unavailable"); + None + } + } + } + + #[allow(clippy::too_many_arguments)] + async fn erase_and_observe_with_submit( + &self, + submitting_identity_id: &Identifier, + contract_id: &Identifier, + document_type_name: &str, + document_id: &Identifier, + signer: &S, + submit: F, + ) -> Result + where + S: Signer + Send + Sync, + F: FnOnce(Arc, IdentityPublicKey) -> Fut, + Fut: Future>, + { + let _guard = self.document_erase_gate.enter(*contract_id, *document_id)?; + let contract = self + .fetch_contract_arc_for_document_op(contract_id, document_type_name) + .await?; + let document_type = contract + .document_type_cloned_for_name(document_type_name) + .map_err(|e| PlatformWalletError::InvalidIdentityData(e.to_string()))?; + validate_erasable_type(&document_type)?; + + let query = DocumentHistoryQuery { + data_contract_id: *contract_id, + document_type_name: document_type_name.to_owned(), + document_id: *document_id, + filter: DocumentHistoryFilter::StartAtTime(0), + limit: Some(1), + }; + let history = self.read_erase_history(query.clone()).await; + let before = observation(history.as_ref()); + let mut newest_owner = None; + if let DocumentLifecycleObservation::Observed(lifecycle) = &before { + if lifecycle.state == DocumentHistoryState::Deleted { + let newest_revision = lifecycle.remaining_revisions; + if newest_revision == 1 { + newest_owner = history.as_ref().and_then(|history| { + history + .entries + .first() + .map(|entry| entry.document.owner_id()) + }); + } else if newest_revision != 0 { + let newest_query = DocumentHistoryQuery { + filter: DocumentHistoryFilter::Revision(newest_revision), + ..query.clone() + }; + newest_owner = self + .read_erase_history(newest_query) + .await + .and_then(|page| { + if page.lifecycle.as_ref() != Some(lifecycle) { + return None; + } + page.entries + .iter() + .find(|entry| entry.revision == newest_revision) + .map(|entry| entry.document.owner_id()) + }); + } + } + } + if let DocumentEraseDecision::NotSubmitted(reason) = + decide(&before, *submitting_identity_id, newest_owner) + { + return Ok(DocumentEraseOutcome::NotSubmitted { reason, before }); + } + let identity = { + let manager = self.wallet_manager.read().await; + let info = manager + .get_wallet_info(&self.wallet_id) + .ok_or_else(|| PlatformWalletError::WalletNotFound(hex::encode(self.wallet_id)))?; + info.identity_manager + .identity(submitting_identity_id) + .map(|managed| managed.identity.clone()) + .ok_or(PlatformWalletError::IdentityNotFound( + *submitting_identity_id, + ))? + }; + // Signer callbacks may re-enter the wallet; the manager lock is released. + let key = select_erase_key(&identity, &document_type, *contract_id, signer)?; + submit(contract, key).await.map_err(|error| { + preserve_signer_key_unavailable_or(error, |error| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to erase document: {error}" + )) + }) + })?; + let after = observation(self.read_erase_history(query).await.as_ref()); + Ok(DocumentEraseOutcome::Submitted { before, after }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; + use crate::wallet::persister::NoPlatformPersistence; + use crate::PlatformWallet; + use dash_sdk::dapi_grpc::platform::v0::GetDocumentHistoryRequest; + use dash_sdk::drive::query::document_history_drive_query::DocumentHistoryLifecycleTimes; + use dash_sdk::platform::Query; + use dpp::document::DocumentV0Setters; + use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::version::PlatformVersion; + + fn observed(state: DocumentHistoryState) -> DocumentLifecycleObservation { + let remaining_revisions = if state == DocumentHistoryState::Absent { + 0 + } else { + 3 + }; + DocumentLifecycleObservation::Observed(DocumentHistoryLifecycle { + state, + remaining_revisions, + times: DocumentHistoryLifecycleTimes::default(), + }) + } + + #[test] + fn should_never_pay_without_an_eligible_preflight() { + let submitter = Identifier::from([1; 32]); + let other = Identifier::from([2; 32]); + for (before, owner, expected) in [ + ( + observed(DocumentHistoryState::Active), + None, + DocumentEraseDecision::NotSubmitted(DocumentEraseNotSubmittedReason::Active), + ), + ( + observed(DocumentHistoryState::Absent), + None, + DocumentEraseDecision::NotSubmitted(DocumentEraseNotSubmittedReason::Absent), + ), + ( + DocumentLifecycleObservation::Unavailable, + None, + DocumentEraseDecision::NotSubmitted( + DocumentEraseNotSubmittedReason::PreflightUnavailable, + ), + ), + ( + observed(DocumentHistoryState::Deleted), + None, + DocumentEraseDecision::NotSubmitted( + DocumentEraseNotSubmittedReason::PreflightUnavailable, + ), + ), + ( + observed(DocumentHistoryState::Deleted), + Some(other), + DocumentEraseDecision::NotSubmitted( + DocumentEraseNotSubmittedReason::NotNewestOwner { owner: other }, + ), + ), + ( + observed(DocumentHistoryState::Deleted), + Some(submitter), + DocumentEraseDecision::Submit, + ), + ( + observed(DocumentHistoryState::Erasing), + Some(other), + DocumentEraseDecision::Submit, + ), + ( + observed(DocumentHistoryState::Erasing), + None, + DocumentEraseDecision::Submit, + ), + ] { + assert_eq!(decide(&before, submitter, owner), expected); + } + } + + #[test] + fn should_release_the_in_flight_guard_on_drop() { + let gate = DocumentEraseGate::default(); + let contract = Identifier::from([1; 32]); + let document = Identifier::from([2; 32]); + let guard = gate.enter(contract, document).unwrap(); + assert!(matches!( + gate.enter(contract, document), + Err(PlatformWalletError::DocumentEraseBusy) + )); + assert!(gate.enter(contract, Identifier::from([3; 32])).is_ok()); + drop(guard); + assert!(gate.enter(contract, document).is_ok()); + } + fn key(id: u32, level: dpp::identity::SecurityLevel) -> IdentityPublicKey { + dpp::identity::identity_public_key::v0::IdentityPublicKeyV0 { + id, + purpose: dpp::identity::Purpose::AUTHENTICATION, + security_level: level, + key_type: KeyType::ECDSA_SECP256K1, + data: vec![id as u8; 33].into(), + ..Default::default() + } + .into() + } + + fn bounds( + key: &mut IdentityPublicKey, + bounds: Option, + ) { + if let IdentityPublicKey::V0(key) = key { + key.contract_bounds = bounds; + } + } + + fn contract() -> DataContract { + contract_with_requirement(dpp::identity::SecurityLevel::HIGH) + } + + fn contract_with_requirement(requirement: dpp::identity::SecurityLevel) -> DataContract { + use dpp::data_contract::factory::DataContractFactory; + use dpp::platform_value::platform_value; + DataContractFactory::new(PlatformVersion::latest().protocol_version) + .unwrap() + .create_with_value_config( + Identifier::from([1; 32]), + 1, + platform_value!({ + "note": { "type": "object", "documentsKeepHistory": true, + "canBeErased": true, "signatureSecurityLevelRequirement": requirement as u8, + "properties": {"message": {"type": "string", "maxLength": 64, "position": 0}}, "additionalProperties": false } + }), + None, + None, + ) + .unwrap() + .data_contract_owned() + } + + #[test] + fn should_select_only_usable_erase_keys_for_the_real_type() { + use super::super::signing_key::tests::available; + use dpp::identity::accessors::IdentitySettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::identity::{Identity, SecurityLevel}; + let contract = contract(); + let document_type = contract.document_type_cloned_for_name("note").unwrap(); + let mut identity = Identity::default_versioned(PlatformVersion::latest()).unwrap(); + let mut wrong_contract = key(1, SecurityLevel::CRITICAL); + bounds( + &mut wrong_contract, + Some(ContractBounds::SingleContract { + id: Identifier::from([9; 32]), + }), + ); + let mut wrong_type = key(2, SecurityLevel::CRITICAL); + bounds( + &mut wrong_type, + Some(ContractBounds::SingleContractDocumentType { + id: contract.id(), + document_type_name: "other".into(), + }), + ); + let mut group = key(3, SecurityLevel::CRITICAL); + bounds( + &mut group, + Some(ContractBounds::ContractGroup { id: contract.id() }), + ); + let mut disabled = key(5, SecurityLevel::CRITICAL); + disabled.set_disabled_at(1); + for candidate in [ + key(0, SecurityLevel::MASTER), + wrong_contract, + wrong_type, + group, + key(4, SecurityLevel::CRITICAL).with_limits(None, Some(1)), + disabled, + key(6, SecurityLevel::HIGH).with_limits(Some(100), None), + key(7, SecurityLevel::HIGH), + key(8, SecurityLevel::CRITICAL), + ] { + identity.add_public_key(candidate); + } + let signer = available(&[0, 1, 2, 3, 4, 5, 6, 7]); + assert_eq!( + select_erase_key(&identity, &document_type, contract.id(), &signer) + .unwrap() + .id(), + 7 + ); + let error = select_erase_key( + &identity, + &document_type, + contract.id(), + &available(&[0, 1, 2, 3, 4, 5]), + ) + .unwrap_err(); + assert!(error.to_string().contains(SIGNER_KEY_UNAVAILABLE_PREFIX)); + identity.set_public_keys(Default::default()); + identity.add_public_key(key(0, SecurityLevel::MASTER)); + assert!(matches!( + select_erase_key(&identity, &document_type, contract.id(), &signer), + Err(PlatformWalletError::InvalidIdentityData(_)) + )); + } + + #[derive(Default)] + struct Contracts( + std::sync::Mutex>>, + std::sync::Mutex>, + ); + + impl dash_sdk::platform::ContextProvider for Contracts { + fn get_data_contract( + &self, + id: &Identifier, + _: &dpp::version::PlatformVersion, + ) -> Result>, dash_sdk::error::ContextProviderError> { + Ok(self + .0 + .lock() + .unwrap() + .as_ref() + .filter(|c| c.id() == *id) + .cloned()) + } + fn register_data_contract(&self, contract: Arc) { + let control = self.1.lock().unwrap().take(); + if let Some(mut control) = control { + assert_eq!( + futures::executor::block_on(history_reads( + &mut control, + &contract, + DocumentHistoryFilter::StartAtTime(0) + )), + 0, + "contract registration must precede every history read" + ); + } + *self.0.lock().unwrap() = Some(contract); + } + fn get_token_configuration( + &self, + _: &Identifier, + ) -> Result< + Option, + dash_sdk::error::ContextProviderError, + > { + Ok(None) + } + fn get_quorum_public_key( + &self, + _: u32, + _: [u8; 32], + _: u32, + ) -> Result<[u8; 48], dash_sdk::error::ContextProviderError> { + Err(dash_sdk::error::ContextProviderError::Config( + "no test quorum".into(), + )) + } + fn get_platform_activation_height( + &self, + ) -> Result { + Ok(1) + } + } + + fn history_query( + contract: &DataContract, + filter: DocumentHistoryFilter, + ) -> DocumentHistoryQuery { + DocumentHistoryQuery { + data_contract_id: contract.id(), + document_type_name: "note".into(), + document_id: Identifier::from([2; 32]), + filter, + limit: Some(1), + } + } + + async fn history_reads( + sdk: &mut dash_sdk::Sdk, + contract: &DataContract, + filter: DocumentHistoryFilter, + ) -> usize { + let request: GetDocumentHistoryRequest = history_query(contract, filter) + .query(&sdk.query_settings()) + .unwrap(); + sdk.mock().request_count(&request).await + } + + fn history(state: DocumentHistoryState, owner: Identifier, newest: bool) -> DocumentHistory { + let absent = state == DocumentHistoryState::Absent; + DocumentHistory { + lifecycle: match observed(state) { + DocumentLifecycleObservation::Observed(lifecycle) => Some(lifecycle), + _ => unreachable!(), + }, + entries: if absent { + vec![] + } else { + vec![dash_sdk::query_types::DocumentHistoryEntry { + time_ms: 1, + revision: if newest { 3 } else { 1 }, + document: dpp::document::DocumentV0 { + id: Identifier::from([2; 32]), + owner_id: owner, + revision: Some(if newest { 3 } else { 1 }), + ..Default::default() + } + .into(), + }] + }, + } + } + + #[tokio::test] + async fn should_register_the_contract_before_skipping_an_active_document() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + let contract = contract(); + let provider = Arc::new(Contracts::default()); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_context_provider_arc(provider.clone()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::StartAtTime(0)), + Some(history( + DocumentHistoryState::Active, + Identifier::default(), + true, + )), + ) + .await + .unwrap(); + *provider.1.lock().unwrap() = Some(sdk.clone()); + let mut control = sdk.clone(); + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + assert!(provider.0.lock().unwrap().is_none()); + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[]), + |_, _| async { panic!("ACTIVE must not submit") }, + ) + .await + .unwrap(); + assert!(matches!( + outcome, + DocumentEraseOutcome::NotSubmitted { + reason: DocumentEraseNotSubmittedReason::Active, + .. + } + )); + assert_eq!( + provider.0.lock().unwrap().as_ref().unwrap().id(), + contract.id() + ); + assert!(provider.1.lock().unwrap().is_none()); + assert_eq!( + history_reads( + &mut control, + &contract, + DocumentHistoryFilter::StartAtTime(0) + ) + .await, + 1 + ); + } + + #[tokio::test] + async fn should_observe_once_after_submission_and_keep_closing_failure_separate() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + for closing_state in [ + Some(DocumentHistoryState::Active), + Some(DocumentHistoryState::Absent), + Some(DocumentHistoryState::Deleted), + Some(DocumentHistoryState::Erasing), + None, + ] { + let contract = contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + let query = history_query(&contract, DocumentHistoryFilter::StartAtTime(0)); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + query.clone(), + Some(history( + DocumentHistoryState::Erasing, + Identifier::from([9; 32]), + true, + )), + ) + .await + .unwrap(); + let mut control = sdk.clone(); + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + let calls = std::sync::atomic::AtomicUsize::new(0); + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[1]), + |_, _| async { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + control + .mock() + .remove_fetch_expectation::(query.clone()) + .await; + if let Some(state) = closing_state { + control + .mock() + .expect_fetch( + query, + Some(history(state, Identifier::from([9; 32]), true)), + ) + .await + .unwrap(); + } + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!( + outcome, + DocumentEraseOutcome::Submitted { + before: observed(DocumentHistoryState::Erasing), + after: closing_state + .map(observed) + .unwrap_or(DocumentLifecycleObservation::Unavailable), + } + ); + } + } + + #[tokio::test] + async fn should_check_the_newest_deleted_owner_and_fail_closed_on_unread_preflight() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + let other = Identifier::from([9; 32]); + for (state, metadata, newest, owner, owner_read, expected) in [ + ( + DocumentHistoryState::Absent, + true, + true, + other, + true, + DocumentEraseNotSubmittedReason::Absent, + ), + ( + DocumentHistoryState::Deleted, + false, + true, + other, + true, + DocumentEraseNotSubmittedReason::PreflightUnavailable, + ), + ( + DocumentHistoryState::Deleted, + true, + true, + other, + true, + DocumentEraseNotSubmittedReason::NotNewestOwner { owner: other }, + ), + ( + DocumentHistoryState::Deleted, + true, + false, + other, + true, + DocumentEraseNotSubmittedReason::NotNewestOwner { owner: other }, + ), + ( + DocumentHistoryState::Deleted, + true, + false, + other, + false, + DocumentEraseNotSubmittedReason::PreflightUnavailable, + ), + ] { + let contract = contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + let mut page = history(state, owner, newest); + if newest && state == DocumentHistoryState::Deleted { + page.lifecycle.as_mut().unwrap().remaining_revisions = 1; + } + if !metadata { + page.lifecycle = None; + } + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::StartAtTime(0)), + Some(page), + ) + .await + .unwrap(); + if !newest && owner_read { + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::Revision(3)), + Some(history(state, owner, true)), + ) + .await + .unwrap(); + } + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[]), + |_, _| async { panic!("ineligible preflight must not submit") }, + ) + .await + .unwrap(); + assert!( + matches!(outcome, DocumentEraseOutcome::NotSubmitted { reason, .. } if reason == expected) + ); + } + } + + #[tokio::test] + async fn should_not_pay_to_erase_gapped_history_as_its_oldest_owner() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + let contract = contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + let mut retained = history(DocumentHistoryState::Deleted, Identifier::default(), false); + retained.lifecycle.as_mut().unwrap().remaining_revisions = 2; + retained.entries[0].revision = 2; + retained.entries[0].document.set_revision(Some(2)); + retained.entries.extend( + history( + DocumentHistoryState::Deleted, + Identifier::from([9; 32]), + true, + ) + .entries, + ); + // The preflight page exposes only revision 2, before the transfer. + retained.entries.truncate(1); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::StartAtTime(0)), + Some(retained), + ) + .await + .unwrap(); + // Revision-count lookup cannot resolve a gapped history. The missing + // Revision(2) expectation makes that read fail, as Drive would refuse it. + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + let calls = std::sync::atomic::AtomicUsize::new(0); + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[1]), + |_, _| async { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + assert!(matches!( + outcome, + DocumentEraseOutcome::NotSubmitted { + reason: DocumentEraseNotSubmittedReason::PreflightUnavailable, + .. + } + )); + } + + #[test] + fn should_skip_each_ineligible_key_even_when_the_signer_has_it() { + use super::super::signing_key::tests::{available, identity}; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::identity::{Purpose, SecurityLevel}; + let contract = contract(); + let document_type = contract.document_type_cloned_for_name("note").unwrap(); + let mut wrong_contract = key(1, SecurityLevel::HIGH); + bounds( + &mut wrong_contract, + Some(ContractBounds::SingleContract { + id: Identifier::from([9; 32]), + }), + ); + let mut wrong_type = key(1, SecurityLevel::HIGH); + bounds( + &mut wrong_type, + Some(ContractBounds::SingleContractDocumentType { + id: contract.id(), + document_type_name: "other".into(), + }), + ); + let mut group = key(1, SecurityLevel::HIGH); + bounds( + &mut group, + Some(ContractBounds::ContractGroup { id: contract.id() }), + ); + for candidate in [ + wrong_contract, + wrong_type, + group, + key(1, SecurityLevel::HIGH).with_limits(None, Some(1)), + key(1, SecurityLevel::MASTER), + ] { + let mut subject = identity( + Purpose::AUTHENTICATION, + SecurityLevel::HIGH, + KeyType::ECDSA_SECP256K1, + ); + subject.add_public_key(candidate); + assert_eq!( + select_erase_key(&subject, &document_type, contract.id(), &available(&[1, 2])) + .unwrap() + .id(), + 2 + ); + } + } + + #[test] + fn should_refuse_a_stored_contested_type_even_when_it_allows_erasure() { + use dpp::data_contract::config::DataContractConfig; + use dpp::platform_value::platform_value; + let version = PlatformVersion::latest(); + let config = DataContractConfig::default_for_version(version).unwrap(); + let document_type = DocumentType::try_from_schema( + Identifier::from([1; 32]), + 1, + config.version(), + "note", + platform_value!({ + "type": "object", "documentsKeepHistory": true, + "documentsMutable": false, "canBeDeleted": true, "canBeErased": true, + "indices": [{ + "name": "byMessage", "properties": [{"message": "asc"}], "unique": true, + "contested": { + "fieldMatches": [{"field": "message", "regexPattern": "^[a-z]{3,10}$"}], + "resolution": 0 + } + }], + "properties": {"message": {"type": "string", "maxLength": 63, "position": 0}}, + "required": ["message"], "additionalProperties": false + }), + None, + &Default::default(), + &config, + false, + &mut vec![], + version, + ) + .unwrap(); + assert!(document_type.documents_keep_history()); + assert!(document_type.documents_can_be_erased()); + assert!(document_type.find_contested_index().is_some()); + assert!(validate_erasable_type(&document_type).is_err()); + } + + #[tokio::test] + async fn should_refuse_contract_types_before_reading_or_signing() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + use dpp::data_contract::factory::DataContractFactory; + use dpp::platform_value::platform_value; + for keeps_history in [false, true] { + let contract = DataContractFactory::new( + PlatformVersion::latest().protocol_version, + ) + .unwrap() + .create_with_value_config( + Identifier::from([1; 32]), + 1, + platform_value!({ + "note": { "type": "object", "documentsKeepHistory": keeps_history, + "canBeErased": false, "properties": {"message": {"type": "string", "maxLength": 64, "position": 0}}, "additionalProperties": false } + }), + None, + None, + ) + .unwrap() + .data_contract_owned(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + let mut control = sdk.clone(); + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + let result = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[]), + |_, _| async { panic!("contract refusal must not submit") }, + ) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::InvalidIdentityData(_)) + )); + assert_eq!( + history_reads( + &mut control, + &contract, + DocumentHistoryFilter::StartAtTime(0) + ) + .await, + 0 + ); + } + } + + #[tokio::test] + async fn should_submit_deleted_only_for_the_newest_owner_and_release_lock_before_signer() { + use super::super::signing_key::tests::{ + available, lock_checking_signer, wallet_with_signing_keys_on, + }; + let contract = contract(); + for no_key in [false, true] { + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::StartAtTime(0)), + Some(history( + DocumentHistoryState::Deleted, + Identifier::from([9; 32]), + false, + )), + ) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::Revision(3)), + Some(history( + DocumentHistoryState::Deleted, + Identifier::default(), + true, + )), + ) + .await + .unwrap(); + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + if no_key { + let signer = lock_checking_signer(wallet.identity()); + let error = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &signer, + |_, _| async { panic!("unavailable key must not submit") }, + ) + .await + .unwrap_err(); + assert!(error.to_string().contains(SIGNER_KEY_UNAVAILABLE_PREFIX)); + } else { + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[1]), + |_, _| async { Ok(()) }, + ) + .await + .unwrap(); + assert!(matches!(outcome, DocumentEraseOutcome::Submitted { .. })); + } + } + } + + #[tokio::test] + async fn should_not_submit_when_the_preflight_read_fails() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + let contract = contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[]), + |_, _| async { panic!("unread preflight must not submit") }, + ) + .await + .unwrap(); + assert!(matches!( + outcome, + DocumentEraseOutcome::NotSubmitted { + reason: DocumentEraseNotSubmittedReason::PreflightUnavailable, + before: DocumentLifecycleObservation::Unavailable + } + )); + } + #[test] + fn should_skip_an_expired_erase_key_even_when_it_is_available() { + use super::super::signing_key::tests::{available, identity}; + use dpp::identity::{Purpose, SecurityLevel}; + let contract = contract(); + let document_type = contract.document_type_cloned_for_name("note").unwrap(); + let mut subject = identity( + Purpose::AUTHENTICATION, + SecurityLevel::HIGH, + KeyType::ECDSA_SECP256K1, + ); + subject.add_public_key(key(1, SecurityLevel::HIGH).with_limits(None, Some(1))); + assert_eq!( + select_erase_key(&subject, &document_type, contract.id(), &available(&[1, 2])) + .unwrap() + .id(), + 2 + ); + } + + #[test] + fn should_prefer_an_unlimited_erase_key_over_an_earlier_budgeted_key() { + use super::super::signing_key::tests::{available, identity}; + use dpp::identity::{Purpose, SecurityLevel}; + let contract = contract(); + let document_type = contract.document_type_cloned_for_name("note").unwrap(); + let mut subject = identity( + Purpose::AUTHENTICATION, + SecurityLevel::HIGH, + KeyType::ECDSA_SECP256K1, + ); + subject.add_public_key(key(1, SecurityLevel::HIGH).with_limits(Some(100), None)); + assert_eq!( + select_erase_key(&subject, &document_type, contract.id(), &available(&[1, 2])) + .unwrap() + .id(), + 2 + ); + } + + #[test] + fn should_use_the_real_document_requirement_and_exclude_master() { + use super::super::signing_key::tests::{available, identity}; + use dpp::identity::{Purpose, SecurityLevel}; + for (requirement, expected) in [ + (SecurityLevel::CRITICAL, 3), + (SecurityLevel::HIGH, 2), + (SecurityLevel::MEDIUM, 1), + ] { + let contract = contract_with_requirement(requirement); + let document_type = contract.document_type_cloned_for_name("note").unwrap(); + let mut subject = identity( + Purpose::AUTHENTICATION, + SecurityLevel::MEDIUM, + KeyType::ECDSA_SECP256K1, + ); + for candidate in [ + key(0, SecurityLevel::MASTER), + key(2, SecurityLevel::HIGH), + key(3, SecurityLevel::CRITICAL), + ] { + subject.add_public_key(candidate); + } + assert_eq!( + select_erase_key( + &subject, + &document_type, + contract.id(), + &available(&[0, 1, 2, 3]) + ) + .unwrap() + .id(), + expected + ); + } + } + + async fn erasing_wallet() -> (Arc, DataContract) { + use super::super::signing_key::tests::wallet_with_signing_keys_on; + let contract = contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::StartAtTime(0)), + Some(history( + DocumentHistoryState::Erasing, + Identifier::from([9; 32]), + false, + )), + ) + .await + .unwrap(); + ( + wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await, + contract, + ) + } + + #[tokio::test] + async fn should_reject_a_concurrent_erase_while_the_first_submission_is_pending() { + use super::super::signing_key::tests::available; + let (wallet, contract) = erasing_wallet().await; + let submitter = Identifier::default(); + let contract_id = contract.id(); + let document_id = Identifier::from([2; 32]); + let signer = available(&[1]); + let entered = tokio::sync::Notify::new(); + let mut first = Box::pin(wallet.identity().erase_and_observe_with_submit( + &submitter, + &contract_id, + "note", + &document_id, + &signer, + |_, _| async { + entered.notify_one(); + std::future::pending::>().await + }, + )); + tokio::select! { + _ = entered.notified() => {}, + result = &mut first => panic!("first submission must remain pending: {result:?}"), + } + let result = wallet + .identity() + .erase_and_observe_with_submit( + &submitter, + &contract_id, + "note", + &document_id, + &signer, + |_, _| async { panic!("concurrent operation must not submit") }, + ) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::DocumentEraseBusy) + )); + drop(first); + } + + #[tokio::test] + async fn should_release_the_in_flight_guard_when_cancelled_during_submission() { + use super::super::signing_key::tests::available; + let (wallet, contract) = erasing_wallet().await; + let submitter = Identifier::default(); + let contract_id = contract.id(); + let document_id = Identifier::from([2; 32]); + let signer = available(&[1]); + let entered = tokio::sync::Notify::new(); + let mut first = Box::pin(wallet.identity().erase_and_observe_with_submit( + &submitter, + &contract_id, + "note", + &document_id, + &signer, + |_, _| async { + entered.notify_one(); + std::future::pending::>().await + }, + )); + tokio::select! { + _ = entered.notified() => {}, + result = &mut first => panic!("first submission must remain pending: {result:?}"), + } + drop(first); + let calls = std::sync::atomic::AtomicUsize::new(0); + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &submitter, + &contract_id, + "note", + &document_id, + &signer, + |_, _| async { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); + assert!(matches!(outcome, DocumentEraseOutcome::Submitted { .. })); + } + + #[tokio::test] + async fn should_not_submit_when_the_newest_owner_page_has_a_different_lifecycle() { + use super::super::signing_key::tests::{available, wallet_with_signing_keys_on}; + let contract = contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::StartAtTime(0)), + Some(history( + DocumentHistoryState::Deleted, + Identifier::from([9; 32]), + false, + )), + ) + .await + .unwrap(); + sdk.mock() + .expect_fetch( + history_query(&contract, DocumentHistoryFilter::Revision(3)), + Some(history( + DocumentHistoryState::Erasing, + Identifier::default(), + true, + )), + ) + .await + .unwrap(); + let mut control = sdk.clone(); + let wallet = wallet_with_signing_keys_on(sdk, Arc::new(NoPlatformPersistence)).await; + let calls = std::sync::atomic::AtomicUsize::new(0); + let outcome = wallet + .identity() + .erase_and_observe_with_submit( + &Identifier::default(), + &contract.id(), + "note", + &Identifier::from([2; 32]), + &available(&[1]), + |_, _| async { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(()) + }, + ) + .await + .unwrap(); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); + assert!(matches!( + outcome, + DocumentEraseOutcome::NotSubmitted { + reason: DocumentEraseNotSubmittedReason::PreflightUnavailable, + .. + } + )); + assert_eq!( + history_reads( + &mut control, + &contract, + DocumentHistoryFilter::StartAtTime(0) + ) + .await, + 1 + ); + assert_eq!( + history_reads(&mut control, &contract, DocumentHistoryFilter::Revision(3)).await, + 1 + ); + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index f54f1791730..fc346c8d038 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -3943,6 +3943,7 @@ mod tests { generation, broadcaster, sdk_writer: Arc::new(super::super::sdk_writer::SdkWriter::new(sdk)), + document_erase_gate: Default::default(), dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs index c8e7937b2e6..d89ea04eaee 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/identity_handle.rs @@ -526,6 +526,8 @@ pub struct IdentityWallet { /// signer-generic `PutDocument` trait) behind two by-value methods /// so the call sites stay simple. pub(crate) sdk_writer: Arc, + /// Prevents overlapping erase attempts for a document across cloned handles. + pub(crate) document_erase_gate: Arc, /// Serializes DPNS marketplace mutations and sync reconciliation for /// this wallet. Every cloned handle shares the same gate. pub(crate) dpns_operation_gate: Arc>, @@ -560,6 +562,7 @@ impl Clone for IdentityWallet { generation: Arc::clone(&self.generation), broadcaster: Arc::clone(&self.broadcaster), sdk_writer: Arc::clone(&self.sdk_writer), + document_erase_gate: Arc::clone(&self.document_erase_gate), dpns_operation_gate: Arc::clone(&self.dpns_operation_gate), dpns_sync_progress: Arc::clone(&self.dpns_sync_progress), } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs b/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs index a1cde7283a6..2b21fde4be0 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs @@ -55,8 +55,8 @@ pub(crate) fn usable_authentication_key<'a>( /// Whether a key carrying `bounds` may sign a `document_type_name` document of `contract_id`. /// /// A contract group bound is answered by group membership, state the wallet does not hold, -/// so a group-bound key is never chosen here: the DashPay writes this picker serves are -/// signed with an unbound key or one bound to DashPay itself. +/// so a group-bound key is never chosen here. Callers use an unbound key or one +/// bound to the target contract or document type. fn bounds_cover( bounds: Option<&ContractBounds>, contract_id: Identifier, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index babb0e9fee1..ac7eba762cd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -37,6 +37,11 @@ mod contract; mod decision_proposal; mod discovery; mod document; +mod document_erase; +pub(crate) use document_erase::DocumentEraseGate; +pub use document_erase::{ + DocumentEraseNotSubmittedReason, DocumentEraseOutcome, DocumentLifecycleObservation, +}; mod dpns; mod dpns_marketplace; mod identity_handle; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs index 5060aa6295d..90591b4ab63 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/payments.rs @@ -13432,6 +13432,7 @@ mod tests { generation: Arc::clone(&real.generation), broadcaster: Arc::new(GatedRejectingBroadcaster { entered, release }), sdk_writer: Arc::clone(&real.sdk_writer), + document_erase_gate: Arc::clone(&real.document_erase_gate), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), } @@ -13474,6 +13475,7 @@ mod tests { generation: Arc::clone(&real.generation), broadcaster: Arc::new(GatedBroadcaster { entered, release }), sdk_writer: Arc::clone(&real.sdk_writer), + document_erase_gate: Arc::clone(&real.document_erase_gate), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), } @@ -13530,6 +13532,7 @@ mod tests { generation: Arc::clone(&real.generation), broadcaster: Arc::new(broadcaster), sdk_writer: Arc::clone(&real.sdk_writer), + document_erase_gate: Arc::clone(&real.document_erase_gate), dpns_operation_gate: Arc::clone(&real.dpns_operation_gate), dpns_sync_progress: Arc::clone(&real.dpns_sync_progress), } diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index c67a5462f70..8a7edc96b0b 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -806,6 +806,7 @@ impl PlatformWallet { sdk_writer: Arc::new( crate::wallet::identity::network::sdk_writer::SdkWriter::new(Arc::clone(&sdk)), ), + document_erase_gate: Default::default(), dpns_operation_gate: Arc::new(tokio::sync::Mutex::new(())), dpns_sync_progress: Arc::new(std::sync::Mutex::new(BTreeMap::new())), }; diff --git a/packages/rs-sdk-ffi/src/document/erase.rs b/packages/rs-sdk-ffi/src/document/erase.rs index ded4dbc41bd..4cb58dc3014 100644 --- a/packages/rs-sdk-ffi/src/document/erase.rs +++ b/packages/rs-sdk-ffi/src/document/erase.rs @@ -94,13 +94,13 @@ pub unsafe extern "C" fn dash_sdk_document_erase( 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)))?; + .map_err(|e| FFIError::InvalidParameter(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)))?; + .map_err(|e| FFIError::InvalidParameter(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)))?; + .map_err(|e| FFIError::InvalidParameter(format!("Invalid contract ID: {}", e)))?; // Resolve the contract through the SDK's current context provider. let data_contract = wrapper.data_contract(&contract_id)?; @@ -259,13 +259,13 @@ pub unsafe extern "C" fn dash_sdk_document_erase_and_wait( 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)))?; + .map_err(|e| FFIError::InvalidParameter(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)))?; + .map_err(|e| FFIError::InvalidParameter(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)))?; + .map_err(|e| FFIError::InvalidParameter(format!("Invalid contract ID: {}", e)))?; // Resolve the contract through the SDK's current context provider. let data_contract = wrapper.data_contract(&contract_id)?; @@ -349,6 +349,43 @@ mod tests { use std::ffi::{CStr, CString}; use std::ptr; + #[test] + fn should_classify_malformed_erase_identifiers_as_invalid_parameter() { + let sdk = create_mock_sdk_handle(); + let valid = CString::new(Identifier::from([1; 32]).to_string(Encoding::Base58)).unwrap(); + let invalid = CString::new("not-base58-0OIl").unwrap(); + let name = CString::new("note").unwrap(); + let key = create_mock_identity_public_key(); + let signer = create_mock_signer(); + let mut observed = Vec::new(); + for export in [dash_sdk_document_erase, dash_sdk_document_erase_and_wait] { + for malformed in 0..3 { + let mut ids = [valid.as_ptr(); 3]; + ids[malformed] = invalid.as_ptr(); + let result = unsafe { + export( + sdk, + ids[0], + ids[1], + ids[2], + name.as_ptr(), + ptr::from_ref(key.as_ref()).cast(), + ptr::from_ref(signer.as_ref()).cast(), + ptr::null(), + ptr::null(), + ) + }; + assert!(!result.error.is_null()); + unsafe { + observed.push((*result.error).code); + crate::dash_sdk_error_free(result.error); + } + } + } + destroy_mock_sdk_handle(sdk); + assert_eq!(observed, vec![DashSDKErrorCode::InvalidParameter; 6]); + } + 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(); diff --git a/packages/rs-sdk-ffi/src/document/queries/history.rs b/packages/rs-sdk-ffi/src/document/queries/history.rs index 68b7863b616..5ad3beea888 100644 --- a/packages/rs-sdk-ffi/src/document/queries/history.rs +++ b/packages/rs-sdk-ffi/src/document/queries/history.rs @@ -290,6 +290,38 @@ mod tests { assert!(message.contains("document type not found"), "{message}"); } + #[test] + fn should_classify_invalid_history_limits_as_invalid_parameter() { + let contract = create_mock_data_contract(); + let contract_id = CString::new(contract.id().to_string(Encoding::Base58)).unwrap(); + let sdk = create_mock_sdk_handle_with_current_contracts(vec![*contract]); + let document_id = + CString::new(Identifier::from([2; 32]).to_string(Encoding::Base58)).unwrap(); + let name = CString::new("testDoc").unwrap(); + let mut codes = Vec::new(); + for limit in [11, u16::MAX as u32 + 1, u32::MAX] { + let result = unsafe { + dash_sdk_document_fetch_history( + sdk, + contract_id.as_ptr(), + name.as_ptr(), + document_id.as_ptr(), + 0, + 0, + 0, + limit, + ) + }; + assert!(!result.error.is_null()); + unsafe { + codes.push((*result.error).code); + crate::dash_sdk_error_free(result.error); + } + } + destroy_mock_sdk_handle(sdk); + assert_eq!(codes, vec![DashSDKErrorCode::InvalidParameter; 3]); + } + fn revision_document(revision: u64) -> Document { let mut properties = BTreeMap::new(); properties.insert( diff --git a/packages/rs-sdk/src/error.rs b/packages/rs-sdk/src/error.rs index a142626ec29..ad236dbdacb 100644 --- a/packages/rs-sdk/src/error.rs +++ b/packages/rs-sdk/src/error.rs @@ -29,7 +29,7 @@ pub enum Error { #[error("SDK misconfigured: {0}")] Config(String), /// The request cannot succeed as written on any node: the SDK refused it before sending - /// it, because no node serves it or no answer to it verifies as the requested result + /// it, because its query syntax or bounds are invalid, no node serves it, or no answer verifies as the requested result /// type, or a fresh verified answer showed that the result cannot be returned as that /// type (for example several documents for a single-document fetch). /// diff --git a/packages/rs-sdk/src/platform/query.rs b/packages/rs-sdk/src/platform/query.rs index 74d24fc11e0..bcca377f85c 100644 --- a/packages/rs-sdk/src/platform/query.rs +++ b/packages/rs-sdk/src/platform/query.rs @@ -408,7 +408,7 @@ impl Query for DocumentHistoryQuery { .limit .map(u16::try_from) .transpose() - .map_err(|_| Error::Generic("history limit out of bounds".to_owned()))?; + .map_err(|_| Error::InvalidRequest("history limit out of bounds".to_owned()))?; DocumentHistoryDriveQuery { contract_id: self.data_contract_id.to_buffer(), document_type_name: self.document_type_name.clone(), @@ -416,7 +416,11 @@ impl Query for DocumentHistoryQuery { filter: self.filter.clone(), limit, } - .validate()?; + .validate() + .map_err(|error| match error { + drive::error::Error::Query(_) => Error::InvalidRequest(error.to_string()), + other => Error::Drive(other), + })?; let filter = match self.filter { DocumentHistoryFilter::StartAtTime(time) => Filter::StartAtMs(time), DocumentHistoryFilter::StartAfter { time_ms, revision } => { @@ -1825,6 +1829,48 @@ mod history_query_tests { assert_eq!(result, expected); } + #[test] + fn should_classify_invalid_history_selectors_as_invalid_requests() { + let request_settings = Default::default(); + let settings = QuerySettings { + request_settings: &request_settings, + protocol_version: PlatformVersion::latest(), + verified_protocol_version: 0, + prove: true, + }; + let invalid = [ + (DocumentHistoryFilter::StartAtTime(0), Some(0)), + (DocumentHistoryFilter::StartAtTime(0), Some(11)), + (DocumentHistoryFilter::StartAtTime(0), Some(u32::MAX)), + (DocumentHistoryFilter::Revision(1), Some(2)), + (DocumentHistoryFilter::StartAtRevision(0), Some(1)), + ]; + for (filter, limit) in invalid { + let query = DocumentHistoryQuery { + data_contract_id: [1; 32].into(), + document_type_name: "note".into(), + document_id: [2; 32].into(), + filter, + limit, + }; + assert!( + matches!(query.query(&settings), Err(Error::InvalidRequest(_))), + "{query:?}: {:?}", + query.query(&settings) + ); + } + for limit in [None, Some(1), Some(10)] { + let query = DocumentHistoryQuery { + data_contract_id: [1; 32].into(), + document_type_name: "note".into(), + document_id: [2; 32].into(), + filter: DocumentHistoryFilter::StartAtTime(0), + limit, + }; + assert!(query.query(&settings).is_ok()); + } + } + #[test] fn should_report_oversized_history_limits_as_request_errors() { let request_settings = Default::default(); @@ -1843,7 +1889,7 @@ mod history_query_tests { limit: Some(limit), }; assert!( - matches!(query.query(&settings), Err(Error::Generic(message)) + matches!(query.query(&settings), Err(Error::InvalidRequest(message)) if message == "history limit out of bounds") ); } diff --git a/packages/rs-unified-sdk-jni/Cargo.toml b/packages/rs-unified-sdk-jni/Cargo.toml index 9f5b2413f06..bf80556772e 100644 --- a/packages/rs-unified-sdk-jni/Cargo.toml +++ b/packages/rs-unified-sdk-jni/Cargo.toml @@ -14,6 +14,8 @@ crate-type = ["cdylib"] [dependencies] jni = "0.21" rs-sdk-ffi = { path = "../rs-sdk-ffi" } +dpp = { path = "../rs-dpp" } +serde_json = "1.0" platform-wallet-ffi = { path = "../rs-platform-wallet-ffi" } log = "0.4" zeroize = "1" @@ -26,9 +28,6 @@ dashcore = { workspace = true } # Anchors the cross-language golden-fixture test to the canonical DashPay # contract id, so the mirrored Kotlin constant can't drift undetected. dashpay-contract = { path = "../dashpay-contract" } -# Builds the state-transition fixtures whose parsed blobs are the goldens -# shared with the Kotlin `StateTransitionParserTest`. -dpp = { path = "../rs-dpp" } [features] default = ["shielded"] diff --git a/packages/rs-unified-sdk-jni/src/transactions.rs b/packages/rs-unified-sdk-jni/src/transactions.rs index f00982c1247..e41f025b5ff 100644 --- a/packages/rs-unified-sdk-jni/src/transactions.rs +++ b/packages/rs-unified-sdk-jni/src/transactions.rs @@ -40,11 +40,17 @@ use crate::pubkey_rows::decode_update_pubkeys_blob; use crate::support::{guard, net_from_ord, take_pwffi_error, throw_sdk_exception}; +use dpp::platform_value::string_encoding::Encoding; +use dpp::prelude::Identifier; use jni::objects::{JByteArray, JClass, JString}; use jni::sys::{jboolean, jint, jlong, jstring}; use jni::JNIEnv; use platform_wallet_ffi::handle::Handle; use platform_wallet_ffi::identity_registration_with_signer::IdentityPubkeyFFI; +use platform_wallet_ffi::{ + DocumentEraseNotSubmittedReasonFFI as Reason, DocumentEraseOutcomeKindFFI as Kind, + DocumentLifecycleObservationFFI, DocumentLifecycleObservationTagFFI as State, +}; use rs_sdk_ffi::SignerHandle; use std::ffi::{CStr, CString}; use std::os::raw::c_char; @@ -746,71 +752,102 @@ 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. +/// Marshal the wallet's single erase operation; selection and submission policy +/// stay in Rust. The caller receives typed-outcome JSON, not an echoed id. #[no_mangle] #[allow(clippy::too_many_arguments)] -pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TransactionsNative_documentErase( +pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TransactionsNative_documentEraseAndObserve( mut env: JNIEnv, _class: JClass, wallet_handle: jlong, - owner_id: JByteArray, + submitting_identity_id: JByteArray, contract_id: JByteArray, document_type: JString, document_id: JByteArray, - signing_key_id: jint, signer_handle: jlong, -) -> jni::sys::jbyteArray { +) -> jstring { 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 { + let Some(submitter) = read_id32(env, &submitting_identity_id, "submittingIdentityId") + 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 { + let Some(document) = read_id32(env, &document_id, "documentId") else { return ptr::null_mut(); }; - let Some(doc_type) = read_cstring(env, &document_type, "documentType") else { + let Some(document_type) = read_cstring(env, &document_type, "documentType") else { return ptr::null_mut(); }; - - let mut out_id = [0u8; 32]; + let mut out = platform_wallet_ffi::DocumentEraseOutcomeFFI::default(); let result = unsafe { - platform_wallet_ffi::platform_wallet_document_erase( + platform_wallet_ffi::platform_wallet_document_erase_and_observe( wallet_handle as Handle, - owner.as_ptr(), + submitter.as_ptr(), contract.as_ptr(), - doc_type.as_ptr(), - doc_id.as_ptr(), - signing_key_id as u32, + document_type.as_ptr(), + document.as_ptr(), signer_handle as *mut SignerHandle, - out_id.as_mut_ptr(), + &mut out, ) }; if take_pwffi_error(env, result) { return ptr::null_mut(); } - - env.byte_array_from_slice(&out_id) - .map(|a| a.into_raw()) + let Ok(json) = erase_outcome_to_json(out) else { + throw_sdk_exception( + env, + 99, + "Erase result unreadable; read history before retrying.", + ); + return ptr::null_mut(); + }; + env.new_string(json) + .map(|string| string.into_raw()) .unwrap_or(ptr::null_mut()) }) } +fn erase_outcome_to_json( + out: platform_wallet_ffi::DocumentEraseOutcomeFFI, +) -> Result { + fn observation(value: DocumentLifecycleObservationFFI) -> serde_json::Value { + let state = match value.state { + State::Unavailable => return serde_json::Value::Null, + State::Active => "ACTIVE", + State::Absent => "ABSENT", + State::Deleted => "DELETED", + State::Erasing => "ERASING", + }; + serde_json::json!({ "state": state, "remaining_revisions": value.remaining_revisions, + "deleted_at_ms": value.deleted_at_ms, "erasing_started_at_ms": value.erasing_started_at_ms, + "erasing_from_time_ms": value.erasing_from_time_ms, "erasing_from_revision": value.erasing_from_revision }) + } + let kind = match out.kind { + Kind::NotSubmitted => "NOT_SUBMITTED", + Kind::Submitted => "SUBMITTED", + Kind::Unset => return Err("missing outcome"), + }; + let reason = match out.reason { + Reason::None => None, + Reason::Active => Some("ACTIVE"), + Reason::Absent => Some("ABSENT"), + Reason::NotNewestOwner => Some("NOT_NEWEST_OWNER"), + Reason::PreflightUnavailable => Some("PREFLIGHT_UNAVAILABLE"), + }; + let owner = if out.reason == Reason::NotNewestOwner { + Some(Identifier::from(out.owner).to_string(Encoding::Base58)) + } else { + None + }; + Ok( + serde_json::json!({ "kind": kind, "reason": reason, "owner": owner, + "before": observation(out.before), "after": observation(out.after) }) + .to_string(), + ) +} + /// 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` @@ -1017,3 +1054,81 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TransactionsNative_ca // `success(null)`), so nothing else to release here. }) } + +#[cfg(test)] +mod erase_outcome_tests { + use super::*; + + #[test] + fn should_preserve_not_submitted_reasons_and_all_observation_states() { + assert!(erase_outcome_to_json(Default::default()).is_err()); + for (reason, expected) in [ + (Reason::Active, "ACTIVE"), + (Reason::Absent, "ABSENT"), + (Reason::NotNewestOwner, "NOT_NEWEST_OWNER"), + (Reason::PreflightUnavailable, "PREFLIGHT_UNAVAILABLE"), + ] { + for (state, expected_state) in [ + (State::Unavailable, None), + (State::Active, Some("ACTIVE")), + (State::Absent, Some("ABSENT")), + (State::Deleted, Some("DELETED")), + (State::Erasing, Some("ERASING")), + ] { + let out = platform_wallet_ffi::DocumentEraseOutcomeFFI { + kind: Kind::NotSubmitted, + reason, + owner: [1; 32], + before: DocumentLifecycleObservationFFI { + state, + remaining_revisions: u64::MAX, + ..Default::default() + }, + ..Default::default() + }; + let json: serde_json::Value = + serde_json::from_str(&erase_outcome_to_json(out).unwrap()).unwrap(); + assert_eq!(json["kind"], "NOT_SUBMITTED"); + assert_eq!(json["reason"], expected); + assert!(json["after"].is_null()); + if reason == Reason::NotNewestOwner { + assert_eq!( + json["owner"], + Identifier::from([1; 32]).to_string(Encoding::Base58) + ); + } else { + assert!(json["owner"].is_null()); + } + if let Some(expected_state) = expected_state { + assert_eq!(json["before"]["state"], expected_state); + assert_eq!(json["before"]["remaining_revisions"], u64::MAX); + } else { + assert!(json["before"].is_null()); + } + } + } + } + + #[test] + fn should_match_the_lifecycle_fixture_decoded_by_kotlin() { + let out = platform_wallet_ffi::DocumentEraseOutcomeFFI { + kind: Kind::Submitted, + before: DocumentLifecycleObservationFFI { + state: State::Erasing, + remaining_revisions: u64::MAX, + deleted_at_ms: 1, + erasing_started_at_ms: 2, + erasing_from_time_ms: 3, + erasing_from_revision: u64::MAX, + }, + ..Default::default() + }; + let actual: serde_json::Value = + serde_json::from_str(&erase_outcome_to_json(out).unwrap()).unwrap(); + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../../kotlin-sdk/sdk/src/test/resources/document_erase_outcome_from_native.json" + )) + .unwrap(); + assert_eq!(actual, expected); + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift index b253238d40a..b2a5dc7ed96 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift @@ -226,6 +226,21 @@ public struct DocumentHistoryLifecycle: Sendable { self.erasingFromRevision = erasingFromRevision } + init(ffi: DocumentLifecycleObservationFFI) throws { + switch ffi.state { + case 1: state = .active + case 2: state = .absent + case 3: state = .deleted + case 4: state = .erasing + default: throw DocumentEraseResultUnreadable() + } + remainingRevisions = ffi.remaining_revisions + deletedAtMs = ffi.deleted_at_ms + erasingStartedAtMs = ffi.erasing_started_at_ms + erasingFromTimeMs = ffi.erasing_from_time_ms + erasingFromRevision = ffi.erasing_from_revision + } + /// 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 diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift index c25452c7c85..a06225fe9dd 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/StateTransitionExtensions.swift @@ -918,103 +918,6 @@ 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/PlatformWallet/DocumentEraseOutcome.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DocumentEraseOutcome.swift new file mode 100644 index 00000000000..d4f768bf3b6 --- /dev/null +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/DocumentEraseOutcome.swift @@ -0,0 +1,62 @@ +import Foundation +import DashSDKFFI + +/// Why Rust did not submit a paid erase. +public enum DocumentEraseNotSubmittedReason: Sendable { + case active + case absent + case notNewestOwner(Identifier) + case preflightUnavailable +} + +/// Submission and lifecycle observation are separate facts. +public enum DocumentEraseOutcome: Sendable { + case notSubmitted(reason: DocumentEraseNotSubmittedReason, before: DocumentHistoryLifecycle?) + case submitted(before: DocumentHistoryLifecycle?, after: DocumentHistoryLifecycle?) + + public var before: DocumentHistoryLifecycle? { + switch self { + case .notSubmitted(_, let before), .submitted(let before, _): return before + } + } + + public var after: DocumentHistoryLifecycle? { + if case .submitted(_, let after) = self { return after } + return nil + } + + init(ffi: DocumentEraseOutcomeFFI) throws { + guard (0...4).contains(ffi.reason) else { + throw DocumentEraseResultUnreadable() + } + func observation(_ value: DocumentLifecycleObservationFFI) throws -> DocumentHistoryLifecycle? { + if value.state == 0 { return nil } + return try DocumentHistoryLifecycle(ffi: value) + } + let before = try observation(ffi.before) + let after = try observation(ffi.after) + switch ffi.kind { + case 1: + let reason: DocumentEraseNotSubmittedReason + switch ffi.reason { + case 1: reason = .active + case 2: reason = .absent + case 3: + var owner = ffi.owner + reason = .notNewestOwner(withUnsafeBytes(of: &owner) { Data($0) }) + case 4: reason = .preflightUnavailable + default: throw DocumentEraseResultUnreadable() + } + self = .notSubmitted(reason: reason, before: before) + case 2: self = .submitted(before: before, after: after) + default: throw DocumentEraseResultUnreadable() + } + } +} + +/// An OK native result could not be decoded; submission failure cannot be inferred. +public struct DocumentEraseResultUnreadable: LocalizedError { + public var errorDescription: String? { + "Erase result unreadable; read history before retrying." + } +} diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index f1b6599554e..dd76967b2b2 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -4995,73 +4995,40 @@ 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, + /// Rust owns eligibility, key selection, one submission and lifecycle observations. + public func eraseDocumentAndObserve( + submittingIdentityId: 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)) + ) async throws -> DocumentEraseOutcome { + guard submittingIdentityId.count == 32, contractId.count == 32, documentId.count == 32 else { + throw PlatformWalletError.invalidParameter("Identifiers must be 32 bytes") } return try await Task.detached(priority: .userInitiated) { [self] in - var documentIdBytes = [UInt8](repeating: 0, count: 32) - + var output = DocumentEraseOutcomeFFI() 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! - ) - } + submittingIdentityId.withUnsafeBytes { owner in + contractId.withUnsafeBytes { contract in + documentType.withCString { type in + documentId.withUnsafeBytes { document in + platform_wallet_document_erase_and_observe( + self.handle, + owner.bindMemory(to: UInt8.self).baseAddress!, + contract.bindMemory(to: UInt8.self).baseAddress!, + type, + document.bindMemory(to: UInt8.self).baseAddress!, + signer.handle, + &output + ) } } } } } - try result.check() - return Data(documentIdBytes) + return try DocumentEraseOutcome(ffi: output) }.value } diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift index c5cf986c4de..5970364bc2d 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/DocumentsView.swift @@ -864,16 +864,29 @@ 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. +/// Display the Rust operation's decision and observations without deciding eligibility. +func describeDocumentEraseOutcome(_ outcome: DocumentEraseOutcome) -> String { + switch outcome { + case .notSubmitted(let reason, _): + let explanation: String + switch reason { + case .active: explanation = "The document is active." + case .absent: explanation = "No retained revisions exist." + case .notNewestOwner(let owner): + explanation = "The newest retained revision belongs to \(owner.toBase58String()). Erase from that identity (Settings β†’ Document Erase)." + case .preflightUnavailable: + explanation = "Lifecycle or ownership could not be read; read history before retrying." + } + return "Erase not submitted. " + explanation + case .submitted(let before, let after): + return "Erase submitted; document absence observed. " + (after.map { + DocumentHistoryLifecycle.describeEraseProgress(before: before, after: $0) + } ?? "Lifecycle not read; query the document history to see what remains.") + } +} + +/// Displays one erase attempt at a time and removes the local row only after +/// a proved observation reports the document absent. struct EraseDocumentView: View { let document: PersistentDocument private let documentIdText: String @@ -901,6 +914,7 @@ struct EraseDocumentView: View { @State private var persistWarning: String? @State private var actionError: DocumentActionErrorBox? + // This hides a button for presentation; Rust re-decides eligibility on every call. private var canSubmitAnother: Bool { guard let lifecycle else { return submissions == 0 } return lifecycle.state == .erasing || lifecycle.state == .deleted @@ -917,7 +931,7 @@ struct EraseDocumentView: View { 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.") + 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. The lifecycle and initial ownership must be read before an erase can be submitted. If either read is unavailable, read history before retrying. 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 { @@ -986,7 +1000,7 @@ struct EraseDocumentView: View { lifecycle = observed } .alert(item: $actionError) { err in - Alert(title: Text("Erase failed"), message: Text(err.message), dismissButton: .default(Text("OK"))) + Alert(title: Text("Erase status"), message: Text(err.message), dismissButton: .default(Text("OK"))) } } } @@ -1004,15 +1018,9 @@ struct EraseDocumentView: View { 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) + guard let walletId = owner.wallet?.walletId, + let wallet = walletManager.wallet(for: walletId) else { + actionError = .init(message: DocumentActionError.noWallet.localizedDescription) return } @@ -1020,55 +1028,38 @@ struct EraseDocumentView: View { 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, + let outcome = try await wallet.eraseDocumentAndObserve( + submittingIdentityId: 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 { + progress = describeDocumentEraseOutcome(outcome) + switch outcome { + case .notSubmitted(_, let before): lifecycle = before + case .submitted(_, let after): + submissions += 1 + lifecycle = after + if after?.state == .absent { persistWarning = DocumentPersistence.applyDelete( - document: document, - modelContext: modelContext + document: document, modelContext: modelContext ) } - } else { - progress = "Lifecycle not read; use Platform Queries β†’ Get Document History to see what remains." } isSubmitting = false } + } catch PlatformWalletError.transactionBroadcastUnconfirmed(_) { + await MainActor.run { + actionError = .init(message: "Erase outcome unknown; do not resubmit automatically; read history first.") + isSubmitting = false + } } catch { await MainActor.run { actionError = .init(message: error.localizedDescription) diff --git a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift index 6779a97b78d..fa181e4a401 100644 --- a/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift +++ b/packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/TransitionDetailView.swift @@ -1231,81 +1231,47 @@ struct TransitionDetailView: View { let signingIdentity = identities.first(where: { $0.identityIdBase58 == selectedIdentityId }) else { throw SDKError.invalidParameter("No identity selected") } - - guard let contractId = formInputs["contractId"], !contractId.isEmpty else { + guard let walletId = signingIdentity.wallet?.walletId, + let wallet = walletManager.wallet(for: walletId) else { + throw SDKError.invalidParameter("Identity has no wallet linkage; cannot erase document history") + } + guard let contractText = formInputs["contractId"], + let contractId = Data.identifier(fromBase58: contractText) 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 { + guard let documentText = formInputs["documentId"], + let documentId = Data.identifier(fromBase58: documentText) 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) - ] + let outcome: DocumentEraseOutcome + do { + outcome = try await wallet.eraseDocumentAndObserve( + submittingIdentityId: signingIdentity.identityId, + contractId: contractId, + documentType: documentType, + documentId: documentId, + signer: signer + ) + } catch PlatformWalletError.transactionBroadcastUnconfirmed(_) { + throw PlatformWalletError.transactionBroadcastUnconfirmed( + "Erase outcome unknown; do not resubmit automatically; read history first." + ) } - - 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." - ] + var result: [String: Any] = ["message": describeDocumentEraseOutcome(outcome)] + let observation: DocumentHistoryLifecycle? + switch outcome { + case .notSubmitted(_, let before): observation = before + case .submitted(_, let after): observation = after } - - return [ - "message": "Erase submitted; document absence observed under proof", - "lifecycle": after.state.rawValue, - "remainingRevisions": after.remainingRevisions, - "progress": DocumentHistoryLifecycle.describeEraseProgress(before: before, after: after) - ] + if let observation { + result["lifecycle"] = observation.state.rawValue + result["remainingRevisions"] = observation.remainingRevisions + } + return result } private func executeDocumentTransfer(sdk: SDK) async throws -> Any { diff --git a/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md b/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md index 466ef778879..7b1b08bcbe2 100644 --- a/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md +++ b/packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md @@ -225,7 +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. | +| DOC-16 | Erase a deleted keep-history document's revisions | Platform | Thorough | πŸ§ͺ | | Routes: **Settings β†’ Platform State Transitions β†’ Document Erase**; **Browse Documents** β†’ document β†’ **β‹―** β†’ **Erase History…**. The erase form calls the Rust wallet read/decide/select/submit/observe operation through `platform_wallet_document_erase_and_observe`. Settings requires an identity linked to a wallet in the active manager; orphaned/import-only identities cannot erase. Rust loads the real contract, rejects ineligible types, skips ACTIVE/ABSENT, and submits nothing when the preflight/ownership read is unavailable. DELETED requires the newest retained revision's owner; ERASING accepts any submitting identity. Keys are selected in Rust using the actual requirement, contract bounds, expiry and supplied signer. A closing-read failure remains a submitted result with unavailable progress; outcome-unknown errors require reading history before any manual retry. Each call submits at most one chunk and never retries automatically. Display skipped/submitted reasons, remaining revisions and cautious progress wording. Needs an erasable keep-history type; not driven on a device or a live provider. | ### 4.8 Tokens β€” `Domain=Token` diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift index f43f620690c..7885bfa87b7 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentHistoryLifecycleTests.swift @@ -1,4 +1,5 @@ import XCTest +import DashSDKFFI @testable import SwiftDashSDK /// The lifecycle block is the only authenticated account of what an erase @@ -6,6 +7,38 @@ import XCTest /// a count or a timestamp the user then acts on. final class DocumentHistoryLifecycleTests: XCTestCase { + func testSubmittedEraseWithUnavailableClosingReadRemainsSubmitted() throws { + var value = DocumentEraseOutcomeFFI() + value.kind = 2 + value.before.state = 4 + value.before.remaining_revisions = UInt64.max + let outcome = try DocumentEraseOutcome(ffi: value) + guard case .submitted(let before, let after) = outcome else { + return XCTFail("Rust reported a submitted erase") + } + XCTAssertEqual(before?.remainingRevisions, UInt64.max) + XCTAssertNil(after) + } + + func testUnknownEraseTagsReportUnreadableResult() { + var value = DocumentEraseOutcomeFFI() + value.kind = 255 + XCTAssertThrowsError(try DocumentEraseOutcome(ffi: value)) { error in + XCTAssertEqual(error.localizedDescription, "Erase result unreadable; read history before retrying.") + } + } + + func testUnavailablePreflightIsNotAnAbsentObservation() throws { + var value = DocumentEraseOutcomeFFI() + value.kind = 1 + value.reason = 4 + let outcome = try DocumentEraseOutcome(ffi: value) + guard case .notSubmitted(.preflightUnavailable, let before) = outcome else { + return XCTFail("Rust did not submit the erase") + } + XCTAssertNil(before) + } + /// 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. diff --git a/packages/swift-sdk/scripts/test_document_erase_preflight.py b/packages/swift-sdk/scripts/test_document_erase_preflight.py index 4968ddb3c23..72ed5d73fa3 100644 --- a/packages/swift-sdk/scripts/test_document_erase_preflight.py +++ b/packages/swift-sdk/scripts/test_document_erase_preflight.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Run the Settings erase route against an offline SDK, without an iOS build.""" +"""Compile the real Settings erase route against a single-operation wallet stub.""" from pathlib import Path import shutil @@ -7,124 +7,140 @@ import tempfile import unittest - -VIEW = (Path(__file__).resolve().parents[1] / "SwiftExampleApp" / - "SwiftExampleApp/Views/TransitionDetailView.swift") +ROOT = Path(__file__).resolve().parents[1] +VIEWS = ROOT / "SwiftExampleApp/SwiftExampleApp/Views" @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() + def test_should_display_rust_outcomes_without_orchestrating_an_erase(self): + source = (VIEWS / "TransitionDetailView.swift").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. + display = (VIEWS / "DocumentsView.swift").read_text() + display_start = display.index("func describeDocumentEraseOutcome(") + display_end = display.index("struct EraseDocumentView:", display_start) harness = r''' import Foundation enum SDKError: Error { case invalidParameter(String) } -enum LifecycleState: String, CaseIterable { case active, deleted, erasing, absent } +enum PlatformWalletError: Error { case transactionBroadcastUnconfirmed(String) } +enum LifecycleState: String { 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." + static func describeEraseProgress(before: Self?, after: Self) -> String { + after.state == .absent ? "Erasure complete" : "Retained revisions remain" } } -struct PublicKey { let id: UInt32 = 0 } +enum DocumentEraseNotSubmittedReason { + case active, absent, preflightUnavailable, notNewestOwner(Data) +} +enum DocumentEraseOutcome { + case notSubmitted(reason: DocumentEraseNotSubmittedReason, before: DocumentHistoryLifecycle?) + case submitted(before: DocumentHistoryLifecycle?, after: DocumentHistoryLifecycle?) + var before: DocumentHistoryLifecycle? { + switch self { case .notSubmitted(_, let b), .submitted(let b, _): return b } + } + var after: DocumentHistoryLifecycle? { + if case .submitted(_, let a) = self { return a }; return nil + } +} +extension Data { + static func identifier(fromBase58: String) -> Data? { Data(repeating: 1, count: 32) } + func toBase58String() -> String { "owner" } +} 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 + let identityId = Data(repeating: 1, count: 32) + var wallet: WalletLink? = WalletLink() } +struct WalletLink { let walletId = Data() } 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 +struct KeychainSigner { init(modelContainer: Int) {} } +struct SDK {} +@MainActor final class Wallet { + let outcome: DocumentEraseOutcome + var calls = 0 + init(_ outcome: DocumentEraseOutcome) { self.outcome = outcome } + func eraseDocumentAndObserve(submittingIdentityId: Data, contractId: Data, + documentType: String, documentId: Data, signer: KeychainSigner) async throws -> DocumentEraseOutcome { + calls += 1 + return outcome } } +@MainActor struct WalletManager { + let loaded: Wallet + func wallet(for: Data) -> Wallet? { loaded } +} +''' + display[display_start:display_end] + r''' @MainActor struct SettingsRoute { let selectedIdentityId = "signer" - let identities = [Identity()] + 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] + let walletManager: WalletManager + func run() 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") + let erasing = DocumentHistoryLifecycle(state: .erasing, remainingRevisions: 50) + let deleted = DocumentHistoryLifecycle(state: .deleted, remainingRevisions: 50) + let outcomes: [DocumentEraseOutcome] = [ + .notSubmitted(reason: .active, before: nil), + .notSubmitted(reason: .absent, before: nil), + .notSubmitted(reason: .preflightUnavailable, before: nil), + .notSubmitted(reason: .notNewestOwner(Data()), before: erasing), + .submitted(before: deleted, after: nil), + .submitted(before: erasing, after: .init(state: .absent, remainingRevisions: 0)), + ] + for outcome in outcomes { + let wallet = Wallet(outcome) + let route = SettingsRoute(identities: [Identity()], walletManager: .init(loaded: wallet)) + let result = try await route.run() + precondition(wallet.calls == 1, "host must call the single Rust operation") + let message = result["message"] as! String + switch outcome { + case .notSubmitted(let reason, let before): + precondition(message.hasPrefix("Erase not submitted")) + if case .absent = reason { precondition(!message.contains("Erasure complete")) } + if let before { + precondition(result["lifecycle"] as? String == before.state.rawValue) + precondition(result["remainingRevisions"] as? UInt64 == before.remainingRevisions) + } else { + precondition(result["lifecycle"] == nil && result["remainingRevisions"] == nil) + } + case .submitted(_, let after): + precondition(message.hasPrefix("Erase submitted")) + if let after { + precondition(result["lifecycle"] as? String == after.state.rawValue) + precondition(result["remainingRevisions"] as? UInt64 == after.remainingRevisions) + } else { + precondition(message.contains("Lifecycle not read")) + precondition(result["lifecycle"] == nil && result["remainingRevisions"] == nil, + "a submitted erase must not display its stale preflight lifecycle") } - } 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) + let wallet = Wallet(outcomes[0]) + var unlinked = Identity(); unlinked.wallet = nil + do { + _ = try await SettingsRoute(identities: [unlinked], walletManager: .init(loaded: wallet)).run() + fatalError("orphaned identity must not reach Rust") + } catch SDKError.invalidParameter(let message) { + precondition(message == "Identity has no wallet linkage; cannot erase document history") } - print("Five erase preflight controls passed") + precondition(wallet.calls == 0) + print("Six typed outcomes and wallet-linkage control passed") } } ''' with tempfile.TemporaryDirectory() as directory: - source_path = Path(directory) / "ErasePreflight.swift" - binary = Path(directory) / "erase-preflight" + source_path = Path(directory) / "EraseRoute.swift" + binary = Path(directory) / "erase-route" source_path.write_text(harness) compiled = subprocess.run( ["swiftc", "-parse-as-library", str(source_path), "-o", str(binary)],