Skip to content

Commit

Permalink
refactor(test): move tx test utils to testenv
Browse files Browse the repository at this point in the history
- add `utils` mod to testenv crate to keep all
utilities moved from `crates/chain/test/common`
- replace all test tx macros in `chain` crate with
import from `testenv` crate
    - tests/test_indexed_tx_graph
    - tests/test_keychain_txout_index
    - tests/test_local_chain
    - tests/test_tx_graph
    - tests/test_tx_graph_conflicts
- deleted all moved macros and functions in
`crates/chain/test/common/mod`
- replace `bitcoin` external crate with
`bd_chain::bitcoin`
- move `DESCRIPTORS` sample array to `utils` for
other crates to use
- rename h! macro to hash! for clarity
- rename localchain! macro parameter from
'block_hash' to 'hash'

[Ticket: #1602]
  • Loading branch information
tvpeter committed Oct 3, 2024
1 parent ec7342d commit 88a8403
Show file tree
Hide file tree
Showing 13 changed files with 368 additions and 350 deletions.
2 changes: 2 additions & 0 deletions crates/chain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ serde_json = { version = "1", optional = true }
[dev-dependencies]
rand = "0.8"
proptest = "1.2.0"
bdk_testenv = { path = "../testenv", default-features = false }


[features]
default = ["std", "miniscript"]
Expand Down
84 changes: 0 additions & 84 deletions crates/chain/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,87 +3,3 @@
mod tx_template;
#[allow(unused_imports)]
pub use tx_template::*;

#[allow(unused_macros)]
macro_rules! block_id {
($height:expr, $hash:literal) => {{
bdk_chain::BlockId {
height: $height,
hash: bitcoin::hashes::Hash::hash($hash.as_bytes()),
}
}};
}

#[allow(unused_macros)]
macro_rules! h {
($index:literal) => {{
bitcoin::hashes::Hash::hash($index.as_bytes())
}};
}

#[allow(unused_macros)]
macro_rules! local_chain {
[ $(($height:expr, $block_hash:expr)), * ] => {{
#[allow(unused_mut)]
bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $block_hash).into()),*].into_iter().collect())
.expect("chain must have genesis block")
}};
}

#[allow(unused_macros)]
macro_rules! chain_update {
[ $(($height:expr, $hash:expr)), * ] => {{
#[allow(unused_mut)]
bdk_chain::local_chain::LocalChain::from_blocks([$(($height, $hash).into()),*].into_iter().collect())
.expect("chain must have genesis block")
.tip()
}};
}

#[allow(unused_macros)]
macro_rules! changeset {
(checkpoints: $($tail:tt)*) => { changeset!(index: TxHeight, checkpoints: $($tail)*) };
(
index: $ind:ty,
checkpoints: [ $(( $height:expr, $cp_to:expr )),* ]
$(,txids: [ $(( $txid:expr, $tx_to:expr )),* ])?
) => {{
use bdk_chain::collections::BTreeMap;

#[allow(unused_mut)]
bdk_chain::sparse_chain::ChangeSet::<$ind> {
checkpoints: {
let mut changes = BTreeMap::default();
$(changes.insert($height, $cp_to);)*
changes
},
txids: {
let mut changes = BTreeMap::default();
$($(changes.insert($txid, $tx_to.map(|h: TxHeight| h.into()));)*)?
changes
}
}
}};
}

#[allow(unused)]
pub fn new_tx(lt: u32) -> bitcoin::Transaction {
bitcoin::Transaction {
version: bitcoin::transaction::Version::non_standard(0x00),
lock_time: bitcoin::absolute::LockTime::from_consensus(lt),
input: vec![],
output: vec![],
}
}

#[allow(unused)]
pub const DESCRIPTORS: [&str; 7] = [
"tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/0/*)",
"tr([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/*)",
"wpkh([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/0/*)",
"tr(tprv8ZgxMBicQKsPd3krDUsBAmtnRsK3rb8u5yi1zhQgMhF1tR8MW7xfE4rnrbbsrbPR52e7rKapu6ztw1jXveJSCGHEriUGZV7mCe88duLp5pj/86'/1'/0'/0/*)",
"tr(tprv8ZgxMBicQKsPd3krDUsBAmtnRsK3rb8u5yi1zhQgMhF1tR8MW7xfE4rnrbbsrbPR52e7rKapu6ztw1jXveJSCGHEriUGZV7mCe88duLp5pj/86'/1'/0'/1/*)",
"wpkh(xprv9s21ZrQH143K4EXURwMHuLS469fFzZyXk7UUpdKfQwhoHcAiYTakpe8pMU2RiEdvrU9McyuE7YDoKcXkoAwEGoK53WBDnKKv2zZbb9BzttX/1/0/*)",
// non-wildcard
"wpkh([73c5da0a/86'/0'/0']xprv9xgqHN7yz9MwCkxsBPN5qetuNdQSUttZNKw1dcYTV4mkaAFiBVGQziHs3NRSWMkCzvgjEe3n9xV8oYywvM8at9yRqyaZVz6TYYhX98VjsUk/1/0)",
];
3 changes: 2 additions & 1 deletion crates/chain/tests/common/tx_template.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![cfg(feature = "miniscript")]

