|
| 1 | +// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd. |
| 2 | +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 |
| 3 | + |
| 4 | +// This program is free software: you can redistribute it and/or modify |
| 5 | +// it under the terms of the GNU General Public License as published by |
| 6 | +// the Free Software Foundation, either version 3 of the License, or |
| 7 | +// (at your option) any later version. |
| 8 | + |
| 9 | +// This program is distributed in the hope that it will be useful, |
| 10 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +// GNU General Public License for more details. |
| 13 | + |
| 14 | +// You should have received a copy of the GNU General Public License |
| 15 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +#![cfg_attr(not(feature = "std"), no_std)] |
| 18 | +#![warn(missing_docs)] |
| 19 | + |
| 20 | +//! A BEEFY+MMR pallet combo. |
| 21 | +//! |
| 22 | +//! While both BEEFY and Merkle Mountain Range (MMR) can be used separately, |
| 23 | +//! these tools were designed to work together in unison. |
| 24 | +//! |
| 25 | +//! The pallet provides a standardized MMR Leaf format that is can be used |
| 26 | +//! to bridge BEEFY+MMR-based networks (both standalone and polkadot-like). |
| 27 | +//! |
| 28 | +//! The MMR leaf contains: |
| 29 | +//! 1. Block number and parent block hash. |
| 30 | +//! 2. Merkle Tree Root Hash of next BEEFY validator set. |
| 31 | +//! 3. Merkle Tree Root Hash of current parachain heads state. |
| 32 | +//! |
| 33 | +//! and thanks to versioning can be easily updated in the future. |
| 34 | +
|
| 35 | +use beefy_primitives::mmr::{BeefyNextAuthoritySet, MmrLeaf, MmrLeafVersion}; |
| 36 | +use codec::Encode; |
| 37 | +use frame_support::traits::Get; |
| 38 | +use pallet_mmr::primitives::LeafDataProvider; |
| 39 | +use sp_runtime::traits::{Convert, Hash}; |
| 40 | +use sp_std::prelude::*; |
| 41 | + |
| 42 | +pub use pallet::*; |
| 43 | + |
| 44 | +#[cfg(test)] |
| 45 | +mod mock; |
| 46 | +#[cfg(test)] |
| 47 | +mod tests; |
| 48 | + |
| 49 | +/// A BEEFY consensus digest item with MMR root hash. |
| 50 | +pub struct DepositBeefyDigest<T>(sp_std::marker::PhantomData<T>); |
| 51 | + |
| 52 | +impl<T> pallet_mmr::primitives::OnNewRoot<beefy_primitives::MmrRootHash> for DepositBeefyDigest<T> |
| 53 | +where |
| 54 | + T: pallet_mmr::Config<Hash = beefy_primitives::MmrRootHash>, |
| 55 | + T: pallet_beefy::Config, |
| 56 | +{ |
| 57 | + fn on_new_root(root: &<T as pallet_mmr::Config>::Hash) { |
| 58 | + let digest = sp_runtime::generic::DigestItem::Consensus( |
| 59 | + beefy_primitives::BEEFY_ENGINE_ID, |
| 60 | + codec::Encode::encode( |
| 61 | + &beefy_primitives::ConsensusLog::<<T as pallet_beefy::Config>::BeefyId>::MmrRoot(*root), |
| 62 | + ), |
| 63 | + ); |
| 64 | + <frame_system::Pallet<T>>::deposit_log(digest); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +/// Convert BEEFY secp256k1 public keys into Ethereum addresses |
| 69 | +pub struct BeefyEcdsaToEthereum; |
| 70 | +impl Convert<beefy_primitives::crypto::AuthorityId, Vec<u8>> for BeefyEcdsaToEthereum { |
| 71 | + fn convert(a: beefy_primitives::crypto::AuthorityId) -> Vec<u8> { |
| 72 | + use sp_core::crypto::Public; |
| 73 | + let compressed_key = a.as_slice(); |
| 74 | + |
| 75 | + secp256k1::PublicKey::parse_slice(compressed_key, Some(secp256k1::PublicKeyFormat::Compressed)) |
| 76 | + // uncompress the key |
| 77 | + .map(|pub_key| pub_key.serialize().to_vec()) |
| 78 | + // now convert to ETH address |
| 79 | + .map(|uncompressed| sp_io::hashing::keccak_256(&uncompressed[1..])[12..].to_vec()) |
| 80 | + .map_err(|_| { |
| 81 | + log::error!(target: "runtime::beefy", "Invalid BEEFY PublicKey format!"); |
| 82 | + }) |
| 83 | + .unwrap_or_default() |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +type MerkleRootOf<T> = <T as pallet_mmr::Config>::Hash; |
| 88 | +type ParaId = u32; |
| 89 | +type ParaHead = Vec<u8>; |
| 90 | + |
| 91 | +/// A type that is able to return current list of parachain heads that end up in the MMR leaf. |
| 92 | +pub trait ParachainHeadsProvider { |
| 93 | + /// Return a list of tuples containing a `ParaId` and Parachain Header data (ParaHead). |
| 94 | + /// |
| 95 | + /// The returned data does not have to be sorted. |
| 96 | + fn parachain_heads() -> Vec<(ParaId, ParaHead)>; |
| 97 | +} |
| 98 | + |
| 99 | +/// A default implementation for runtimes without parachains. |
| 100 | +impl ParachainHeadsProvider for () { |
| 101 | + fn parachain_heads() -> Vec<(ParaId, ParaHead)> { |
| 102 | + Default::default() |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +#[frame_support::pallet] |
| 107 | +pub mod pallet { |
| 108 | + #![allow(missing_docs)] |
| 109 | + |
| 110 | + use super::*; |
| 111 | + use frame_support::pallet_prelude::*; |
| 112 | + |
| 113 | + /// BEEFY-MMR pallet. |
| 114 | + #[pallet::pallet] |
| 115 | + #[pallet::generate_store(pub(super) trait Store)] |
| 116 | + pub struct Pallet<T>(_); |
| 117 | + |
| 118 | + /// The module's configuration trait. |
| 119 | + #[pallet::config] |
| 120 | + #[pallet::disable_frame_system_supertrait_check] |
| 121 | + pub trait Config: pallet_mmr::Config + pallet_beefy::Config { |
| 122 | + /// Current leaf version. |
| 123 | + /// |
| 124 | + /// Specifies the version number added to every leaf that get's appended to the MMR. |
| 125 | + /// Read more in [`MmrLeafVersion`] docs about versioning leaves. |
| 126 | + type LeafVersion: Get<MmrLeafVersion>; |
| 127 | + |
| 128 | + /// Convert BEEFY AuthorityId to a form that would end up in the Merkle Tree. |
| 129 | + /// |
| 130 | + /// For instance for ECDSA (secp256k1) we want to store uncompressed public keys (65 bytes) |
| 131 | + /// and later to Ethereum Addresses (160 bits) to simplify using them on Ethereum chain, |
| 132 | + /// but the rest of the Substrate codebase is storing them compressed (33 bytes) for |
| 133 | + /// efficiency reasons. |
| 134 | + type BeefyAuthorityToMerkleLeaf: Convert<<Self as pallet_beefy::Config>::BeefyId, Vec<u8>>; |
| 135 | + |
| 136 | + /// Retrieve a list of current parachain heads. |
| 137 | + /// |
| 138 | + /// The trait is implemented for `paras` module, but since not all chains might have parachains, |
| 139 | + /// and we want to keep the MMR leaf structure uniform, it's possible to use `()` as well to |
| 140 | + /// simply put dummy data to the leaf. |
| 141 | + type ParachainHeads: ParachainHeadsProvider; |
| 142 | + } |
| 143 | + |
| 144 | + /// Details of next BEEFY authority set. |
| 145 | + /// |
| 146 | + /// This storage entry is used as cache for calls to [`update_beefy_next_authority_set`]. |
| 147 | + #[pallet::storage] |
| 148 | + #[pallet::getter(fn beefy_next_authorities)] |
| 149 | + pub type BeefyNextAuthorities<T: Config> = StorageValue<_, BeefyNextAuthoritySet<MerkleRootOf<T>>, ValueQuery>; |
| 150 | +} |
| 151 | + |
| 152 | +impl<T: Config> LeafDataProvider for Pallet<T> |
| 153 | +where |
| 154 | + MerkleRootOf<T>: From<beefy_merkle_tree::Hash> + Into<beefy_merkle_tree::Hash>, |
| 155 | +{ |
| 156 | + type LeafData = |
| 157 | + MmrLeaf<<T as frame_system::Config>::BlockNumber, <T as frame_system::Config>::Hash, MerkleRootOf<T>>; |
| 158 | + |
| 159 | + fn leaf_data() -> Self::LeafData { |
| 160 | + MmrLeaf { |
| 161 | + version: T::LeafVersion::get(), |
| 162 | + parent_number_and_hash: frame_system::Pallet::<T>::leaf_data(), |
| 163 | + parachain_heads: Pallet::<T>::parachain_heads_merkle_root(), |
| 164 | + beefy_next_authority_set: Pallet::<T>::update_beefy_next_authority_set(), |
| 165 | + } |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +impl<T: Config> beefy_merkle_tree::Hasher for Pallet<T> |
| 170 | +where |
| 171 | + MerkleRootOf<T>: Into<beefy_merkle_tree::Hash>, |
| 172 | +{ |
| 173 | + fn hash(data: &[u8]) -> beefy_merkle_tree::Hash { |
| 174 | + <T as pallet_mmr::Config>::Hashing::hash(data).into() |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +impl<T: Config> Pallet<T> |
| 179 | +where |
| 180 | + MerkleRootOf<T>: From<beefy_merkle_tree::Hash> + Into<beefy_merkle_tree::Hash>, |
| 181 | +{ |
| 182 | + /// Returns latest root hash of a merkle tree constructed from all active parachain headers. |
| 183 | + /// |
| 184 | + /// The leafs are sorted by `ParaId` to allow more efficient lookups and non-existence proofs. |
| 185 | + /// |
| 186 | + /// NOTE this does not include parathreads - only parachains are part of the merkle tree. |
| 187 | + /// |
| 188 | + /// NOTE This is an initial and inefficient implementation, which re-constructs |
| 189 | + /// the merkle tree every block. Instead we should update the merkle root in [Self::on_initialize] |
| 190 | + /// call of this pallet and update the merkle tree efficiently (use on-chain storage to persist inner nodes). |
| 191 | + fn parachain_heads_merkle_root() -> MerkleRootOf<T> { |
| 192 | + let mut para_heads = T::ParachainHeads::parachain_heads(); |
| 193 | + para_heads.sort(); |
| 194 | + let para_heads = para_heads.into_iter().map(|pair| pair.encode()); |
| 195 | + beefy_merkle_tree::merkle_root::<Self, _, _>(para_heads).into() |
| 196 | + } |
| 197 | + |
| 198 | + /// Returns details of the next BEEFY authority set. |
| 199 | + /// |
| 200 | + /// Details contain authority set id, authority set length and a merkle root, |
| 201 | + /// constructed from uncompressed secp256k1 public keys converted to Ethereum addresses |
| 202 | + /// of the next BEEFY authority set. |
| 203 | + /// |
| 204 | + /// This function will use a storage-cached entry in case the set didn't change, or compute and cache |
| 205 | + /// new one in case it did. |
| 206 | + fn update_beefy_next_authority_set() -> BeefyNextAuthoritySet<MerkleRootOf<T>> { |
| 207 | + let id = pallet_beefy::Pallet::<T>::validator_set_id() + 1; |
| 208 | + let current_next = Self::beefy_next_authorities(); |
| 209 | + // avoid computing the merkle tree if validator set id didn't change. |
| 210 | + if id == current_next.id { |
| 211 | + return current_next; |
| 212 | + } |
| 213 | + |
| 214 | + let beefy_addresses = pallet_beefy::Pallet::<T>::next_authorities() |
| 215 | + .into_iter() |
| 216 | + .map(T::BeefyAuthorityToMerkleLeaf::convert) |
| 217 | + .collect::<Vec<_>>(); |
| 218 | + let len = beefy_addresses.len() as u32; |
| 219 | + let root = beefy_merkle_tree::merkle_root::<Self, _, _>(beefy_addresses).into(); |
| 220 | + let next_set = BeefyNextAuthoritySet { id, len, root }; |
| 221 | + // cache the result |
| 222 | + BeefyNextAuthorities::<T>::put(&next_set); |
| 223 | + next_set |
| 224 | + } |
| 225 | +} |
0 commit comments