Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,52 @@ class FfiSmokeTest {
}
}

/**
* Native Clear has the persistence bridge wipe its shielded rows, so
* `SHIELDED_STATE_WIPE` holds only for a bridge that overrides
* `onWipeShieldedState` AND declares the bit: JNI leaves the slot
* unwired for an inherited body, and Rust strips an undeclared bit.
*/
@Test
fun shieldedStateWipeCapabilityNeedsTheOverrideAndTheDeclaration() {
NativeLoader.ensureLoaded()
val bit = NativePersistenceBridge.CAPABILITY_SHIELDED_STATE_WIPE
fun effective(bridge: NativePersistenceBridge): Boolean =
WalletManagerNative.nativeEffectivePersistenceCapabilityBits(bridge) and bit == bit

assertFalse(
"declared, inherited body",
effective(object : NativePersistenceBridge() {
override fun persistenceCapabilitiesVersion(): Int = 1
override fun persistenceCapabilitiesBits(): Long = bit
}),
)
assertFalse(
"overridden, not declared",
effective(object : NativePersistenceBridge() {
override fun persistenceCapabilitiesVersion(): Int = 1
override fun onWipeShieldedState(network: Int): Int = 0
}),
)
assertTrue(
"overridden and declared",
effective(object : NativePersistenceBridge() {
override fun persistenceCapabilitiesVersion(): Int = 1
override fun persistenceCapabilitiesBits(): Long = bit
override fun onWipeShieldedState(network: Int): Int = 0
}),
)
val db = DashDatabase.createInMemory(ApplicationProvider.getApplicationContext())
try {
assertTrue(
"the Room handler",
effective(PlatformWalletPersistenceHandler(db, Dispatchers.Unconfined)),
)
} finally {
db.close()
}
}

/**
* Rust↔Kotlin persistence-descriptor lockstep. The trampolines resolve
* each bridge method by (name, descriptor) only when its slot first
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,15 @@ abstract class NativePersistenceBridge {
*/
const val CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE: Long = 1L shl 15

/**
* `PersistenceCapabilities::SHIELDED_STATE_WIPE` (bit 16,
* `0x10000`): the store deletes its shielded rows for a network when
* native Clear asks ([onWipeShieldedState]). Native Clear refuses
* without it. The one Kotlin home of this bit, aliased by the public
* diagnostic mirror.
*/
const val CAPABILITY_SHIELDED_STATE_WIPE: Long = 1L shl 16

/**
* Packed row widths of [onPersistPrivateContactScanState] and
* [onLoadPrivateContactScanState]: a read position is the identity
Expand Down Expand Up @@ -916,6 +925,22 @@ abstract class NativePersistenceBridge {
fvkBytes: ByteArray,
): Int = 0

/**
* `on_wipe_shielded_state_fn`. Descriptor `(I)I`. Delete every shielded
* row kept for [network] (an `FFINetwork` discriminant,
* [org.dashfoundation.dashsdk.Network.ffiValue]): the viewing keys,
* notes, outgoing notes, sync watermarks and activity of every wallet on
* that network, loaded or not, in one transaction. Return 0 once they are
* gone; non-zero leaves them in place and fails the Clear.
*
* Native Clear calls it once, after its own reset and before it returns,
* with every other shielded operation held out. JNI wires the slot only
* for a subclass that overrides this method, and the store must also
* declare [CAPABILITY_SHIELDED_STATE_WIPE]; the inherited body is never
* called.
*/
open fun onWipeShieldedState(network: Int): Int = -1

// ── Load callbacks ────────────────────────────────────────────────
//
// These return objects rather than `Int`, so [PERSIST_RC_TRANSIENT] and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ class PlatformWalletPersistenceHandler(
CAPABILITY_DPNS_NAME_STATES or
CAPABILITY_TRACKED_ASSET_LOCKS or
CAPABILITY_CORE_SWEEP_REMOVAL or
CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE
CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE or
CAPABILITY_SHIELDED_STATE_WIPE

