Skip to content

Commit

Permalink
perf(merkle): optimize Poseidon hash using direct hades_permutation
Browse files Browse the repository at this point in the history
  • Loading branch information
0x471 committed Jan 1, 2025
1 parent d9729b7 commit 6fad4b8
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions packages/merkle_tree/src/hashes.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use core::hash::HashStateTrait;
use core::pedersen::PedersenTrait;
use core::poseidon::PoseidonTrait;
use core::traits::PartialOrd;
use core::poseidon::hades_permutation;

/// Computes a commutative hash of a sorted pair of felt252 values.
///
Expand Down Expand Up @@ -33,14 +34,15 @@ pub impl PedersenCHasher of CommutativeHasher {

/// Computes the Poseidon commutative hash of a sorted pair of felt252 values.
pub impl PoseidonCHasher of CommutativeHasher {
/// Computes the Poseidon hash of the concatenation of two values, sorting the pair first.
/// Computes the Poseidon hash by directly using hades_permutation with the two values
/// and a length indicator, sorting the pair first.
fn commutative_hash(a: felt252, b: felt252) -> felt252 {
let hash_state = PoseidonTrait::new();
if a < b {
hash_state.update(a).update(b).finalize()
let (result, _, _) = if a < b {
hades_permutation(a, b, 2)
} else {
hash_state.update(b).update(a).finalize()
}
hades_permutation(b, a, 2)
};
result
}
}

Expand Down

0 comments on commit 6fad4b8

Please sign in to comment.