0

I am trying to compare an unknown input_hash with a default_hash_value which my runtime is aware of.

The default_hash_value in hex is 5198bfa9da6f9c9d22dd2b0ce301dde9fd3c5826a117705d3ffa415d83a6bde8 generated using Blake2 hashing algorithm from a string A nice default hash.

a) I presume T::Hash the correct input type, but...

b) How to I encode default_hash_value in my runtime module so that I can make the comparison something along the lines of:


if let default_hash_value = input_hash {
    //... this is the default value do, something
} else {
    //... this is not the default value, do something else
}

The main issue is encoding the known value.

T9b
  • 3,312
  • 5
  • 31
  • 50

1 Answers1

1
fn compare(input: T::Hash) {
    let default_hash = hex!("5198bfa9da6f9c9d22dd2b0ce301dde9fd3c5826a117705d3ffa415d83a6bde8");

    ensure!(default_hash == input.encode().as_slice(), "not equal");
}

Here I converted both values to a byte array and then compared them.

The hex! macro comes from the hex-literal crate: https://docs.rs/hex-literal/0.2.1/hex_literal/

This crate provides hex! macro for converting hexadecimal string literal to byte array at compile time.

And the T::Hash is converted using the parity_codec::Encode trait: https://substrate.dev/rustdocs/master/parity_scale_codec/index.html#encode

encode(&self) -> Vec: Encodes the type data and returns a slice.

Not sure if this is the most efficient or ergonomic way, but I have tested it to work.

Shawn Tabrizi
  • 12,206
  • 1
  • 38
  • 69
  • Thanks. I had seen this in the testing for the SRML modules, but could not get it to work (didn't know where to find the macro definition). The `hex_literal` crate is not included in `Cargo.toml` for node-template, even though the `hex!` macro is often used in testing. I think it should be added. – T9b Oct 08 '19 at 08:42
  • In general, it is good practice to only include crates which you actually use. So unless we use it in the node template, I don't think it will be added by default – Shawn Tabrizi Oct 08 '19 at 10:44