/**
* The single-thread executor created when no [dispatcher] is injected.
Expand Down Expand Up @@ -2683,6 +2684,47 @@ class PlatformWalletPersistenceHandler(
0
}

/**
* Native Clear's host half: drop the shielded rows of every wallet on
* [network] in one transaction. Scoped by the wallet rows' network rather
* than the loaded fleet, so a same-network wallet that failed restore
* loses its rows too.
*
* Shielded rows carry no wallet FK, so they are enumerated from the
* shielded tables. Rows of a wallet with no wallet row belong to no
* wallet on any network and go too, as a wallet deletion would have
* taken them. Rows of a wallet whose network is not yet known fail the
* wipe with nothing deleted: they may be [network]'s, and reporting
* success with them in place would let a later bind restore them.
*/
override fun onWipeShieldedState(network: Int): Int = guarded {
runBlockingResult {
database.withTransaction {
val dao = database.shieldedDao()
val doomed = ArrayList<ByteArray>()
for (walletId in dao.getShieldedWalletIds()) {
val wallet = database.walletDao().getByWalletId(walletId)
when {
wallet == null -> doomed += walletId
wallet.networkRaw == null -> {
Log.e(TAG, "shielded wipe refused: a wallet with shielded rows has no network")
return@withTransaction 1
}
wallet.networkRaw == network -> doomed += walletId
}
}
Comment on lines +2700 to +2715

@thepastaclaw thepastaclaw Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Resolved at 2352c3c6; see the replies below.

🔴 Blocking: Do not report a successful wipe while unclassified shielded rows remain

The host callback enumerates only wallet metadata rows whose networkRaw matches the requested network. networkRaw is nullable while metadata is being completed, and the shielded tables have no wallet foreign key, so viewing keys, notes, sync state, or activity can exist for a wallet that is absent from this query or still has a null network. The callback then returns success while those rows remain and Clear reports success. A later metadata write can make the surviving rows eligible for restoration, defeating Clear. Classify unresolved or buffered wallet metadata before wiping, or fail closed when any shielded rows cannot be assigned to the requested network. The Swift handler has the same selection defect.

Raised on code unchanged since the last review, and confirmed by an independent pass: If a shielded row exists for wallet W while W has no wallet metadata row or its networkRaw is null, clearShielded(N) makes both handlers enumerate no W, yet they return success. The native reset therefore completes while W's viewing key, notes, sync state, or activity remain; if W's metadata is later completed with network N, those rows become restorable on a later load and defeat Clear.

source: gpt-6.1-sol (phase2-reviewer: security-auditor)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2352c3c, in both the Kotlin and Swift handlers. They now enumerate wallet ids from the shielded tables themselves:

  • rows of a wallet whose network is null fail the wipe and nothing is deleted;
  • rows of a wallet on this network are deleted;
  • rows with no wallet row at all are deleted, the same way wallet deletion removes them.

Failing closed on that last case would block shielded use permanently, because no network-locked manager can ever load such a wallet.


🤖 Posted autonomously by Claude on behalf of pasta.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved (re-reviewed at 2352c3c6): Both managed-language handlers now enumerate shielded rows directly, delete orphan rows, and refuse the wipe when a wallet's network is still unknown.

for (walletId in doomed) {
dao.deleteActivityByWallet(walletId)
dao.deleteOutgoingNotesByWallet(walletId)
dao.deleteNotesByWallet(walletId)
dao.deleteSyncStatesByWallet(walletId)
dao.deleteViewingKeysByWallet(walletId)
}
0
}
}
}

// ── Load callbacks ────────────────────────────────────────────────

/**
Expand Down Expand Up @@ -4211,6 +4253,9 @@ class PlatformWalletPersistenceHandler(
internal const val CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE: Long =
NativePersistenceBridge.CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE

internal const val CAPABILITY_SHIELDED_STATE_WIPE: Long =
NativePersistenceBridge.CAPABILITY_SHIELDED_STATE_WIPE

private const val TAG = "DashPersistence"

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ import org.dashfoundation.dashsdk.persistence.entities.ShieldedViewingKeyEntity
@Dao
interface ShieldedDao {

/** Every wallet any shielded table holds a row of. */
@Query(
"SELECT walletId FROM shielded_notes " +
"UNION SELECT walletId FROM shielded_outgoing_notes " +
"UNION SELECT walletId FROM shielded_activities " +
"UNION SELECT walletId FROM shielded_sync_states " +
"UNION SELECT walletId FROM shielded_viewing_keys"
)
suspend fun getShieldedWalletIds(): List<ByteArray>

// MARK: Notes (received, spendable)

@Query("SELECT * FROM shielded_notes WHERE nullifier = :nullifier")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package org.dashfoundation.dashsdk.services

