Skip to content

Commit 90c5921

Browse files
notmandatoryrustaceanrob
authored andcommitted
refactor(chain)!: update KeychainTxOutIndex methods to use owned ScriptBuf
1 parent 264991f commit 90c5921

File tree

9 files changed

+50
-48
lines changed

9 files changed

+50
-48
lines changed

crates/chain/src/indexer/keychain_txout.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::{
88
DescriptorExt, DescriptorId, Indexed, Indexer, KeychainIndexed, SpkIterator, SpkTxOutIndex,
99
};
1010
use alloc::{borrow::ToOwned, vec::Vec};
11-
use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
11+
use bitcoin::{Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
1212
use core::{
1313
fmt::Debug,
1414
ops::{Bound, RangeBounds},
@@ -254,14 +254,14 @@ impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
254254
/// Return the script that exists under the given `keychain`'s `index`.
255255
///
256256
/// This calls [`SpkTxOutIndex::spk_at_index`] internally.
257-
pub fn spk_at_index(&self, keychain: K, index: u32) -> Option<&Script> {
257+
pub fn spk_at_index(&self, keychain: K, index: u32) -> Option<ScriptBuf> {
258258
self.inner.spk_at_index(&(keychain.clone(), index))
259259
}
260260

261261
/// Returns the keychain and keychain index associated with the spk.
262262
///
263263
/// This calls [`SpkTxOutIndex::index_of_spk`] internally.
264-
pub fn index_of_spk(&self, script: &Script) -> Option<&(K, u32)> {
264+
pub fn index_of_spk(&self, script: ScriptBuf) -> Option<&(K, u32)> {
265265
self.inner.index_of_spk(script)
266266
}
267267

@@ -495,7 +495,7 @@ impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
495495
pub fn revealed_spks(
496496
&self,
497497
range: impl RangeBounds<K>,
498-
) -> impl Iterator<Item = KeychainIndexed<K, &Script>> {
498+
) -> impl Iterator<Item = KeychainIndexed<K, ScriptBuf>> + '_ {
499499
let start = range.start_bound();
500500
let end = range.end_bound();
501501
let mut iter_last_revealed = self
@@ -522,7 +522,7 @@ impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
522522
let (current_keychain, last_revealed) = current_keychain?;
523523

524524
if current_keychain == keychain && Some(*index) <= last_revealed {
525-
break Some(((keychain.clone(), *index), spk.as_script()));
525+
break Some(((keychain.clone(), *index), spk.clone()));
526526
}
527527
})
528528
}
@@ -534,24 +534,24 @@ impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
534534
pub fn revealed_keychain_spks(
535535
&self,
536536
keychain: K,
537-
) -> impl DoubleEndedIterator<Item = Indexed<&Script>> {
537+
) -> impl DoubleEndedIterator<Item = Indexed<ScriptBuf>> + '_ {
538538
let end = self
539539
.last_revealed_index(keychain.clone())
540540
.map(|v| v + 1)
541541
.unwrap_or(0);
542542
self.inner
543543
.all_spks()
544544
.range((keychain.clone(), 0)..(keychain.clone(), end))
545-
.map(|((_, index), spk)| (*index, spk.as_script()))
545+
.map(|((_, index), spk)| (*index, spk.clone()))
546546
}
547547

548548
/// Iterate over revealed, but unused, spks of all keychains.
549549
pub fn unused_spks(
550550
&self,
551-
) -> impl DoubleEndedIterator<Item = KeychainIndexed<K, &Script>> + Clone {
551+
) -> impl DoubleEndedIterator<Item = KeychainIndexed<K, ScriptBuf>> + Clone + '_ {
552552
self.keychain_to_descriptor_id.keys().flat_map(|keychain| {
553553
self.unused_keychain_spks(keychain.clone())
554-
.map(|(i, spk)| ((keychain.clone(), i), spk))
554+
.map(|(i, spk)| ((keychain.clone(), i), spk.clone()))
555555
})
556556
}
557557

