trezoa_sha256_hasher/
lib.rs

1#![no_std]
2#[cfg(any(feature = "sha2", not(target_os = "trezoa")))]
3use sha2::{Digest, Sha256};
4use trezoa_hash::Hash;
5
6#[cfg(any(feature = "sha2", not(target_os = "trezoa")))]
7#[derive(Clone, Default)]
8pub struct Hasher {
9    hasher: Sha256,
10}
11
12#[cfg(any(feature = "sha2", not(target_os = "trezoa")))]
13impl Hasher {
14    pub fn hash(&mut self, val: &[u8]) {
15        self.hasher.update(val);
16    }
17    pub fn hashv(&mut self, vals: &[&[u8]]) {
18        for val in vals {
19            self.hash(val);
20        }
21    }
22    pub fn result(self) -> Hash {
23        let bytes: [u8; trezoa_hash::HASH_BYTES] = self.hasher.finalize().into();
24        bytes.into()
25    }
26}
27
28#[cfg(target_os = "trezoa")]
29pub use trezoa_define_syscall::definitions::trz_sha256;
30
31/// Return a Sha256 hash for the given data.
32pub fn hashv(vals: &[&[u8]]) -> Hash {
33    // Perform the calculation inline, calling this from within a program is
34    // not supported
35    #[cfg(not(target_os = "trezoa"))]
36    {
37        let mut hasher = Hasher::default();
38        hasher.hashv(vals);
39        hasher.result()
40    }
41    // Call via a system call to perform the calculation
42    #[cfg(target_os = "trezoa")]
43    {
44        let mut hash_result = [0; trezoa_hash::HASH_BYTES];
45        unsafe {
46            trz_sha256(
47                vals as *const _ as *const u8,
48                vals.len() as u64,
49                &mut hash_result as *mut _ as *mut u8,
50            );
51        }
52        Hash::new_from_array(hash_result)
53    }
54}
55
56/// Return a Sha256 hash for the given data.
57pub fn hash(val: &[u8]) -> Hash {
58    hashv(&[val])
59}
60
61/// Return the hash of the given hash extended with the given value.
62#[deprecated(since = "3.2.3", note = "Use `hashv(&[hash.as_ref(), val])` directly")]
63pub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {
64    let mut hash_data = id.as_ref().to_vec();
65    hash_data.extend_from_slice(val);
66    hash(&hash_data)
67}