diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt index f662cfae2fe..7d6ba3275c5 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/ffi/NativePersistenceBridge.kt @@ -1117,7 +1117,9 @@ class ProviderSpecialTxRestoreData( * `onWalletChangesetUtxoAdded`); [scriptPubKey] is the output script — * the Rust side reconstructs the address from `(script, network)`, so * no address string crosses the FFI. `isTrusted` is runtime-only and - * recomputed on the next SPV pass (not carried). + * recomputed on the next SPV pass (not carried). [parentContext] / + * [parentBlockHeight] carry the creating transaction's row so the loader + * can raise a coin that lags its own transaction's confirmation. */ class UtxoRestoreData( @JvmField val typeTag: Byte, @@ -1136,6 +1138,14 @@ class UtxoRestoreData( @JvmField val isConfirmed: Boolean, @JvmField val isInstantLocked: Boolean, @JvmField val isLocked: Boolean, + /** + * The stored context of the coin's creating transaction, copied as-is + * (0=mempool, 1=instantSend, 2=inBlock, 3=inChainLockedBlock; 0 when + * there is no row). The Rust loader decides what it means for the coin. + */ + @JvmField val parentContext: Int, + /** The stored block height of the coin's creating transaction; 0 when none. */ + @JvmField val parentBlockHeight: Int, ) /** diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt index 62dfdf82093..2464cbf95ca 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandler.kt @@ -3230,10 +3230,21 @@ class PlatformWalletPersistenceHandler( * except here the single row is skipped rather than failing the * whole load, matching this builder's per-row-skip convention. */ + /** The txid of the transaction that created this coin: the row's own column, else the outpoint's txid half. */ + private fun TxoEntity.creatingTxid(): ByteArray = txid ?: outpoint.copyOfRange(0, minOf(32, outpoint.size)) + private suspend fun buildUtxoRestoreData(walletId: ByteArray): Array { val rows = database.txoDao().observeUnspentByWallet(walletId).first() if (rows.isEmpty()) return emptyArray() val out = ArrayList(rows.size) + // The creating transactions' rows, read once for the whole batch: + // each coin carries its transaction's stored context so the Rust + // loader can raise a coin that lags its own transaction's + // confirmation. + val parentByTxid = chunkedFlatMap( + rows.map { it.creatingTxid() }.distinctBy { it.toHex() }, + ) { database.transactionDao().getConfirmationsByTxids(it) } + .associateBy { it.txid.toHex() } // Per-call memo of address → account row (a wallet's UTXOs // cluster on few addresses/accounts; avoids N duplicate joins). val accountByAddress = HashMap() @@ -3281,11 +3292,12 @@ class PlatformWalletPersistenceHandler( continue } val typeTag = account.accountType.toByte() - val prevTxid = txo.txid ?: txo.outpoint.copyOfRange(0, minOf(32, txo.outpoint.size)) + val prevTxid = txo.creatingTxid() if (prevTxid.size != 32) { Log.w(TAG, "load: skipping UTXO with ${prevTxid.size}-byte txid") continue } + val parent = parentByTxid[prevTxid.toHex()] out.add( UtxoRestoreData( typeTag = typeTag, @@ -3304,6 +3316,8 @@ class PlatformWalletPersistenceHandler( isConfirmed = txo.isConfirmed, isInstantLocked = txo.isInstantLocked, isLocked = txo.isLocked, + parentContext = parent?.context ?: 0, + parentBlockHeight = parent?.blockHeight ?: 0, ), ) } diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/TransactionDao.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/TransactionDao.kt index c72a5569832..5a185af0eed 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/TransactionDao.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/persistence/dao/TransactionDao.kt @@ -102,6 +102,14 @@ interface TransactionDao { @Query("SELECT * FROM transactions WHERE txid IN (:txids)") suspend fun getByTxids(txids: List): List + /** + * The confirmation columns of the given transactions, without their + * raw bytes — what the wallet load needs for each coin's creating + * transaction. Chunked by the caller like [getByTxids]. + */ + @Query("SELECT txid, context, blockHeight FROM transactions WHERE txid IN (:txids)") + suspend fun getConfirmationsByTxids(txids: List): List + /** * Delete a sweep batch's losers in one statement, after every hold on * their inputs is in place: the FK cascade takes any still-attached @@ -159,3 +167,11 @@ interface TransactionDao { } } } + +/** The confirmation columns of one [TransactionEntity] row. */ +class TransactionConfirmation( + val txid: ByteArray, + /** 0=mempool, 1=instantSend, 2=inBlock, 3=inChainLockedBlock. */ + val context: Int, + val blockHeight: Int, +) diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt index cc6dede2141..58233ff98e3 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/persistence/PlatformWalletPersistenceHandlerTest.kt @@ -2189,6 +2189,48 @@ class PlatformWalletPersistenceHandlerTest { ) } + @Test + fun shouldCarryTheCreatingTransactionsStoredContextOnARestoredCoin() = runTest { + // A coin row can lag its own transaction's row: the transaction was + // confirmed through a record that named none of its coins, so only + // the transaction row was rewritten. The restore row carries the + // transaction's stored context and height as-is; the Rust loader + // decides what they mean for the coin. + seedWalletWithAddress(walletId, "yLagAddr") + val txid = ByteArray(32) { 31 } + handler.onChangesetBegin(walletId) + recordTransaction( + handler, + walletId, txid, ByteArray(10) { 4 }, 0, 0, ByteArray(32), + 0, 0, "Standard", 0, 40_000, 0, false, "", 1_700_000_000, + ByteArray(0), 0, + ) + handler.onWalletChangesetUtxoAdded( + walletId, txid, 1, 40_000, "yLagAddr", ByteArray(25) { 6 }, + 0, false, false, false, false, + ) + handler.onChangesetEnd(walletId, success = true) + + val inMempool = handler.onLoadWalletList().single().utxos.single() + assertEquals(0, inMempool.parentContext) + assertEquals(0, inMempool.parentBlockHeight) + + // The block reaches the transaction row only. + handler.onChangesetBegin(walletId) + recordTransaction( + handler, + walletId, txid, ByteArray(10) { 4 }, 2, 500, ByteArray(32) { 7 }, + 1_700_000_500, 0, "Standard", 0, 40_000, 0, false, "", 1_700_000_000, + ByteArray(0), 0, + ) + handler.onChangesetEnd(walletId, success = true) + + val lagging = handler.onLoadWalletList().single().utxos.single() + assertFalse(lagging.isConfirmed) + assertEquals(2, lagging.parentContext) + assertEquals(500, lagging.parentBlockHeight) + } + @Test fun loadWalletListRestoresUnspentUtxosAndExcludesConfirmedSpends() = runTest { // CORE-06 regression: persisted unspent TXOs must come back on diff --git a/packages/rs-platform-wallet-ffi/src/persistence.rs b/packages/rs-platform-wallet-ffi/src/persistence.rs index aba5e2ed668..3b9128ad405 100644 --- a/packages/rs-platform-wallet-ffi/src/persistence.rs +++ b/packages/rs-platform-wallet-ffi/src/persistence.rs @@ -36,6 +36,7 @@ use platform_wallet::changeset::{ PlatformWalletChangeSet, PlatformWalletPersistence, ProviderKeyAccountEntry, ProviderKeyExtendedPubKey, PERSISTENCE_CAPABILITIES_VERSION, }; +use platform_wallet::wallet::core::stored_coin::{reconcile_with_parent, StoredParentState}; use platform_wallet::wallet::platform_wallet::WalletId; #[cfg(feature = "shielded")] use platform_wallet::wallet::shielded::ShieldedActivityStatus; @@ -95,6 +96,8 @@ use std::ffi::CStr; /// `Mempool` vs no-evidence); see each match's comment. pub(crate) const TX_CONTEXT_RAW_IN_BLOCK: u32 = 2; pub(crate) const TX_CONTEXT_RAW_IN_CHAIN_LOCKED_BLOCK: u32 = 3; +/// The InstantSend discriminant of the same encoding. +pub(crate) const TX_CONTEXT_RAW_INSTANT_SEND: u32 = 1; /// Byte budget for decoding a host-supplied account extended public key. /// @@ -3982,7 +3985,7 @@ impl PlatformWalletPersistence for FFIPersister { let context = match context_kind { 0 => TransactionContext::Mempool, - 1 => { + k if u32::from(k) == TX_CONTEXT_RAW_INSTANT_SEND => { // InstantSend requires the IS-lock blob, which the // persister doesn't currently store. Treat as miss // so the proof flow's SPV wait path completes the @@ -5741,7 +5744,7 @@ fn build_wallet_start_state( value: u.value_duffs, script_pubkey, }; - let utxo = key_wallet::Utxo { + let mut utxo = key_wallet::Utxo { outpoint, txout, address, @@ -5755,6 +5758,15 @@ fn build_wallet_start_state( // us). Recompute on the next SPV pass; default to false. is_trusted: false, }; + // The coin row can lag its own transaction's row: the transaction + // was confirmed or locked through a record that named none of its + // coins, so only the transaction row was rewritten. Raise the coin + // to what its transaction's row says. + reconcile_with_parent( + &mut utxo, + stored_parent_state(u), + wallet_info.metadata.last_processed_height, + ); // Route into the target funds-bearing account. Match on the // resolved `AccountType` and look up the right map field. Keys // and Platform variants are intentionally no-ops. @@ -6963,6 +6975,21 @@ impl UnresolvedRestoreStats { } } +/// What the host's row for a restored coin's creating transaction says, +/// decoded from the raw context the host copied. +fn stored_parent_state(u: &UtxoRestoreEntryFFI) -> StoredParentState { + match u.parent_context { + TX_CONTEXT_RAW_IN_BLOCK | TX_CONTEXT_RAW_IN_CHAIN_LOCKED_BLOCK => { + StoredParentState::InBlock { + height: u.parent_block_height, + } + } + TX_CONTEXT_RAW_INSTANT_SEND => StoredParentState::InstantLocked, + // Mempool, no row, or a value this build does not know: no evidence. + _ => StoredParentState::Unconfirmed, + } +} + /// Project a slice of [`UnresolvedAssetLockTxRecordFFI`] rows onto the /// in-memory `transactions()` maps of the rebuilt `ManagedWalletInfo`, /// routing each record to the first present family the proof lookup @@ -10113,12 +10140,15 @@ mod tests { use dashcore::blockdata::transaction::txout::TxOut; use dashcore::blockdata::transaction::Transaction; use dashcore::consensus::encode::serialize; + use dashcore::hashes::Hash; use dashcore::secp256k1::Secp256k1; use dashcore::{Network, ScriptBuf}; + use dashcore::{OutPoint, Txid}; use key_wallet::account::{Account, AccountType, StandardAccountType}; use key_wallet::bip32::{ExtendedPrivKey, ExtendedPubKey}; use key_wallet::managed_account::managed_account_trait::ManagedAccountTrait; use key_wallet::mnemonic::Mnemonic; + use key_wallet::test_utils::TestWalletContext; use key_wallet::wallet::Wallet; /// Regression: restored pool addresses must be tagged with the @@ -10976,6 +11006,112 @@ mod tests { assert!(restored_eddsa.is_watch_only); } + /// A coin stored unconfirmed under a transaction the store has in a block + /// this wallet has processed is restored confirmed at that block's + /// height; one under an InstantSend-locked transaction is restored + /// locked; one under a mempool transaction, an unknown context, or a + /// block beyond this wallet's processed height is restored as stored. + #[test] + fn should_restore_a_coin_as_final_as_its_stored_transaction() { + let wallet = Wallet::from_seed_bytes( + [0x42; 64], + Network::Testnet, + key_wallet::wallet::initialization::WalletAccountCreationOptions::Default, + ) + .expect("seeded wallet"); + let bip44 = AccountType::Standard { + index: 0, + standard_account_type: StandardAccountType::BIP44Account, + }; + let xpub = wallet + .accounts + .standard_bip44_accounts + .get(&0) + .expect("bip44 account") + .account_xpub; + let xpub_bytes = bincode::encode_to_vec(xpub, config::standard()).expect("encode xpub"); + let specs = [build_account_spec_ffi(&bip44, &xpub_bytes)]; + let script = TestWalletContext::new_random() + .receive_address + .script_pubkey(); + let coin = + |txid_byte: u8, parent_context: u32, parent_block_height: u32| UtxoRestoreEntryFFI { + type_tag: specs[0].type_tag, + standard_tag: specs[0].standard_tag, + account_index: specs[0].index, + registration_index: specs[0].registration_index, + key_class: specs[0].key_class, + user_identity_id: specs[0].user_identity_id, + friend_identity_id: specs[0].friend_identity_id, + prev_txid: [txid_byte; 32], + vout: 1, + value_duffs: 1_000_000, + script_pubkey: script.as_bytes().as_ptr(), + script_pubkey_len: script.len(), + height: 0, + is_coinbase: false, + is_confirmed: false, + is_instantlocked: false, + is_locked: false, + parent_context, + parent_block_height, + }; + let utxos = [ + coin(1, TX_CONTEXT_RAW_IN_BLOCK, 500), + coin(2, TX_CONTEXT_RAW_INSTANT_SEND, 0), + coin(3, 0, 0), + coin(4, TX_CONTEXT_RAW_IN_CHAIN_LOCKED_BLOCK, 600), + coin(5, 7, 700), + coin(6, TX_CONTEXT_RAW_IN_BLOCK, 2_000), + ]; + let entry = WalletRestoreEntryFFI { + wallet_id: wallet.wallet_id, + network: Network::Testnet.into(), + accounts: specs.as_ptr(), + accounts_count: specs.len(), + utxos: utxos.as_ptr(), + utxos_count: utxos.len(), + synced_height: 1_000, + last_processed_height: 1_000, + ..Default::default() + }; + + let (state, _) = build_wallet_start_state(&entry).expect("the wallet restores"); + + let account = state + .wallet_info + .accounts + .standard_bip44_accounts + .get(&0) + .expect("bip44 managed account"); + let restored = |txid_byte: u8| { + account + .utxos + .get(&OutPoint { + txid: Txid::from_byte_array([txid_byte; 32]), + vout: 1, + }) + .expect("the coin is restored") + }; + let in_block = restored(1); + assert!(in_block.is_confirmed); + assert_eq!(in_block.height, 500); + let locked = restored(2); + assert!(locked.is_instantlocked); + assert!(!locked.is_confirmed); + let mempool = restored(3); + assert!(!mempool.is_confirmed); + assert!(!mempool.is_instantlocked); + let chain_locked = restored(4); + assert!(chain_locked.is_confirmed); + assert_eq!(chain_locked.height, 600); + let unknown_context = restored(5); + assert!(!unknown_context.is_confirmed); + assert!(!unknown_context.is_instantlocked); + let above_this_wallet = restored(6); + assert!(!above_this_wallet.is_confirmed); + } + /// The BLS xpub decoder is the only account-xpub graph with a /// length-prefixed field (the public key bytes). A host-supplied blob /// whose prefix claims a gigabyte must fail on the decode budget, before diff --git a/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs b/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs index a835b46b6f0..e5cfdfa0dab 100644 --- a/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs +++ b/packages/rs-platform-wallet-ffi/src/wallet_restore_types.rs @@ -462,6 +462,15 @@ pub struct UtxoRestoreEntryFFI { pub is_confirmed: bool, pub is_instantlocked: bool, pub is_locked: bool, + /// The store's context for the coin's creating transaction, in the + /// `TransactionRecordFFI.context` encoding (`0` mempool, `1` + /// InstantSend, `2` in a block, `3` in a chain-locked block). `0` when + /// the store has no row for it. Hosts copy the row's value as-is; the + /// loader decides what it means for the coin. + pub parent_context: u32, + /// The store's block height for the coin's creating transaction; `0` + /// when it has none. + pub parent_block_height: u32, } /// One persisted transaction record carried back at load time so the diff --git a/packages/rs-platform-wallet/src/wallet/core/mod.rs b/packages/rs-platform-wallet/src/wallet/core/mod.rs index e03363948f2..db7b647b1ff 100644 --- a/packages/rs-platform-wallet/src/wallet/core/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/core/mod.rs @@ -5,6 +5,7 @@ pub mod generation; // Inherent `CoreWallet::sign_message` only — no types to re-export. mod sign_message; pub mod spend_observer; +pub mod stored_coin; pub(crate) use sign_message::is_signable_funding_account; mod transaction; pub mod wallet; diff --git a/packages/rs-platform-wallet/src/wallet/core/stored_coin.rs b/packages/rs-platform-wallet/src/wallet/core/stored_coin.rs new file mode 100644 index 00000000000..98354727013 --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/core/stored_coin.rs @@ -0,0 +1,136 @@ +//! A stored coin's flags, checked against its creating transaction's row. +//! +//! A store that keeps each coin's `is_confirmed` / `is_instantlocked` / +//! `height` next to the transaction rows can hold the two apart: the +//! transaction row says the transaction is in a block, the coin row still +//! says it is not. A coin is in a block exactly when its creating transaction +//! is, so the transaction row is the evidence; without it the engine restores +//! the coin as unconfirmed and no later event repairs it, because the block +//! was already processed. + +use key_wallet::Utxo; + +/// What a store's row for a coin's creating transaction says about it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StoredParentState { + /// No row, a placeholder row, or a transaction last seen in the mempool. + Unconfirmed, + /// The transaction is InstantSend-locked. + InstantLocked, + /// The transaction is in the block at `height`. + InBlock { + /// Height of the block holding the transaction. + height: u32, + }, +} + +/// Bring a restored coin's flags up to what its creating transaction's row +/// says. Only raises: a coin is never made less final than its own row. +/// +/// - Transaction in a block → the coin is confirmed at that block's height +/// (a coin already confirmed keeps its own height unless it has none). +/// - Transaction InstantSend-locked → the coin is InstantSend-locked (a lock +/// is permanent for its transaction). +/// +/// A block above `processed_height` (the last block this wallet processed) +/// is not taken: the transaction row is keyed by txid alone, so on a device +/// with several wallets it can come from a wallet that has synced further, +/// and this wallet records the transaction itself when it reaches the block. +pub fn reconcile_with_parent(utxo: &mut Utxo, parent: StoredParentState, processed_height: u32) { + match parent { + StoredParentState::Unconfirmed => {} + StoredParentState::InstantLocked => utxo.is_instantlocked = true, + StoredParentState::InBlock { height } if height > 0 && height <= processed_height => { + if !utxo.is_confirmed || utxo.height == 0 { + utxo.is_confirmed = true; + utxo.height = height; + } + } + StoredParentState::InBlock { .. } => {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use dashcore::{Address, Network, OutPoint, TxOut}; + + fn coin(is_confirmed: bool, height: u32) -> Utxo { + let address = Address::dummy(Network::Testnet, 0); + let mut utxo = Utxo::new( + OutPoint::null(), + TxOut { + value: 1_000, + script_pubkey: address.script_pubkey(), + }, + address, + height, + false, + ); + utxo.is_confirmed = is_confirmed; + utxo + } + + #[test] + fn should_confirm_a_coin_whose_transaction_is_in_a_block() { + let mut utxo = coin(false, 0); + reconcile_with_parent(&mut utxo, StoredParentState::InBlock { height: 500 }, 1_000); + assert!(utxo.is_confirmed); + assert_eq!(utxo.height, 500); + } + + #[test] + fn should_lock_a_coin_whose_transaction_is_instant_locked() { + let mut utxo = coin(false, 0); + reconcile_with_parent(&mut utxo, StoredParentState::InstantLocked, 1_000); + assert!(utxo.is_instantlocked); + assert!(!utxo.is_confirmed); + } + + #[test] + fn should_leave_a_coin_alone_when_its_transaction_is_unconfirmed() { + let mut utxo = coin(false, 0); + reconcile_with_parent(&mut utxo, StoredParentState::Unconfirmed, 1_000); + assert!(!utxo.is_confirmed); + assert!(!utxo.is_instantlocked); + } + + #[test] + fn should_keep_a_confirmed_coins_own_height() { + let mut utxo = coin(true, 400); + reconcile_with_parent(&mut utxo, StoredParentState::InBlock { height: 500 }, 1_000); + assert!(utxo.is_confirmed); + assert_eq!(utxo.height, 400); + } + + #[test] + fn should_give_a_confirmed_coin_without_a_height_its_transactions_height() { + let mut utxo = coin(true, 0); + reconcile_with_parent(&mut utxo, StoredParentState::InBlock { height: 500 }, 1_000); + assert!(utxo.is_confirmed); + assert_eq!(utxo.height, 500); + } + + #[test] + fn should_keep_a_locked_coin_locked_under_an_unconfirmed_transaction() { + let mut utxo = coin(false, 0); + utxo.is_instantlocked = true; + reconcile_with_parent(&mut utxo, StoredParentState::Unconfirmed, 1_000); + assert!(utxo.is_instantlocked); + } + + #[test] + fn should_not_confirm_from_a_block_this_wallet_has_not_processed() { + let mut utxo = coin(false, 0); + reconcile_with_parent(&mut utxo, StoredParentState::InBlock { height: 500 }, 499); + assert!(!utxo.is_confirmed); + assert_eq!(utxo.height, 0); + } + + #[test] + fn should_not_confirm_from_a_block_row_without_a_height() { + let mut utxo = coin(false, 0); + reconcile_with_parent(&mut utxo, StoredParentState::InBlock { height: 0 }, 1_000); + assert!(!utxo.is_confirmed); + } +} diff --git a/packages/rs-unified-sdk-jni/src/persistence.rs b/packages/rs-unified-sdk-jni/src/persistence.rs index da5d40e8f04..d9d79713b43 100644 --- a/packages/rs-unified-sdk-jni/src/persistence.rs +++ b/packages/rs-unified-sdk-jni/src/persistence.rs @@ -3004,6 +3004,12 @@ fn build_utxo_restore_entries( let is_confirmed = env.get_field(&h, "isConfirmed", "Z")?.z()?; let is_instantlocked = env.get_field(&h, "isInstantLocked", "Z")?.z()?; let is_locked = env.get_field(&h, "isLocked", "Z")?.z()?; + // Kotlin carries the store's unsigned columns as `Int`; a + // negative value is a corrupt row, read as "no evidence". + let parent_context = + u32::try_from(env.get_field(&h, "parentContext", "I")?.i()?).unwrap_or(0); + let parent_block_height = + u32::try_from(env.get_field(&h, "parentBlockHeight", "I")?.i()?).unwrap_or(0); Ok(UtxoRestoreStaged { entry: UtxoRestoreEntryFFI { type_tag, @@ -3023,6 +3029,8 @@ fn build_utxo_restore_entries( is_confirmed, is_instantlocked, is_locked, + parent_context, + parent_block_height, }, script, }) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift index 927bd581694..64f6357d54b 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletPersistenceHandler.swift @@ -6920,6 +6920,9 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { \.account, // Read once per row by the asset-lock spend guard below. \.spendingTransaction, + // Read once per row for the txid and the creating + // transaction's context in `buildUtxoRestoreBuffer`. + \.transaction, ] // Bail with `errored = true` on a SwiftData failure rather // than degrading to an empty bucket map. Without this, Rust @@ -7502,6 +7505,11 @@ public final class PlatformWalletPersistenceHandler: @unchecked Sendable { utxo.is_confirmed = record.isConfirmed utxo.is_instantlocked = record.isInstantLocked utxo.is_locked = record.isLocked + // The creating transaction's row, copied as-is: the loader + // raises a coin that lags its own transaction's confirmation. + // A placeholder parent row carries context 0 and adds nothing. + utxo.parent_context = record.transaction?.context ?? 0 + utxo.parent_block_height = record.transaction?.blockHeight ?? 0 buf[written] = utxo written += 1 } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/CoreTxoReconcileTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/CoreTxoReconcileTests.swift index eac6a57af07..9eee2e260b6 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/CoreTxoReconcileTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/CoreTxoReconcileTests.swift @@ -269,6 +269,69 @@ final class CoreTxoReconcileTests: XCTestCase { return Int(entriesPtr[0].utxos_count) } + // MARK: Restore carries the creating transaction's stored context + + /// A coin row can lag its own transaction's row: the transaction was + /// confirmed through a record that named none of its coins, so only the + /// transaction row was rewritten. The load hands the coin to the loader + /// with the transaction row's context and height, copied as-is, so the + /// loader can raise the coin. + func testRestoreCarriesTheCreatingTransactionsStoredContext() throws { + let (handler, container) = try makeHandler() + try seedWallet(in: container) + try seedUnspentTxo(in: container, txid: txid(0x81)) + let context = ModelContext(container) + let outpoint = PersistentTxo.makeOutpoint(txid: txid(0x81), vout: 0) + let coin = try XCTUnwrap(context.fetch( + FetchDescriptor(predicate: #Predicate { $0.outpoint == outpoint }) + ).first) + coin.isConfirmed = false + coin.height = 0 + let parent = try XCTUnwrap(coin.transaction) + parent.context = 2 + parent.blockHeight = 500 + try context.save() + + let (entries, count, errored) = handler.loadWalletList() + XCTAssertFalse(errored) + XCTAssertEqual(count, 1) + let entriesPtr = try XCTUnwrap(entries) + defer { handler.loadWalletListFree(entries: UnsafeRawPointer(entriesPtr)) } + XCTAssertEqual(entriesPtr[0].utxos_count, 1) + let restored = try XCTUnwrap(entriesPtr[0].utxos).pointee + XCTAssertFalse(restored.is_confirmed, "the coin row is handed over as stored") + XCTAssertEqual(restored.parent_context, 2) + XCTAssertEqual(restored.parent_block_height, 500) + } + + /// The same hand-over for a transaction row that is InstantSend-locked. + func testRestoreCarriesAnInstantLockedTransactionsContext() throws { + let (handler, container) = try makeHandler() + try seedWallet(in: container) + try seedUnspentTxo(in: container, txid: txid(0x82)) + let context = ModelContext(container) + let outpoint = PersistentTxo.makeOutpoint(txid: txid(0x82), vout: 0) + let coin = try XCTUnwrap(context.fetch( + FetchDescriptor(predicate: #Predicate { $0.outpoint == outpoint }) + ).first) + coin.isConfirmed = false + coin.height = 0 + let parent = try XCTUnwrap(coin.transaction) + parent.context = 1 + parent.blockHeight = 0 + try context.save() + + let (entries, count, errored) = handler.loadWalletList() + XCTAssertFalse(errored) + XCTAssertEqual(count, 1) + let entriesPtr = try XCTUnwrap(entries) + defer { handler.loadWalletListFree(entries: UnsafeRawPointer(entriesPtr)) } + let restored = try XCTUnwrap(entriesPtr[0].utxos).pointee + XCTAssertFalse(restored.is_instantlocked, "the coin row is handed over as stored") + XCTAssertEqual(restored.parent_context, 1) + XCTAssertEqual(restored.parent_block_height, 0) + } + // MARK: 1. Positive engine evidence marks a local unspent row spent func testPositiveEngineVerdictMarksALocalUnspentRowSpent() throws {