Skip to content

Commit 3567fb0

Browse files
committed
feat(chain,wallet)!: Add ability to modify canonicalization algorithm
Introduce `CanonicalizationMods` which is passed in to `CanonicalIter::new`. `CanonicalizationMods::assume_canonical` is the only field right now. This contains a list of txids that we assume to be canonical, superceding any other canonicalization rules.
1 parent 251bd7e commit 3567fb0

File tree

15 files changed

+229
-84
lines changed

15 files changed

+229
-84
lines changed

crates/bitcoind_rpc/tests/test_emitter.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use bdk_chain::{
55
bitcoin::{Address, Amount, Txid},
66
local_chain::{CheckPoint, LocalChain},
77
spk_txout::SpkTxOutIndex,
8-
Balance, BlockId, IndexedTxGraph, Merge,
8+
Balance, BlockId, CanonicalizationMods, IndexedTxGraph, Merge,
99
};
1010
use bdk_testenv::{anyhow, TestEnv};
1111
use bitcoin::{hashes::Hash, Block, OutPoint, ScriptBuf, WScriptHash};
@@ -306,9 +306,13 @@ fn get_balance(
306306
) -> anyhow::Result<Balance> {
307307
let chain_tip = recv_chain.tip().block_id();
308308
let outpoints = recv_graph.index.outpoints().clone();
309-
let balance = recv_graph
310-
.graph()
311-
.balance(recv_chain, chain_tip, outpoints, |_, _| true);
309+
let balance = recv_graph.graph().balance(
310+
recv_chain,
311+
chain_tip,
312+
CanonicalizationMods::NONE,
313+
outpoints,
314+
|_, _| true,
315+
);
312316
Ok(balance)
313317
}
314318

