From c1b4c5fbee17dd202e82bddfde67394cfbf56130 Mon Sep 17 00:00:00 2001 From: Steve Myers Date: Wed, 10 Dec 2025 15:42:45 -0600 Subject: [PATCH 1/2] feat(chain): add sent_and_received_txouts method to SPK and keychain indexes Implement sent_and_received_txouts methods on SpkTxOutIndex and KeychainTxOutIndex. These methods return actual TxOut structs allowing callers to access complete transaction output information including script pubkeys and values. --- crates/chain/src/indexer/keychain_txout.rs | 15 +++ crates/chain/src/indexer/spk_txout.rs | 70 +++++++++++++ crates/chain/tests/test_spk_txout_index.rs | 113 +++++++++++++++++++++ 3 files changed, 198 insertions(+) diff --git a/crates/chain/src/indexer/keychain_txout.rs b/crates/chain/src/indexer/keychain_txout.rs index 99931cf5e..b243460e7 100644 --- a/crates/chain/src/indexer/keychain_txout.rs +++ b/crates/chain/src/indexer/keychain_txout.rs @@ -418,6 +418,21 @@ impl KeychainTxOutIndex { .sent_and_received(tx, self.map_to_inner_bounds(range)) } + /// Returns the sent and received [`TxOut`]s for this `tx` relative to the script pubkeys + /// belonging to the keychains in `range`. A TxOut is *sent* when a script pubkey in the + /// `range` is on an input and *received* when it is on an output. For `sent` to be computed + /// correctly, the index must have already scanned the output being spent. Calculating + /// received just uses the [`Transaction`] outputs directly, so it will be correct even if + /// it has not been scanned. + pub fn sent_and_received_txouts( + &self, + tx: &Transaction, + range: impl RangeBounds, + ) -> (Vec, Vec) { + self.inner + .sent_and_received_txouts(tx, self.map_to_inner_bounds(range)) + } + /// Computes the net value that this transaction gives to the script pubkeys in the index and /// *takes* from the transaction outputs in the index. Shorthand for calling /// [`sent_and_received`] and subtracting sent from received. diff --git a/crates/chain/src/indexer/spk_txout.rs b/crates/chain/src/indexer/spk_txout.rs index 32ad6f0d9..a66ffef94 100644 --- a/crates/chain/src/indexer/spk_txout.rs +++ b/crates/chain/src/indexer/spk_txout.rs @@ -9,6 +9,8 @@ use crate::{ }; use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid}; +use alloc::vec::Vec; + /// An index storing [`TxOut`]s that have a script pubkey that matches those in a list. /// /// The basic idea is that you insert script pubkeys you care about into the index with @@ -318,6 +320,74 @@ impl SpkTxOutIndex { (sent, received) } + /// Collects the sent and received [`TxOut`]s for `tx` on the script pubkeys in `range`. + /// TxOuts are *sent* when a script pubkey in the `range` is on an input and *received* when + /// it is on an output. For `sent` to be computed correctly, the index must have already + /// scanned the output being spent. Calculating received just uses the [`Transaction`] + /// outputs directly, so it will be correct even if it has not been scanned. + /// + /// Returns a tuple of (sent_txouts, received_txouts). + /// + /// # Example + /// Shows the addresses of the TxOut sent from or received by a Transaction relevant to all spks + /// in this index. + /// + /// ```rust + /// # use bdk_chain::spk_txout::SpkTxOutIndex; + /// # use bitcoin::{Address, Network, Transaction}; + /// # use std::str::FromStr; + /// # + /// # fn example() -> Result<(), Box> { + /// let mut index = SpkTxOutIndex::::default(); + /// + /// // ... scan transactions to populate the index ... + /// # let tx = Transaction { version: bitcoin::transaction::Version::TWO, lock_time: bitcoin::locktime::absolute::LockTime::ZERO, input: vec![], output: vec![] }; + /// + /// // Get sent and received txouts for a transaction across all tracked addresses + /// let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx, ..); + /// + /// // Display addresses and amounts + /// println!("Sent:"); + /// for txout in sent_txouts { + /// let address = Address::from_script(&txout.script_pubkey, Network::Bitcoin)?; + /// println!(" from {} - {} sats", address, txout.value.to_sat()); + /// } + /// + /// println!("Received:"); + /// for txout in received_txouts { + /// let address = Address::from_script(&txout.script_pubkey, Network::Bitcoin)?; + /// println!(" to {} - {} sats", address, txout.value.to_sat()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn sent_and_received_txouts( + &self, + tx: &Transaction, + range: impl RangeBounds, + ) -> (Vec, Vec) { + let mut sent = Vec::new(); + let mut received = Vec::new(); + + for txin in &tx.input { + if let Some((index, txout)) = self.txout(txin.previous_output) { + if range.contains(index) { + sent.push(txout.clone()); + } + } + } + + for txout in &tx.output { + if let Some(index) = self.index_of_spk(txout.script_pubkey.clone()) { + if range.contains(index) { + received.push(txout.clone()); + } + } + } + + (sent, received) + } + /// Computes the net value transfer effect of `tx` on the script pubkeys in `range`. Shorthand /// for calling [`sent_and_received`] and subtracting sent from received. /// diff --git a/crates/chain/tests/test_spk_txout_index.rs b/crates/chain/tests/test_spk_txout_index.rs index 1aa6ff4c7..537add2ae 100644 --- a/crates/chain/tests/test_spk_txout_index.rs +++ b/crates/chain/tests/test_spk_txout_index.rs @@ -80,6 +80,119 @@ fn spk_txout_sent_and_received() { assert_eq!(index.net_value(&tx2, ..), SignedAmount::from_sat(8_000)); } +#[test] +fn spk_txout_sent_and_received_txouts() { + let spk1 = ScriptBuf::from_hex("001404f1e52ce2bab3423c6a8c63b7cd730d8f12542c").unwrap(); + let spk2 = ScriptBuf::from_hex("00142b57404ae14f08c3a0c903feb2af7830605eb00f").unwrap(); + + let mut index = SpkTxOutIndex::default(); + index.insert_spk(0, spk1.clone()); + index.insert_spk(1, spk2.clone()); + + let tx1 = Transaction { + version: transaction::Version::TWO, + lock_time: absolute::LockTime::ZERO, + input: vec![], + output: vec![TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + }], + }; + + let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx1, ..); + assert!(sent_txouts.is_empty()); + assert_eq!( + received_txouts, + vec![TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + }] + ); + let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx1, ..1); + assert!(sent_txouts.is_empty()); + assert_eq!( + received_txouts, + vec![TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + }] + ); + let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx1, 1..); + assert!(sent_txouts.is_empty() && received_txouts.is_empty()); + + index.index_tx(&tx1); + + let tx2 = Transaction { + version: transaction::Version::ONE, + lock_time: absolute::LockTime::ZERO, + input: vec![TxIn { + previous_output: OutPoint { + txid: tx1.compute_txid(), + vout: 0, + }, + ..Default::default() + }], + output: vec![ + TxOut { + value: Amount::from_sat(20_000), + script_pubkey: spk2.clone(), + }, + TxOut { + script_pubkey: spk1.clone(), + value: Amount::from_sat(30_000), + }, + ], + }; + + let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx2, ..); + assert_eq!( + sent_txouts, + vec![TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + }] + ); + assert_eq!( + received_txouts, + vec![ + TxOut { + value: Amount::from_sat(20_000), + script_pubkey: spk2.clone(), + }, + TxOut { + value: Amount::from_sat(30_000), + script_pubkey: spk1.clone(), + } + ] + ); + + let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx2, ..1); + assert_eq!( + sent_txouts, + vec![TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + }] + ); + assert_eq!( + received_txouts, + vec![TxOut { + value: Amount::from_sat(30_000), + script_pubkey: spk1.clone(), + }] + ); + + let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx2, 1..); + assert!(sent_txouts.is_empty()); + assert_eq!( + received_txouts, + vec![TxOut { + value: Amount::from_sat(20_000), + script_pubkey: spk2.clone(), + }] + ); +} + #[test] fn mark_used() { let spk1 = ScriptBuf::from_hex("001404f1e52ce2bab3423c6a8c63b7cd730d8f12542c").unwrap(); From 6ff9f26cdbd6f4dcbe14e5b2a16ac8406e1636fb Mon Sep 17 00:00:00 2001 From: Steve Myers Date: Thu, 11 Dec 2025 11:26:25 -0600 Subject: [PATCH 2/2] feat(chain): add input/output indices to sent_and_received_txouts Return tuple of (index, TxOut) in sent_and_received_txouts methods to identify which input/output positions the TxOuts correspond to in the original transaction. --- crates/chain/src/indexer.rs | 7 ++ crates/chain/src/indexer/keychain_txout.rs | 4 +- crates/chain/src/indexer/spk_txout.rs | 20 ++--- crates/chain/src/lib.rs | 2 +- crates/chain/tests/test_spk_txout_index.rs | 89 ++++++++++++++-------- 5 files changed, 76 insertions(+), 46 deletions(-) diff --git a/crates/chain/src/indexer.rs b/crates/chain/src/indexer.rs index 22e839815..75d5ad432 100644 --- a/crates/chain/src/indexer.rs +++ b/crates/chain/src/indexer.rs @@ -1,11 +1,18 @@ //! [`Indexer`] provides utilities for indexing transaction data. +use alloc::vec::Vec; use bitcoin::{OutPoint, Transaction, TxOut}; #[cfg(feature = "miniscript")] pub mod keychain_txout; pub mod spk_txout; +/// Type alias for a list of indexed transaction outputs. +/// +/// Each element is a tuple of `(index, TxOut)` where index is the index of the input or output in +/// the original [`Transaction`]. +pub type IndexedTxOuts = Vec<(usize, TxOut)>; + /// Utilities for indexing transaction data. /// /// Types which implement this trait can be used to construct an [`IndexedTxGraph`]. diff --git a/crates/chain/src/indexer/keychain_txout.rs b/crates/chain/src/indexer/keychain_txout.rs index b243460e7..df84dc2c6 100644 --- a/crates/chain/src/indexer/keychain_txout.rs +++ b/crates/chain/src/indexer/keychain_txout.rs @@ -8,7 +8,7 @@ use crate::{ spk_client::{FullScanRequestBuilder, SyncRequestBuilder}, spk_iter::BIP32_MAX_INDEX, spk_txout::SpkTxOutIndex, - DescriptorExt, DescriptorId, Indexed, Indexer, KeychainIndexed, SpkIterator, + DescriptorExt, DescriptorId, Indexed, IndexedTxOuts, Indexer, KeychainIndexed, SpkIterator, }; use alloc::{borrow::ToOwned, vec::Vec}; use bitcoin::{ @@ -428,7 +428,7 @@ impl KeychainTxOutIndex { &self, tx: &Transaction, range: impl RangeBounds, - ) -> (Vec, Vec) { + ) -> (IndexedTxOuts, IndexedTxOuts) { self.inner .sent_and_received_txouts(tx, self.map_to_inner_bounds(range)) } diff --git a/crates/chain/src/indexer/spk_txout.rs b/crates/chain/src/indexer/spk_txout.rs index a66ffef94..73aee0c8b 100644 --- a/crates/chain/src/indexer/spk_txout.rs +++ b/crates/chain/src/indexer/spk_txout.rs @@ -5,7 +5,7 @@ use core::ops::RangeBounds; use crate::{ collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap}, - Indexer, + IndexedTxOuts, Indexer, }; use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid}; @@ -348,15 +348,15 @@ impl SpkTxOutIndex { /// /// // Display addresses and amounts /// println!("Sent:"); - /// for txout in sent_txouts { + /// for (i, txout) in sent_txouts { /// let address = Address::from_script(&txout.script_pubkey, Network::Bitcoin)?; - /// println!(" from {} - {} sats", address, txout.value.to_sat()); + /// println!("input {}: from {} - {} sats", i, address, txout.value.to_sat()); /// } /// /// println!("Received:"); - /// for txout in received_txouts { + /// for (i, txout) in received_txouts { /// let address = Address::from_script(&txout.script_pubkey, Network::Bitcoin)?; - /// println!(" to {} - {} sats", address, txout.value.to_sat()); + /// println!("output {}: to {} + {} sats", i, address, txout.value.to_sat()); /// } /// # Ok(()) /// # } @@ -365,22 +365,22 @@ impl SpkTxOutIndex { &self, tx: &Transaction, range: impl RangeBounds, - ) -> (Vec, Vec) { + ) -> (IndexedTxOuts, IndexedTxOuts) { let mut sent = Vec::new(); let mut received = Vec::new(); - for txin in &tx.input { + for (i, txin) in tx.input.iter().enumerate() { if let Some((index, txout)) = self.txout(txin.previous_output) { if range.contains(index) { - sent.push(txout.clone()); + sent.push((i, txout.clone())); } } } - for txout in &tx.output { + for (i, txout) in tx.output.iter().enumerate() { if let Some(index) = self.index_of_spk(txout.script_pubkey.clone()) { if range.contains(index) { - received.push(txout.clone()); + received.push((i, txout.clone())); } } } diff --git a/crates/chain/src/lib.rs b/crates/chain/src/lib.rs index be9170b1a..e81fef78e 100644 --- a/crates/chain/src/lib.rs +++ b/crates/chain/src/lib.rs @@ -36,7 +36,7 @@ pub mod indexed_tx_graph; pub use indexed_tx_graph::IndexedTxGraph; pub mod indexer; pub use indexer::spk_txout; -pub use indexer::Indexer; +pub use indexer::{IndexedTxOuts, Indexer}; pub mod local_chain; mod tx_data_traits; pub use tx_data_traits::*; diff --git a/crates/chain/tests/test_spk_txout_index.rs b/crates/chain/tests/test_spk_txout_index.rs index 537add2ae..ea460bbbc 100644 --- a/crates/chain/tests/test_spk_txout_index.rs +++ b/crates/chain/tests/test_spk_txout_index.rs @@ -98,24 +98,29 @@ fn spk_txout_sent_and_received_txouts() { script_pubkey: spk1.clone(), }], }; - let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx1, ..); assert!(sent_txouts.is_empty()); assert_eq!( received_txouts, - vec![TxOut { - value: Amount::from_sat(42_000), - script_pubkey: spk1.clone(), - }] + vec![( + 0, + TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + } + )] ); let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx1, ..1); assert!(sent_txouts.is_empty()); assert_eq!( received_txouts, - vec![TxOut { - value: Amount::from_sat(42_000), - script_pubkey: spk1.clone(), - }] + vec![( + 0, + TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + } + )] ); let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx1, 1..); assert!(sent_txouts.is_empty() && received_txouts.is_empty()); @@ -147,49 +152,67 @@ fn spk_txout_sent_and_received_txouts() { let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx2, ..); assert_eq!( sent_txouts, - vec![TxOut { - value: Amount::from_sat(42_000), - script_pubkey: spk1.clone(), - }] + vec![( + 0, + TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + } + )] ); assert_eq!( received_txouts, vec![ - TxOut { - value: Amount::from_sat(20_000), - script_pubkey: spk2.clone(), - }, - TxOut { - value: Amount::from_sat(30_000), - script_pubkey: spk1.clone(), - } + ( + 0, + TxOut { + value: Amount::from_sat(20_000), + script_pubkey: spk2.clone(), + } + ), + ( + 1, + TxOut { + value: Amount::from_sat(30_000), + script_pubkey: spk1.clone(), + } + ) ] ); let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx2, ..1); assert_eq!( sent_txouts, - vec![TxOut { - value: Amount::from_sat(42_000), - script_pubkey: spk1.clone(), - }] + vec![( + 0, + TxOut { + value: Amount::from_sat(42_000), + script_pubkey: spk1.clone(), + } + )] ); assert_eq!( received_txouts, - vec![TxOut { - value: Amount::from_sat(30_000), - script_pubkey: spk1.clone(), - }] + vec![( + 1, + TxOut { + value: Amount::from_sat(30_000), + script_pubkey: spk1.clone(), + } + )] ); let (sent_txouts, received_txouts) = index.sent_and_received_txouts(&tx2, 1..); assert!(sent_txouts.is_empty()); assert_eq!( received_txouts, - vec![TxOut { - value: Amount::from_sat(20_000), - script_pubkey: spk2.clone(), - }] + vec![( + 0, + TxOut { + value: Amount::from_sat(20_000), + script_pubkey: spk2.clone(), + } + )] ); }