diff --git a/substrate/primitives/core/src/hasher.rs b/substrate/primitives/core/src/hasher.rs index 96a79bf5f6..8ccaa4d90a 100644 --- a/substrate/primitives/core/src/hasher.rs +++ b/substrate/primitives/core/src/hasher.rs @@ -36,3 +36,23 @@ pub mod blake2 { } } } + +pub mod keccak { + use hash_db::Hasher; + use hash256_std_hasher::Hash256StdHasher; + use crate::hash::H256; + + /// Concrete implementation of Hasher using Keccak 256-bit hashes + #[derive(Debug)] + pub struct KeccakHasher; + + impl Hasher for KeccakHasher { + type Out = H256; + type StdHasher = Hash256StdHasher; + const LENGTH: usize = 32; + + fn hash(x: &[u8]) -> Self::Out { + crate::hashing::keccak_256(x).into() + } + } +} diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index 91bdf6683d..56dbbc7b78 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -83,6 +83,8 @@ pub use crypto::{DeriveJunction, Pair, Public}; pub use hash_db::Hasher; #[cfg(feature = "std")] pub use self::hasher::blake2::Blake2Hasher; +#[cfg(feature = "std")] +pub use self::hasher::keccak::KeccakHasher; pub use sp_storage as storage; diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index 687e01060f..f28f3e2c95 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -300,6 +300,16 @@ pub trait Trie { fn blake2_256_ordered_root(input: Vec>) -> H256 { Layout::::ordered_trie_root(input) } + + /// A trie root formed from the iterated items. + fn keccak_256_root(input: Vec<(Vec, Vec)>) -> H256 { + Layout::::trie_root(input) + } + + /// A trie root formed from the enumerated items. + fn keccak_256_ordered_root(input: Vec>) -> H256 { + Layout::::ordered_trie_root(input) + } } /// Interface that provides miscellaneous functions for communicating between the runtime and the node. diff --git a/substrate/primitives/runtime/src/traits.rs b/substrate/primitives/runtime/src/traits.rs index 7e7b5558b5..7d7e969427 100644 --- a/substrate/primitives/runtime/src/traits.rs +++ b/substrate/primitives/runtime/src/traits.rs @@ -376,6 +376,33 @@ impl Hash for BlakeTwo256 { } } +/// Keccak-256 Hash implementation. +#[derive(PartialEq, Eq, Clone, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(Serialize, Deserialize))] +pub struct Keccak256; + +impl Hasher for Keccak256 { + type Out = sp_core::H256; + type StdHasher = hash256_std_hasher::Hash256StdHasher; + const LENGTH: usize = 32; + + fn hash(s: &[u8]) -> Self::Out { + sp_io::hashing::keccak_256(s).into() + } +} + +impl Hash for Keccak256 { + type Output = sp_core::H256; + + fn trie_root(input: Vec<(Vec, Vec)>) -> Self::Output { + sp_io::trie::keccak_256_root(input) + } + + fn ordered_trie_root(input: Vec>) -> Self::Output { + sp_io::trie::keccak_256_ordered_root(input) + } +} + /// Something that can be checked for equality and printed out to a debug channel if bad. pub trait CheckEqual { /// Perform the equality check.