Search code examples
paritysubstrate

In a Substrate runtime module how do I compare an input hash to a known default hash value?


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.


Solution

  • 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.