From b9640fbb55e8e0a2f819b04f81d67da672bf6f29 Mon Sep 17 00:00:00 2001 From: Conrado Gouvea Date: Thu, 17 Mar 2022 17:24:48 -0300 Subject: [PATCH] fix(chain): make FromHex consistent with ToHex for tx/block hashes (#3893) --- zebra-chain/src/block/hash.rs | 3 ++- zebra-chain/src/block/tests/prop.rs | 11 +++++++++++ zebra-chain/src/transaction/hash.rs | 3 ++- zebra-chain/src/transaction/tests/prop.rs | 11 +++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/zebra-chain/src/block/hash.rs b/zebra-chain/src/block/hash.rs index a74e6817e..ce679a8d8 100644 --- a/zebra-chain/src/block/hash.rs +++ b/zebra-chain/src/block/hash.rs @@ -74,7 +74,8 @@ impl FromHex for Hash { type Error = <[u8; 32] as FromHex>::Error; fn from_hex>(hex: T) -> Result { - let hash = <[u8; 32]>::from_hex(hex)?; + let mut hash = <[u8; 32]>::from_hex(hex)?; + hash.reverse(); Ok(hash.into()) } diff --git a/zebra-chain/src/block/tests/prop.rs b/zebra-chain/src/block/tests/prop.rs index b7bc34b64..9b09a6323 100644 --- a/zebra-chain/src/block/tests/prop.rs +++ b/zebra-chain/src/block/tests/prop.rs @@ -2,6 +2,8 @@ use std::{env, io::ErrorKind}; use proptest::{arbitrary::any, prelude::*, test_runner::Config}; +use hex::{FromHex, ToHex}; + use zebra_test::prelude::*; use crate::{ @@ -43,6 +45,15 @@ proptest! { prop_assert_eq!(hash, parsed); } + #[test] + fn block_hash_hex_roundtrip(hash in any::()) { + zebra_test::init(); + + let hex_hash: String = hash.encode_hex(); + let new_hash = Hash::from_hex(hex_hash).expect("hex hash should parse"); + prop_assert_eq!(hash, new_hash); + } + #[test] fn blockheader_roundtrip(header in any::
()) { zebra_test::init(); diff --git a/zebra-chain/src/transaction/hash.rs b/zebra-chain/src/transaction/hash.rs index fd18a56a0..63f9837a7 100644 --- a/zebra-chain/src/transaction/hash.rs +++ b/zebra-chain/src/transaction/hash.rs @@ -137,7 +137,8 @@ impl FromHex for Hash { type Error = <[u8; 32] as FromHex>::Error; fn from_hex>(hex: T) -> Result { - let hash = <[u8; 32]>::from_hex(hex)?; + let mut hash = <[u8; 32]>::from_hex(hex)?; + hash.reverse(); Ok(hash.into()) } diff --git a/zebra-chain/src/transaction/tests/prop.rs b/zebra-chain/src/transaction/tests/prop.rs index e0a89f6b7..b0f470911 100644 --- a/zebra-chain/src/transaction/tests/prop.rs +++ b/zebra-chain/src/transaction/tests/prop.rs @@ -6,6 +6,8 @@ use std::io::Cursor; use zebra_test::prelude::*; +use hex::{FromHex, ToHex}; + use super::super::*; use crate::{ @@ -51,6 +53,15 @@ proptest! { } } + #[test] + fn transaction_hash_hex_roundtrip(hash in any::()) { + zebra_test::init(); + + let hex_hash: String = hash.encode_hex(); + let new_hash = Hash::from_hex(hex_hash).expect("hex hash should parse"); + prop_assert_eq!(hash, new_hash); + } + #[test] fn transaction_auth_digest_struct_display_roundtrip(auth_digest in any::()) { zebra_test::init();