openvm_keccak256_guest/lib.rs
1#![no_std]
2
3/// This is custom-0 defined in RISC-V spec document
4pub const OPCODE: u8 = 0x0b;
5pub const KECCAK256_FUNCT3: u8 = 0b100;
6pub const KECCAK256_FUNCT7: u8 = 0;
7
8/// Native hook for keccak256 for use with `alloy-primitives` "native-keccak" feature.
9///
10/// # Safety
11///
12/// The VM accepts the preimage by pointer and length, and writes the
13/// 32-byte hash.
14/// - `bytes` must point to an input buffer at least `len` long.
15/// - `output` must point to a buffer that is at least 32-bytes long.
16///
17/// [`keccak256`]: https://en.wikipedia.org/wiki/SHA-3
18/// [`sha3`]: https://docs.rs/sha3/latest/sha3/
19/// [`tiny_keccak`]: https://docs.rs/tiny-keccak/latest/tiny_keccak/
20#[cfg(target_os = "zkvm")]
21#[inline(always)]
22#[no_mangle]
23pub extern "C" fn native_keccak256(bytes: *const u8, len: usize, output: *mut u8) {
24 openvm_platform::custom_insn_r!(
25 opcode = OPCODE,
26 funct3 = KECCAK256_FUNCT3,
27 funct7 = KECCAK256_FUNCT7,
28 rd = In output,
29 rs1 = In bytes,
30 rs2 = In len
31 );
32}