Amiya Behera
Amiya Behera

Reputation: 2270

Hashing in Substrate and checking the hash does match

fn reveal_vote(phrase: Vec<u8>, hash: Vec<u8>) {

}

I want to check hash of the phrase matches with hash submitted as Vec<u8>.
I tried using hex and sha3 package. But both hex and format! macro are not allowed in Substrate.
How can I match the hash? Any specific way to do in Substrate?

Using sp_io::hashing

#[weight = 10_000 + T::DbWeight::get().reads_writes(3,3)]
        pub fn test_hash(origin, phrase: Vec<u8>, hash:Vec<u8>) -> dispatch::DispatchResult   {
            let phrase_bytes: &[u8] = &phrase;
            let data = sp_io::hashing::keccak_256(phrase_bytes);
            println!("{:?}", data.to_vec());
            println!("{:?}", hash);

             Ok(())

        }

Tests:

#[test]
fn hash_test() {
    new_test_ext().execute_with(|| {
        let ok = TemplateModule::test_hash(Origin::signed(1),"1-abcdef".as_bytes().to_vec(), "e2a18e9b74f228590ca8c563cecfc58c28455b2dde25b4bbdc663e99e791f47c".as_bytes().to_vec());
    });
}

The problem is data.to_vec() and hash doesn't match.

data.to_vec() value is:

[226, 161, 142, 155, 116, 242, 40, 89, 12, 168, 197, 99, 206, 207, 197, 140, 40, 69, 91, 45, 222, 37, 180, 187, 220, 102, 62, 153, 231, 145, 244, 124]

hash value is:

[101, 50, 97, 49, 56, 101, 57, 98, 55, 52, 102, 50, 50, 56, 53, 57, 48, 99, 97, 56, 99, 53, 54, 51, 99, 101, 99, 102, 99, 53, 56, 99, 50, 56, 52, 53, 53, 98, 50, 100, 100, 101, 50, 53, 98, 52, 98, 98, 100, 99, 54, 54, 51, 101, 57, 57, 101, 55, 57, 49, 102, 52, 55, 99]

Upvotes: 0

Views: 324

Answers (1)

Amiya Behera
Amiya Behera

Reputation: 2270

Solved it by passing [u8;32] instead of hex string as Vec<u8>. Not sure if it's the intuitive way to solve.

In front end:

import {keccakAsU8a} from "@polkadot/util-crypto"
let hash = keccakAsU8a("1-abcdef");
console.log(hash)

Then passing the hash to runtime function

#[weight = 10_000 + T::DbWeight::get().reads_writes(0,1)]
pub fn test_hash(origin, phrase: Vec<u8>, hash:[u8; 32]) -> dispatch::DispatchResult   {
   let phrase_bytes: &[u8] = &phrase;
   let data = sp_io::hashing::keccak_256(phrase_bytes); 
   ensure!(data == hash, Error::<T>::CommitVoteMismatch);
   Ok(())
}

Upvotes: 1

Related Questions