SHA-256

The OpenVM SHA-256 extension provides tools for using the SHA-256 hash function. Refer here for more details on SHA-256. The functional part is provided by the openvm-sha256-guest crate, which is a guest library that can be used in any OpenVM program.

Functions for guest code

The OpenVM SHA-256Guest extension provides two functions for using in your guest code:

  • sha256(input: &[u8]) -> [u8; 32]: Computes the SHA-256 hash of the input data and returns it as an array of 32 bytes.
  • set_sha256(input: &[u8], output: &mut [u8; 32]): Sets the output to the SHA-256 hash of the input data into the provided output buffer.

See the full example here.

Example

use alloc::vec::Vec;
use core::hint::black_box;

use hex::FromHex;
use openvm_sha256_guest::sha256;
openvm::entry!(main);

pub fn main() {
    let test_vectors = [(
        "",
        "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    )];
    for (input, expected_output) in test_vectors.iter() {
        let input = Vec::from_hex(input).unwrap();
        let expected_output = Vec::from_hex(expected_output).unwrap();
        let output = sha256(&black_box(input));
        if output != *expected_output {
            panic!();
        }
    }
}

To be able to import the sha256 function, add the following to your Cargo.toml file:

openvm-sha256-guest = { git = "https://github.com/openvm-org/openvm.git" }
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }

External Linking

The SHA-256 guest extension also provides another way to use the intrinsic SHA-256 implementation. It provides a function that is meant to be linked to other external libraries. The external libraries can use this function as a hook for the SHA-256 intrinsic. This is enabled only when the target is zkvm.

  • zkvm_sha256_impl(input: *const u8, len: usize, output: *mut u8): This function has C ABI. It takes in a pointer to the input, the length of the input, and a pointer to the output buffer.

In the external library, you can do the following:

#![allow(unused)]
fn main() {
extern "C" {
    fn zkvm_sha256_impl(input: *const u8, len: usize, output: *mut u8);
}

fn sha256(input: &[u8]) -> [u8; 32] {
    #[cfg(target_os = "zkvm")]
    {
        let mut output = [0u8; 32];
        unsafe {
            zkvm_sha256_impl(input.as_ptr(), input.len(), output.as_mut_ptr() as *mut u8);
        }
        output
    }
    #[cfg(not(target_os = "zkvm"))] {
        // Regular SHA-256 implementation
    }
}
}

Config parameters

For the guest program to build successfully add the following to your .toml file:

[app_vm_config.sha256]