From e0b627ea816a730949cdb200105598600fcac094 Mon Sep 17 00:00:00 2001 From: aagbotemi Date: Fri, 18 Apr 2025 22:51:21 +0100 Subject: [PATCH] deserialize witness from a list of hex strings - ci(primitives): enable hex feature in CI build - from_hex() implemented more efficiently --- primitives/src/witness.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/primitives/src/witness.rs b/primitives/src/witness.rs index 3eb62a023..bbbc05376 100644 --- a/primitives/src/witness.rs +++ b/primitives/src/witness.rs @@ -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(iter: I) -> Result + where + I: IntoIterator, + T: AsRef, + { + let result: Vec> = iter.into_iter().map(|hex_str| Vec::from_hex(hex_str.as_ref())).collect::, _>>()?; + 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); + } }