use bdk_testenv::utils::DESCRIPTORS;
use rand::distributions::{Alphanumeric, DistString};
use std::collections::HashMap;

Expand Down Expand Up @@ -55,7 +56,7 @@ pub fn init_graph<'a, A: Anchor + Clone + 'a>(
tx_templates: impl IntoIterator<Item = &'a TxTemplate<'a, A>>,
) -> (TxGraph<A>, SpkTxOutIndex<u32>, HashMap<&'a str, Txid>) {
let (descriptor, _) =
Descriptor::parse_descriptor(&Secp256k1::signing_only(), super::DESCRIPTORS[2]).unwrap();
Descriptor::parse_descriptor(&Secp256k1::signing_only(), DESCRIPTORS[2]).unwrap();
let mut graph = TxGraph::<A>::default();
let mut spk_index = SpkTxOutIndex::default();
(0..10).for_each(|index| {
Expand Down
42 changes: 23 additions & 19 deletions crates/chain/tests/test_indexed_tx_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ mod common;

use std::{collections::BTreeSet, sync::Arc};

use crate::common::DESCRIPTORS;
use bdk_chain::{
indexed_tx_graph::{self, IndexedTxGraph},
indexer::keychain_txout::KeychainTxOutIndex,
local_chain::LocalChain,
tx_graph, Balance, ChainPosition, ConfirmationBlockTime, DescriptorExt,
};
use bdk_testenv::{
block_id, hash,
utils::{new_tx, DESCRIPTORS},
};
use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxIn, TxOut};
use miniscript::Descriptor;

Expand Down Expand Up @@ -49,23 +52,23 @@ fn insert_relevant_txs() {
script_pubkey: spk_1,
},
],
..common::new_tx(0)
..new_tx(0)
};

let tx_b = Transaction {
input: vec![TxIn {
previous_output: OutPoint::new(tx_a.compute_txid(), 0),
..Default::default()
}],
..common::new_tx(1)
..new_tx(1)
};

let tx_c = Transaction {
input: vec![TxIn {
previous_output: OutPoint::new(tx_a.compute_txid(), 1),
..Default::default()
}],
..common::new_tx(2)
..new_tx(2)
};

let txs = [tx_c, tx_b, tx_a];
Expand Down Expand Up @@ -126,15 +129,16 @@ fn insert_relevant_txs() {
#[test]
fn test_list_owned_txouts() {
// Create Local chains
let local_chain = LocalChain::from_blocks((0..150).map(|i| (i as u32, h!("random"))).collect())
.expect("must have genesis hash");
let local_chain =
LocalChain::from_blocks((0..150).map(|i| (i as u32, hash!("random"))).collect())
.expect("must have genesis hash");

// Initiate IndexedTxGraph

let (desc_1, _) =
Descriptor::parse_descriptor(&Secp256k1::signing_only(), common::DESCRIPTORS[2]).unwrap();
Descriptor::parse_descriptor(&Secp256k1::signing_only(), DESCRIPTORS[2]).unwrap();
let (desc_2, _) =
Descriptor::parse_descriptor(&Secp256k1::signing_only(), common::DESCRIPTORS[3]).unwrap();
Descriptor::parse_descriptor(&Secp256k1::signing_only(), DESCRIPTORS[3]).unwrap();

let mut graph = IndexedTxGraph::<ConfirmationBlockTime, KeychainTxOutIndex<String>>::new(
KeychainTxOutIndex::new(10),
Expand Down Expand Up @@ -187,7 +191,7 @@ fn test_list_owned_txouts() {
value: Amount::from_sat(70000),
script_pubkey: trusted_spks[0].to_owned(),
}],
..common::new_tx(0)
..new_tx(0)
};

// tx2 is an incoming transaction received at untrusted keychain at block 1.
Expand All @@ -196,7 +200,7 @@ fn test_list_owned_txouts() {
value: Amount::from_sat(30000),
script_pubkey: untrusted_spks[0].to_owned(),
}],
..common::new_tx(0)
..new_tx(0)
};

