Merge rust-bitcoin/rust-bitcoin#4366: Deserialize witness from a list of hex strings

e0b627ea81 deserialize witness from a list of hex strings - ci(primitives): enable hex feature in CI build - from_hex() implemented more efficiently (aagbotemi)

Pull request description:

  This PR implements `from_hex` function for deserialize `Witness` from a list of hex strings. Added unit test.

  This PR fixes #4350

ACKs for top commit:
  apoelstra:
    ACK e0b627ea816a730949cdb200105598600fcac094; successfully ran local tests
  tcharding:
    ACK e0b627ea81

Tree-SHA512: deec3f9e5f67a0915b11a811c40c341dd9f24d0394d6cfbd6a09f765ce3fc0dcce2740949c264d4aa2d2db748a5ce81416b4dac15b1b64475a7c024b205e40ab
This commit is contained in:
merge-script 2025-04-21 13:36:56 +00:00
commit 3e6de4604e
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 29 additions and 0 deletions

View File

@ -9,6 +9,8 @@ use core::ops::Index;
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
#[cfg(feature = "hex")]
use hex::{error::HexToBytesError, FromHex};
use internals::compact_size;
use internals::slice::SliceExt;
use internals::wrap_debug::WrapDebug;
@ -218,6 +220,21 @@ impl Witness {
let end = element_len as usize;
Some(&slice[..end])
}
/// Creates a new witness from a list of hex strings.
///
/// # Errors
///
/// This function will return an error if any of the hex strings are invalid.
#[cfg(feature = "hex")]
pub fn from_hex<I, T>(iter: I) -> Result<Self, HexToBytesError>
where
I: IntoIterator<Item = T>,
T: AsRef<str>,
{
let result: Vec<Vec<u8>> = iter.into_iter().map(|hex_str| Vec::from_hex(hex_str.as_ref())).collect::<Result<Vec<_>, _>>()?;
Ok(Self::from_slice(&result))
}
}
/// Correctness Requirements: value must always fit within u32
@ -840,4 +857,16 @@ mod test {
let json = serde_json::to_string(&witness).unwrap();
assert_eq!(json, r#"["007b4b","0206030708"]"#);
}
#[cfg(feature = "hex")]
#[test]
fn test_from_hex() {
let hex_strings = [
"30440220703350f1c8be5b41b4cb03b3b680c4f3337f987514a6b08e16d5d9f81e9b5f72022018fb269ba5b82864c0e1edeaf788829eb332fe34a859cc1f99c4a02edfb5d0df01",
"0208689fe2cca52d8726cefaf274de8fa61d5faa5e1058ad35b49fb194c035f9a4",
];
let witness = Witness::from_hex(hex_strings).unwrap();
assert_eq!(witness.len(), 2);
}
}