import androidx.room.withTransaction
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
Expand Down Expand Up @@ -385,53 +384,28 @@ class ShieldedService(private val database: DashDatabase) {

/**
* Reset shielded state for the bound wallet — port of Swift
* `ShieldedService.clearLocalState(modelContext:)`. Two ordered halves:
* `ShieldedService.clearLocalState()`.
*
* 1. **Rust-side reset FIRST** via
* [PlatformWalletManager.clearShieldedStorage]
* (`platform_wallet_manager_shielded_clear`): quiesce the background
* sync loop, drop every wallet registration from the network-scoped
* coordinator, empty the shared commitment tree, and reset the
* caught-up cooldown. This MUST run before the Room wipe — the
* coordinator keeps every bound wallet registered, so without it the
* next sync pass's persister callback immediately re-creates the very
* rows we're about to delete. It also resets the on-disk tree size, so
* the post-clear resync cold-rebuilds from index 0 instead of
* gate-skipping every re-downloaded position against a stale tree
* (the frozen-tree / zero-notes desync this Clear exists to fix).
* 2. **Room wipe — every wallet on THIS network** (INCLUDING
* `shielded_sync_states`, the per-subwallet watermark; leaving any
* would let [bind]'s `restore_for_wallet` re-seed a caught-up
* watermark and re-freeze the tree) in one transaction, and zero the
* published counters. Scoped to the active network's wallets
* (`walletDao().getByNetwork`), NOT global: [clearShieldedStorage]
* empties only this network's `shielded_tree_<network>.sqlite`, so
* wiping other networks' rows would drop notes/activity/watermarks
* whose Rust trees are still populated → data loss + Room↔Rust
* divergence on the next network switch. Within this network the wipe
* must cover EVERY wallet (not just the loaded/bound fleet — an
* unloaded same-network wallet's surviving watermark would restore a
* position ahead of the now-empty shared tree on re-bind and
* gate-skip every note, the exact Room↔SQLite watermark-divergence
* freeze this Clear exists to fix).
* 3. **Re-bind + restart sync** — [clearShieldedStorage] dropped every
* coordinator registration and quiesced the sync loop, so nothing
* would resync until the next app relaunch otherwise. Re-run [bind]
* for the mirror wallet (re-registers the viewing keys on the
* now-empty coordinator, its `restore_for_wallet` finding no
* watermark → starts at index 0), then [bindEngine] every OTHER
* loaded wallet — mirror-bind failure does NOT skip the others
* ([bind] swallows its errors; the fleet pass runs regardless, the
* iOS best-effort lesson) — and restart the background loop, so the
* button alone triggers an in-session cold rebuild 0→N for the
* whole fleet.
* 1. **Native Clear** via [PlatformWalletManager.clearShieldedStorage]
* (`platform_wallet_manager_shielded_clear`). It resets the network's
* shielded state in Rust and then, before returning and with every
* other shielded operation held out, has the persistence handler
* delete this network's shielded Room rows
* ([org.dashfoundation.dashsdk.persistence.PlatformWalletPersistenceHandler.onWipeShieldedState]).
* Nothing is deleted here. A failure throws and the published
* counters stay as they were.
* 2. **Re-bind + restart sync** — Clear dropped every coordinator
* registration and quiesced the sync loop, so nothing would resync
* until the next app relaunch otherwise. Re-run [bind] for the mirror
* wallet, then [bindEngine] every OTHER loaded wallet — mirror-bind
* failure does NOT skip the others ([bind] swallows its errors; the
* fleet pass runs regardless, the iOS best-effort lesson) — and
* restart the background loop, so the button alone triggers an
* in-session cold rebuild 0→N for the whole fleet.
*
* Fail-closed: if the Rust reset throws, the exception propagates and the
* Room rows are left intact — the FFI's contract is that the host must
* not drop its persistence while the shared tree may still be populated.
* No-op when unbound.
*/
suspend fun clearLocalState(db: DashDatabase = database) {
suspend fun clearLocalState() {
val walletId = boundWalletId ?: return
// Snapshot bind credentials up front so the re-bind at the end is
// driven off a stable set (bind() retains credentials across its own
Expand All @@ -441,48 +415,15 @@ class ShieldedService(private val database: DashDatabase) {
val accounts = _boundAccounts.value.ifEmpty { listOf(0) }

// A bound service must have a manager (both are set together in
// bind, cleared together in unbind). If it doesn't, the Rust-side
// reset can't run — fail LOUDLY rather than silently wiping only
// Room and leaving the on-disk tree at its full size (which would
// re-freeze the tree on the next cold resync).
// bind, cleared together in unbind).
if (mgr == null) {
error("Shielded clear: bound wallet has no manager — cannot reset the Rust store")
}

// Rust-side reset FIRST (empties the on-disk commitment tree +
// watermarks, durably). This THROWS on failure (native FFI error →
// DashSDKException), and we deliberately do NOT catch it: the Room
// wipe below must not run unless the tree was truly reset, else the
// host drops its rows while the shared tree stays populated and the
// next resync gate-skips every position. Fail-closed by propagation.
val walletIdHex = walletId.joinToString("") { "%02x".format(it) }
android.util.Log.i(TAG, "Shielded clear: resetting Rust store for $walletIdHex")
android.util.Log.i(TAG, "Shielded clear: resetting shielded state for $walletIdHex")
mgr.clearShieldedStorage()
android.util.Log.i(TAG, "Shielded clear: Rust store reset OK; wiping Room rows")

// Wipe every wallet on THIS network, but NOT other networks'. `mgr`
// is network-scoped and its shielded tree
// (`shielded_tree_<network>.sqlite`) is per-network, so the Rust
// reset above emptied only the ACTIVE network's SHARED tree. A
// global deleteAll* would drop other networks' notes/activity/
// watermarks while their Rust trees stay populated → Room/Rust
// divergence + data loss on the next network switch. Scope to the
// network via `walletDao().getByNetwork` — NOT `mgr.wallets`, which
// only holds the successfully-loaded fleet: a same-network wallet
// that failed restore still has Room rows, and a surviving watermark
// would restore a position ahead of the now-empty tree on re-bind
// and gate-skip every note (see doc, step 2).
val networkWalletIds = db.walletDao()
.getByNetwork(mgr.network.ffiValue)
.map { it.walletId }
db.withTransaction {
for (wid in networkWalletIds) {
db.shieldedDao().deleteActivityByWallet(wid)
db.shieldedDao().deleteOutgoingNotesByWallet(wid)
db.shieldedDao().deleteNotesByWallet(wid)
db.shieldedDao().deleteSyncStatesByWallet(wid)
}
}
android.util.Log.i(TAG, "Shielded clear: native and Room shielded state reset")
_state.update { it.copy(shieldedBalance = 0, totalScanned = 0, totalNewNotes = 0) }

// Re-bind + restart so the cold rebuild runs now, not just after a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ data class PlatformWalletPersistenceCapabilities(
*/
const val PRIVATE_CONTACT_REQUEST_SCAN_STATE: Long =
NativePersistenceBridge.CAPABILITY_PRIVATE_CONTACT_REQUEST_SCAN_STATE
/**
* The store deletes its shielded rows for a network when native
* Clear asks, which [PlatformWalletManager.clearShieldedStorage]
* requires. Mirrors `PersistenceCapabilities::SHIELDED_STATE_WIPE`.
*/
const val SHIELDED_STATE_WIPE: Long =
NativePersistenceBridge.CAPABILITY_SHIELDED_STATE_WIPE
}
}

Expand Down Expand Up @@ -1628,21 +1635,23 @@ class PlatformWalletManager(
}

/**
* Reset the Rust-side shielded state on this manager — port of Swift's
* Reset the shielded state of this manager's network — port of Swift's
* `PlatformWalletManager.clearShielded()`
* (`PlatformWalletManagerShieldedSync.swift`). Quiesces the background
* sync loop, drops every wallet registration from the network-scoped
* coordinator, empties the shared commitment tree, and resets the
* caught-up cooldown, so the next [bindShielded] + sync cold-rebuilds
* from index 0.
* coordinator, empties the shared commitment tree, resets the caught-up
* cooldown, and has the persistence handler delete this network's
* shielded Room rows before returning, with every other shielded
* operation held out. The next [bindShielded] + sync cold-rebuilds from
* index 0. The caller deletes nothing itself.
*
* The per-network SQLite file stays on disk (its contents are reset);
* the host must wipe its own Room rows AFTER this succeeds
* ([org.dashfoundation.dashsdk.services.ShieldedService.clearLocalState]
* orders the two). Throws on a store-reset failure so the caller can
* fail closed and keep its rows rather than orphan a still-populated
* tree. Only meaningful on a shielded build ([Sdk.hasShielded]); the
* native entry point is absent otherwise and this throws.
* Throws when the persistence handler does not declare
* [PlatformWalletPersistenceCapabilities.SHIELDED_STATE_WIPE] (nothing is
* reset), when the native reset fails, or when the Room wipe fails after
* the native reset; in the last case binds are refused until a retried
* Clear succeeds. Only meaningful on a shielded build
* ([Sdk.hasShielded]); the native entry point is absent otherwise and
* this throws.
*/
suspend fun clearShieldedStorage() = withContext(Dispatchers.IO) {
mapNativeErrors { WalletManagerNative.shieldedClear(managerHandle) }
Expand Down
Loading
Loading