Skip to content

Commit c8f2ddf

Browse files
committed
feat(chain)!: 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 68db7e5 commit c8f2ddf

File tree

15 files changed

+409
-98
lines changed

15 files changed

+409
-98
lines changed

crates/bitcoind_rpc/examples/filter_iter.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ fn main() -> anyhow::Result<()> {
9292
.filter_chain_unspents(
9393
&chain,
9494
chain.tip().block_id(),
95+
Default::default(),
9596
graph.index.outpoints().clone(),
9697
)
9798
.collect();

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, CanonicalizationParams, 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+
CanonicalizationParams::default(),
313+
outpoints,
314+
|_, _| true,
315+
);
312316
Ok(balance)
313317
}
314318

crates/chain/benches/canonicalization.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use bdk_chain::CanonicalizationParams;
12
use bdk_chain::{keychain_txout::KeychainTxOutIndex, local_chain::LocalChain, IndexedTxGraph};
23
use bdk_core::{BlockId, CheckPoint};
34
use bdk_core::{ConfirmationBlockTime, TxUpdate};
@@ -90,16 +91,19 @@ fn setup<F: Fn(&mut KeychainTxGraph, &LocalChain)>(f: F) -> (KeychainTxGraph, Lo
9091
}
9192

9293
fn run_list_canonical_txs(tx_graph: &KeychainTxGraph, chain: &LocalChain, exp_txs: usize) {
93-
let txs = tx_graph
94-
.graph()
95-
.list_canonical_txs(chain, chain.tip().block_id());
94+
let txs = tx_graph.graph().list_canonical_txs(
95+
chain,
96+
chain.tip().block_id(),
97+
CanonicalizationParams::default(),
98+
);
9699
assert_eq!(txs.count(), exp_txs);
97100
}
98101

