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