Skip to content

Commit

Permalink
Merge bitcoindevkit#1612: Refactor: Move transaction testing utilitie…
Browse files Browse the repository at this point in the history
…s from `crates/chain/tests/common` to `testenv` crate

88a8403 refactor(test): move tx test utils to testenv (Vihiga Tyonum)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  This change moves all transaction testing utilities (macros and functions) from `crates/chain/tests/common` to `crates/testenv/tx_utils` to minimize duplication.

  Closes bitcoindevkit#1602

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [x] I'm linking the issue being fixed by this PR

ACKs for top commit:
  ValuedMammal:
    ACK 88a8403
  notmandatory:
    ACK 88a8403

Tree-SHA512: aa85c6683d44463e8858f18840fd628d98f54757edff85fe0489c7954fc56998456ce8069e328eff46e907235d092059975c10e420fe7dfe83e5cdd9b63fc8ed
  • Loading branch information
notmandatory committed Oct 14, 2024
2 parents ec7342d + 88a8403 commit ad59970
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 ad59970

Please sign in to comment.