Skip to main content

truthlinked_sdk/
hashing.rs

1//! Cryptographic hashing utilities.
2//!
3//! This module provides SHA-256 hashing functions for deriving storage slots
4//! and creating namespaces.
5
6use sha2::{Digest, Sha256};
7
8/// Computes the SHA-256 hash of the given data.
9pub fn hash32(data: &[u8]) -> [u8; 32] {
10    let mut h = Sha256::new();
11    h.update(data);
12    let out = h.finalize();
13    let mut slot = [0u8; 32];
14    slot.copy_from_slice(&out);
15    slot
16}
17
18/// Derives a storage slot from a namespace and key parts.
19///
20/// Uses a domain-separated hash to prevent collisions.
21pub fn derive_slot(namespace: &[u8], parts: &[&[u8]]) -> [u8; 32] {
22    let mut h = Sha256::new();
23    h.update(b"trth:sdk:slot:v1");
24    h.update(&[0u8]);
25    h.update(namespace);
26    for part in parts {
27        h.update(&[0xFF]);
28        h.update(part);
29    }
30    let out = h.finalize();
31    let mut slot = [0u8; 32];
32    slot.copy_from_slice(&out);
33    slot
34}
35
36/// Converts a `u64` index to little-endian bytes.
37#[inline]
38pub fn index_u64(i: u64) -> [u8; 8] {
39    i.to_le_bytes()
40}
41
42/// Creates a namespace hash from a label.
43#[inline]
44pub fn namespace(label: &str) -> [u8; 32] {
45    hash32(label.as_bytes())
46}