diff --git a/grandpa/src/consensus.rs b/grandpa/src/consensus.rs index 1790faa..fdaa260 100644 --- a/grandpa/src/consensus.rs +++ b/grandpa/src/consensus.rs @@ -61,6 +61,7 @@ where T: pallet_ismp::Config + super::Config, T::BlockNumber: Into, T::Hash: From, + H256: From, { fn verify_consensus( &self, diff --git a/grandpa/src/lib.rs b/grandpa/src/lib.rs index abd26cf..63cd96c 100644 --- a/grandpa/src/lib.rs +++ b/grandpa/src/lib.rs @@ -65,6 +65,7 @@ pub mod pallet { impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Add some new parachains to the list of parachains in the relay chain consensus state #[pallet::call_index(0)] diff --git a/pallet-ismp/evm/src/precompiles.rs b/pallet-ismp/evm/src/precompiles.rs index a745a59..da80048 100644 --- a/pallet-ismp/evm/src/precompiles.rs +++ b/pallet-ismp/evm/src/precompiles.rs @@ -38,6 +38,7 @@ impl Precompile for IsmpPostDispatcher where T: pallet_ismp::Config + pallet_evm::Config, ::Hash: From, + H256: From<::Hash>, { fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { let input = handle.input(); @@ -82,6 +83,7 @@ impl Precompile for IsmpGetDispatcher where T: pallet_ismp::Config + pallet_evm::Config, ::Hash: From, + H256: From<::Hash>, { fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { let input = handle.input(); @@ -129,6 +131,7 @@ impl Precompile for IsmpResponseDispatcher where T: pallet_ismp::Config + pallet_evm::Config, ::Hash: From, + H256: From<::Hash>, { fn execute(handle: &mut impl PrecompileHandle) -> PrecompileResult { let input = handle.input(); diff --git a/pallet-ismp/primitives/src/mmr.rs b/pallet-ismp/primitives/src/mmr.rs index e9b52cb..20ae5d6 100644 --- a/pallet-ismp/primitives/src/mmr.rs +++ b/pallet-ismp/primitives/src/mmr.rs @@ -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; @@ -42,7 +41,7 @@ pub enum Leaf { impl Leaf { /// Returns the hash of a leaf - fn hash(&self) -> H256 { + fn hash(&self) -> H256 { match self { Leaf::Request(req) => hash_request::(req), Leaf::Response(res) => hash_response::(res), @@ -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 { +pub enum DataOrHash { /// Arbitrary data in its full form. Data(Leaf), /// A hash of some data. - Hash(<::Hashing as traits::Hash>::Output), + Hash(H256), } -impl core::fmt::Debug for DataOrHash { +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(), @@ -68,26 +67,20 @@ impl core::fmt::Debug for DataOrHash { } } -impl From for DataOrHash { +impl From for DataOrHash { fn from(l: Leaf) -> Self { Self::Data(l) } } -impl DataOrHash -where - T: frame_system::Config, - T::Hash: From, -{ +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( - &self, - ) -> <::Hashing as traits::Hash>::Output { + pub fn hash(&self) -> H256 { match *self { - Self::Data(ref leaf) => ::from(leaf.hash::()), + Self::Data(ref leaf) => leaf.hash::(), Self::Hash(ref hash) => *hash, } } @@ -100,14 +93,17 @@ impl merkle_mountain_range::Merge for MmrHasher where T: frame_system::Config, T::Hash: From, - H: IsmpHost, + H256: From, + H: Keccak256, { - type Item = DataOrHash; + type Item = DataOrHash; fn merge(left: &Self::Item, right: &Self::Item) -> merkle_mountain_range::Result { let mut concat = left.hash::().as_ref().to_vec(); concat.extend_from_slice(right.hash::().as_ref()); - Ok(DataOrHash::Hash(<::Hashing as traits::Hash>::hash(&concat))) + Ok(DataOrHash::Hash( + <::Hashing as traits::Hash>::hash(&concat).into(), + )) } } diff --git a/pallet-ismp/primitives/state-machine/src/lib.rs b/pallet-ismp/primitives/state-machine/src/lib.rs index 714d291..596f099 100644 --- a/pallet-ismp/primitives/state-machine/src/lib.rs +++ b/pallet-ismp/primitives/state-machine/src/lib.rs @@ -55,6 +55,7 @@ where T: pallet_ismp::Config, T::BlockNumber: Into, T::Hash: From, + H256: From, { fn verify_membership( &self, @@ -68,8 +69,8 @@ where })?; let nodes = membership.proof.into_iter().map(|h| DataOrHash::Hash(h.into())).collect(); let proof = - MerkleProof::, MmrHasher>>::new(membership.mmr_size, nodes); - let leaves: Vec<(u64, DataOrHash)> = match item { + MerkleProof::>>::new(membership.mmr_size, nodes); + let leaves: Vec<(u64, DataOrHash)> = match item { RequestResponse::Request(req) => membership .leaf_indices .into_iter() diff --git a/pallet-ismp/src/benchmarking.rs b/pallet-ismp/src/benchmarking.rs index 91b7338..9cc6c1e 100644 --- a/pallet-ismp/src/benchmarking.rs +++ b/pallet-ismp/src/benchmarking.rs @@ -29,6 +29,7 @@ use frame_system::RawOrigin; #[benchmarks( where ::Hash: From, +H256: From<::Hash>, T: pallet_timestamp::Config, ::Moment: From )] diff --git a/pallet-ismp/src/dispatcher.rs b/pallet-ismp/src/dispatcher.rs index 2a6e4d3..d2d6186 100644 --- a/pallet-ismp/src/dispatcher.rs +++ b/pallet-ismp/src/dispatcher.rs @@ -44,6 +44,7 @@ impl IsmpDispatcher for Dispatcher where T: Config, ::Hash: From, + H256: From<::Hash>, { fn dispatch_request(&self, request: DispatchRequest) -> Result<(), IsmpError> { let host = Host::::default(); diff --git a/pallet-ismp/src/handlers.rs b/pallet-ismp/src/handlers.rs index d38d151..43f8428 100644 --- a/pallet-ismp/src/handlers.rs +++ b/pallet-ismp/src/handlers.rs @@ -15,6 +15,7 @@ use sp_core::H256; impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Dispatch an outgoing request pub fn dispatch_request(request: Request) -> Result<(), IsmpError> { diff --git a/pallet-ismp/src/host.rs b/pallet-ismp/src/host.rs index 27e9466..358d730 100644 --- a/pallet-ismp/src/host.rs +++ b/pallet-ismp/src/host.rs @@ -50,6 +50,7 @@ impl Default for Host { impl IsmpHost for Host where ::Hash: From, + H256: From<::Hash>, { fn host_state_machine(&self) -> StateMachine { T::StateMachine::get() @@ -155,13 +156,6 @@ where ::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 { ChallengePeriod::::get(&id).map(Duration::from_secs) } @@ -259,3 +253,12 @@ where AllowedProxies::::set(allowed); } } + +impl ismp_rs::util::Keccak256 for Host { + fn keccak256(bytes: &[u8]) -> H256 + where + Self: Sized, + { + sp_io::hashing::keccak_256(bytes).into() + } +} diff --git a/pallet-ismp/src/lib.rs b/pallet-ismp/src/lib.rs index ce0b5b1..322c60e 100644 --- a/pallet-ismp/src/lib.rs +++ b/pallet-ismp/src/lib.rs @@ -147,7 +147,7 @@ pub mod pallet { /// Latest MMR Root hash #[pallet::storage] #[pallet::getter(fn mmr_root_hash)] - pub type RootHash = StorageValue<_, ::Hash, ValueQuery>; + pub type RootHash = StorageValue<_, H256, ValueQuery>; /// Current size of the MMR (number of leaves) for requests. #[pallet::storage] @@ -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 = - StorageMap<_, Identity, NodeIndex, ::Hash, OptionQuery>; + pub type Nodes = StorageMap<_, Identity, NodeIndex, H256, OptionQuery>; /// Holds a map of state machine heights to their verified state commitments #[pallet::storage] @@ -275,6 +274,7 @@ pub mod pallet { impl Hooks> for Pallet where ::Hash: From, + H256: From<::Hash>, { fn on_initialize(_n: T::BlockNumber) -> Weight { // return Mmr finalization weight here @@ -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()); @@ -324,6 +324,7 @@ pub mod pallet { impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Handles ismp messages #[pallet::weight(get_weight::(&messages))] @@ -456,6 +457,7 @@ pub mod pallet { impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Generate an MMR proof for the given `leaf_indices`. /// Note this method can only be used from an off-chain context @@ -464,8 +466,7 @@ where /// It may return an error or panic if used incorrectly. pub fn generate_proof( leaf_indices: Vec, - ) -> Result<(Vec, primitives::Proof<::Hash>), primitives::Error> - { + ) -> Result<(Vec, primitives::Proof), primitives::Error> { let leaves_count = NumberOfLeaves::::get(); let mmr = Mmr::::new(leaves_count); mmr.generate_proof(leaf_indices) @@ -549,7 +550,7 @@ where } /// Return the on-chain MMR root hash. - pub fn mmr_root() -> ::Hash { + pub fn mmr_root() -> H256 { Self::mmr_root_hash() } @@ -569,6 +570,7 @@ pub struct RequestResponseLog { impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Returns the offchain key for a request leaf index pub fn request_leaf_index_offchain_key( @@ -597,7 +599,7 @@ where pub fn get_request(leaf_index: LeafIndex) -> Option { let key = Pallet::::offchain_key(leaf_index); if let Some(elem) = sp_io::offchain::local_storage_get(StorageKind::PERSISTENT, &key) { - let data_or_hash = DataOrHash::::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), @@ -613,7 +615,7 @@ where pub fn get_response(leaf_index: LeafIndex) -> Option { let key = Pallet::::offchain_key(leaf_index); if let Some(elem) = sp_io::offchain::local_storage_get(StorageKind::PERSISTENT, &key) { - let data_or_hash = DataOrHash::::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), @@ -736,7 +738,7 @@ where impl Pallet { /// Get a node from runtime storage - fn get_node(pos: NodeIndex) -> Option> { + fn get_node(pos: NodeIndex) -> Option { Nodes::::get(pos).map(DataOrHash::Hash) } @@ -746,7 +748,7 @@ impl Pallet { } /// Insert a node into storage - fn insert_node(pos: NodeIndex, node: ::Hash) { + fn insert_node(pos: NodeIndex, node: H256) { Nodes::::insert(pos, node) } diff --git a/pallet-ismp/src/mmr/mmr.rs b/pallet-ismp/src/mmr/mmr.rs index d3249c4..9ceee61 100644 --- a/pallet-ismp/src/mmr/mmr.rs +++ b/pallet-ismp/src/mmr/mmr.rs @@ -33,18 +33,20 @@ use sp_std::prelude::*; pub struct Mmr where T: Config, - Storage: mmr_lib::MMRStore>, + Storage: mmr_lib::MMRStore, ::Hash: From, + H256: From<::Hash>, { - mmr: mmr_lib::MMR, MmrHasher>, Storage>, + mmr: mmr_lib::MMR>, Storage>, leaves: NodeIndex, } impl Mmr where T: Config, - Storage: mmr_lib::MMRStore>, + Storage: mmr_lib::MMRStore, ::Hash: From, + H256: From<::Hash>, { /// Create a pointer to an existing MMR with given number of leaves. pub fn new(leaves: NodeIndex) -> Self { @@ -58,6 +60,7 @@ impl Mmr where T: Config, ::Hash: From, + H256: From<::Hash>, { /// Push another item to the MMR and commit /// @@ -71,7 +74,7 @@ where } /// Calculate the new MMR's root hash. - pub fn finalize(self) -> Result<::Hash, Error> { + pub fn finalize(self) -> Result { let root = self.mmr.get_root().map_err(|_| Error::GetRoot)?; Ok(root.hash::>()) } @@ -82,6 +85,7 @@ impl Mmr where T: Config, ::Hash: From, + H256: From<::Hash>, { /// Generate a proof for given leaf indices. /// @@ -90,7 +94,7 @@ where pub fn generate_proof( &self, positions: Vec, - ) -> Result<(Vec, Proof<::Hash>), Error> { + ) -> Result<(Vec, Proof), Error> { let store = >::default(); let leaves = positions .iter() diff --git a/pallet-ismp/src/mmr/storage.rs b/pallet-ismp/src/mmr/storage.rs index 34433b9..1b376a4 100644 --- a/pallet-ismp/src/mmr/storage.rs +++ b/pallet-ismp/src/mmr/storage.rs @@ -53,11 +53,11 @@ impl Default for Storage { } } -impl mmr_lib::MMRStore> for Storage +impl mmr_lib::MMRStore for Storage where T: Config, { - fn get_elem(&self, pos: NodeIndex) -> mmr_lib::Result>> { + fn get_elem(&self, pos: NodeIndex) -> mmr_lib::Result> { let key = Pallet::::offchain_key(pos); debug!( target: "runtime::mmr::offchain", "offchain db get {}: key {:?}", @@ -71,21 +71,21 @@ where Ok(None) } - fn append(&mut self, _: NodeIndex, _: Vec>) -> mmr_lib::Result<()> { + fn append(&mut self, _: NodeIndex, _: Vec) -> mmr_lib::Result<()> { panic!("MMR must not be altered in the off-chain context.") } } -impl mmr_lib::MMRStore> for Storage +impl mmr_lib::MMRStore for Storage where T: Config, ::Hash: From, { - fn get_elem(&self, pos: NodeIndex) -> mmr_lib::Result>> { + fn get_elem(&self, pos: NodeIndex) -> mmr_lib::Result> { Ok(Pallet::::get_node(pos)) } - fn append(&mut self, pos: NodeIndex, elems: Vec>) -> mmr_lib::Result<()> { + fn append(&mut self, pos: NodeIndex, elems: Vec) -> mmr_lib::Result<()> { if elems.is_empty() { return Ok(()) } @@ -144,7 +144,7 @@ where T: Config, { /// Store a node in the offchain db - fn store_to_offchain(pos: NodeIndex, node: &DataOrHash) { + fn store_to_offchain(pos: NodeIndex, node: &DataOrHash) { let encoded_node = node.encode(); let key = Pallet::::offchain_key(pos); diff --git a/pallet-ismp/src/tests.rs b/pallet-ismp/src/tests.rs index c14d516..f292368 100644 --- a/pallet-ismp/src/tests.rs +++ b/pallet-ismp/src/tests.rs @@ -107,8 +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::, MmrHasher>>::new(mmr_size, nodes); + let proof = MerkleProof::>>::new(mmr_size, nodes); let calculated_root = proof .calculate_root(vec![(positions[0], DataOrHash::Data(leaves[0].clone()))]) .unwrap(); @@ -139,8 +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::, MmrHasher>>::new(mmr_size, nodes); + let proof = MerkleProof::>>::new(mmr_size, nodes); let calculated_root = proof .calculate_root( indices @@ -179,8 +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::, MmrHasher>>::new(mmr_size, nodes); + let proof = MerkleProof::>>::new(mmr_size, nodes); let calculated_root = proof .calculate_root( indices diff --git a/parachain/src/consensus.rs b/parachain/src/consensus.rs index 5383516..4cacab5 100644 --- a/parachain/src/consensus.rs +++ b/parachain/src/consensus.rs @@ -77,6 +77,7 @@ where T: pallet_ismp::Config + super::Config, T::BlockNumber: Into, T::Hash: From, + H256: From, { fn verify_consensus( &self, diff --git a/parachain/src/lib.rs b/parachain/src/lib.rs index 1e5acde..8edfe92 100644 --- a/parachain/src/lib.rs +++ b/parachain/src/lib.rs @@ -78,6 +78,7 @@ pub mod pallet { impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Rather than users manually submitting consensus updates for sibling parachains, we /// instead make it the responsibility of the block builder to insert the consensus @@ -135,6 +136,7 @@ pub mod pallet { impl Hooks> for Pallet where ::Hash: From, + H256: From<::Hash>, { fn on_finalize(_n: T::BlockNumber) { let state = RelaychainDataProvider::::current_relay_chain_state(); @@ -170,6 +172,7 @@ pub mod pallet { impl ProvideInherent for Pallet where ::Hash: From, + H256: From<::Hash>, { type Call = Call; type Error = sp_inherents::MakeFatalError<()>; @@ -205,6 +208,7 @@ pub mod pallet { impl GenesisBuild for GenesisConfig where ::Hash: From, + H256: From<::Hash>, { fn build(&self) { let host = Host::::default(); @@ -221,6 +225,7 @@ pub mod pallet { impl Pallet where ::Hash: From, + H256: From<::Hash>, { /// Returns the list of parachains who's consensus updates will be inserted by the inherent /// data provider