Merge rust-bitcoin/rust-bitcoin#7008: primitives: Improve unit tests
What changed, and why it matters
This commit only improves and cleans up unit tests in the rust-bitcoin library. It renames misspelled test functions, removes unnecessary feature gates, adds missing test cases for hash types, simplifies Merkle root test assertions, and renames a test module for consistency. There are no changes to production code, so this does not fix or introduce any security vulnerability.
No security action required. Treat as routine test-quality maintenance.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The merge commit contains seven child commits that are exclusively test-only refactorings in primitives/src/hash_types/mod.rs, primitives/src/merkle_tree.rs, primitives/src/transaction.rs, and primitives/src/witness.rs. Changes include: removing redundant #[cfg(feature = “alloc”)] gates inside test modules; correcting ‘rountrips’ to ‘roundtrips’ in OutPoint serde test names; extending lower-hex and as_byte_array roundtrip coverage to all hash types (Txid, Wtxid, etc.); renaming witness module from ‘test’ to ‘tests’; and replacing a self-contained stack-based Merkle root reference implementation in tests with assert_roots_match cases that exercise the real calculate_root implementation. No runtime logic is modified.
Changed components
primitives/src/hash_types/mod.rsprimitives/src/merkle_tree.rsprimitives/src/transaction.rsprimitives/src/witness.rsInspect captured patch +32 / −119
### primitives/src/hash_types/mod.rs
@@ -211,7 +211,6 @@ mod tests {
#[cfg(feature = "serde")]
fn dummy_test_case() -> Txid { DUMMY_TXID_HEX_STR.parse::<Txid>().unwrap() }
- #[cfg(feature = "alloc")]
fn ab_test_case() -> (Txid, &'static str) {
let mut a = [0xab; 32];
a[0] = 0xff; // Just so we can see which way the array is printing.
@@ -239,9 +238,8 @@ mod tests {
assert_eq!(got, tc);
}
+ // Debug printing works with and without the "hex" feature.
#[test]
- // This is solely to test that we can debug print WITH and WITHOUT "hex" so its ok to require "alloc".
- #[cfg(feature = "alloc")]
fn debug() {
let (tc, want) = ab_test_case();
let got = alloc::format!("{:?}", tc);
@@ -264,18 +262,15 @@ mod tests {
}
macro_rules! byte_array_roundtrip_test {
- ($($name:ident, $ty:ident, $len:expr, $byte:expr $(, $check:ident)?);* $(;)?) => {
+ ($($name:ident, $ty:ident, $len:expr, $byte:expr);* $(;)?) => {
$(
#[test]
fn $name() {
let bytes = [$byte; $len];
let value = $ty::from_byte_array(bytes);
assert_eq!(value.to_byte_array(), bytes);
- $(
- let _ = stringify!($check);
- assert_eq!(value.as_byte_array(), &bytes);
- )?
+ assert_eq!(value.as_byte_array(), &bytes);
}
)*
}
@@ -284,14 +279,14 @@ mod tests {
#[rustfmt::skip]
byte_array_roundtrip_test! {
txid_byte_array_roundtrip, Txid, 32, 0x12;
- ntxid_byte_array_roundtrip, Ntxid, 32, 0x13, as_byte_array;
- wtxid_byte_array_roundtrip, Wtxid, 32, 0x14, as_byte_array;
+ ntxid_byte_array_roundtrip, Ntxid, 32, 0x13;
+ wtxid_byte_array_roundtrip, Wtxid, 32, 0x14;
block_hash_byte_array_roundtrip, BlockHash, 32, 0x15;
tx_merkle_node_byte_array_roundtrip, TxMerkleNode, 32, 0x16;
witness_merkle_node_byte_array_roundtrip, WitnessMerkleNode, 32, 0x17;
- witness_commitment_byte_array_roundtrip, WitnessCommitment, 32, 0x18, as_byte_array;
- script_hash_byte_array_roundtrip, ScriptHash, 20, 0x19, as_byte_array;
- wscript_hash_byte_array_roundtrip, WScriptHash, 32, 0x1a, as_byte_array;
+ witness_commitment_byte_array_roundtrip, WitnessCommitment, 32, 0x18;
+ script_hash_byte_array_roundtrip, ScriptHash, 20, 0x19;
+ wscript_hash_byte_array_roundtrip, WScriptHash, 32, 0x1a;
}
macro_rules! hex_roundtrip_test_display {
@@ -354,7 +349,9 @@ mod tests {
#[rustfmt::skip]
hex_roundtrip_test_lower_hex! {
+ txid_lower_hex_roundtrip, Txid, 32, 0x34;
ntxid_lower_hex_roundtrip, Ntxid, 32, 0x1c;
+ wtxid_lower_hex_roundtrip, Wtxid, 32, 0x35;
block_hash_lower_hex_roundtrip, BlockHash, 32, 0x1d;
tx_merkle_node_lower_hex_roundtrip, TxMerkleNode, 32, 0x1e;
witness_merkle_node_lower_hex_roundtrip, WitnessMerkleNode, 32, 0x1f;
### primitives/src/merkle_tree.rs
@@ -224,8 +224,7 @@ mod tests {
fn tx_merkle_node_single_leaf() {
let (leaf, node) = make_leaf_node(1);
let root = TxMerkleNode::calculate_root([leaf]);
- assert!(root.is_some(), "Root should exist for a single leaf");
- assert_eq!(root.unwrap(), node, "Root should equal the leaf node");
+ assert_eq!(root, Some(node));
}
#[test]
@@ -235,27 +234,20 @@ mod tests {
let combined = node1.combine(&node2);
let root = TxMerkleNode::calculate_root([leaf1, leaf2]);
- assert_eq!(
- root.unwrap(),
- combined,
- "Root of two leaves should equal combine of the two leaf nodes"
- );
+ assert_eq!(root, Some(combined));
}
#[test]
fn tx_merkle_node_duplicate_leaves() {
let leaf = Txid::from_byte_array([3; 32]);
// Duplicate transaction list should be rejected (CVE 2012‑2459).
let root = TxMerkleNode::calculate_root([leaf, leaf]);
- assert!(root.is_none(), "Duplicate leaves should return None");
+ assert_eq!(root, None);
}
#[test]
fn tx_merkle_node_empty() {
- assert!(
- TxMerkleNode::calculate_root([].into_iter()).is_none(),
- "Empty iterator should return None"
- );
+ assert_eq!(TxMerkleNode::calculate_root([]), None);
}
#[test]
@@ -330,76 +322,18 @@ mod tests {
assert_ne!(root, None);
}
- #[test]
- #[cfg(feature = "alloc")]
- fn merkle_root_batched() {
- use alloc::vec::Vec;
-
- // copy of `MerkleNode::calculate_root` (stack-based) implementation to test against the new batched approach
- fn stack_based_root<I: Iterator<Item = Txid>>(iter: I) -> Option<TxMerkleNode> {
- let mut stack = Vec::<(usize, TxMerkleNode)>::with_capacity(32);
-
- for (mut n, leaf) in iter.enumerate() {
- stack.push((0, TxMerkleNode::from_leaf(leaf)));
-
- while n & 1 == 1 {
- let right = stack.pop().unwrap();
- let left = stack.pop().unwrap();
- if left.1 == right.1 {
- return None;
- }
- debug_assert_eq!(left.0, right.0);
- stack.push((left.0 + 1, left.1.combine(&right.1)));
- n >>= 1;
- }
- }
-
- while stack.len() > 1 {
- let mut right = stack.pop().unwrap();
- let left = stack.pop().unwrap();
- while right.0 != left.0 {
- assert!(right.0 < left.0);
- right = (right.0 + 1, right.1.combine(&right.1)); // combine with self
- }
- stack.push((left.0 + 1, left.1.combine(&right.1)));
- }
-
- stack.pop().map(|(_, h)| h)
- }
-
- fn make_leaves(count: usize) -> Vec<Txid> {
- (0..count as u32)
- .map(|i| {
- let mut buf = [0u8; 32];
- buf[..4].copy_from_slice(&i.to_le_bytes());
- Txid::from_byte_array(buf)
- })
- .collect()
- }
-
- // test odd and even count
- for size in [32, 33] {
- let leaves = make_leaves(size);
- let got = TxMerkleNode::calculate_root(leaves.iter().copied());
- let expected = stack_based_root(leaves.iter().copied());
- assert_eq!(got, expected);
- }
- }
-
#[test]
fn witness_merkle_node_single_leaf() {
let leaf = Wtxid::from_byte_array([1; 32]);
let root = WitnessMerkleNode::calculate_root([leaf]);
- assert!(root.is_some(), "Root should exist for a single witness leaf");
- let node = WitnessMerkleNode::from_leaf(leaf);
- assert_eq!(root.unwrap(), node, "Root should equal the leaf node");
+ assert_eq!(root, Some(WitnessMerkleNode::from_leaf(leaf)));
}
#[test]
fn witness_merkle_node_duplicate_leaves() {
let leaf = Wtxid::from_byte_array([2; 32]);
let root = WitnessMerkleNode::calculate_root([leaf, leaf]);
- assert!(root.is_none(), "Duplicate witness leaves should return None");
+ assert_eq!(root, None);
}
// The tests below exercise the default trait `MerkleNode::calculate_root`
@@ -467,6 +401,18 @@ mod tests {
#[test]
fn calculate_root_seven_leaves_unbalanced() { assert_roots_match(&[1, 2, 3, 4, 5, 6, 7]); }
+ #[test]
+ fn calculate_root_thirty_two_leaves() {
+ let leaves: [u8; 32] = core::array::from_fn(|i| i as u8);
+ assert_roots_match(&leaves);
+ }
+
+ #[test]
+ fn calculate_root_thirty_three_leaves_unbalanced() {
+ let leaves: [u8; 33] = core::array::from_fn(|i| i as u8);
+ assert_roots_match(&leaves);
+ }
+
#[test]
fn calculate_root_correct_root_value() {
assert_roots_match(&[10, 20]);
### primitives/src/transaction.rs
@@ -2113,7 +2113,7 @@ mod tests {
#[test]
#[cfg(feature = "serde")]
- fn out_point_serde_human_readable_rountrips() {
+ fn out_point_serde_human_readable_roundtrips() {
let out_point = tc_out_point();
let ser = serde_json::to_string(&out_point).unwrap();
@@ -2124,7 +2124,7 @@ mod tests {
#[test]
#[cfg(feature = "serde")]
- fn out_point_serde_non_human_readable_rountrips() {
+ fn out_point_serde_non_human_readable_roundtrips() {
let out_point = tc_out_point();
let ser = bincode::serialize(&out_point).unwrap();
### primitives/src/witness.rs
@@ -1127,17 +1127,13 @@ pub mod error {
}
#[cfg(test)]
-mod test {
- #[cfg(feature = "alloc")]
+mod tests {
use alloc::string::ToString;
- #[cfg(feature = "alloc")]
use alloc::{format, vec};
#[cfg(feature = "std")]
use std::error::Error as _;
- use encoding::check_encode;
- #[cfg(feature = "alloc")]
- use encoding::{Decode as _, Decoder as _};
+ use encoding::{check_encode, Decode as _, Decoder as _};
use super::*;
@@ -1388,7 +1384,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn oversized_element_does_not_compare_equal_to_different_stack() {
let oversized = vec![0u8; MAX_WITNESS_ITEM_SIZE + 1];
let witness = Witness::from_slice(&[oversized]);
@@ -1592,7 +1587,6 @@ mod test {
assert_eq!(&got, &want);
}
- #[cfg(feature = "alloc")]
fn witness_test_case() -> (Witness, Vec<u8>) {
let bytes1 = [1u8];
let bytes2 = [2u8, 3];
@@ -1613,7 +1607,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_witness_one_single_call() {
let (want, encoded) = witness_test_case();
@@ -1627,7 +1620,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
#[allow(clippy::many_single_char_names)]
fn decode_witness_many_calls() {
let (want, encoded) = witness_test_case();
@@ -1656,7 +1648,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_max_serialized_size() {
let element_len = MAX_WITNESS_SIZE
- crate::compact_size_encode(1usize).as_slice().len()
@@ -1674,7 +1665,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_length_prefix_error() {
let mut encoded = Vec::new();
encoded.extend_from_slice(crate::compact_size_encode(1usize).as_slice());
@@ -1693,7 +1683,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_empty_witness() {
// Witness with 0 elements.
let encoded = vec![0x00];
@@ -1708,7 +1697,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_single_element() {
// Witness with 1 element containing [0xAB, 0xCD].
let encoded = vec![0x01, 0x02, 0xAB, 0xCD];
@@ -1723,7 +1711,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_empty_element() {
// Witness with 1 element that is empty (0 bytes).
let encoded = vec![0x01, 0x00];
@@ -1738,7 +1725,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_multiple_empty_elements() {
// Witness with 3 empty elements.
let encoded = vec![0x03, 0x00, 0x00, 0x00];
@@ -1755,7 +1741,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_incomplete_witness_count() {
// 3-byte compact size but only provide 2 bytes.
let encoded = vec![0xFD, 0x03];
@@ -1769,7 +1754,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_incomplete_element_length() {
// Witness count = 1, but element length is incomplete.
let encoded = vec![0x01, 0xFD, 0x05]; // Element length should be 3 bytes.
@@ -1783,7 +1767,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_incomplete_element_data() {
// Witness count = 1, element length = 5, but only 3 bytes of data provided.
let encoded = vec![0x01, 0x05, 0xAA, 0xBB, 0xCC];
@@ -1797,7 +1780,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decoder_read_limit() {
let mut decoder = Witness::decoder();
// witness_count_decoder is CompactSize: needs 1 byte.
@@ -1827,7 +1809,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decoder_end_without_witness_count_errors() {
let err = WitnessDecoder::new().end().unwrap_err();
assert!(matches!(
@@ -1842,7 +1823,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decoder_unexpected_eof_error() {
let mut decoder = WitnessDecoder::new();
let mut slice = [0x01].as_slice(); // witness element count = 1.
@@ -1856,7 +1836,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn decode_buffer_resizing() {
// Create a witness with elements larger than initial 128-byte allocation.
let large_element = vec![0xFF; 500];
@@ -1877,14 +1856,12 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn iter_next_none_if_cursor_decode_fails() {
let witness = Witness { content: vec![], witness_elements: 1, indices_start: 0 };
assert!(witness.iter().next().is_none());
}
#[test]
- #[cfg(feature = "alloc")]
fn iter_next_none_if_element_len_too_big() {
// Element length = 4_000_001 which is larger than MAX_VEC_SIZE (4_000_000).
let mut content = vec![0xFE];
@@ -1897,7 +1874,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn witness_debug() {
let witness = Witness::from_slice(&[&[0xAAu8][..]]);
let s = format!("{:?}", witness);
@@ -1919,7 +1895,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn oversized_public_witness_size_matches_encoding_length() {
// Public constructors can hold an oversized item even though Iter::next() rejects it.
// size() must not silently omit bytes that Encode will still serialize.
@@ -1930,7 +1905,6 @@ mod test {
}
#[test]
- #[cfg(feature = "alloc")]
fn witness_encoder_len_matches_encoding_length() {
use encoding::{Encode as _, ExactSizeEncoder as _};
@@ -2030,7 +2004,6 @@ mod test {
let _ = decode_unchecked(&mut slice);
}
- #[cfg(feature = "alloc")]
#[test]
fn dos_protection() {
let element_len = MAX_WITNESS_SIZE
@@ -2051,7 +2024,6 @@ mod test {
assert!(dec.content.capacity() < 100_000);
}
- #[cfg(feature = "alloc")]
#[test]
fn element_length_limit_applies_to_every_element() {
// 4_000_001, which exceeds `MAX_WITNESS_ITEM_SIZE` but is below the default 32MB compact
@@ -2073,7 +2045,6 @@ mod test {
assert!(dec.push_bytes(&mut encoded.as_slice()).is_err());
}
- #[cfg(feature = "alloc")]
#[test]
fn decode_rejects_witness_over_limit_due_to_aggregate_data() {
let element_len = MAX_WITNESS_ITEM_SIZE / 2 + 1;
@@ -2099,7 +2070,6 @@ mod test {
);
}
- #[cfg(feature = "alloc")]
#[test]
fn decode_rejects_witness_over_limit_due_to_prefix_overhead() {
let count = MAX_WITNESS_SIZE;Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.