Skip to content
Open
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 @@ -192,12 +192,11 @@ fun SendTransactionScreen(
}
}

// Shielded credits — unspent-note sum from Room, only on a shielded
// build (same source WalletDetailScreen's Shielded row reads).
// Ordinary shielded sends spend account zero.
val hasShielded = remember { Sdk.hasShielded() }
val shieldedBalance by remember(walletIdHex) {
if (hasShielded) {
container.database.shieldedDao().observeUnspentNotesByWallet(walletId)
container.database.shieldedDao().observeUnspentNotesByWalletAccount(walletId, 0)
.map { notes -> notes.sumOf { it.value } }
} else {
MutableStateFlow(0L)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ interface ShieldedDao {
@Query("SELECT * FROM shielded_notes WHERE walletId = :walletId AND isSpent = 0")
fun observeUnspentNotesByWallet(walletId: ByteArray): Flow<List<ShieldedNoteEntity>>

@Query("SELECT * FROM shielded_notes WHERE walletId = :walletId AND accountIndex = :accountIndex AND isSpent = 0")
fun observeUnspentNotesByWalletAccount(
walletId: ByteArray,
accountIndex: Int,
): Flow<List<ShieldedNoteEntity>>

@Upsert
suspend fun upsertNote(note: ShieldedNoteEntity)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.dashfoundation.dashsdk.persistence.entities.AccountEntity
import org.dashfoundation.dashsdk.persistence.entities.IdentityEntity
import org.dashfoundation.dashsdk.persistence.entities.ShieldedNoteEntity
import org.dashfoundation.dashsdk.persistence.entities.ShieldedViewingKeyEntity
import org.dashfoundation.dashsdk.persistence.entities.TokenBalanceEntity
import org.dashfoundation.dashsdk.persistence.entities.TokenEntity
Expand Down Expand Up @@ -42,6 +43,31 @@ class DashDatabaseTest {
db.close()
}

@Test
fun ordinarySendBalanceIncludesOnlyUnspentAccountZeroNotes() = runTest {
val dao = db.shieldedDao()
fun note(id: Int, account: Int, value: Long, spent: Boolean = false, wallet: ByteArray = walletId) =
ShieldedNoteEntity(
nullifier = ByteArray(32) { id.toByte() },
walletId = wallet,
accountIndex = account,
position = id.toLong(),
cmx = ByteArray(32),
blockHeight = 1,
isSpent = spent,
value = value,
noteData = ByteArray(115),
)
dao.upsertNote(note(1, 0x40000000, 900))
assertEquals(0L, dao.observeUnspentNotesByWalletAccount(walletId, 0).first().sumOf { it.value })
dao.upsertNote(note(2, 0, 100))
dao.upsertNote(note(3, 0, 200))
dao.upsertNote(note(4, 1, 500))
dao.upsertNote(note(5, 0, 700, spent = true))
dao.upsertNote(note(6, 0, 800, wallet = ByteArray(32) { 2 }))
assertEquals(300L, dao.observeUnspentNotesByWalletAccount(walletId, 0).first().sumOf { it.value })
}

@Test
fun walletRoundTripsThroughUpsertAndFlow() = runTest {
val wallet = WalletEntity(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -815,8 +815,8 @@ mod tests {
use dpp::tests::fixtures::get_data_contract_fixture;
use platform_version::TryIntoPlatformVersioned;

/// The versions that refuse a tradeable token: the last whose software cannot decode
/// the mode, and protocol version 15, which decodes it but creates none of its state.
/// The versions that refuse a tradeable token: the last whose software cannot decode
/// the mode, and protocol version 15, which decodes it but creates none of its state.
fn protocol_versions_before_tradeable() -> [&'static PlatformVersion; 2] {
[
PlatformVersion::get(14).expect("expected protocol version 14"),
Expand Down
5 changes: 5 additions & 0 deletions packages/rs-platform-wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,8 @@ pub use key_wallet_manager;
// the crate can pass it to `ManagedIdentity` mutation methods
// (`set_dashpay_profile`, `record_dashpay_payment`, `add_identity`, …).
pub use wallet::persister::WalletPersister;

#[cfg(feature = "shielded")]
pub use wallet::shielded::tips::{
is_shielded_identity_account, shielded_identity_account_index, SHIELDED_IDENTITY_ACCOUNT_BASE,
};
194 changes: 172 additions & 22 deletions packages/rs-platform-wallet/src/wallet/platform_wallet.rs

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ pub struct NetworkShieldedCoordinator {
/// other way round.
lifecycle: tokio::sync::Mutex<()>,

/// Clear waits for operations that bind/flush viewing keys or spend from
/// extracted notes. Separate from `lifecycle`, which bind takes internally.
/// Lock order: `operation_admission` → `lifecycle` → `store`.
operation_admission: RwLock<()>,

/// Wallets whose per-subwallet store state has been successfully
/// hydrated from the host's persisted snapshot this session
/// (`restore_for_wallet` completed without error after the
Expand Down Expand Up @@ -420,6 +425,7 @@ impl NetworkShieldedCoordinator {
progress_handler: std::sync::Mutex::new(None),
tree_progress_handler: std::sync::Mutex::new(None),
lifecycle: tokio::sync::Mutex::new(()),
operation_admission: RwLock::new(()),
hydrated: RwLock::new(std::collections::BTreeSet::new()),
clear_generation: std::sync::atomic::AtomicU64::new(0),
}
Expand All @@ -441,6 +447,23 @@ impl NetworkShieldedCoordinator {
self.network
}

/// Refuse a wallet of another network. A bind derives the wallet's
/// viewing keys for the wallet's network: registered on this coordinator
/// they would be scanned for on another network's chain, so the bind
/// would succeed and the wallet would never see a note.
pub(crate) fn ensure_network(
&self,
wallet_network: dashcore::Network,
) -> Result<(), PlatformWalletError> {
if self.network != wallet_network {
return Err(PlatformWalletError::InvalidParameter(format!(
"the shielded coordinator is for {:?}, this wallet for {:?}",
self.network, wallet_network
)));
}
Ok(())
}

/// Install (or replace) the per-chunk progress handler. The
/// callback runs from inside `sync_shielded_notes`'s chunk loop
/// — once per ~2048 notes processed — so keep it cheap. Used by
Expand Down Expand Up @@ -679,6 +702,12 @@ impl NetworkShieldedCoordinator {
}
}

/// Acquire before wallet placement/configuration locks; retain through persistence
/// and the operation result so Clear cannot delete state while it is still in use.
pub(crate) async fn operation_guard(&self) -> tokio::sync::RwLockReadGuard<'_, ()> {
self.operation_admission.read().await
}

/// [`register_wallet`](Self::register_wallet)'s body, with the
/// lifecycle mutex already held by the caller's transaction.
async fn register_locked(
Expand Down Expand Up @@ -1222,6 +1251,7 @@ impl NetworkShieldedCoordinator {
/// stays populated, and the next cold resync would gate-skip every
/// re-downloaded position against the stale `tree_size`.
pub async fn clear(&self) -> Result<(), crate::error::PlatformWalletError> {
let _operations = self.operation_admission.write().await;
// Held across the whole Clear, store reset included, so no bind
// install can be halfway through its transaction here: one that
// already registered would otherwise restore its pre-Clear
Expand Down
4 changes: 4 additions & 0 deletions packages/rs-platform-wallet/src/wallet/shielded/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ pub mod prover;
pub mod seed_pool;
pub mod store;
pub mod sync;
pub mod tips;
pub use tips::{
is_shielded_identity_account, shielded_identity_account_index, SHIELDED_IDENTITY_ACCOUNT_BASE,
};
#[cfg(test)]
mod viewing_key_bind_tests;
#[cfg(test)]
Expand Down
Loading
Loading