Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for keccak256 #42

Merged
merged 6 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ exclude = ["/ci/*", "/scripts/*", "/.github/*", "/bors.toml"]

[dependencies]
sha2 = { version = "0.10", default-features = false }
tiny-keccak = { version = "2.0", features = ["keccak"],optional=true }

# standard crate data is left out
[dev-dependencies]
Expand All @@ -23,3 +24,4 @@ rayon = "1.5.1"
[features]
default = ['std']
std = ["sha2/std"]
keccak256 = ["dep:tiny-keccak"]
22 changes: 22 additions & 0 deletions src/algorithms/keccak256.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#[cfg(feature = "keccak256")]
use crate::{prelude::*, Hasher};

#[cfg(feature = "keccak256")]
use tiny_keccak::{Hasher as KeccakHasher, Keccak};

#[cfg(feature = "keccak256")]
#[derive(Clone)]
pub struct Keccak256Algorithm {}

#[cfg(feature = "keccak256")]
impl Hasher for Keccak256Algorithm {
type Hash = [u8; 32];

fn hash(data: &[u8]) -> Self::Hash {
let mut hasher = Keccak::v256();
let mut output = [0u8; 32];
hasher.update(data);
hasher.finalize(&mut output);
output
}
}
6 changes: 6 additions & 0 deletions src/algorithms/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,11 @@
mod sha256;
mod sha384;

#[cfg(feature = "keccak256")]
mod keccak256;

pub use sha256::Sha256Algorithm as Sha256;
pub use sha384::Sha384Algorithm as Sha384;

#[cfg(feature = "keccak256")]
pub use keccak256::Keccak256Algorithm as Keccak256;
22 changes: 22 additions & 0 deletions tests/common.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use rayon::prelude::*;
#[cfg(feature = "keccak256")]
use rs_merkle::algorithms::Keccak256;
use rs_merkle::{
algorithms::{Sha256, Sha384},
Hasher, MerkleTree,
Expand All @@ -16,6 +18,12 @@ pub struct TestData48 {
pub leaf_hashes: Vec<[u8; 48]>,
}

pub struct TestDataKeccak256 {
pub leaf_values: Vec<String>,
pub expected_root_hex: String,
pub leaf_hashes: Vec<[u8; 32]>,
}

fn combine<T: Clone>(active: Vec<T>, rest: Vec<T>, mut combinations: Vec<Vec<T>>) -> Vec<Vec<T>> {
return if rest.is_empty() {
if active.is_empty() {
Expand Down Expand Up @@ -69,6 +77,20 @@ pub fn setup_sha384() -> TestData48 {
expected_root_hex: String::from(expected_root_hex),
}
}
#[cfg(feature = "keccak256")]
pub fn setup_keccak256() -> TestDataKeccak256 {
let leaf_values = ["a", "b", "c", "d", "e", "f"];
let expected_root_hex = "9012f1e18a87790d2e01faace75aaaca38e53df437cdce2c0552464dda4af49c";
let leaf_hashes = leaf_values
.iter()
.map(|x| Keccak256::hash(x.as_bytes()))
.collect();
TestDataKeccak256 {
leaf_values: leaf_values.iter().cloned().map(String::from).collect(),
leaf_hashes,
expected_root_hex: String::from(expected_root_hex),
}
}

#[derive(Clone)]
pub struct ProofTestCases {
Expand Down
28 changes: 28 additions & 0 deletions tests/merkle_proof_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ mod common;
pub mod root {
use crate::common;
use rayon::prelude::*;
#[cfg(feature = "keccak256")]
use rs_merkle::algorithms::Keccak256;
use rs_merkle::{
algorithms::Sha256, proof_serializers::DirectHashesOrder, Error, MerkleProof, MerkleTree,
};
Expand Down Expand Up @@ -83,6 +85,32 @@ pub mod root {
Ok(())
}

#[test]
#[cfg(feature = "keccak256")]
pub fn should_return_a_correct_root_keccak256() -> Result<(), Error> {
let test_data = common::setup_keccak256();
let expected_root = test_data.expected_root_hex.clone();
let leaf_hashes = &test_data.leaf_hashes;
let indices_to_prove = vec![3, 4];

let leaves_to_prove: Vec<[u8; 32]> = indices_to_prove
.iter()
.map(|i| *leaf_hashes.get(*i).unwrap())
.collect();

let merkle_tree = MerkleTree::<Keccak256>::from_leaves(&test_data.leaf_hashes);
let proof = merkle_tree.proof(&indices_to_prove);
let extracted_root = proof.root_hex(
&indices_to_prove,
&leaves_to_prove,
test_data.leaf_values.len(),
)?;

assert_eq!(extracted_root, expected_root.to_string());

Ok(())
}

#[test]
pub fn should_return_error_not_enough_hashes_to_calculate_root() {
let test_data = common::setup();
Expand Down
Loading