Skip to content
This repository has been archived by the owner on Nov 10, 2023. It is now read-only.

Commit

Permalink
refactor hashing in pallet
Browse files Browse the repository at this point in the history
  • Loading branch information
Wizdave97 committed Aug 1, 2023
1 parent 8f561ba commit 735574b
Show file tree
Hide file tree
Showing 15 changed files with 74 additions and 57 deletions.
1 change: 1 addition & 0 deletions grandpa/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ where
T: pallet_ismp::Config + super::Config,
T::BlockNumber: Into<u32>,
T::Hash: From<H256>,
H256: From<T::Hash>,
{
fn verify_consensus(
&self,
Expand Down
1 change: 1 addition & 0 deletions grandpa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub mod pallet {
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Add some new parachains to the list of parachains in the relay chain consensus state
#[pallet::call_index(0)]
Expand Down
3 changes: 3 additions & 0 deletions pallet-ismp/evm/src/precompiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ impl<T> Precompile for IsmpPostDispatcher<T>
where
T: pallet_ismp::Config + pallet_evm::Config,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult {
let input = handle.input();
Expand Down Expand Up @@ -82,6 +83,7 @@ impl<T> Precompile for IsmpGetDispatcher<T>
where
T: pallet_ismp::Config + pallet_evm::Config,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult {
let input = handle.input();
Expand Down Expand Up @@ -129,6 +131,7 @@ impl<T> Precompile for IsmpResponseDispatcher<T>
where
T: pallet_ismp::Config + pallet_evm::Config,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult {
let input = handle.input();
Expand Down
34 changes: 15 additions & 19 deletions pallet-ismp/primitives/src/mmr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ use core::fmt::Formatter;

use codec::{Decode, Encode};
use ismp::{
host::IsmpHost,
router::{Request, Response},
util::{hash_request, hash_response},
util::{hash_request, hash_response, Keccak256},
};
use primitive_types::H256;
use sp_runtime::traits;
Expand All @@ -42,7 +41,7 @@ pub enum Leaf {

impl Leaf {
/// Returns the hash of a leaf
fn hash<H: IsmpHost>(&self) -> H256 {
fn hash<H: Keccak256>(&self) -> H256 {
match self {
Leaf::Request(req) => hash_request::<H>(req),
Leaf::Response(res) => hash_response::<H>(res),
Expand All @@ -52,14 +51,14 @@ impl Leaf {

/// An element representing either full data or its hash.
#[derive(Clone, PartialEq, Eq, Encode, Decode, scale_info::TypeInfo)]
pub enum DataOrHash<T: frame_system::Config> {
pub enum DataOrHash {
/// Arbitrary data in its full form.
Data(Leaf),
/// A hash of some data.
Hash(<<T as frame_system::Config>::Hashing as traits::Hash>::Output),
Hash(H256),
}

impl<T: frame_system::Config> core::fmt::Debug for DataOrHash<T> {
impl core::fmt::Debug for DataOrHash {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
DataOrHash::Data(leaf) => f.debug_struct("DataOrHash").field("Data", leaf).finish(),
Expand All @@ -68,26 +67,20 @@ impl<T: frame_system::Config> core::fmt::Debug for DataOrHash<T> {
}
}

impl<T: frame_system::Config> From<Leaf> for DataOrHash<T> {
impl From<Leaf> for DataOrHash {
fn from(l: Leaf) -> Self {
Self::Data(l)
}
}

impl<T> DataOrHash<T>
where
T: frame_system::Config,
T::Hash: From<H256>,
{
impl DataOrHash {
/// Retrieve a hash of this item.
///
/// Depending on the node type it's going to either be a contained value for [DataOrHash::Hash]
/// node, or a hash of SCALE-encoded [DataOrHash::Data] data.
pub fn hash<H: IsmpHost>(
&self,
) -> <<T as frame_system::Config>::Hashing as traits::Hash>::Output {
pub fn hash<H: Keccak256>(&self) -> H256 {
match *self {
Self::Data(ref leaf) => <T::Hash>::from(leaf.hash::<H>()),
Self::Data(ref leaf) => leaf.hash::<H>(),
Self::Hash(ref hash) => *hash,
}
}
Expand All @@ -100,14 +93,17 @@ impl<T, H> merkle_mountain_range::Merge for MmrHasher<T, H>
where
T: frame_system::Config,
T::Hash: From<H256>,
H: IsmpHost,
H256: From<T::Hash>,
H: Keccak256,
{
type Item = DataOrHash<T>;
type Item = DataOrHash;

fn merge(left: &Self::Item, right: &Self::Item) -> merkle_mountain_range::Result<Self::Item> {
let mut concat = left.hash::<H>().as_ref().to_vec();
concat.extend_from_slice(right.hash::<H>().as_ref());

Ok(DataOrHash::Hash(<<T as frame_system::Config>::Hashing as traits::Hash>::hash(&concat)))
Ok(DataOrHash::Hash(
<<T as frame_system::Config>::Hashing as traits::Hash>::hash(&concat).into(),
))
}
}
5 changes: 3 additions & 2 deletions pallet-ismp/primitives/state-machine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ where
T: pallet_ismp::Config,
T::BlockNumber: Into<u32>,
T::Hash: From<H256>,
H256: From<T::Hash>,
{
fn verify_membership(
&self,
Expand All @@ -68,8 +69,8 @@ where
})?;
let nodes = membership.proof.into_iter().map(|h| DataOrHash::Hash(h.into())).collect();
let proof =
MerkleProof::<DataOrHash<T>, MmrHasher<T, Host<T>>>::new(membership.mmr_size, nodes);
let leaves: Vec<(u64, DataOrHash<T>)> = match item {
MerkleProof::<DataOrHash, MmrHasher<T, Host<T>>>::new(membership.mmr_size, nodes);
let leaves: Vec<(u64, DataOrHash)> = match item {
RequestResponse::Request(req) => membership
.leaf_indices
.into_iter()
Expand Down
1 change: 1 addition & 0 deletions pallet-ismp/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use frame_system::RawOrigin;
#[benchmarks(
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
T: pallet_timestamp::Config,
<T as pallet_timestamp::Config>::Moment: From<u64>
)]
Expand Down
1 change: 1 addition & 0 deletions pallet-ismp/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ impl<T> IsmpDispatcher for Dispatcher<T>
where
T: Config,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
fn dispatch_request(&self, request: DispatchRequest) -> Result<(), IsmpError> {
let host = Host::<T>::default();
Expand Down
1 change: 1 addition & 0 deletions pallet-ismp/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use sp_core::H256;
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Dispatch an outgoing request
pub fn dispatch_request(request: Request) -> Result<(), IsmpError> {
Expand Down
17 changes: 10 additions & 7 deletions pallet-ismp/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ impl<T: Config> Default for Host<T> {
impl<T: Config> IsmpHost for Host<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
fn host_state_machine(&self) -> StateMachine {
T::StateMachine::get()
Expand Down Expand Up @@ -155,13 +156,6 @@ where
<T as Config>::ConsensusClientProvider::consensus_client(id)
}

fn keccak256(bytes: &[u8]) -> H256
where
Self: Sized,
{
sp_io::hashing::keccak_256(bytes).into()
}

fn challenge_period(&self, id: ConsensusStateId) -> Option<Duration> {
ChallengePeriod::<T>::get(&id).map(Duration::from_secs)
}
Expand Down Expand Up @@ -259,3 +253,12 @@ where
AllowedProxies::<T>::set(allowed);
}
}

impl<T: Config> ismp_rs::util::Keccak256 for Host<T> {
fn keccak256(bytes: &[u8]) -> H256
where
Self: Sized,
{
sp_io::hashing::keccak_256(bytes).into()
}
}
24 changes: 13 additions & 11 deletions pallet-ismp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ pub mod pallet {
/// Latest MMR Root hash
#[pallet::storage]
#[pallet::getter(fn mmr_root_hash)]
pub type RootHash<T: Config> = StorageValue<_, <T as frame_system::Config>::Hash, ValueQuery>;
pub type RootHash<T: Config> = StorageValue<_, H256, ValueQuery>;

/// Current size of the MMR (number of leaves) for requests.
#[pallet::storage]
Expand All @@ -160,8 +160,7 @@ pub mod pallet {
/// are pruned and only stored in the Offchain DB.
#[pallet::storage]
#[pallet::getter(fn request_peaks)]
pub type Nodes<T: Config> =
StorageMap<_, Identity, NodeIndex, <T as frame_system::Config>::Hash, OptionQuery>;
pub type Nodes<T: Config> = StorageMap<_, Identity, NodeIndex, H256, OptionQuery>;

/// Holds a map of state machine heights to their verified state commitments
#[pallet::storage]
Expand Down Expand Up @@ -275,6 +274,7 @@ pub mod pallet {
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
fn on_initialize(_n: T::BlockNumber) -> Weight {
// return Mmr finalization weight here
Expand All @@ -299,7 +299,7 @@ pub mod pallet {

root
} else {
H256::default().into()
H256::default()
};

let digest = sp_runtime::generic::DigestItem::Consensus(ISMP_ID, root.encode());
Expand All @@ -324,6 +324,7 @@ pub mod pallet {
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Handles ismp messages
#[pallet::weight(get_weight::<T>(&messages))]
Expand Down Expand Up @@ -456,6 +457,7 @@ pub mod pallet {
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Generate an MMR proof for the given `leaf_indices`.
/// Note this method can only be used from an off-chain context
Expand All @@ -464,8 +466,7 @@ where
/// It may return an error or panic if used incorrectly.
pub fn generate_proof(
leaf_indices: Vec<LeafIndex>,
) -> Result<(Vec<Leaf>, primitives::Proof<<T as frame_system::Config>::Hash>), primitives::Error>
{
) -> Result<(Vec<Leaf>, primitives::Proof<H256>), primitives::Error> {
let leaves_count = NumberOfLeaves::<T>::get();
let mmr = Mmr::<mmr::storage::OffchainStorage, T>::new(leaves_count);
mmr.generate_proof(leaf_indices)
Expand Down Expand Up @@ -549,7 +550,7 @@ where
}

/// Return the on-chain MMR root hash.
pub fn mmr_root() -> <T as frame_system::Config>::Hash {
pub fn mmr_root() -> H256 {
Self::mmr_root_hash()
}

Expand All @@ -569,6 +570,7 @@ pub struct RequestResponseLog<T: Config> {
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Returns the offchain key for a request leaf index
pub fn request_leaf_index_offchain_key(
Expand Down Expand Up @@ -597,7 +599,7 @@ where
pub fn get_request(leaf_index: LeafIndex) -> Option<Request> {
let key = Pallet::<T>::offchain_key(leaf_index);
if let Some(elem) = sp_io::offchain::local_storage_get(StorageKind::PERSISTENT, &key) {
let data_or_hash = DataOrHash::<T>::decode(&mut &*elem).ok()?;
let data_or_hash = DataOrHash::decode(&mut &*elem).ok()?;
return match data_or_hash {
DataOrHash::Data(leaf) => match leaf {
Leaf::Request(req) => Some(req),
Expand All @@ -613,7 +615,7 @@ where
pub fn get_response(leaf_index: LeafIndex) -> Option<Response> {
let key = Pallet::<T>::offchain_key(leaf_index);
if let Some(elem) = sp_io::offchain::local_storage_get(StorageKind::PERSISTENT, &key) {
let data_or_hash = DataOrHash::<T>::decode(&mut &*elem).ok()?;
let data_or_hash = DataOrHash::decode(&mut &*elem).ok()?;
return match data_or_hash {
DataOrHash::Data(leaf) => match leaf {
Leaf::Response(res) => Some(res),
Expand Down Expand Up @@ -736,7 +738,7 @@ where

impl<T: Config> Pallet<T> {
/// Get a node from runtime storage
fn get_node(pos: NodeIndex) -> Option<DataOrHash<T>> {
fn get_node(pos: NodeIndex) -> Option<DataOrHash> {
Nodes::<T>::get(pos).map(DataOrHash::Hash)
}

Expand All @@ -746,7 +748,7 @@ impl<T: Config> Pallet<T> {
}

/// Insert a node into storage
fn insert_node(pos: NodeIndex, node: <T as frame_system::Config>::Hash) {
fn insert_node(pos: NodeIndex, node: H256) {
Nodes::<T>::insert(pos, node)
}

Expand Down
14 changes: 9 additions & 5 deletions pallet-ismp/src/mmr/mmr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,20 @@ use sp_std::prelude::*;
pub struct Mmr<StorageType, T>
where
T: Config,
Storage<StorageType, T>: mmr_lib::MMRStore<DataOrHash<T>>,
Storage<StorageType, T>: mmr_lib::MMRStore<DataOrHash>,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
mmr: mmr_lib::MMR<DataOrHash<T>, MmrHasher<T, Host<T>>, Storage<StorageType, T>>,
mmr: mmr_lib::MMR<DataOrHash, MmrHasher<T, Host<T>>, Storage<StorageType, T>>,
leaves: NodeIndex,
}

impl<StorageType, T> Mmr<StorageType, T>
where
T: Config,
Storage<StorageType, T>: mmr_lib::MMRStore<DataOrHash<T>>,
Storage<StorageType, T>: mmr_lib::MMRStore<DataOrHash>,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Create a pointer to an existing MMR with given number of leaves.
pub fn new(leaves: NodeIndex) -> Self {
Expand All @@ -58,6 +60,7 @@ impl<T> Mmr<RuntimeStorage, T>
where
T: Config,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Push another item to the MMR and commit
///
Expand All @@ -71,7 +74,7 @@ where
}

/// Calculate the new MMR's root hash.
pub fn finalize(self) -> Result<<T as frame_system::Config>::Hash, Error> {
pub fn finalize(self) -> Result<H256, Error> {
let root = self.mmr.get_root().map_err(|_| Error::GetRoot)?;
Ok(root.hash::<Host<T>>())
}
Expand All @@ -82,6 +85,7 @@ impl<T> Mmr<OffchainStorage, T>
where
T: Config,
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
/// Generate a proof for given leaf indices.
///
Expand All @@ -90,7 +94,7 @@ where
pub fn generate_proof(
&self,
positions: Vec<NodeIndex>,
) -> Result<(Vec<Leaf>, Proof<<T as frame_system::Config>::Hash>), Error> {
) -> Result<(Vec<Leaf>, Proof<H256>), Error> {
let store = <Storage<OffchainStorage, T>>::default();
let leaves = positions
.iter()
Expand Down
Loading

0 comments on commit 735574b

Please sign in to comment.