Skip to main content

thruput_sdk/
hash.rs

1//! Hash trait
2
3use crate::crypto::{SHA256Hash, sha256};
4use crate::{FaultString, HandlingError, library_throw};
5
6/// SHA-256 of a value's CXS encoding.
7///
8/// The blanket impl covers every [`WriteXDR`](xdrs::WriteXDR) type: it encodes
9/// the value into the shared scratch buffer and hashes the bytes. Under the
10/// `alloc` feature the scratch grows to fit, so there is no size limit. In the
11/// no-alloc guest the scratch is a fixed [`SCRATCH_MAX`](crate::internal::SCRATCH_MAX)
12/// (4 KiB) buffer; a value whose encoding exceeds it throws
13/// [`HandlingError::EncodingException`] (a non-returning library exception),
14/// matching how terminal returns and aborts handle the same overflow.
15pub trait Hash {
16    fn hash(&self) -> SHA256Hash;
17}
18
19// We encode the whole value into the shared scratch buffer before hashing.
20// TODO: Use the incremental-hashing interface.
21impl<T> Hash for T
22where
23    T: xdrs::WriteXDR,
24{
25    fn hash(&self) -> SHA256Hash {
26        crate::call::with_scratch(|buf| {
27            crate::internal::encode_scratch(buf, self).unwrap_or_else(|e| {
28                library_throw(HandlingError::EncodingException(
29                    FaultString::via_display(&e),
30                ))
31            });
32            sha256(buf.as_slice())
33        })
34    }
35}