2

I have a hash string "0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49". How can i convert back to H256.

I used function below but it return difference H256 0xa8fb46593dfc218a4de6fcf14e0c9baa4bcf947b953c181689015793883b3a1d

let hex_string = "0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49".as_bytes().to_vec();
info!("{:?}", hex_string);
let hex_string_hash = hash::<Runtime>(&hex_string);
info!("{:?}", hex_string_hash);

pub fn hash<Runtime>(data: &[u8]) -> H256
where
    Runtime: frame_system::Config,
    H256: From<<Runtime as frame_system::Config>::Hash>,
{
    <Runtime as frame_system::Config>::Hashing::hash(data).into()
}

Edit: As aurevoirxavier answer. I have updated my code like this:

use primitive_types::H256;
fn main() {
    let hex = "0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49";
    match array_bytes::hex_n_into::<H256, 32>(hex) {
        Ok(h256) => {
            println!("{:?}", h256);
        }
        _ => (),
    }
}
2

2 Answers 2

3

I recommend using array-bytes, see https://github.com/paritytech/substrate/pull/12190.

let hex = "0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49";
if let Ok(h256) = array_bytes::hex_n_into::<H256, 32>() {
    info!("{:?}", h256);
}

For your steps, you should remove the 0x prefix. It isn't a part of bytes.

With array-bytes, it will handle this automatically.

1

if you don't want to remove '0x',you could use Macro ckb_types::h256 in https://docs.rs/ckb-types/0.110.0/ckb_types/macro.h256.html :

use ckb_types::h256;
h256!("0xf8dd02cc2a3174933fac4e87d7f6360c3cc67167db105b28d0bc434a60674e49")

with cargo.toml: ckb-types = "0.108"

1
  • I just mean. hex crate can not handle that. array-bytes will handle the 0x automatically. Whether it exists or not. I prefer using a function instead of a macro.
    – aurexav
    Commented May 17, 2023 at 3:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.