// tx3 spends tx2 and gives a change back in trusted keychain. Confirmed at Block 2.
Expand All @@ -209,7 +213,7 @@ fn test_list_owned_txouts() {
value: Amount::from_sat(10000),
script_pubkey: trusted_spks[1].to_owned(),
}],
..common::new_tx(0)
..new_tx(0)
};

// tx4 is an external transaction receiving at untrusted keychain, unconfirmed.
Expand All @@ -218,7 +222,7 @@ fn test_list_owned_txouts() {
value: Amount::from_sat(20000),
script_pubkey: untrusted_spks[1].to_owned(),
}],
..common::new_tx(0)
..new_tx(0)
};

// tx5 is an external transaction receiving at trusted keychain, unconfirmed.
Expand All @@ -227,11 +231,11 @@ fn test_list_owned_txouts() {
value: Amount::from_sat(15000),
script_pubkey: trusted_spks[2].to_owned(),
}],
..common::new_tx(0)
..new_tx(0)
};

// tx6 is an unrelated transaction confirmed at 3.
let tx6 = common::new_tx(0);
let tx6 = new_tx(0);

// Insert transactions into graph with respective anchors
// Insert unconfirmed txs with a last_seen timestamp
Expand Down Expand Up @@ -597,7 +601,7 @@ fn test_get_chain_position() {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(0)
..new_tx(0)
},
anchor: None,
last_seen: None,
Expand All @@ -610,7 +614,7 @@ fn test_get_chain_position() {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(1)
..new_tx(1)
},
anchor: None,
last_seen: Some(2),
Expand All @@ -623,7 +627,7 @@ fn test_get_chain_position() {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(2)
..new_tx(2)
},
anchor: Some(blocks[1]),
last_seen: None,
Expand All @@ -636,7 +640,7 @@ fn test_get_chain_position() {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(3)
..new_tx(3)
},
anchor: Some(block_id!(2, "B'")),
last_seen: Some(2),
Expand All @@ -649,7 +653,7 @@ fn test_get_chain_position() {
value: Amount::ONE_BTC,
script_pubkey: spk.clone(),
}],
..common::new_tx(4)
..new_tx(4)
},
anchor: Some(block_id!(2, "B'")),
last_seen: None,
Expand Down
17 changes: 8 additions & 9 deletions crates/chain/tests/test_keychain_txout_index.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
#![cfg(feature = "miniscript")]

#[macro_use]
mod common;
use bdk_chain::{
collections::BTreeMap,
indexer::keychain_txout::{ChangeSet, KeychainTxOutIndex},
DescriptorExt, DescriptorId, Indexer, Merge,
};

use bdk_testenv::{
hash,
utils::{new_tx, DESCRIPTORS},
};
use bitcoin::{secp256k1::Secp256k1, Amount, OutPoint, ScriptBuf, Transaction, TxOut};
use miniscript::{Descriptor, DescriptorPublicKey};

use crate::common::DESCRIPTORS;

#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
enum TestKeychain {
External,
Expand Down Expand Up @@ -253,7 +252,7 @@ fn test_lookahead() {
value: Amount::from_sat(10_000),
},
],
..common::new_tx(external_index)
..new_tx(external_index)
};
assert_eq!(txout_index.index_tx(&tx), ChangeSet::default());
assert_eq!(
Expand Down Expand Up @@ -305,7 +304,7 @@ fn test_scan_with_lookahead() {
.collect();

for (&spk_i, spk) in &spks {
let op = OutPoint::new(h!("fake tx"), spk_i);
let op = OutPoint::new(hash!("fake tx"), spk_i);
let txout = TxOut {
script_pubkey: spk.clone(),
value: Amount::ZERO,
Expand All @@ -331,7 +330,7 @@ fn test_scan_with_lookahead() {
.at_derivation_index(41)
.unwrap()
.script_pubkey();
let op = OutPoint::new(h!("fake tx"), 41);
let op = OutPoint::new(hash!("fake tx"), 41);
let txout = TxOut {
script_pubkey: spk_41,
value: Amount::ZERO,
Expand Down Expand Up @@ -656,7 +655,7 @@ fn reassigning_keychain_to_a_new_descriptor_should_error() {
#[test]
fn when_querying_over_a_range_of_keychains_the_utxos_should_show_up() {
let mut indexer = KeychainTxOutIndex::<usize>::new(0);
let mut tx = common::new_tx(0);
let mut tx = new_tx(0);

for (i, descriptor) in DESCRIPTORS.iter().enumerate() {
let descriptor = parse_descriptor(descriptor);
Expand Down
Loading

0 comments on commit 88a8403

Please sign in to comment.