solana_program/
keccak.rs

1//! Hashing with the [keccak] (SHA-3) hash function.
2//!
3//! [keccak]: https://keccak.team/keccak.html
4
5use {
6    crate::sanitize::Sanitize,
7    borsh::{BorshDeserialize, BorshSchema, BorshSerialize},
8    sha3::{Digest, Keccak256},
9    std::{convert::TryFrom, fmt, mem, str::FromStr},
10    thiserror::Error,
11};
12
13pub const HASH_BYTES: usize = 32;
14/// Maximum string length of a base58 encoded hash
15const MAX_BASE58_LEN: usize = 44;
16#[derive(
17    Serialize,
18    Deserialize,
19    BorshSerialize,
20    BorshDeserialize,
21    BorshSchema,
22    Clone,
23    Copy,
24    Default,
25    Eq,
26    PartialEq,
27    Ord,
28    PartialOrd,
29    Hash,
30    AbiExample,
31)]
32#[repr(transparent)]
33pub struct Hash(pub [u8; HASH_BYTES]);
34
35#[derive(Clone, Default)]
36pub struct Hasher {
37    hasher: Keccak256,
38}
39
40impl Hasher {
41    pub fn hash(&mut self, val: &[u8]) {
42        self.hasher.update(val);
43    }
44    pub fn hashv(&mut self, vals: &[&[u8]]) {
45        for val in vals {
46            self.hash(val);
47        }
48    }
49    pub fn result(self) -> Hash {
50        // At the time of this writing, the sha3 library is stuck on an old version
51        // of generic_array (0.9.0). Decouple ourselves with a clone to our version.
52        Hash(<[u8; HASH_BYTES]>::try_from(self.hasher.finalize().as_slice()).unwrap())
53    }
54}
55
56impl Sanitize for Hash {}
57
58impl AsRef<[u8]> for Hash {
59    fn as_ref(&self) -> &[u8] {
60        &self.0[..]
61    }
62}
63
64impl fmt::Debug for Hash {
65    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66        write!(f, "{}", bs58::encode(self.0).into_string())
67    }
68}
69
70impl fmt::Display for Hash {
71    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72        write!(f, "{}", bs58::encode(self.0).into_string())
73    }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Error)]
77pub enum ParseHashError {
78    #[error("string decoded to wrong size for hash")]
79    WrongSize,
80    #[error("failed to decoded string to hash")]
81    Invalid,
82}
83
84impl FromStr for Hash {
85    type Err = ParseHashError;
86
87    fn from_str(s: &str) -> Result<Self, Self::Err> {
88        if s.len() > MAX_BASE58_LEN {
89            return Err(ParseHashError::WrongSize);
90        }
91        let bytes = bs58::decode(s)
92            .into_vec()
93            .map_err(|_| ParseHashError::Invalid)?;
94        if bytes.len() != mem::size_of::<Hash>() {
95            Err(ParseHashError::WrongSize)
96        } else {
97            Ok(Hash::new(&bytes))
98        }
99    }
100}
101
102impl Hash {
103    pub fn new(hash_slice: &[u8]) -> Self {
104        Hash(<[u8; HASH_BYTES]>::try_from(hash_slice).unwrap())
105    }
106
107    pub const fn new_from_array(hash_array: [u8; HASH_BYTES]) -> Self {
108        Self(hash_array)
109    }
110
111    /// unique Hash for tests and benchmarks.
112    pub fn new_unique() -> Self {
113        use crate::atomic_u64::AtomicU64;
114        static I: AtomicU64 = AtomicU64::new(1);
115
116        let mut b = [0u8; HASH_BYTES];
117        let i = I.fetch_add(1);
118        b[0..8].copy_from_slice(&i.to_le_bytes());
119        Self::new(&b)
120    }
121
122    pub fn to_bytes(self) -> [u8; HASH_BYTES] {
123        self.0
124    }
125}
126
127/// Return a Keccak256 hash for the given data.
128pub fn hashv(vals: &[&[u8]]) -> Hash {
129    // Perform the calculation inline, calling this from within a program is
130    // not supported
131    #[cfg(not(target_os = "solana"))]
132    {
133        let mut hasher = Hasher::default();
134        hasher.hashv(vals);
135        hasher.result()
136    }
137    // Call via a system call to perform the calculation
138    #[cfg(target_os = "solana")]
139    {
140        let mut hash_result = [0; HASH_BYTES];
141        unsafe {
142            crate::syscalls::sol_keccak256(
143                vals as *const _ as *const u8,
144                vals.len() as u64,
145                &mut hash_result as *mut _ as *mut u8,
146            );
147        }
148        Hash::new_from_array(hash_result)
149    }
150}
151
152/// Return a Keccak256 hash for the given data.
153pub fn hash(val: &[u8]) -> Hash {
154    hashv(&[val])
155}
156
157/// Return the hash of the given hash extended with the given value.
158pub fn extend_and_hash(id: &Hash, val: &[u8]) -> Hash {
159    let mut hash_data = id.as_ref().to_vec();
160    hash_data.extend_from_slice(val);
161    hash(&hash_data)
162}