How to compute the hash of a wasm?

In Motoko I have a parent canister that holds the wasm for spinning up other canister actors. If I’m performing rolling upgrades of child canister actors, it’s very likely that at I may need to have multiple versions of a wasm in case a rolling upgrade attempt fails part-way through (and I need to roll back). I’d like to create a lookup table with a upgrade version and the wasm hash of that version.

How should I compute a hash of the wasm in Motoko? (the hash implementation should align with what is currently used by the IC when comparing canister install upgrades)

If this capability doesn’t yet exist in Motoko, what is the recommended way to hash a wasm in JavaScript?

If this hasn’t been done yet in JavaScript :sweat_smile: …how do I hash a wasm in Rust?

This line made me giggle :slight_smile:

Here’s how to hash in rust:

use sha2::{Digest, Sha256};

[...]

pub const BUCKET_WASM: &[u8] = std::include_bytes!(
    "../../../target/wasm32-unknown-unknown/release/quickstart_scaling_bucket-opt.wasm"
);

[...]

#[query(name = "getWasmHash")]
fn get_wasm_hash() -> String {
    let mut hasher = Sha256::new();
    hasher.update(BUCKET_WASM);
    let result = hasher.finalize();

    return format!("{:x}", result);
}

This will output this for my quickscale example:

getWasmHash: () → (text) query

("a2e4b49bd8ea77a64c139e661aa846f975b9b1bd6cd7e45855dacf55eb81cba0")

And we can verify it with dfx status like so:

$ dfx canister status rdmx6-jaaaa-aaaaa-aaadq-cai
Canister status call result for rdmx6-jaaaa-aaaaa-aaadq-cai.
Status: Running
Controllers: l6s27-7ndcl-nowe5-xeyf7-ymdnq-dkemz-jkhfw-zr5wu-jvf2p-aupzq-2qe ryjl3-tyaaa-aaaaa-aaaba-cai
Memory allocation: 0
Compute allocation: 0
Freezing threshold: 2_592_000
Memory Size: Nat(1871213)
Balance: 100_000_000_000 Cycles
Module hash: 0xa2e4b49bd8ea77a64c139e661aa846f975b9b1bd6cd7e45855dacf55eb81cba0
1 Like

Ah ok great, so it’s just the sha256 hash of the wasm, with the wasm being an array of 8-bit unsigned integers. Should be easy enough and doable in Motoko with @quint’s GitHub - aviate-labs/crypto.mo: Crypto Package for Motoko library. Thanks for the Rust implmentation!

2 Likes