crates/chain/benches/canonicalization.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use bdk_chain::CanonicalizationMods;
12
use bdk_chain::{keychain_txout::KeychainTxOutIndex, local_chain::LocalChain, IndexedTxGraph};
23
use bdk_core::{BlockId, CheckPoint};
34
use bdk_core::{ConfirmationBlockTime, TxUpdate};
@@ -92,14 +93,15 @@ fn setup<F: Fn(&mut KeychainTxGraph, &LocalChain)>(f: F) -> (KeychainTxGraph, Lo
9293
fn run_list_canonical_txs(tx_graph: &KeychainTxGraph, chain: &LocalChain, exp_txs: usize) {
9394
let txs = tx_graph
9495
.graph()
95-
.list_canonical_txs(chain, chain.tip().block_id());
96+
.list_canonical_txs(chain, chain.tip().block_id(), CanonicalizationMods::NONE);
9697
assert_eq!(txs.count(), exp_txs);
9798
}
9899

99100
fn run_filter_chain_txouts(tx_graph: &KeychainTxGraph, chain: &LocalChain, exp_txos: usize) {
100101
let utxos = tx_graph.graph().filter_chain_txouts(
101102
chain,
102103
chain.tip().block_id(),
104+
CanonicalizationMods::NONE,
103105
tx_graph.index.outpoints().clone(),
104106
);
105107
assert_eq!(utxos.count(), exp_txos);
@@ -109,6 +111,7 @@ fn run_filter_chain_unspents(tx_graph: &KeychainTxGraph, chain: &LocalChain, exp
109111
let utxos = tx_graph.graph().filter_chain_unspents(
110112
chain,
111113
chain.tip().block_id(),
114+
CanonicalizationMods::NONE,
112115
tx_graph.index.outpoints().clone(),
113116
);
114117
assert_eq!(utxos.count(), exp_utxos);

crates/chain/src/canonical_iter.rs

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,34 @@ use crate::{Anchor, ChainOracle, TxGraph};
44
use alloc::boxed::Box;
55
use alloc::collections::BTreeSet;
66
use alloc::sync::Arc;
7+
use alloc::vec::Vec;
78
use bdk_core::BlockId;
89
use bitcoin::{Transaction, Txid};
910

11+
/// Modifies the canonicalization algorithm.
12+
#[derive(Debug, Default, Clone)]
13+
pub struct CanonicalizationMods {
14+
/// Transactions that will supercede all other transactions.
15+
///
16+
/// In case of conflicting transactions within `assume_canonical`, transactions that appear
17+
/// later in the list (have higher index) have precedence.
18+
pub assume_canonical: Vec<Txid>,
19+
}
20+
21+
impl CanonicalizationMods {
22+
/// No mods.
23+
pub const NONE: Self = Self {
24+
assume_canonical: Vec::new(),
25+
};
26+
}
27+
1028
/// Iterates over canonical txs.
1129
pub struct CanonicalIter<'g, A, C> {
1230
tx_graph: &'g TxGraph<A>,
1331
chain: &'g C,
1432
chain_tip: BlockId,
1533

34+
unprocessed_assumed_txs: Box<dyn Iterator<Item = (Txid, Arc<Transaction>)> + 'g>,
1635
unprocessed_anchored_txs:
1736
Box<dyn Iterator<Item = (Txid, Arc<Transaction>, &'g BTreeSet<A>)> + 'g>,
1837
unprocessed_seen_txs: Box<dyn Iterator<Item = (Txid, Arc<Transaction>, u64)> + 'g>,
@@ -26,8 +45,19 @@ pub struct CanonicalIter<'g, A, C> {
2645

2746
impl<'g, A: Anchor, C: ChainOracle> CanonicalIter<'g, A, C> {
2847
/// Constructs [`CanonicalIter`].
29-
pub fn new(tx_graph: &'g TxGraph<A>, chain: &'g C, chain_tip: BlockId) -> Self {
48+
pub fn new(
49+
tx_graph: &'g TxGraph<A>,
50+
chain: &'g C,
51+
chain_tip: BlockId,
52+
mods: CanonicalizationMods,
53+
) -> Self {
3054
let anchors = tx_graph.all_anchors();
55+
let unprocessed_assumed_txs = Box::new(
56+
mods.assume_canonical
57+
.into_iter()
58+
.rev()
59+
.filter_map(|txid| Some((txid, tx_graph.get_tx(txid)?))),
60+
);
3161
let unprocessed_anchored_txs = Box::new(
3262
tx_graph
3363
.txids_by_descending_anchor_height()
@@ -42,6 +72,7 @@ impl<'g, A: Anchor, C: ChainOracle> CanonicalIter<'g, A, C> {
4272
tx_graph,
4373
chain,
4474
chain_tip,
75+
unprocessed_assumed_txs,
4576
unprocessed_anchored_txs,
4677
unprocessed_seen_txs,
4778
unprocessed_leftover_txs: VecDeque::new(),
@@ -147,6 +178,12 @@ impl<A: Anchor, C: ChainOracle> Iterator for CanonicalIter<'_, A, C> {
147178
return Some(Ok((txid, tx, reason)));
148179
}
149180

181+
if let Some((txid, tx)) = self.unprocessed_assumed_txs.next() {
182+
if !self.is_canonicalized(txid) {
183+
self.mark_canonical(txid, tx, CanonicalReason::assumed());
184+
}
185+
}
186+
150187
if let Some((txid, tx, anchors)) = self.unprocessed_anchored_txs.next() {
151188
if !self.is_canonicalized(txid) {
152189
if let Err(err) = self.scan_anchors(txid, tx, anchors) {
@@ -189,6 +226,12 @@ pub enum ObservedIn {
189226
/// The reason why a transaction is canonical.
190227
#[derive(Debug, Clone, PartialEq, Eq)]
191228
pub enum CanonicalReason<A> {
229+
/// This transaction is explicitly assumed to be canonical by the caller, superceding all other
230+
/// canonicalization rules.
231+
Assumed {
232+
/// Whether it is a descendant that is assumed to be canonical.
233+
descendant: Option<Txid>,
234+
},
192235
/// This transaction is anchored in the best chain by `A`, and therefore canonical.
193236
Anchor {
194237
/// The anchor that anchored the transaction in the chain.
@@ -207,6 +250,12 @@ pub enum CanonicalReason<A> {
207250
}
208251

209252
impl<A: Clone> CanonicalReason<A> {
253+
/// Constructs a [`CanonicalReason`] for a transaction that is assumed to supercede all other
254+
/// transactions.
255+
pub fn assumed() -> Self {
256+
Self::Assumed { descendant: None }
257+
}
258+
210259
/// Constructs a [`CanonicalReason`] from an `anchor`.
211260
pub fn from_anchor(anchor: A) -> Self {
212261
Self::Anchor {
@@ -229,6 +278,9 @@ impl<A: Clone> CanonicalReason<A> {
229278
/// descendant, but is transitively relevant.
230279
pub fn to_transitive(&self, descendant: Txid) -> Self {
231280
match self {
281+
CanonicalReason::Assumed { .. } => Self::Assumed {
282+
descendant: Some(descendant),
283+
},
232284
CanonicalReason::Anchor { anchor, .. } => Self::Anchor {
233285
anchor: anchor.clone(),
234286
descendant: Some(descendant),
@@ -244,6 +296,7 @@ impl<A: Clone> CanonicalReason<A> {
244296
/// descendant.
245297
pub fn descendant(&self) -> &Option<Txid> {
246298
match self {
299+
CanonicalReason::Assumed { descendant, .. } => descendant,
247300
CanonicalReason::Anchor { descendant, .. } => descendant,
248301
CanonicalReason::ObservedIn { descendant, .. } => descendant,
249302
}

0 commit comments

Comments
 (0)