@@ -560,7 +560,7 @@ impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
560560
pub fn unused_keychain_spks(
561561
&self,
562562
keychain: K,
563-
) -> impl DoubleEndedIterator<Item = Indexed<&Script>> + Clone {
563+
) -> impl DoubleEndedIterator<Item = Indexed<ScriptBuf>> + Clone + '_ {
564564
let end = match self.keychain_to_descriptor_id.get(&keychain) {
565565
Some(did) => self.last_revealed.get(did).map(|v| *v + 1).unwrap_or(0),
566566
None => 0,
@@ -701,7 +701,7 @@ impl<K: Clone + Ord + Debug> KeychainTxOutIndex<K> {
701701
.inner
702702
.spk_at_index(&(keychain.clone(), next_index))
703703
.expect("we just inserted it");
704-
Some(((next_index, script.into()), changeset))
704+
Some(((next_index, script), changeset))
705705
}
706706

707707
/// Gets the next unused script pubkey in the keychain. I.e., the script pubkey with the lowest

crates/chain/src/indexer/spk_txout.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::{
66
collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap},
77
Indexer,
88
};
9-
use bitcoin::{Amount, OutPoint, Script, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
9+
use bitcoin::{Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
1010

1111
/// An index storing [`TxOut`]s that have a script pubkey that matches those in a list.
1212
///
@@ -176,8 +176,8 @@ impl<I: Clone + Ord + core::fmt::Debug> SpkTxOutIndex<I> {
176176
/// Returns the script that has been inserted at the `index`.
177177
///
178178
/// If that index hasn't been inserted yet, it will return `None`.
179-
pub fn spk_at_index(&self, index: &I) -> Option<&Script> {
180-
self.spks.get(index).map(|s| s.as_script())
179+
pub fn spk_at_index(&self, index: &I) -> Option<ScriptBuf> {
180+
self.spks.get(index).cloned()
181181
}
182182

183183
/// The script pubkeys that are being tracked by the index.
@@ -217,7 +217,10 @@ impl<I: Clone + Ord + core::fmt::Debug> SpkTxOutIndex<I> {
217217
/// let unused_change_spks =
218218
/// txout_index.unused_spks((change_index, u32::MIN)..(change_index, u32::MAX));
219219
/// ```
220-
pub fn unused_spks<R>(&self, range: R) -> impl DoubleEndedIterator<Item = (&I, &Script)> + Clone
220+
pub fn unused_spks<R>(
221+
&self,
222+
range: R,
223+
) -> impl DoubleEndedIterator<Item = (&I, ScriptBuf)> + Clone + '_
221224
where
222225
R: RangeBounds<I>,
223226
{
@@ -268,8 +271,8 @@ impl<I: Clone + Ord + core::fmt::Debug> SpkTxOutIndex<I> {
268271
}
269272

270273
/// Returns the index associated with the script pubkey.
271-
pub fn index_of_spk(&self, script: &Script) -> Option<&I> {
272-
self.spk_indices.get(script)
274+
pub fn index_of_spk(&self, script: ScriptBuf) -> Option<&I> {
275+
self.spk_indices.get(script.as_script())
273276
}
274277

275278
/// Computes the total value transfer effect `tx` has on the script pubkeys in `range`. Value is
@@ -293,7 +296,7 @@ impl<I: Clone + Ord + core::fmt::Debug> SpkTxOutIndex<I> {
293296
}
294297
}
295298
for txout in &tx.output {
296-
if let Some(index) = self.index_of_spk(&txout.script_pubkey) {
299+
if let Some(index) = self.index_of_spk(txout.script_pubkey.clone()) {
297300
if range.contains(index) {
298301
received += txout.value;
299302
}

crates/chain/src/tx_graph.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ use crate::{
9494
use alloc::collections::vec_deque::VecDeque;
9595
use alloc::sync::Arc;
9696
use alloc::vec::Vec;
97-
use bitcoin::{Amount, OutPoint, Script, SignedAmount, Transaction, TxOut, Txid};
97+
use bitcoin::{Amount, OutPoint, ScriptBuf, SignedAmount, Transaction, TxOut, Txid};
9898
use core::fmt::{self, Formatter};
9999
use core::{
100100
convert::Infallible,
@@ -1163,7 +1163,7 @@ impl<A: Anchor> TxGraph<A> {
11631163
chain: &C,
11641164
chain_tip: BlockId,
11651165
outpoints: impl IntoIterator<Item = (OI, OutPoint)>,
1166-
mut trust_predicate: impl FnMut(&OI, &Script) -> bool,
1166+
mut trust_predicate: impl FnMut(&OI, ScriptBuf) -> bool,
11671167
) -> Result<Balance, C::Error> {
11681168
let mut immature = Amount::ZERO;
11691169
let mut trusted_pending = Amount::ZERO;
@@ -1182,7 +1182,7 @@ impl<A: Anchor> TxGraph<A> {
11821182
}
11831183
}
11841184
ChainPosition::Unconfirmed(_) => {
1185-
if trust_predicate(&spk_i, &txout.txout.script_pubkey) {
1185+
if trust_predicate(&spk_i, txout.txout.script_pubkey) {
11861186
trusted_pending += txout.txout.value;
11871187
} else {
11881188
untrusted_pending += txout.txout.value;
@@ -1209,7 +1209,7 @@ impl<A: Anchor> TxGraph<A> {
12091209
chain: &C,
12101210
chain_tip: BlockId,
12111211
outpoints: impl IntoIterator<Item = (OI, OutPoint)>,
1212-
trust_predicate: impl FnMut(&OI, &Script) -> bool,
1212+
trust_predicate: impl FnMut(&OI, ScriptBuf) -> bool,
12131213
) -> Balance {
12141214
self.try_balance(chain, chain_tip, outpoints, trust_predicate)
12151215
.expect("oracle is infallible")

crates/chain/tests/common/tx_template.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ pub fn init_graph<'a, A: Anchor + Clone + 'a>(
119119
},
120120
Some(index) => TxOut {
121121
value: Amount::from_sat(output.value),
122-
script_pubkey: spk_index.spk_at_index(index).unwrap().to_owned(),
122+
script_pubkey: spk_index.spk_at_index(index).unwrap(),
123123
},
124124
})
125125
.collect(),

crates/chain/tests/test_indexed_tx_graph.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ use bdk_chain::{
1212
local_chain::LocalChain,
1313
tx_graph, Balance, ChainPosition, ConfirmationHeightAnchor, DescriptorExt, Merge,
1414
};
15-
use bitcoin::{
16-
secp256k1::Secp256k1, Amount, OutPoint, Script, ScriptBuf, Transaction, TxIn, TxOut,
17-
};
15+
use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxIn, TxOut};
1816
use miniscript::Descriptor;
1917

2018
/// Ensure [`IndexedTxGraph::insert_relevant_txs`] can successfully index transactions NOT presented
@@ -289,7 +287,7 @@ fn test_list_owned_txouts() {
289287
&local_chain,
290288
chain_tip,
291289
graph.index.outpoints().iter().cloned(),
292-
|_, spk: &Script| trusted_spks.contains(&spk.to_owned()),
290+
|_, spk: ScriptBuf| trusted_spks.contains(&spk),
293291
);
294292

295293
let confirmed_txouts_txid = txouts

crates/chain/tests/test_tx_graph_conflicts.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ mod common;
66
use std::collections::{BTreeSet, HashSet};
77

88
use bdk_chain::{Balance, BlockId};
9-
use bitcoin::{Amount, OutPoint, Script};
9+
use bitcoin::{Amount, OutPoint, ScriptBuf};
1010
use common::*;
1111

1212
#[allow(dead_code)]
@@ -659,7 +659,7 @@ fn test_tx_conflict_handling() {
659659
&local_chain,
660660
chain_tip,
661661
spk_index.outpoints().iter().cloned(),
662-
|_, spk: &Script| spk_index.index_of_spk(spk).is_some(),
662+
|_, spk: ScriptBuf| spk_index.index_of_spk(spk).is_some(),
663663
);
664664
assert_eq!(
665665
balance, scenario.exp_balance,

crates/wallet/src/wallet/mod.rs

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ use bdk_chain::{
3333
};
3434
use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
3535
use bitcoin::{
36-
absolute, psbt, Address, Block, FeeRate, Network, OutPoint, Script, ScriptBuf, Sequence,
37-
Transaction, TxOut, Txid, Witness,
36+
absolute, psbt, Address, Block, FeeRate, Network, OutPoint, ScriptBuf, Sequence, Transaction,
37+
TxOut, Txid, Witness,
3838
};
3939
use bitcoin::{consensus::encode::serialize, transaction, BlockHash, Psbt};
4040
use bitcoin::{constants::genesis_block, Amount};
@@ -764,20 +764,21 @@ impl Wallet {
764764
.unused_keychain_spks(keychain)
765765
.map(move |(index, spk)| AddressInfo {
766766
index,
767-
address: Address::from_script(spk, self.network).expect("must have address form"),
767+
address: Address::from_script(spk.as_script(), self.network)
768+
.expect("must have address form"),
768769
keychain,
769770
})
770771
}
771772

772773
/// Return whether or not a `script` is part of this wallet (either internal or external)
773-
pub fn is_mine(&self, script: &Script) -> bool {
774+
pub fn is_mine(&self, script: ScriptBuf) -> bool {
774775
self.indexed_graph.index.index_of_spk(script).is_some()
775776
}
776777

777778
/// Finds how the wallet derived the script pubkey `spk`.
778779
///
779780
/// Will only return `Some(_)` if the wallet has given out the spk.
780-
pub fn derivation_of_spk(&self, spk: &Script) -> Option<(KeychainKind, u32)> {
781+
pub fn derivation_of_spk(&self, spk: ScriptBuf) -> Option<(KeychainKind, u32)> {
781782
self.indexed_graph.index.index_of_spk(spk).cloned()
782783
}
783784

@@ -1364,7 +1365,7 @@ impl Wallet {
13641365
return Err(CreateTxError::OutputBelowDustLimit(index));
13651366
}
13661367

1367-
if self.is_mine(script_pubkey) {
1368+
if self.is_mine(script_pubkey.clone()) {
13681369
received += Amount::from_sat(value);
13691370
}
13701371

@@ -1471,7 +1472,7 @@ impl Wallet {
14711472
remaining_amount, ..
14721473
} => fee_amount += remaining_amount,
14731474
Change { amount, fee } => {
1474-
if self.is_mine(&drain_script) {
1475+
if self.is_mine(drain_script.clone()) {
14751476
received += Amount::from_sat(*amount);
14761477
}
14771478
fee_amount += fee;
@@ -1592,7 +1593,7 @@ impl Wallet {
15921593
.cloned()
15931594
.into();
15941595

1595-
let weighted_utxo = match txout_index.index_of_spk(&txout.script_pubkey) {
1596+
let weighted_utxo = match txout_index.index_of_spk(txout.script_pubkey.clone()) {
15961597
Some(&(keychain, derivation_index)) => {
15971598
let satisfaction_weight = self
15981599
.public_descriptor(keychain)
@@ -1637,7 +1638,7 @@ impl Wallet {
16371638
let mut change_index = None;
16381639
for (index, txout) in tx.output.iter().enumerate() {
16391640
let change_keychain = KeychainKind::Internal;
1640-
match txout_index.index_of_spk(&txout.script_pubkey) {
1641+
match txout_index.index_of_spk(txout.script_pubkey.clone()) {
16411642
Some((keychain, _)) if *keychain == change_keychain => {
16421643
change_index = Some(index)
16431644
}
@@ -1899,7 +1900,7 @@ impl Wallet {
18991900
pub fn cancel_tx(&mut self, tx: &Transaction) {
19001901
let txout_index = &mut self.indexed_graph.index;
19011902
for txout in &tx.output {
1902-
if let Some((keychain, index)) = txout_index.index_of_spk(&txout.script_pubkey) {
1903+
if let Some((keychain, index)) = txout_index.index_of_spk(txout.script_pubkey.clone()) {
19031904
// NOTE: unmark_used will **not** make something unused if it has actually been used
19041905
// by a tx in the tracker. It only removes the superficial marking.
19051906
txout_index.unmark_used(*keychain, *index);
@@ -1911,7 +1912,7 @@ impl Wallet {
19111912
let &(keychain, child) = self
19121913
.indexed_graph
19131914
.index
1914-
.index_of_spk(&txout.script_pubkey)?;
1915+
.index_of_spk(txout.script_pubkey.clone())?;
19151916
let descriptor = self.public_descriptor(keychain);
19161917
descriptor.at_derivation_index(child).ok()
19171918
}
@@ -2126,7 +2127,7 @@ impl Wallet {
21262127
let &(keychain, child) = self
21272128
.indexed_graph
21282129
.index
2129-
.index_of_spk(&utxo.txout.script_pubkey)
2130+
.index_of_spk(utxo.txout.script_pubkey)
21302131
.ok_or(CreateTxError::UnknownUtxo)?;
21312132

21322133
let mut psbt_input = psbt::Input {
@@ -2172,7 +2173,7 @@ impl Wallet {
21722173
// Try to figure out the keychain and derivation for every input and output
21732174
for (is_input, index, out) in utxos.into_iter() {
21742175
if let Some(&(keychain, child)) =
2175-
self.indexed_graph.index.index_of_spk(&out.script_pubkey)
2176+
self.indexed_graph.index.index_of_spk(out.script_pubkey)
21762177
{
21772178
let desc = self.public_descriptor(keychain);
21782179
let desc = desc

crates/wallet/tests/wallet.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4070,7 +4070,7 @@ fn test_tx_cancellation() {
40704070
.unsigned_tx
40714071
.output
40724072
.iter()
4073-
.find_map(|txout| wallet.derivation_of_spk(&txout.script_pubkey))
4073+
.find_map(|txout| wallet.derivation_of_spk(txout.script_pubkey.clone()))
40744074
.unwrap();
40754075
assert_eq!(change_derivation_1, (KeychainKind::Internal, 0));
40764076

@@ -4080,7 +4080,7 @@ fn test_tx_cancellation() {
40804080
.unsigned_tx
40814081
.output
40824082
.iter()
4083-
.find_map(|txout| wallet.derivation_of_spk(&txout.script_pubkey))
4083+
.find_map(|txout| wallet.derivation_of_spk(txout.script_pubkey.clone()))
40844084
.unwrap();
40854085
assert_eq!(change_derivation_2, (KeychainKind::Internal, 1));
40864086

@@ -4091,7 +4091,7 @@ fn test_tx_cancellation() {
40914091
.unsigned_tx
40924092
.output
40934093
.iter()
4094-
.find_map(|txout| wallet.derivation_of_spk(&txout.script_pubkey))
4094+
.find_map(|txout| wallet.derivation_of_spk(txout.script_pubkey.clone()))
40954095
.unwrap();
40964096
assert_eq!(change_derivation_3, (KeychainKind::Internal, 0));
40974097

@@ -4100,7 +4100,7 @@ fn test_tx_cancellation() {
41004100
.unsigned_tx
41014101
.output
41024102
.iter()
4103-
.find_map(|txout| wallet.derivation_of_spk(&txout.script_pubkey))
4103+
.find_map(|txout| wallet.derivation_of_spk(txout.script_pubkey.clone()))
41044104
.unwrap();
41054105
assert_eq!(change_derivation_3, (KeychainKind::Internal, 2));
41064106

@@ -4111,7 +4111,7 @@ fn test_tx_cancellation() {
41114111
.unsigned_tx
41124112
.output
41134113
.iter()
4114-
.find_map(|txout| wallet.derivation_of_spk(&txout.script_pubkey))
4114+
.find_map(|txout| wallet.derivation_of_spk(txout.script_pubkey.clone()))
41154115
.unwrap();
41164116
assert_eq!(change_derivation_4, (KeychainKind::Internal, 2));
41174117
}

example-crates/example_cli/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,7 @@ where
502502
false => Keychain::External,
503503
};
504504
for (spk_i, spk) in index.revealed_keychain_spks(target_keychain) {
505-
let address = Address::from_script(spk, network)
505+
let address = Address::from_script(spk.as_script(), network)
506506
.expect("should always be able to derive address");
507507
println!(
508508
"{:?} {} used:{}",

0 commit comments

Comments
 (0)