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

Refactor mmr hasher #80

Merged
merged 1 commit into from
Aug 1, 2023
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: 0 additions & 2 deletions grandpa/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@ where
T::Header: Header<Hash = H256, Number = u32>,
T: pallet_ismp::Config + super::Config,
T::BlockNumber: Into<u32>,
T::Hash: From<H256>,
H256: From<T::Hash>,
{
fn verify_consensus(
&self,
Expand Down
9 changes: 2 additions & 7 deletions grandpa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ extern crate alloc;
pub mod consensus;
pub mod messages;

use alloc::{vec, vec::Vec};
use alloc::vec::Vec;
pub use pallet::*;
use pallet_ismp::host::Host;

Expand All @@ -28,7 +28,6 @@ pub mod pallet {
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use ismp::host::IsmpHost;
use primitive_types::H256;
use primitives::ConsensusState;

#[pallet::pallet]
Expand Down Expand Up @@ -62,11 +61,7 @@ pub mod pallet {
}

#[pallet::call]
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
impl<T: Config> Pallet<T> {
/// Add some new parachains to the list of parachains in the relay chain consensus state
#[pallet::call_index(0)]
#[pallet::weight((0, DispatchClass::Mandatory))]
Expand Down
8 changes: 1 addition & 7 deletions pallet-ismp/evm/src/precompiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use ismp_rs::{
router::{DispatchGet, DispatchPost, DispatchRequest, IsmpDispatcher, Post, PostResponse},
};
use pallet_evm::GasWeightMapping;
use sp_core::{H160, H256};
use sp_core::H160;
use sp_std::prelude::*;

/// Ismp Request Dispatcher precompile for evm contracts
Expand All @@ -37,8 +37,6 @@ pub const GET_REQUEST_DISPATCHER: H160 = H160(hex!("f2d8dc5239ddc053ba5151302483
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,8 +80,6 @@ pub struct IsmpGetDispatcher<T> {
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 @@ -130,8 +126,6 @@ pub struct IsmpResponseDispatcher<T> {
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
13 changes: 4 additions & 9 deletions pallet-ismp/primitives/src/mmr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
use core::fmt::Formatter;

use codec::{Decode, Encode};
use frame_support::sp_io;
use ismp::{
router::{Request, Response},
util::{hash_request, hash_response, Keccak256},
};
use primitive_types::H256;
use sp_runtime::traits;

/// Index of a leaf in the MMR
pub type LeafIndex = u64;
Expand Down Expand Up @@ -87,13 +87,10 @@ impl DataOrHash {
}

/// Default Merging & Hashing behavior for MMR.
pub struct MmrHasher<T, H>(core::marker::PhantomData<(T, H)>);
pub struct MmrHasher<H>(core::marker::PhantomData<H>);

impl<T, H> merkle_mountain_range::Merge for MmrHasher<T, H>
impl<H> merkle_mountain_range::Merge for MmrHasher<H>
where
T: frame_system::Config,
T::Hash: From<H256>,
H256: From<T::Hash>,
H: Keccak256,
{
type Item = DataOrHash;
Expand All @@ -102,8 +99,6 @@ where
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).into(),
))
Ok(DataOrHash::Hash(sp_io::hashing::keccak_256(&concat).into()))
}
}
6 changes: 1 addition & 5 deletions pallet-ismp/primitives/state-machine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ use ismp_primitives::{
};
use merkle_mountain_range::MerkleProof;
use pallet_ismp::host::Host;
use primitive_types::H256;
use sp_runtime::traits::{BlakeTwo256, Keccak256};
use sp_trie::{HashDBT, LayoutV0, StorageProof, Trie, TrieDBBuilder, EMPTY_PREFIX};

Expand All @@ -54,8 +53,6 @@ impl<T> StateMachineClient for SubstrateStateMachine<T>
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 +65,7 @@ where
Error::ImplementationSpecific(format!("Cannot decode membership proof: {e:?}"))
})?;
let nodes = membership.proof.into_iter().map(|h| DataOrHash::Hash(h.into())).collect();
let proof =
MerkleProof::<DataOrHash, MmrHasher<T, Host<T>>>::new(membership.mmr_size, nodes);
let proof = MerkleProof::<DataOrHash, MmrHasher<Host<T>>>::new(membership.mmr_size, nodes);
let leaves: Vec<(u64, DataOrHash)> = match item {
RequestResponse::Request(req) => membership
.leaf_indices
Expand Down
2 changes: 0 additions & 2 deletions pallet-ismp/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ use frame_system::RawOrigin;
/// modules using the [`crate::ismp_mocks::ModuleId`] as it's module id
#[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
3 changes: 0 additions & 3 deletions pallet-ismp/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use ismp_rs::{
host::IsmpHost,
router::{DispatchRequest, Get, IsmpDispatcher, Post, PostResponse, Request, Response},
};
use sp_core::H256;

/// A receipt or an outgoing or incoming request or response
#[derive(Encode, Decode, scale_info::TypeInfo)]
Expand All @@ -43,8 +42,6 @@ impl<T> Default for Dispatcher<T> {
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
7 changes: 1 addition & 6 deletions pallet-ismp/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,8 @@ use ismp_rs::{
router::{Request, Response},
util::{hash_request, hash_response},
};
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>,
{
impl<T: Config> Pallet<T> {
/// Dispatch an outgoing request
pub fn dispatch_request(request: Request) -> Result<(), IsmpError> {
let commitment = hash_request::<Host<T>>(&request);
Expand Down
6 changes: 1 addition & 5 deletions pallet-ismp/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,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>,
{
impl<T: Config> IsmpHost for Host<T> {
fn host_state_machine(&self) -> StateMachine {
T::StateMachine::get()
}
Expand Down
24 changes: 4 additions & 20 deletions pallet-ismp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,7 @@ pub mod pallet {

// Pallet implements [`Hooks`] trait to define some logic to execute in some context.
#[pallet::hooks]
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>,
{
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(_n: T::BlockNumber) -> Weight {
// return Mmr finalization weight here
<T as Config>::WeightInfo::on_finalize(Self::number_of_leaves() as u32)
Expand Down Expand Up @@ -321,11 +317,7 @@ pub mod pallet {
}

#[pallet::call]
impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
impl<T: Config> Pallet<T> {
/// Handles ismp messages
#[pallet::weight(get_weight::<T>(&messages))]
#[pallet::call_index(0)]
Expand Down Expand Up @@ -454,11 +446,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>,
{
impl<T: Config> Pallet<T> {
/// Generate an MMR proof for the given `leaf_indices`.
/// Note this method can only be used from an off-chain context
/// (Offchain Worker or Runtime API call), since it requires
Expand Down Expand Up @@ -567,11 +555,7 @@ pub struct RequestResponseLog<T: Config> {
mmr_root_hash: <T as frame_system::Config>::Hash,
}

impl<T: Config> Pallet<T>
where
<T as frame_system::Config>::Hash: From<H256>,
H256: From<<T as frame_system::Config>::Hash>,
{
impl<T: Config> Pallet<T> {
/// Returns the offchain key for a request leaf index
pub fn request_leaf_index_offchain_key(
source_chain: StateMachine,
Expand Down
10 changes: 1 addition & 9 deletions pallet-ismp/src/mmr/mmr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,15 @@ pub struct Mmr<StorageType, T>
where
T: Config,
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, MmrHasher<T, Host<T>>, Storage<StorageType, T>>,
mmr: mmr_lib::MMR<DataOrHash, MmrHasher<Host<T>>, Storage<StorageType, T>>,
leaves: NodeIndex,
}

impl<StorageType, T> Mmr<StorageType, T>
where
T: Config,
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 @@ -59,8 +55,6 @@ where
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 @@ -84,8 +78,6 @@ where
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 Down
3 changes: 1 addition & 2 deletions pallet-ismp/src/mmr/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use codec::Encode;
use frame_support::log::{debug, trace};
use ismp_primitives::mmr::{DataOrHash, NodeIndex};
use mmr_lib::helper;
use sp_core::{offchain::StorageKind, H256};
use sp_core::offchain::StorageKind;
use sp_std::iter::Peekable;
#[cfg(not(feature = "std"))]
use sp_std::prelude::*;
Expand Down Expand Up @@ -79,7 +79,6 @@ where
impl<T> mmr_lib::MMRStore<DataOrHash> for Storage<RuntimeStorage, T>
where
T: Config,
<T as frame_system::Config>::Hash: From<H256>,
{
fn get_elem(&self, pos: NodeIndex) -> mmr_lib::Result<Option<DataOrHash>> {
Ok(Pallet::<T>::get_node(pos))
Expand Down
6 changes: 3 additions & 3 deletions pallet-ismp/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ fn should_generate_proofs_correctly_for_single_leaf_mmr() {

let mmr_size = NodesUtils::new(proof.leaf_count).size();
let nodes = proof.items.into_iter().map(|h| DataOrHash::Hash(h.into())).collect();
let proof = MerkleProof::<DataOrHash, MmrHasher<Test, Host<Test>>>::new(mmr_size, nodes);
let proof = MerkleProof::<DataOrHash, MmrHasher<Host<Test>>>::new(mmr_size, nodes);
let calculated_root = proof
.calculate_root(vec![(positions[0], DataOrHash::Data(leaves[0].clone()))])
.unwrap();
Expand Down Expand Up @@ -138,7 +138,7 @@ fn should_generate_and_verify_batch_proof_correctly() {

let mmr_size = NodesUtils::new(proof.leaf_count).size();
let nodes = proof.items.into_iter().map(|h| DataOrHash::Hash(h.into())).collect();
let proof = MerkleProof::<DataOrHash, MmrHasher<Test, Host<Test>>>::new(mmr_size, nodes);
let proof = MerkleProof::<DataOrHash, MmrHasher<Host<Test>>>::new(mmr_size, nodes);
let calculated_root = proof
.calculate_root(
indices
Expand Down Expand Up @@ -177,7 +177,7 @@ fn should_generate_and_verify_batch_proof_for_leaves_inserted_across_multiple_bl

let mmr_size = NodesUtils::new(proof.leaf_count).size();
let nodes = proof.items.into_iter().map(|h| DataOrHash::Hash(h.into())).collect();
let proof = MerkleProof::<DataOrHash, MmrHasher<Test, Host<Test>>>::new(mmr_size, nodes);
let proof = MerkleProof::<DataOrHash, MmrHasher<Host<Test>>>::new(mmr_size, nodes);
let calculated_root = proof
.calculate_root(
indices
Expand Down
2 changes: 0 additions & 2 deletions parachain/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ where
R: RelayChainOracle,
T: pallet_ismp::Config + super::Config,
T::BlockNumber: Into<u32>,
T::Hash: From<H256>,
H256: From<T::Hash>,
{
fn verify_consensus(
&self,
Expand Down
Loading