diff --git a/packages/rs-platform-wallet-storage/src/sqlite/persister.rs b/packages/rs-platform-wallet-storage/src/sqlite/persister.rs index fb4080cc63c..0a4fd87ff01 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/persister.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/persister.rs @@ -444,9 +444,10 @@ impl SqlitePersister { /// database restored from a backup and reloaded clean reports clean. A /// `load()` that returns `Err` leaves it empty — the error is the /// verdict there, not a partial tally. - /// [`load_unowned_identities`](Self::load_unowned_identities) *adds* - /// into the current snapshot, so its counts read as "since the last - /// `load()`". Reading does not clear. The point read + /// [`load_unowned_identities`](Self::load_unowned_identities) and + /// [`asset_lock_status`](Self::asset_lock_status) *add* into the current + /// snapshot, so their counts read as "since the last `load()`". Reading + /// does not clear. The point read /// [`get_core_tx_record`](PlatformWalletPersistence::get_core_tx_record) /// is the exception: its tolerated drift is logged and never tallied, /// because one read per transaction folded into a per-load snapshot @@ -634,6 +635,41 @@ impl SqlitePersister { prune_backups_in(dir, policy) } + /// One asset lock's persisted status by outpoint, `Consumed` rows + /// included, or `None` when `wallet_id` stored none for it. + /// + /// `load()` does not rehydrate a consumed lock without an operation ID, + /// so a lock missing from the live wallet after a reopen may have been + /// spent or never stored here; + /// this read tells them apart. A wallet delete removes every row, so a + /// re-imported wallet reads `None` for locks it held before. + /// + /// Reads the *committed* table: in [`FlushMode::Manual`] a row still in + /// the write buffer is not visible yet. + /// + /// Status drift between the typed column and the lifecycle blob follows + /// the load policy: under [`LoadPolicy::Strict`] it is + /// [`WalletStorageError::AssetLockStatusMismatch`]; under + /// [`LoadPolicy::Recovery`] the read returns the reconciled status + /// (consumption is sticky) and *adds* one `AssetLockStatusDrift` to + /// [`last_load_degradation`](Self::last_load_degradation). The tally + /// counts reads, not rows: reading the same drifted lock again counts it + /// again. + pub fn asset_lock_status( + &self, + wallet_id: &WalletId, + outpoint: &dashcore::OutPoint, + ) -> Result< + Option, + WalletStorageError, + > { + let conn = self.conn()?; + let ctx = LoadCtx::new(self.config.load_policy); + let status = schema::asset_locks::status_of(&conn, wallet_id, outpoint, &ctx)?; + self.merge_load_degradation(ctx.degradation()); + Ok(status) + } + /// Read every identity that belongs to NO wallet, each already /// carrying its own persisted public keys. /// diff --git a/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs b/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs index e0bb8032e06..57b827c88c6 100644 --- a/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs +++ b/packages/rs-platform-wallet-storage/src/sqlite/schema/asset_locks.rs @@ -428,6 +428,47 @@ pub fn load_state( Ok(out) } +/// One asset lock's status by outpoint, **including** a terminal `Consumed` +/// row, or `None` when `wallet_id` has no row for it. The point lookup a +/// host uses to tell a lock this wallet spent from one it never stored: +/// [`load_unconsumed`] drops a consumed lock without an operation ID, so +/// absence there proves nothing. +/// Decoding and status drift follow [`load_state`]. +pub fn status_of( + conn: &Connection, + wallet_id: &WalletId, + outpoint: &OutPoint, + ctx: &LoadCtx, +) -> Result, WalletStorageError> { + let op_bytes = blob::encode_outpoint(outpoint)?; + let mut stmt = conn.prepare_cached( + "SELECT length(outpoint), outpoint, account_index, length(lifecycle_blob), lifecycle_blob, status, operation_id, shielded_recipient \ + FROM asset_locks WHERE wallet_id = ?1 AND outpoint = ?2", + )?; + let mut rows = stmt.query(params![wallet_id.as_slice(), &op_bytes[..]])?; + let Some(row) = rows.next()? else { + return Ok(None); + }; + blob::check_size(row.get::<_, i64>(0)?)?; + let op_bytes: Vec = row.get(1)?; + let account_index: i64 = row.get(2)?; + blob::check_size(row.get::<_, i64>(3)?)?; + let blob_bytes: Vec = row.get(4)?; + let status: String = row.get(5)?; + let operation_id: Option> = row.get(6)?; + let shielded_recipient: Option> = row.get(7)?; + let (_, _, tracked) = decode_row( + &op_bytes, + account_index, + &blob_bytes, + &status, + operation_id, + shielded_recipient, + ctx, + )?; + Ok(Some(tracked.status)) +} + /// Status-filtered rehydration feed: every asset lock **except** terminal /// `Consumed` rows without an operation ID, bucketed by account index. /// Consumed wallet-drain locks are non-actionable recovery tombstones: retaining diff --git a/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs b/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs index 3c3a14eafa3..52fd8143443 100644 --- a/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs +++ b/packages/rs-platform-wallet-storage/tests/integration/sqlite_asset_locks_filter.rs @@ -447,3 +447,174 @@ fn sqlite_advertises_asset_lock_shielded_recipients() { fn recipient_bytes(seed_byte: u8) -> ShieldedRecipientRaw { [seed_byte; SHIELDED_RECIPIENT_SIZE] } + +/// The point read sees a `Consumed` row the rehydration feed drops, keeps +/// it across a reopen, returns a live row's status, and `None` for an +/// outpoint the wallet never stored or another wallet's row. +#[test] +fn should_read_an_asset_locks_status_by_outpoint_including_consumed_after_reopen() { + let (persister, _tmp, path) = fresh_persister(); + let w = wid(0xA6); + let other = wid(0xA7); + ensure_wallet_meta(&persister, &w); + ensure_wallet_meta(&persister, &other); + let consumed = op(0x30); + let live = op(0x31); + let mut cs = AssetLockChangeSet::default(); + cs.asset_locks + .insert(consumed, entry(consumed, AssetLockStatus::Consumed)); + cs.asset_locks + .insert(live, entry(live, AssetLockStatus::InstantSendLocked)); + persister + .store( + w, + platform_wallet::changeset::PlatformWalletChangeSet { + asset_locks: Some(cs), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!( + persister.asset_lock_status(&w, &consumed).unwrap(), + Some(AssetLockStatus::Consumed) + ); + drop(persister); + + let p2 = reopen(&path); + assert_eq!( + p2.asset_lock_status(&w, &consumed).unwrap(), + Some(AssetLockStatus::Consumed), + "a consumed row reads back after a reopen" + ); + assert_eq!( + p2.asset_lock_status(&w, &live).unwrap(), + Some(AssetLockStatus::InstantSendLocked) + ); + assert_eq!(p2.asset_lock_status(&w, &op(0x32)).unwrap(), None); + assert_eq!( + p2.asset_lock_status(&other, &consumed).unwrap(), + None, + "another wallet's row is not this wallet's" + ); +} + +/// Plant a row whose typed status says `consumed` while its lifecycle blob +/// says `Built`. +fn plant_consumed_column_over_built_blob( + persister: &platform_wallet_storage::SqlitePersister, + w: &platform_wallet::wallet::platform_wallet::WalletId, + outpoint: OutPoint, +) { + use platform_wallet_storage::sqlite::schema::blob; + ensure_wallet_meta(persister, w); + let conn = persister.lock_conn_for_test(); + conn.execute( + "INSERT INTO asset_locks \ + (wallet_id, outpoint, status, account_index, identity_index, amount_duffs, lifecycle_blob) \ + VALUES (?1, ?2, 'consumed', 0, 0, 1000, ?3)", + rusqlite::params![ + w.as_slice(), + blob::encode_outpoint(&outpoint).unwrap(), + asset_locks::encode_entry_for_test(&entry(outpoint, AssetLockStatus::Built)).unwrap() + ], + ) + .expect("plant asset-lock status drift"); +} + +/// Status drift through the point read: Strict refuses it with the named +/// error; Recovery returns the sticky `Consumed` and adds one drift per +/// read to the degradation snapshot. +#[test] +fn should_follow_the_load_policy_when_a_point_read_meets_status_drift() { + use platform_wallet_storage::LoadSite; + let w = wid(0xA8); + let drifted = op(0x40); + + let (strict, _tmp, _path) = fresh_persister(); + plant_consumed_column_over_built_blob(&strict, &w, drifted); + assert!(matches!( + strict.asset_lock_status(&w, &drifted), + Err(WalletStorageError::AssetLockStatusMismatch { .. }) + )); + assert!(!strict.last_load_degradation().degraded); + + let (recovery, _tmp, _path) = common::fresh_recovery_persister(|strict| { + plant_consumed_column_over_built_blob(strict, &w, drifted); + }); + for reads in 1..=2 { + assert_eq!( + recovery.asset_lock_status(&w, &drifted).unwrap(), + Some(AssetLockStatus::Consumed), + "consumption is sticky" + ); + let degradation = recovery.last_load_degradation(); + assert!(degradation.degraded); + assert_eq!( + degradation + .by_site + .get(&LoadSite::AssetLockStatusDrift) + .copied(), + Some(reads), + "{:?}", + degradation.by_site + ); + assert_eq!(degradation.total, reads); + } +} + +/// A `DrainCompleted` lock reads back as exactly that, though its typed +/// column projects it to `consumed`. +#[test] +fn should_read_a_drain_completed_lock_as_drain_completed() { + let (persister, _tmp, _path) = fresh_persister(); + let w = wid(0xA9); + ensure_wallet_meta(&persister, &w); + let drained = op(0x41); + let mut cs = AssetLockChangeSet::default(); + cs.asset_locks + .insert(drained, entry(drained, AssetLockStatus::DrainCompleted)); + persister + .store( + w, + platform_wallet::changeset::PlatformWalletChangeSet { + asset_locks: Some(cs), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!( + persister.asset_lock_status(&w, &drained).unwrap(), + Some(AssetLockStatus::DrainCompleted) + ); + assert!(!persister.last_load_degradation().degraded); +} + +/// Under `FlushMode::Manual` a stored lock is in the write buffer, not the +/// committed table: the point read sees none until the flush. +#[test] +fn should_not_see_a_buffered_lock_until_its_flush() { + let (persister, _tmp, _path) = common::fresh_persister_with_mode(common::FlushMode::Manual); + let w = wid(0xAA); + ensure_wallet_meta(&persister, &w); + let buffered = op(0x42); + let mut cs = AssetLockChangeSet::default(); + cs.asset_locks.insert( + buffered, + entry(buffered, AssetLockStatus::InstantSendLocked), + ); + persister + .store( + w, + platform_wallet::changeset::PlatformWalletChangeSet { + asset_locks: Some(cs), + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(persister.asset_lock_status(&w, &buffered).unwrap(), None); + persister.flush(w).unwrap(); + assert_eq!( + persister.asset_lock_status(&w, &buffered).unwrap(), + Some(AssetLockStatus::InstantSendLocked) + ); +}