casper_execution_engine/runtime/
cryptography.rs

1//! Cryptography module containing hashing functions used internally
2//! by the execution engine
3
4use blake2::{
5    digest::{Update, VariableOutput},
6    Blake2bVar,
7};
8use sha2::{Digest, Sha256};
9
10/// The number of bytes in a hash.
11/// All hash functions in this module have a digest length of 32.
12pub const DIGEST_LENGTH: usize = 32;
13
14/// The 32-byte digest blake2b hash function
15pub fn blake2b<T: AsRef<[u8]>>(data: T) -> [u8; DIGEST_LENGTH] {
16    let mut result = [0; DIGEST_LENGTH];
17    // NOTE: Assumed safe as `BLAKE2B_DIGEST_LENGTH` is a valid value for a hasher
18    let mut hasher = Blake2bVar::new(DIGEST_LENGTH).expect("should create hasher");
19
20    hasher.update(data.as_ref());
21
22    // NOTE: This should never fail, because result is exactly DIGEST_LENGTH long
23    hasher.finalize_variable(&mut result).ok();
24
25    result
26}
27
28/// The 32-byte digest blake3 hash function
29pub fn blake3<T: AsRef<[u8]>>(data: T) -> [u8; DIGEST_LENGTH] {
30    let mut result = [0; DIGEST_LENGTH];
31    let mut hasher = blake3::Hasher::new();
32
33    hasher.update(data.as_ref());
34    let hash = hasher.finalize();
35    let hash_bytes: &[u8; DIGEST_LENGTH] = hash.as_bytes();
36    result.copy_from_slice(hash_bytes);
37    result
38}
39
40/// The 32-byte digest sha256 hash function
41pub fn sha256<T: AsRef<[u8]>>(data: T) -> [u8; DIGEST_LENGTH] {
42    Sha256::digest(data).into()
43}