From 6465689555873a73439079e1b28e2b9348475fe9 Mon Sep 17 00:00:00 2001 From: Kiminuo Date: Tue, 12 May 2020 13:12:11 +0000 Subject: [PATCH] transaction/hash.rs: Add FromStr implementation (issue #299) Co-authored-by: Deirdre Connolly --- zebra-chain/src/transaction/hash.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/zebra-chain/src/transaction/hash.rs b/zebra-chain/src/transaction/hash.rs index af353921..1fbf7f3c 100644 --- a/zebra-chain/src/transaction/hash.rs +++ b/zebra-chain/src/transaction/hash.rs @@ -3,7 +3,10 @@ use std::fmt; #[cfg(test)] use proptest_derive::Arbitrary; -use crate::{serialization::ZcashSerialize, sha256d_writer::Sha256dWriter}; +use crate::{ + serialization::{SerializationError, ZcashSerialize}, + sha256d_writer::Sha256dWriter, +}; use super::Transaction; @@ -33,6 +36,19 @@ impl fmt::Debug for TransactionHash { } } +impl std::str::FromStr for TransactionHash { + type Err = SerializationError; + + fn from_str(s: &str) -> Result { + let mut bytes = [0; 32]; + if hex::decode_to_slice(s, &mut bytes[..]).is_err() { + Err(SerializationError::Parse("hex decoding error")) + } else { + Ok(TransactionHash(bytes)) + } + } +} + #[cfg(test)] mod tests { use std::io::Write; @@ -51,7 +67,16 @@ mod tests { assert_eq!( format!("{:?}", hash), - "TransactionHash(\"bf46b4b5030752fedac6f884976162bbfb29a9398f104a280b3e34d51b416631\")" + r#"TransactionHash("bf46b4b5030752fedac6f884976162bbfb29a9398f104a280b3e34d51b416631")"# + ); + } + + #[test] + fn transactionhash_from_str() { + let hash:TransactionHash = "bf46b4b5030752fedac6f884976162bbfb29a9398f104a280b3e34d51b416631".parse().unwrap(); + assert_eq!( + format!("{:?}", hash), + r#"TransactionHash("bf46b4b5030752fedac6f884976162bbfb29a9398f104a280b3e34d51b416631")"# ); } }