alloy_primitives/utils/
mod.rs1use crate::B256;
4use alloc::{boxed::Box, collections::TryReserveError, vec::Vec};
5use cfg_if::cfg_if;
6use core::{
7 fmt,
8 mem::{ManuallyDrop, MaybeUninit},
9};
10
11mod units;
12pub use units::{
13 DecimalSeparator, ParseUnits, Unit, UnitsError, format_ether, format_units, format_units_with,
14 parse_ether, parse_units,
15};
16
17mod hint;
18
19#[cfg(feature = "keccak-cache")]
20mod keccak_cache;
21
22pub const EIP191_PREFIX: &str = "\x19Ethereum Signed Message:\n";
24
25pub const KECCAK256_EMPTY: B256 =
27 b256!("0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
28
29#[macro_export]
31macro_rules! try_vec {
32 () => {
33 $crate::private::Vec::new()
34 };
35 ($elem:expr; $n:expr) => {
36 $crate::utils::vec_try_from_elem($elem, $n)
37 };
38 ($($x:expr),+ $(,)?) => {
39 match $crate::utils::box_try_new([$($x),+]) {
40 ::core::result::Result::Ok(x) => ::core::result::Result::Ok(<[_]>::into_vec(x)),
41 ::core::result::Result::Err(e) => ::core::result::Result::Err(e),
42 }
43 };
44}
45
46#[inline]
51pub fn box_try_new<T>(value: T) -> Result<Box<T>, TryReserveError> {
52 let mut boxed = box_try_new_uninit::<T>()?;
53 unsafe {
54 boxed.as_mut_ptr().write(value);
55 let ptr = Box::into_raw(boxed);
56 Ok(Box::from_raw(ptr.cast()))
57 }
58}
59
60#[inline]
65pub fn box_try_new_uninit<T>() -> Result<Box<MaybeUninit<T>>, TryReserveError> {
66 let mut vec = Vec::<MaybeUninit<T>>::new();
67
68 vec.try_reserve_exact(1)?;
70
71 vec.shrink_to(1);
74
75 let mut vec = ManuallyDrop::new(vec);
76
77 Ok(unsafe { Box::from_raw(vec.as_mut_ptr()) })
79}
80
81pub fn try_collect_vec<I: Iterator<Item = T>, T>(iter: I) -> Result<Vec<T>, TryReserveError> {
83 let mut vec = Vec::new();
84 if let Some(size_hint) = iter.size_hint().1 {
85 vec.try_reserve(size_hint.max(4))?;
86 }
87 vec.extend(iter);
88 Ok(vec)
89}
90
91#[inline]
93pub fn vec_try_with_capacity<T>(capacity: usize) -> Result<Vec<T>, TryReserveError> {
94 let mut vec = Vec::new();
95 vec.try_reserve(capacity).map(|()| vec)
96}
97
98#[doc(hidden)]
101pub fn vec_try_from_elem<T: Clone>(elem: T, n: usize) -> Result<Vec<T>, TryReserveError> {
102 let mut vec = Vec::new();
103 vec.try_reserve(n)?;
104 vec.resize(n, elem);
105 Ok(vec)
106}
107
108pub fn eip191_hash_message<T: AsRef<[u8]>>(message: T) -> B256 {
117 keccak256(eip191_message(message))
118}
119
120pub fn eip191_message<T: AsRef<[u8]>>(message: T) -> Vec<u8> {
127 fn eip191_message(message: &[u8]) -> Vec<u8> {
128 let len = message.len();
129 let mut len_string_buffer = itoa::Buffer::new();
130 let len_string = len_string_buffer.format(len);
131
132 let mut eth_message = Vec::with_capacity(EIP191_PREFIX.len() + len_string.len() + len);
133 eth_message.extend_from_slice(EIP191_PREFIX.as_bytes());
134 eth_message.extend_from_slice(len_string.as_bytes());
135 eth_message.extend_from_slice(message);
136 eth_message
137 }
138
139 eip191_message(message.as_ref())
140}
141
142pub fn keccak256<T: AsRef<[u8]>>(bytes: T) -> B256 {
148 #[cfg(feature = "keccak-cache-global")]
149 return keccak_cache::compute(bytes.as_ref());
150 #[cfg(not(feature = "keccak-cache-global"))]
151 return keccak256_impl(bytes.as_ref());
152}
153
154pub fn keccak256_cached<T: AsRef<[u8]>>(bytes: T) -> B256 {
161 #[cfg(feature = "keccak-cache")]
162 return keccak_cache::compute(bytes.as_ref());
163 #[cfg(not(feature = "keccak-cache"))]
164 return keccak256_impl(bytes.as_ref());
165}
166
167#[inline]
175pub fn keccak256_uncached<T: AsRef<[u8]>>(bytes: T) -> B256 {
176 keccak256_impl(bytes.as_ref())
177}
178
179fn keccak256_impl(bytes: &[u8]) -> B256 {
180 let mut output = MaybeUninit::<B256>::uninit();
181
182 cfg_if! {
183 if #[cfg(all(feature = "native-keccak", not(any(feature = "sha3-keccak", feature = "tiny-keccak", miri))))] {
184 #[link(wasm_import_module = "vm_hooks")]
185 unsafe extern "C" {
186 fn native_keccak256(bytes: *const u8, len: usize, output: *mut u8);
202 }
203
204 unsafe { native_keccak256(bytes.as_ptr(), bytes.len(), output.as_mut_ptr().cast::<u8>()) };
206 } else {
207 let mut hasher = Keccak256::new();
208 hasher.update(bytes);
209 unsafe { hasher.finalize_into_raw(output.as_mut_ptr().cast()) };
211 }
212 }
213
214 unsafe { output.assume_init() }
216}
217
218mod keccak256_state {
219 cfg_if::cfg_if! {
220 if #[cfg(all(feature = "asm-keccak", not(miri)))] {
221 pub(super) use keccak_asm::Digest;
222
223 pub(super) type State = keccak_asm::Keccak256;
224 } else if #[cfg(feature = "sha3-keccak")] {
225 pub(super) use sha3::Digest;
226
227 pub(super) type State = sha3::Keccak256;
228 } else {
229 pub(super) use tiny_keccak::Hasher as Digest;
230
231 #[derive(Clone)]
233 pub(super) struct State(tiny_keccak::Keccak);
234
235 impl State {
236 #[inline]
237 pub(super) fn new() -> Self {
238 Self(tiny_keccak::Keccak::v256())
239 }
240
241 #[inline]
242 pub(super) fn finalize_into(self, output: &mut [u8; 32]) {
243 self.0.finalize(output);
244 }
245
246 #[inline]
247 pub(super) fn update(&mut self, bytes: &[u8]) {
248 self.0.update(bytes);
249 }
250 }
251 }
252 }
253}
254#[allow(unused_imports)]
255use keccak256_state::Digest;
256
257#[derive(Clone)]
264pub struct Keccak256 {
265 state: keccak256_state::State,
266}
267
268impl Default for Keccak256 {
269 #[inline]
270 fn default() -> Self {
271 Self::new()
272 }
273}
274
275impl fmt::Debug for Keccak256 {
276 #[inline]
277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278 f.debug_struct("Keccak256").finish_non_exhaustive()
279 }
280}
281
282impl Keccak256 {
283 #[inline]
285 pub fn new() -> Self {
286 Self { state: keccak256_state::State::new() }
287 }
288
289 #[inline]
291 pub fn update(&mut self, bytes: impl AsRef<[u8]>) {
292 self.state.update(bytes.as_ref());
293 }
294
295 #[inline]
297 pub fn finalize(self) -> B256 {
298 let mut output = MaybeUninit::<B256>::uninit();
299 unsafe { self.finalize_into_raw(output.as_mut_ptr().cast()) };
301 unsafe { output.assume_init() }
303 }
304
305 #[inline]
311 #[track_caller]
312 pub fn finalize_into(self, output: &mut [u8]) {
313 self.finalize_into_array(output.try_into().unwrap())
314 }
315
316 #[inline]
318 #[allow(clippy::useless_conversion)]
319 pub fn finalize_into_array(self, output: &mut [u8; 32]) {
320 self.state.finalize_into(output.into());
321 }
322
323 #[inline]
329 pub unsafe fn finalize_into_raw(self, output: *mut u8) {
330 self.finalize_into_array(unsafe { &mut *output.cast::<[u8; 32]>() })
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337 use alloc::string::ToString;
338
339 #[test]
342 fn test_hash_message() {
343 let msg = "Hello World";
344 let eip191_msg = eip191_message(msg);
345 let hash = keccak256(&eip191_msg);
346 assert_eq!(
347 eip191_msg,
348 [EIP191_PREFIX.as_bytes(), msg.len().to_string().as_bytes(), msg.as_bytes()].concat()
349 );
350 assert_eq!(
351 hash,
352 b256!("0xa1de988600a42c4b4ab089b619297c17d53cffae5d5120d82d8a92d0bb3b78f2")
353 );
354 assert_eq!(eip191_hash_message(msg), hash);
355 }
356
357 #[test]
358 fn keccak256_hasher() {
359 let expected = b256!("0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad");
360 assert_eq!(keccak256("hello world"), expected);
361
362 let mut hasher = Keccak256::new();
363 hasher.update(b"hello");
364 hasher.update(b" world");
365
366 assert_eq!(hasher.clone().finalize(), expected);
367
368 let mut hash = [0u8; 32];
369 hasher.clone().finalize_into(&mut hash);
370 assert_eq!(hash, expected);
371
372 let mut hash = [0u8; 32];
373 hasher.clone().finalize_into_array(&mut hash);
374 assert_eq!(hash, expected);
375
376 let mut hash = [0u8; 32];
377 unsafe { hasher.finalize_into_raw(hash.as_mut_ptr()) };
378 assert_eq!(hash, expected);
379 }
380
381 #[test]
382 fn test_try_boxing() {
383 let x = Box::new(42);
384 let y = box_try_new(42).unwrap();
385 assert_eq!(x, y);
386
387 let x = vec![1; 3];
388 let y = try_vec![1; 3].unwrap();
389 assert_eq!(x, y);
390
391 let x = vec![1, 2, 3];
392 let y = try_vec![1, 2, 3].unwrap();
393 assert_eq!(x, y);
394 }
395
396 #[test]
397 #[cfg(feature = "keccak-cache")]
398 fn test_keccak256_cache_edge_cases() {
399 use keccak256_cached as keccak256;
400 assert_eq!(keccak256([]), KECCAK256_EMPTY);
401 assert_eq!(keccak256([]), KECCAK256_EMPTY);
402
403 let max_cacheable = vec![0xAA; keccak_cache::MAX_INPUT_LEN];
404 let hash1 = keccak256(&max_cacheable);
405 let hash2 = keccak256_impl(&max_cacheable);
406 assert_eq!(hash1, hash2);
407
408 let over_max = vec![0xBB; keccak_cache::MAX_INPUT_LEN + 1];
409 let hash1 = keccak256(&over_max);
410 let hash2 = keccak256_impl(&over_max);
411 assert_eq!(hash1, hash2);
412
413 let long_input = vec![0xCC; 1000];
414 let hash1 = keccak256(&long_input);
415 let hash2 = keccak256_impl(&long_input);
416 assert_eq!(hash1, hash2);
417
418 let max = if cfg!(miri) { 10 } else { 255 };
419 for byte in 0..=max {
420 let data = &[byte];
421 let hash1 = keccak256(data);
422 let hash2 = keccak256_impl(data);
423 assert_eq!(hash1, hash2);
424 }
425 }
426
427 #[test]
428 #[cfg(all(feature = "keccak-cache", feature = "rand"))]
429 fn test_keccak256_cache_multithreaded() {
430 use keccak256_cached as keccak256;
431 use rand::{Rng, SeedableRng};
432 use std::{sync::Arc, thread};
433
434 let num_threads = if cfg!(miri) {
436 2
437 } else {
438 thread::available_parallelism().map(|n| n.get()).unwrap_or(8)
439 };
440 let iterations_per_thread = if cfg!(miri) { 10 } else { 1000 };
441 let num_test_vectors = if cfg!(miri) { 5 } else { 100 };
442 let max_data_length = keccak_cache::MAX_INPUT_LEN;
443
444 let test_vectors: Arc<Vec<Vec<u8>>> = Arc::new({
446 let mut rng = rand::rngs::StdRng::seed_from_u64(42);
447 (0..num_test_vectors)
448 .map(|_| {
449 let len = rng.random_range(0..=max_data_length);
450 (0..len).map(|_| rng.random()).collect()
451 })
452 .collect()
453 });
454
455 let mut handles = vec![];
456
457 for thread_id in 0..num_threads {
458 let test_vectors = Arc::clone(&test_vectors);
459
460 let handle = thread::spawn(move || {
461 let mut rng = rand::rngs::StdRng::seed_from_u64(thread_id as u64);
463 let max_data_length = keccak_cache::MAX_INPUT_LEN;
464
465 for _ in 0..iterations_per_thread {
466 if rng.random_range(0..10) < 7 && !test_vectors.is_empty() {
468 let idx = rng.random_range(0..test_vectors.len());
469 let data = &test_vectors[idx];
470
471 let cached_hash = keccak256(data);
472 let direct_hash = keccak256_impl(data);
473
474 assert_eq!(
475 cached_hash,
476 direct_hash,
477 "Thread {}: Cached hash mismatch for shared vector {} (len {})",
478 thread_id,
479 idx,
480 data.len()
481 );
482 } else {
483 let len = rng.random_range(0..max_data_length + 20);
485 let data: Vec<u8> = (0..len).map(|_| rng.random()).collect();
486
487 let cached_hash = keccak256(&data);
488 let direct_hash = keccak256_impl(&data);
489
490 assert_eq!(
491 cached_hash, direct_hash,
492 "Thread {thread_id}: Cached hash mismatch for random data (len {len})"
493 );
494 }
495 }
496 });
497
498 handles.push(handle);
499 }
500
501 for handle in handles {
503 handle.join().expect("Thread panicked");
504 }
505 }
506}