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 `tx_utils` to house all transaction
utilities moved from `crates/chain/test/common`
- deleted all moved macros and functions in
`crates/chain/test/common/mod`
- add `bitcoin` crate to `testenv` crate
- add `tx_utils` mod to lib in testenv

[Issue: bitcoindevkit#1602]

Refactor: use tx utils from testenv in chain crate

- import testenv crate in chain crate
- replace all macros and fns in the following
tests 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

[issue: bitcoindevkit#1602]

Refactor: Replace block_id macro def with tx util

- import testenv crate
- delete common module and import `block_id` from
testenv crate

[issue: bitcoindevkit#1602]

Refactor: replace bitcoin with bdk_chain::bitcoin

replace external crate `bitcoin` with re-exported
`bdk_chain::bitcoin`

[Ticket: bitcoindevkit#1602]

Refactor: rename `tx_utils` to `utils` in testenv

- Rename `tx_utils.rs` to `utils.rs` in `testenv`
to allow all testing utilities to be included.
- update all imports

[Ticket: X]

Refactor: move DESCRIPTORS sample array to testenv

move `DESCRIPTORS` sample array to `testenv` for
other crates to use

[Ticket: X]
  • Loading branch information
tvpeter committed Oct 1, 2024
1 parent 139d971 commit 78d078a
Show file tree
Hide file tree
Showing 13 changed files with 153 additions and 148 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
37 changes: 20 additions & 17 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, h,
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 @@ -132,9 +135,9 @@ fn test_list_owned_txouts() {
// 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 +190,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 +199,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 +212,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 +221,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 +230,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 +600,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 +613,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 +626,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 +639,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 +652,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
13 changes: 6 additions & 7 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::{
h,
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 @@ -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
1 change: 1 addition & 0 deletions crates/chain/tests/test_local_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use bdk_chain::{
},
BlockId,
};
use bdk_testenv::{chain_update, h, local_chain};
use bitcoin::{block::Header, hashes::Hash, BlockHash};
use proptest::prelude::*;

Expand Down
Loading

0 comments on commit 78d078a

Please sign in to comment.