99102
fn run_filter_chain_txouts(tx_graph: &KeychainTxGraph, chain: &LocalChain, exp_txos: usize) {
100103
let utxos = tx_graph.graph().filter_chain_txouts(
101104
chain,
102105
chain.tip().block_id(),
106+
CanonicalizationParams::default(),
103107
tx_graph.index.outpoints().clone(),
104108
);
105109
assert_eq!(utxos.count(), exp_txos);
@@ -109,6 +113,7 @@ fn run_filter_chain_unspents(tx_graph: &KeychainTxGraph, chain: &LocalChain, exp
109113
let utxos = tx_graph.graph().filter_chain_unspents(
110114
chain,
111115
chain.tip().block_id(),
116+
CanonicalizationParams::default(),
112117
tx_graph.index.outpoints().clone(),
113118
);
114119
assert_eq!(utxos.count(), exp_utxos);

crates/chain/src/canonical_iter.rs

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,26 @@ 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 CanonicalizationParams {
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+
}
1020
/// Iterates over canonical txs.
1121
pub struct CanonicalIter<'g, A, C> {
1222
tx_graph: &'g TxGraph<A>,
1323
chain: &'g C,
1424
chain_tip: BlockId,
1525

26+
unprocessed_assumed_txs: Box<dyn Iterator<Item = (Txid, Arc<Transaction>)> + 'g>,
1627
unprocessed_anchored_txs:
1728
Box<dyn Iterator<Item = (Txid, Arc<Transaction>, &'g BTreeSet<A>)> + 'g>,
1829
unprocessed_seen_txs: Box<dyn Iterator<Item = (Txid, Arc<Transaction>, u64)> + 'g>,
@@ -26,8 +37,19 @@ pub struct CanonicalIter<'g, A, C> {
2637

2738
impl<'g, A: Anchor, C: ChainOracle> CanonicalIter<'g, A, C> {
2839
/// Constructs [`CanonicalIter`].
29-
pub fn new(tx_graph: &'g TxGraph<A>, chain: &'g C, chain_tip: BlockId) -> Self {
40+
pub fn new(
41+
tx_graph: &'g TxGraph<A>,
42+
chain: &'g C,
43+
chain_tip: BlockId,
44+
mods: CanonicalizationParams,
45+
) -> Self {
3046
let anchors = tx_graph.all_anchors();
47+
let unprocessed_assumed_txs = Box::new(
48+
mods.assume_canonical
49+
.into_iter()
50+
.rev()
51+
.filter_map(|txid| Some((txid, tx_graph.get_tx(txid)?))),
52+
);
3153
let unprocessed_anchored_txs = Box::new(
3254
tx_graph
3355
.txids_by_descending_anchor_height()
@@ -42,6 +64,7 @@ impl<'g, A: Anchor, C: ChainOracle> CanonicalIter<'g, A, C> {
4264
tx_graph,
4365
chain,
4466
chain_tip,
67+
unprocessed_assumed_txs,
4568
unprocessed_anchored_txs,
4669
unprocessed_seen_txs,
4770
unprocessed_leftover_txs: VecDeque::new(),
@@ -147,6 +170,12 @@ impl<A: Anchor, C: ChainOracle> Iterator for CanonicalIter<'_, A, C> {
147170
return Some(Ok((txid, tx, reason)));
148171
}
149172

173+
if let Some((txid, tx)) = self.unprocessed_assumed_txs.next() {
174+
if !self.is_canonicalized(txid) {
175+
self.mark_canonical(txid, tx, CanonicalReason::assumed());
176+
}
177+
}
178+
150179
if let Some((txid, tx, anchors)) = self.unprocessed_anchored_txs.next() {
151180
if !self.is_canonicalized(txid) {
152181
if let Err(err) = self.scan_anchors(txid, tx, anchors) {
@@ -189,6 +218,12 @@ pub enum ObservedIn {
189218
/// The reason why a transaction is canonical.
190219
#[derive(Debug, Clone, PartialEq, Eq)]
191220
pub enum CanonicalReason<A> {
221+
/// This transaction is explicitly assumed to be canonical by the caller, superceding all other
222+
/// canonicalization rules.
223+
Assumed {
224+
/// Whether it is a descendant that is assumed to be canonical.
225+
descendant: Option<Txid>,
226+
},
192227
/// This transaction is anchored in the best chain by `A`, and therefore canonical.
193228
Anchor {
194229
/// The anchor that anchored the transaction in the chain.
@@ -207,6 +242,12 @@ pub enum CanonicalReason<A> {
207242
}
208243

209244
impl<A: Clone> CanonicalReason<A> {
245+
/// Constructs a [`CanonicalReason`] for a transaction that is assumed to supercede all other
246+
/// transactions.
247+
pub fn assumed() -> Self {
248+
Self::Assumed { descendant: None }
249+
}
250+
210251
/// Constructs a [`CanonicalReason`] from an `anchor`.
211252
pub fn from_anchor(anchor: A) -> Self {
212253
Self::Anchor {
@@ -229,6 +270,9 @@ impl<A: Clone> CanonicalReason<A> {
229270
/// descendant, but is transitively relevant.
230271
pub fn to_transitive(&self, descendant: Txid) -> Self {
231272
match self {
273+
CanonicalReason::Assumed { .. } => Self::Assumed {
274+
descendant: Some(descendant),
275+
},
232276
CanonicalReason::Anchor { anchor, .. } => Self::Anchor {
233277
anchor: anchor.clone(),
234278
descendant: Some(descendant),
@@ -244,6 +288,7 @@ impl<A: Clone> CanonicalReason<A> {
244288
/// descendant.
245289
pub fn descendant(&self) -> &Option<Txid> {
246290
match self {
291+
CanonicalReason::Assumed { descendant, .. } => descendant,
247292
CanonicalReason::Anchor { descendant, .. } => descendant,
248293
CanonicalReason::ObservedIn { descendant, .. } => descendant,
249294
}

0 commit comments

Comments
 (0)