Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
*
Expand Down Expand Up @@ -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 " +
Expand Down Expand Up @@ -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"),
Expand All @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
@@ -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"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
Expand Down
Loading
Loading