Skip to content

Commit

Permalink
Add keccak256 hash function
Browse files Browse the repository at this point in the history
  • Loading branch information
ClementWalter committed Nov 12, 2024
1 parent 3636393 commit d963259
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
19 changes: 18 additions & 1 deletion cairo/ethereum/crypto/hash.cairo
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
from ethereum.base_types import Bytes32
from ethereum.base_types import Bytes32, Bytes, Uint256
from src.utils.bytes import bytes_to_bytes8_little_endian
from starkware.cairo.common.builtin_keccak.keccak import keccak_bigend
from starkware.cairo.common.cairo_builtins import BitwiseBuiltin, KeccakBuiltin
from starkware.cairo.common.alloc import alloc

using Hash32 = Bytes32;

func keccak256{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, keccak_ptr: KeccakBuiltin*}(
buffer: Bytes
) -> Hash32 {
alloc_locals;
let (local dst: felt*) = alloc();
bytes_to_bytes8_little_endian(dst, buffer.value.len, buffer.value.data);

let (code_hash) = keccak_bigend(dst, buffer.value.len);
tempvar value = new Uint256(low=code_hash.low, high=code_hash.high);
tempvar hash = Hash32(value=value);
return hash;
}
11 changes: 11 additions & 0 deletions cairo/tests/ethereum/crypto/test_hash.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from ethereum.crypto.hash import keccak256, Hash32
from ethereum.base_types import Bytes
from starkware.cairo.common.cairo_builtins import KeccakBuiltin, BitwiseBuiltin

func test_keccak256{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, keccak_ptr: KeccakBuiltin*}(
) -> Hash32 {
tempvar buffer: Bytes;
%{ memory[ap - 1] = gen_arg(program_input["buffer"]) %}
let hash = keccak256(buffer);
return hash;
}
12 changes: 12 additions & 0 deletions cairo/tests/ethereum/crypto/test_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import hypothesis.strategies as st
from hypothesis import given

from ethereum.crypto.hash import keccak256


class TestHash:

class TestKeccak256:
@given(buffer=st.binary(min_size=0, max_size=1000))
def test_keccak256(self, cairo_run, buffer):
assert keccak256(buffer) == cairo_run("test_keccak256", buffer=buffer)

0 comments on commit d963259

Please sign in to comment.