51 lines
1.5 KiB
Rust
Raw Normal View History

2022-07-26 11:02:12 -07:00
use std::str::FromStr;
use anyhow::Result;
use ethereum_types::U256;
use rand::{thread_rng, Rng};
2022-08-18 16:21:52 -07:00
use sha2::{Digest, Sha256};
2022-07-26 11:02:12 -07:00
use crate::cpu::kernel::aggregator::combined_kernel;
use crate::cpu::kernel::interpreter::run_with_kernel;
2022-08-18 16:22:43 -07:00
2022-10-03 14:07:21 -07:00
/// Standard Sha2 implementation.
fn sha2(input: Vec<u8>) -> U256 {
let mut hasher = Sha256::new();
2022-10-03 14:08:09 -07:00
hasher.update(input);
2022-10-03 14:07:21 -07:00
U256::from(&hasher.finalize()[..])
}
2022-09-25 20:13:04 -07:00
2022-10-03 14:07:21 -07:00
fn test_hash(hash_fn_label: &str, standard_implementation: &dyn Fn(Vec<u8>) -> U256) -> Result<()> {
let kernel = combined_kernel();
2022-07-26 11:02:12 -07:00
let mut rng = thread_rng();
2022-09-19 10:31:55 -07:00
// Generate a random message, between 0 and 9999 bytes.
2022-09-09 12:31:29 -07:00
let num_bytes = rng.gen_range(0..10000);
let message: Vec<u8> = (0..num_bytes).map(|_| rng.gen()).collect();
2022-09-19 10:32:52 -07:00
2022-10-03 14:07:21 -07:00
// Hash the message using a standard implementation.
let expected = standard_implementation(message.clone());
2022-09-19 10:32:52 -07:00
2022-09-19 10:31:55 -07:00
// Load the message onto the stack.
2022-08-23 15:27:20 -07:00
let mut initial_stack = vec![U256::from(num_bytes)];
2022-09-19 10:31:55 -07:00
let bytes: Vec<U256> = message.iter().map(|&x| U256::from(x as u32)).collect();
2022-08-23 15:27:20 -07:00
initial_stack.extend(bytes);
initial_stack.push(U256::from_str("0xdeadbeef").unwrap());
initial_stack.reverse();
2022-08-08 11:37:35 -07:00
2022-10-03 14:07:21 -07:00
// Run the kernel code.
let kernel_function = kernel.global_labels[hash_fn_label];
let result = run_with_kernel(&kernel, kernel_function, initial_stack)?;
let actual = result.stack()[0];
2022-09-09 12:31:29 -07:00
2022-09-19 10:31:55 -07:00
// Check that the result is correct.
2022-09-09 12:31:29 -07:00
assert_eq!(expected, actual);
2022-08-18 16:21:52 -07:00
2022-07-26 11:02:12 -07:00
Ok(())
}
2022-10-03 14:07:21 -07:00
#[test]
fn test_sha2() -> Result<()> {
test_hash("sha2", &sha2)
}