1#![no_std]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
4#[cfg(feature = "borsh")]
5use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
6#[cfg(any(feature = "std", target_arch = "wasm32"))]
7extern crate std;
8#[cfg(feature = "bytemuck")]
9use bytemuck_derive::{Pod, Zeroable};
10#[cfg(feature = "serde")]
11use serde_derive::{Deserialize, Serialize};
12#[cfg(any(all(feature = "borsh", feature = "std"), target_arch = "wasm32"))]
13use std::string::ToString;
14use {
15 core::{
16 convert::TryFrom,
17 fmt, mem,
18 str::{from_utf8, FromStr},
19 },
20 solana_sanitize::Sanitize,
21};
22#[cfg(target_arch = "wasm32")]
23use {
24 js_sys::{Array, Uint8Array},
25 std::{boxed::Box, format, string::String, vec},
26 wasm_bindgen::{prelude::*, JsCast},
27};
28
29pub const HASH_BYTES: usize = 32;
31pub const MAX_BASE58_LEN: usize = 44;
33
34#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
42#[cfg_attr(feature = "frozen-abi", derive(solana_frozen_abi_macro::AbiExample))]
43#[cfg_attr(
44 feature = "borsh",
45 derive(BorshSerialize, BorshDeserialize),
46 borsh(crate = "borsh")
47)]
48#[cfg_attr(all(feature = "borsh", feature = "std"), derive(BorshSchema))]
49#[cfg_attr(feature = "bytemuck", derive(Pod, Zeroable))]
50#[cfg_attr(feature = "serde", derive(Serialize, Deserialize,))]
51#[derive(Clone, Copy, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
52#[repr(transparent)]
53pub struct Hash(pub(crate) [u8; HASH_BYTES]);
54
55impl Sanitize for Hash {}
56
57impl From<[u8; HASH_BYTES]> for Hash {
58 fn from(from: [u8; 32]) -> Self {
59 Self(from)
60 }
61}
62
63impl AsRef<[u8]> for Hash {
64 fn as_ref(&self) -> &[u8] {
65 &self.0[..]
66 }
67}
68
69fn write_as_base58(f: &mut fmt::Formatter, h: &Hash) -> fmt::Result {
70 let mut out = [0u8; MAX_BASE58_LEN];
71 let out_slice: &mut [u8] = &mut out;
72 let len = bs58::encode(h.0).onto(out_slice).unwrap();
75 let as_str = from_utf8(&out[..len]).unwrap();
76 f.write_str(as_str)
77}
78
79impl fmt::Debug for Hash {
80 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81 write_as_base58(f, self)
82 }
83}
84
85impl fmt::Display for Hash {
86 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87 write_as_base58(f, self)
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub enum ParseHashError {
93 WrongSize,
94 Invalid,
95}
96
97#[cfg(feature = "std")]
98impl std::error::Error for ParseHashError {}
99
100impl fmt::Display for ParseHashError {
101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102 match self {
103 ParseHashError::WrongSize => f.write_str("string decoded to wrong size for hash"),
104 ParseHashError::Invalid => f.write_str("failed to decoded string to hash"),
105 }
106 }
107}
108
109impl FromStr for Hash {
110 type Err = ParseHashError;
111
112 fn from_str(s: &str) -> Result<Self, Self::Err> {
113 if s.len() > MAX_BASE58_LEN {
114 return Err(ParseHashError::WrongSize);
115 }
116 let mut bytes = [0; HASH_BYTES];
117 let decoded_size = bs58::decode(s)
118 .onto(&mut bytes)
119 .map_err(|_| ParseHashError::Invalid)?;
120 if decoded_size != mem::size_of::<Hash>() {
121 Err(ParseHashError::WrongSize)
122 } else {
123 Ok(bytes.into())
124 }
125 }
126}
127
128impl Hash {
129 pub fn new(hash_slice: &[u8]) -> Self {
130 Hash(<[u8; HASH_BYTES]>::try_from(hash_slice).unwrap())
131 }
132
133 pub const fn new_from_array(hash_array: [u8; HASH_BYTES]) -> Self {
134 Self(hash_array)
135 }
136
137 pub fn new_unique() -> Self {
139 use solana_atomic_u64::AtomicU64;
140 static I: AtomicU64 = AtomicU64::new(1);
141
142 let mut b = [0u8; HASH_BYTES];
143 let i = I.fetch_add(1);
144 b[0..8].copy_from_slice(&i.to_le_bytes());
145 Self::new(&b)
146 }
147
148 pub fn to_bytes(self) -> [u8; HASH_BYTES] {
149 self.0
150 }
151}
152
153#[cfg(target_arch = "wasm32")]
154#[allow(non_snake_case)]
155#[wasm_bindgen]
156impl Hash {
157 #[wasm_bindgen(constructor)]
161 pub fn constructor(value: JsValue) -> Result<Hash, JsValue> {
162 if let Some(base58_str) = value.as_string() {
163 base58_str
164 .parse::<Hash>()
165 .map_err(|x| JsValue::from(x.to_string()))
166 } else if let Some(uint8_array) = value.dyn_ref::<Uint8Array>() {
167 Ok(Hash::new(&uint8_array.to_vec()))
168 } else if let Some(array) = value.dyn_ref::<Array>() {
169 let mut bytes = vec![];
170 let iterator = js_sys::try_iter(&array.values())?.expect("array to be iterable");
171 for x in iterator {
172 let x = x?;
173
174 if let Some(n) = x.as_f64() {
175 if n >= 0. && n <= 255. {
176 bytes.push(n as u8);
177 continue;
178 }
179 }
180 return Err(format!("Invalid array argument: {:?}", x).into());
181 }
182 Ok(Hash::new(&bytes))
183 } else if value.is_undefined() {
184 Ok(Hash::default())
185 } else {
186 Err("Unsupported argument".into())
187 }
188 }
189
190 pub fn toString(&self) -> String {
192 self.to_string()
193 }
194
195 pub fn equals(&self, other: &Hash) -> bool {
197 self == other
198 }
199
200 pub fn toBytes(&self) -> Box<[u8]> {
202 self.0.clone().into()
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn test_new_unique() {
212 assert!(Hash::new_unique() != Hash::new_unique());
213 }
214
215 #[test]
216 fn test_hash_fromstr() {
217 let hash = Hash::new_from_array([1; 32]);
218
219 let mut hash_base58_str = bs58::encode(hash).into_string();
220
221 assert_eq!(hash_base58_str.parse::<Hash>(), Ok(hash));
222
223 hash_base58_str.push_str(&bs58::encode(hash.as_ref()).into_string());
224 assert_eq!(
225 hash_base58_str.parse::<Hash>(),
226 Err(ParseHashError::WrongSize)
227 );
228
229 hash_base58_str.truncate(hash_base58_str.len() / 2);
230 assert_eq!(hash_base58_str.parse::<Hash>(), Ok(hash));
231
232 hash_base58_str.truncate(hash_base58_str.len() / 2);
233 assert_eq!(
234 hash_base58_str.parse::<Hash>(),
235 Err(ParseHashError::WrongSize)
236 );
237
238 let input_too_big = bs58::encode(&[0xffu8; HASH_BYTES + 1]).into_string();
239 assert!(input_too_big.len() > MAX_BASE58_LEN);
240 assert_eq!(
241 input_too_big.parse::<Hash>(),
242 Err(ParseHashError::WrongSize)
243 );
244
245 let mut hash_base58_str = bs58::encode(hash.as_ref()).into_string();
246 assert_eq!(hash_base58_str.parse::<Hash>(), Ok(hash));
247
248 hash_base58_str.replace_range(..1, "I");
250 assert_eq!(
251 hash_base58_str.parse::<Hash>(),
252 Err(ParseHashError::Invalid)
253 );
254 }
255}