From 0c31149c073bc61fb248b084148758d7464b1e04 Mon Sep 17 00:00:00 2001 From: Jeon1691 <16333003+Jeon1691@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:03:43 +0900 Subject: [PATCH 1/2] wollet: cache: skip outputs spent by known txs `update_unspent` adds the wallet outputs of every tx new to `heights`, but only removes the inputs of the txs in the same update. An output already spent by a known tx was added back to `unspent`, so `Wollet::utxos()` returned it, the balance counted it and the tx builder could select it, making the broadcast fail. This happens when: * a tx is removed by a scan and found again, while its spending tx stays in the history; * a tx is found after its spending tx, for example through another wallet script. Before adding the outputs, drop the ones spent by a known tx. A spending tx cannot confirm before the tx it spends, so only the known txs at the same height or above, and the unconfirmed ones, are read. A scan can read servers at different heights, so a tx can be reported unconfirmed while its spending tx is cached as confirmed, and the spending tx is then not read: * for a tx found again unconfirmed, all the known txs are read; a server reporting it as confirmed has seen its block, so the height bound reads its spending tx; * when the height of a known tx changes, its unspent outputs are checked again, so an output added with an inconsistent height is removed once a scan reports the right height. This also covers a tx found for the first time. Updates that neither add a wallet output nor change the height of a tx with unspent outputs read no tx, so updates still do not read every stored tx. Fixes https://github.com/Blockstream/lwk/issues/201 --- lwk_wollet/CHANGELOG.md | 1 + lwk_wollet/src/cache.rs | 99 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 96 insertions(+), 4 deletions(-) diff --git a/lwk_wollet/CHANGELOG.md b/lwk_wollet/CHANGELOG.md index a50bfb6d7..d8e3120bc 100644 --- a/lwk_wollet/CHANGELOG.md +++ b/lwk_wollet/CHANGELOG.md @@ -6,6 +6,7 @@ * Removed `Amp2::new_testnet()`, use `Amp2::new()`; also removed old AMP2 testnet consts. * Breaking: update the re-exported `age` crate to 0.12. Its `fl!` localization macro dependency emitted arguments in random order, making builds non-deterministic. See the [age 0.12 changelog](https://github.com/str4d/rage/blob/main/age/CHANGELOG.md) for API changes. * Breaking: `AddressResult::new()` takes the full derivation path of the address, `None` if unknown, readable with the new `AddressResult::derivation_path()`. +* Fix `Wollet::utxos()` returning an output already spent by a known wallet transaction, when the transaction paying it is removed by a scan and then found again, or is found after the spending transaction. The spent output was counted in the balance and could be selected by the transaction builder, making the broadcast fail. Wallets with a persisted transaction store keep an output already affected until they are scanned again from an empty store. ## 0.20.0 diff --git a/lwk_wollet/src/cache.rs b/lwk_wollet/src/cache.rs index 57e70ff70..a47bfc1cb 100644 --- a/lwk_wollet/src/cache.rs +++ b/lwk_wollet/src/cache.rs @@ -18,6 +18,11 @@ fn tx_key(txid: &Txid) -> String { format!("wollet:tx:{}", txid) } +/// Height used to order txs, unconfirmed txs (`None`) are considered above any confirmed tx. +fn height_sort_key(height: Option) -> Height { + height.unwrap_or(Height::MAX) +} + /// `Cache` is a cache of wallet data, like wallet transactions. /// It is fully reconstructable from the CT Descriptor and the blockchain. pub struct Cache { @@ -318,23 +323,49 @@ impl Cache { let mut sorted: Vec = self.heights.keys().cloned().collect(); sorted.sort_by(|a, b| { // cannot panic here, sorted is heights keys - let ha = self.heights[a].unwrap_or(u32::MAX); - let hb = self.heights[b].unwrap_or(u32::MAX); + let ha = height_sort_key(self.heights[a]); + let hb = height_sort_key(self.heights[b]); hb.cmp(&ha).then(b.cmp(a)) }); self.sorted_txids = sorted; } + /// Outpoints spent by the known txs (in `heights` but not in `skip`) with a + /// `height_sort_key` of `min_key` or above. + /// + /// A spending tx cannot confirm before the tx it spends, so to check the outputs of a tx + /// only the txs at its height or above, and the unconfirmed ones, need to be read. + /// `sorted_txids` is ordered by descending height with unconfirmed txs first, so the + /// iteration stops at the first lower tx. `Height::MIN` reads all the known txs. This + /// requires `sorted_txids` to be rebuilt after `heights` is updated. + fn spent_by_known_txs( + &self, + min_key: Height, + skip: &HashSet<&Txid>, + txs: &[(Txid, Transaction)], + ) -> HashSet { + self.sorted_txids + .iter() + .take_while(|txid| { + height_sort_key(self.heights.get(*txid).copied().flatten()) >= min_key + }) + .filter(|txid| !skip.contains(txid)) + .filter_map(|txid| self.tx_as_fallback(txid, txs)) + .flat_map(|tx| tx.input.into_iter().map(|i| i.previous_output)) + .collect() + } + fn update_unspent( &mut self, txid_height_new: &[(Txid, Option)], deleted_txids: &[Txid], new_txs: &[(Txid, Transaction)], known_txids: &HashSet, + readded_unconfirmed: &HashSet, ) { let txids_new: HashSet<&Txid> = txid_height_new.iter().map(|(txid, _)| txid).collect(); - let outputs_new: Vec<(OutPoint, Script)> = self + let mut outputs_new: Vec<(OutPoint, Script)> = self .unblinded .keys() .filter(|op| txids_new.contains(&op.txid)) @@ -347,6 +378,49 @@ impl Cache { .filter(|(_, script)| self.paths.contains_key(script)) .collect(); + // A tx that is new to `heights` can have outputs already spent by a known tx, for example + // when it comes back after being deleted by a previous update, or when its spending tx + // was found first. Inputs of the txs in this update are removed below. + // + // Scans can read servers that are at different heights, so a tx can be reported + // unconfirmed while its spending tx is cached as confirmed, which is then not read. + // - For a tx coming back unconfirmed, all the known txs are read. + // - The unspent outputs of known txs in this update, for example whose height changed, + // are checked again, so that an output added with an inconsistent height is removed + // once a scan reports its height. + let known_in_update: HashSet<&Txid> = txids_new + .iter() + .copied() + .filter(|txid| known_txids.contains(*txid)) + .collect(); + let known_unspent: Vec = if known_in_update.is_empty() { + Vec::new() + } else { + self.unspent + .keys() + .filter(|op| known_in_update.contains(&op.txid)) + .copied() + .collect() + }; + let min_key = if outputs_new + .iter() + .any(|(op, _)| readded_unconfirmed.contains(&op.txid)) + { + Some(Height::MIN) + } else { + outputs_new + .iter() + .map(|(op, _)| op) + .chain(known_unspent.iter()) + .map(|op| height_sort_key(self.heights.get(&op.txid).copied().flatten())) + .min() + }; + if let Some(min_key) = min_key { + let spent = self.spent_by_known_txs(min_key, &txids_new, new_txs); + outputs_new.retain(|(op, _)| !spent.contains(op)); + self.unspent.retain(|op, _| !spent.contains(op)); + } + let inputs_new: HashSet = txids_new .iter() .filter_map(|txid| self.tx_as_fallback(txid, new_txs)) @@ -508,6 +582,17 @@ impl Cache { use_unspent_snapshot: bool, ) -> Result<(), Error> { // TODO: cleanup this functions + // Txs coming back unconfirmed after a previous update deleted them, they are still in the + // txs store. A server reporting a tx as confirmed has seen its block, so the spending tx + // is at that height or above, while one reporting it as unconfirmed can be behind the + // cached spending tx. + let readded_unconfirmed: HashSet = txid_height_new + .iter() + .filter(|(txid, height)| { + height.is_none() && !self.heights.contains_key(txid) && self.txids.contains(txid) + }) + .map(|(txid, _)| *txid) + .collect(); self.extend_all_txs(txs)?; // Txids known before this update, so `update_unspent` can distinguish new // txs from txs whose height only changed. @@ -526,7 +611,13 @@ impl Cache { if use_unspent_snapshot || utxo_only { self.update_unspent_from_snapshot(unspent, txs); } else { - self.update_unspent(txid_height_new, deleted_txids, txs, &known_txids); + self.update_unspent( + txid_height_new, + deleted_txids, + txs, + &known_txids, + &readded_unconfirmed, + ); } Ok(()) } From f83999ef62c2c97680e0c0a236f853ccdccb2008 Mon Sep 17 00:00:00 2001 From: Jeon1691 <16333003+Jeon1691@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:31:43 +0900 Subject: [PATCH 2/2] wollet: cache: test outputs spent by known txs Cover the cases where `update_unspent` added an output already spent by a known tx: a tx found again after a scan removed it, with a confirmed or unconfirmed spending tx, and a tx found after its spending tx, also in the same block. A re-added tx with no spending tx must keep its output unspent. Also cover a tx reported unconfirmed by a server that has not seen the block of its cached spending tx: found again, also when another wallet tx is in a later block, and found for the first time, then reported with its height. --- lwk_wollet/src/cache.rs | 154 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) diff --git a/lwk_wollet/src/cache.rs b/lwk_wollet/src/cache.rs index a47bfc1cb..f731d711c 100644 --- a/lwk_wollet/src/cache.rs +++ b/lwk_wollet/src/cache.rs @@ -727,4 +727,158 @@ mod tests { assert_eq!(live.all_txids(), restored.all_txids()); } + + #[test] + fn test_output_spent_by_known_tx_is_not_unspent() { + use crate::descriptor::Chain; + use elements::bitcoin::bip32::ChildNumber; + use elements::confidential::{AssetBlindingFactor, ValueBlindingFactor}; + use elements::{AssetId, OutPoint, Script, TxIn, TxOut, TxOutSecrets}; + + let script = Script::from(vec![0x51]); + // A pays one output to a wallet script. + let a = Transaction { + version: 2, + lock_time: elements::LockTime::ZERO, + input: vec![], + output: vec![TxOut { + script_pubkey: script.clone(), + ..Default::default() + }], + }; + let a_txid = a.txid(); + let a0 = OutPoint::new(a_txid, 0); + // B spends A:0. + let b = Transaction { + version: 2, + lock_time: elements::LockTime::ZERO, + input: vec![TxIn { + previous_output: a0, + ..Default::default() + }], + output: vec![], + }; + let b_txid = b.txid(); + let secrets = TxOutSecrets::new( + AssetId::from_byte_array([1u8; 32]), + AssetBlindingFactor::zero(), + 1000, + ValueBlindingFactor::zero(), + ); + + // (new txids with heights, deleted txids, downloaded txs) + type Step = ( + Vec<(Txid, Option)>, + Vec, + Vec<(Txid, Transaction)>, + ); + let a_seen = + |height| -> Step { (vec![(a_txid, height)], vec![], vec![(a_txid, a.clone())]) }; + let a_back = |height| -> Step { (vec![(a_txid, height)], vec![], vec![]) }; + let b_seen = + |height| -> Step { (vec![(b_txid, height)], vec![], vec![(b_txid, b.clone())]) }; + let a_missing: Step = (vec![], vec![a_txid], vec![]); + // C is an unrelated wallet tx. + let c = Transaction { + version: 2, + lock_time: elements::LockTime::ZERO, + input: vec![], + output: vec![], + }; + let c_seen = |height| -> Step { + ( + vec![(c.txid(), height)], + vec![], + vec![(c.txid(), c.clone())], + ) + }; + + let cases: Vec<(&str, Vec, bool)> = vec![ + ( + // A drops out of the history for one scan while B stays, then comes back. + "re-added tx, confirmed spender", + vec![ + a_seen(Some(100)), + b_seen(Some(101)), + a_missing.clone(), + a_back(Some(100)), + ], + false, + ), + ( + "re-added tx, unconfirmed spender", + vec![ + a_seen(Some(100)), + b_seen(None), + a_missing.clone(), + a_back(Some(100)), + ], + false, + ), + ( + // B is found first, through another wallet script, then A is found. + "first seen tx, already known spender", + vec![b_seen(Some(101)), a_seen(Some(100))], + false, + ), + ( + "first seen tx, already known spender in the same block", + vec![b_seen(Some(100)), a_seen(Some(100))], + false, + ), + ( + // A comes back from a server that has not seen block 101 yet, while a previous + // scan cached B at 101. + "re-added tx reported unconfirmed, spender confirmed", + vec![ + a_seen(None), + b_seen(None), + (vec![(b_txid, Some(101))], vec![a_txid], vec![]), + a_back(None), + ], + false, + ), + ( + "re-added tx reported unconfirmed, spender confirmed below the last block", + vec![ + a_seen(None), + b_seen(None), + (vec![(b_txid, Some(101))], vec![a_txid], vec![]), + c_seen(Some(102)), + a_back(None), + ], + false, + ), + ( + // A is first reported by a server that has not seen block 101 yet, then with its + // height. + "first seen tx reported unconfirmed, then confirmed", + vec![b_seen(Some(101)), a_seen(None), a_back(Some(101))], + false, + ), + ( + "re-added tx, no spender", + vec![a_seen(Some(100)), a_missing, a_back(Some(100))], + true, + ), + ]; + + for (name, steps, expected_unspent) in cases { + let mut cache = Cache::default(); + cache + .paths + .insert(script.clone(), (Chain::External, ChildNumber::from(0))); + cache.extend_unblinded([(a0, secrets)]); + for (new, deleted, txs) in steps { + cache + .update(&new, &deleted, &txs, false, vec![], false) + .unwrap(); + } + assert_eq!( + cache.unspent().contains_key(&a0), + expected_unspent, + "{name}" + ); + } + } }