在 Substrate 运行时模块中,如何将输入哈希值与已知的默认哈希值进行比较?

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

我正在尝试将一个未知的 input_hash 与我的运行时知道的 default_hash_value 进行比较。

十六进制的 default_hash_value 是 5198bfa9da6f9c9d22dd2b0ce301dde9fd3c5826a117705d3ffa415d83a6bde8 使用 Blake2 哈希算法从字符串 A nice default hash.

生成的

a) 我假定 T::Hash 正确的输入类型,但是...

b) 如何在我的运行时模块中对 default_hash_value 进行编码,以便我可以按照以下方式进行比较:


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

主要问题是编码已知值。

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

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

这里我把两个值都转换成一个字节数组,然后比较它们。

hex! 宏来自 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.

并且 T::Hash 使用 parity_codec::Encode 特征进行转换:https://substrate.dev/rustdocs/master/parity_scale_codec/index.html#encode

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

不确定这是否是最有效或最符合人体工程学的方式,但我已经测试过它可以工作。